blob: bed7fc099313badab12567fdb3d3965a032dd6a7 [file] [log] [blame]
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001//===--- CGDebugInfo.cpp - Emit Debug Information for a Module ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the debug information generation while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGDebugInfo.h"
15#include "CGBlocks.h"
David Blaikie9dfd2432013-05-10 21:53:14 +000016#include "CGCXXABI.h"
Guy Benyei7f92f2d2012-12-18 14:30:41 +000017#include "CGObjCRuntime.h"
18#include "CodeGenFunction.h"
19#include "CodeGenModule.h"
20#include "clang/AST/ASTContext.h"
21#include "clang/AST/DeclFriend.h"
22#include "clang/AST/DeclObjC.h"
23#include "clang/AST/DeclTemplate.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/RecordLayout.h"
26#include "clang/Basic/FileManager.h"
27#include "clang/Basic/SourceManager.h"
28#include "clang/Basic/Version.h"
29#include "clang/Frontend/CodeGenOptions.h"
30#include "llvm/ADT/SmallVector.h"
31#include "llvm/ADT/StringExtras.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000032#include "llvm/IR/Constants.h"
33#include "llvm/IR/DataLayout.h"
34#include "llvm/IR/DerivedTypes.h"
35#include "llvm/IR/Instructions.h"
36#include "llvm/IR/Intrinsics.h"
37#include "llvm/IR/Module.h"
Guy Benyei7f92f2d2012-12-18 14:30:41 +000038#include "llvm/Support/Dwarf.h"
39#include "llvm/Support/FileSystem.h"
40using namespace clang;
41using namespace clang::CodeGen;
42
43CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
Eric Christopher688cf5b2013-07-14 21:12:44 +000044 : CGM(CGM), DebugKind(CGM.getCodeGenOpts().getDebugInfo()),
45 DBuilder(CGM.getModule()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +000046 CreateCompileUnit();
47}
48
49CGDebugInfo::~CGDebugInfo() {
50 assert(LexicalBlockStack.empty() &&
51 "Region stack mismatch, stack not empty!");
52}
53
Adrian Prantled6bbe42013-07-18 00:28:02 +000054
55NoLocation::NoLocation(CodeGenFunction &CGF, CGBuilderTy &B)
56 : DI(CGF.getDebugInfo()), Builder(B) {
57 if (DI) {
58 SavedLoc = DI->getLocation();
59 DI->CurLoc = SourceLocation();
60 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
61 }
62}
63
64NoLocation::~NoLocation() {
65 if (DI) {
66 assert(Builder.getCurrentDebugLocation().isUnknown());
67 DI->CurLoc = SavedLoc;
68 }
69}
70
Adrian Prantlb061ce22013-07-18 01:36:04 +000071ArtificialLocation::ArtificialLocation(CodeGenFunction &CGF, CGBuilderTy &B)
Adrian Prantled6bbe42013-07-18 00:28:02 +000072 : DI(CGF.getDebugInfo()), Builder(B) {
73 if (DI) {
74 SavedLoc = DI->getLocation();
Adrian Prantlb6cdc962013-07-24 20:34:39 +000075 DI->CurLoc = SourceLocation();
76 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
77 }
78}
79
80void ArtificialLocation::Emit() {
81 if (DI) {
Adrian Prantled6bbe42013-07-18 00:28:02 +000082 // Sync the Builder.
83 DI->EmitLocation(Builder, SavedLoc);
84 DI->CurLoc = SourceLocation();
85 // Construct a location that has a valid scope, but no line info.
Adrian Prantlb6cdc962013-07-24 20:34:39 +000086 assert(!DI->LexicalBlockStack.empty());
87 llvm::DIDescriptor Scope(DI->LexicalBlockStack.back());
Adrian Prantled6bbe42013-07-18 00:28:02 +000088 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(0, 0, Scope));
89 }
90}
91
Adrian Prantlb061ce22013-07-18 01:36:04 +000092ArtificialLocation::~ArtificialLocation() {
Adrian Prantled6bbe42013-07-18 00:28:02 +000093 if (DI) {
94 assert(Builder.getCurrentDebugLocation().getLine() == 0);
95 DI->CurLoc = SavedLoc;
96 }
97}
98
Guy Benyei7f92f2d2012-12-18 14:30:41 +000099void CGDebugInfo::setLocation(SourceLocation Loc) {
100 // If the new location isn't valid return.
Adrian Prantl5f4554f2013-07-18 00:27:56 +0000101 if (Loc.isInvalid()) return;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000102
103 CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc);
104
105 // If we've changed files in the middle of a lexical scope go ahead
106 // and create a new lexical scope with file node if it's different
107 // from the one in the scope.
108 if (LexicalBlockStack.empty()) return;
109
110 SourceManager &SM = CGM.getContext().getSourceManager();
111 PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
112 PresumedLoc PPLoc = SM.getPresumedLoc(PrevLoc);
113
114 if (PCLoc.isInvalid() || PPLoc.isInvalid() ||
115 !strcmp(PPLoc.getFilename(), PCLoc.getFilename()))
116 return;
117
118 llvm::MDNode *LB = LexicalBlockStack.back();
119 llvm::DIScope Scope = llvm::DIScope(LB);
120 if (Scope.isLexicalBlockFile()) {
121 llvm::DILexicalBlockFile LBF = llvm::DILexicalBlockFile(LB);
122 llvm::DIDescriptor D
123 = DBuilder.createLexicalBlockFile(LBF.getScope(),
124 getOrCreateFile(CurLoc));
125 llvm::MDNode *N = D;
126 LexicalBlockStack.pop_back();
127 LexicalBlockStack.push_back(N);
David Blaikiea6504852013-01-26 22:16:26 +0000128 } else if (Scope.isLexicalBlock() || Scope.isSubprogram()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000129 llvm::DIDescriptor D
130 = DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc));
131 llvm::MDNode *N = D;
132 LexicalBlockStack.pop_back();
133 LexicalBlockStack.push_back(N);
134 }
135}
136
137/// getContextDescriptor - Get context info for the decl.
David Blaikiebb000792013-04-19 06:56:38 +0000138llvm::DIScope CGDebugInfo::getContextDescriptor(const Decl *Context) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000139 if (!Context)
140 return TheCU;
141
142 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
143 I = RegionMap.find(Context);
144 if (I != RegionMap.end()) {
145 llvm::Value *V = I->second;
David Blaikiebb000792013-04-19 06:56:38 +0000146 return llvm::DIScope(dyn_cast_or_null<llvm::MDNode>(V));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000147 }
148
149 // Check namespace.
150 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
David Blaikiebb000792013-04-19 06:56:38 +0000151 return getOrCreateNameSpace(NSDecl);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000152
David Blaikiebb000792013-04-19 06:56:38 +0000153 if (const RecordDecl *RDecl = dyn_cast<RecordDecl>(Context))
154 if (!RDecl->isDependentType())
155 return getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000156 getOrCreateMainFile());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000157 return TheCU;
158}
159
160/// getFunctionName - Get function name for the given FunctionDecl. If the
161/// name is constructred on demand (e.g. C++ destructor) then the name
162/// is stored on the side.
163StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
164 assert (FD && "Invalid FunctionDecl!");
165 IdentifierInfo *FII = FD->getIdentifier();
166 FunctionTemplateSpecializationInfo *Info
167 = FD->getTemplateSpecializationInfo();
168 if (!Info && FII)
169 return FII->getName();
170
171 // Otherwise construct human readable name for debug info.
Benjamin Kramer5eada842013-02-22 15:46:01 +0000172 SmallString<128> NS;
173 llvm::raw_svector_ostream OS(NS);
174 FD->printName(OS);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000175
176 // Add any template specialization args.
177 if (Info) {
178 const TemplateArgumentList *TArgs = Info->TemplateArguments;
179 const TemplateArgument *Args = TArgs->data();
180 unsigned NumArgs = TArgs->size();
181 PrintingPolicy Policy(CGM.getLangOpts());
Benjamin Kramer5eada842013-02-22 15:46:01 +0000182 TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs,
183 Policy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000184 }
185
186 // Copy this name on the side and use its reference.
Benjamin Kramer5eada842013-02-22 15:46:01 +0000187 OS.flush();
188 char *StrPtr = DebugInfoNames.Allocate<char>(NS.size());
189 memcpy(StrPtr, NS.data(), NS.size());
190 return StringRef(StrPtr, NS.size());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000191}
192
193StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
194 SmallString<256> MethodName;
195 llvm::raw_svector_ostream OS(MethodName);
196 OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
197 const DeclContext *DC = OMD->getDeclContext();
Eric Christopher6537f082013-05-16 00:45:12 +0000198 if (const ObjCImplementationDecl *OID =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000199 dyn_cast<const ObjCImplementationDecl>(DC)) {
200 OS << OID->getName();
Eric Christopher6537f082013-05-16 00:45:12 +0000201 } else if (const ObjCInterfaceDecl *OID =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000202 dyn_cast<const ObjCInterfaceDecl>(DC)) {
203 OS << OID->getName();
Eric Christopher6537f082013-05-16 00:45:12 +0000204 } else if (const ObjCCategoryImplDecl *OCD =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000205 dyn_cast<const ObjCCategoryImplDecl>(DC)){
206 OS << ((const NamedDecl *)OCD)->getIdentifier()->getNameStart() << '(' <<
207 OCD->getIdentifier()->getNameStart() << ')';
Adrian Prantlb5092242013-05-17 23:58:45 +0000208 } else if (isa<ObjCProtocolDecl>(DC)) {
Adrian Prantl687ecae2013-05-17 23:49:10 +0000209 // We can extract the type of the class from the self pointer.
210 if (ImplicitParamDecl* SelfDecl = OMD->getSelfDecl()) {
211 QualType ClassTy =
212 cast<ObjCObjectPointerType>(SelfDecl->getType())->getPointeeType();
213 ClassTy.print(OS, PrintingPolicy(LangOptions()));
214 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000215 }
216 OS << ' ' << OMD->getSelector().getAsString() << ']';
217
218 char *StrPtr = DebugInfoNames.Allocate<char>(OS.tell());
219 memcpy(StrPtr, MethodName.begin(), OS.tell());
220 return StringRef(StrPtr, OS.tell());
221}
222
223/// getSelectorName - Return selector name. This is used for debugging
224/// info.
225StringRef CGDebugInfo::getSelectorName(Selector S) {
226 const std::string &SName = S.getAsString();
227 char *StrPtr = DebugInfoNames.Allocate<char>(SName.size());
228 memcpy(StrPtr, SName.data(), SName.size());
229 return StringRef(StrPtr, SName.size());
230}
231
232/// getClassName - Get class name including template argument list.
Eric Christopher6537f082013-05-16 00:45:12 +0000233StringRef
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000234CGDebugInfo::getClassName(const RecordDecl *RD) {
235 const ClassTemplateSpecializationDecl *Spec
236 = dyn_cast<ClassTemplateSpecializationDecl>(RD);
237 if (!Spec)
238 return RD->getName();
239
240 const TemplateArgument *Args;
241 unsigned NumArgs;
242 if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) {
243 const TemplateSpecializationType *TST =
244 cast<TemplateSpecializationType>(TAW->getType());
245 Args = TST->getArgs();
246 NumArgs = TST->getNumArgs();
247 } else {
248 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
249 Args = TemplateArgs.data();
250 NumArgs = TemplateArgs.size();
251 }
252 StringRef Name = RD->getIdentifier()->getName();
253 PrintingPolicy Policy(CGM.getLangOpts());
Benjamin Kramer5eada842013-02-22 15:46:01 +0000254 SmallString<128> TemplateArgList;
255 {
256 llvm::raw_svector_ostream OS(TemplateArgList);
257 TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs,
258 Policy);
259 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000260
261 // Copy this name on the side and use its reference.
262 size_t Length = Name.size() + TemplateArgList.size();
263 char *StrPtr = DebugInfoNames.Allocate<char>(Length);
264 memcpy(StrPtr, Name.data(), Name.size());
265 memcpy(StrPtr + Name.size(), TemplateArgList.data(), TemplateArgList.size());
266 return StringRef(StrPtr, Length);
267}
268
269/// getOrCreateFile - Get the file debug info descriptor for the input location.
270llvm::DIFile CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
271 if (!Loc.isValid())
272 // If Location is not valid then use main input file.
273 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
274
275 SourceManager &SM = CGM.getContext().getSourceManager();
276 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
277
278 if (PLoc.isInvalid() || StringRef(PLoc.getFilename()).empty())
279 // If the location is not valid then use main input file.
280 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
281
282 // Cache the results.
283 const char *fname = PLoc.getFilename();
284 llvm::DenseMap<const char *, llvm::WeakVH>::iterator it =
285 DIFileCache.find(fname);
286
287 if (it != DIFileCache.end()) {
288 // Verify that the information still exists.
289 if (llvm::Value *V = it->second)
290 return llvm::DIFile(cast<llvm::MDNode>(V));
291 }
292
293 llvm::DIFile F = DBuilder.createFile(PLoc.getFilename(), getCurrentDirname());
294
295 DIFileCache[fname] = F;
296 return F;
297}
298
299/// getOrCreateMainFile - Get the file info for main compile unit.
300llvm::DIFile CGDebugInfo::getOrCreateMainFile() {
301 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
302}
303
304/// getLineNumber - Get line number for the location. If location is invalid
305/// then use current location.
306unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
307 if (Loc.isInvalid() && CurLoc.isInvalid())
308 return 0;
309 SourceManager &SM = CGM.getContext().getSourceManager();
310 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
311 return PLoc.isValid()? PLoc.getLine() : 0;
312}
313
314/// getColumnNumber - Get column number for the location.
Adrian Prantl00df5ea2013-03-12 20:43:25 +0000315unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000316 // We may not want column information at all.
Adrian Prantl00df5ea2013-03-12 20:43:25 +0000317 if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000318 return 0;
319
320 // If the location is invalid then use the current column.
321 if (Loc.isInvalid() && CurLoc.isInvalid())
322 return 0;
323 SourceManager &SM = CGM.getContext().getSourceManager();
324 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
325 return PLoc.isValid()? PLoc.getColumn() : 0;
326}
327
328StringRef CGDebugInfo::getCurrentDirname() {
329 if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
330 return CGM.getCodeGenOpts().DebugCompilationDir;
331
332 if (!CWDName.empty())
333 return CWDName;
334 SmallString<256> CWD;
335 llvm::sys::fs::current_path(CWD);
336 char *CompDirnamePtr = DebugInfoNames.Allocate<char>(CWD.size());
337 memcpy(CompDirnamePtr, CWD.data(), CWD.size());
338 return CWDName = StringRef(CompDirnamePtr, CWD.size());
339}
340
341/// CreateCompileUnit - Create new compile unit.
342void CGDebugInfo::CreateCompileUnit() {
343
344 // Get absolute path name.
345 SourceManager &SM = CGM.getContext().getSourceManager();
346 std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
347 if (MainFileName.empty())
348 MainFileName = "<unknown>";
349
350 // The main file name provided via the "-main-file-name" option contains just
351 // the file name itself with no path information. This file name may have had
352 // a relative path, so we look into the actual file entry for the main
353 // file to determine the real absolute path for the file.
354 std::string MainFileDir;
355 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
356 MainFileDir = MainFile->getDir()->getName();
357 if (MainFileDir != ".")
358 MainFileName = MainFileDir + "/" + MainFileName;
359 }
360
361 // Save filename string.
362 char *FilenamePtr = DebugInfoNames.Allocate<char>(MainFileName.length());
363 memcpy(FilenamePtr, MainFileName.c_str(), MainFileName.length());
364 StringRef Filename(FilenamePtr, MainFileName.length());
Eric Christopherff971d72013-02-22 23:50:16 +0000365
366 // Save split dwarf file string.
367 std::string SplitDwarfFile = CGM.getCodeGenOpts().SplitDwarfFile;
368 char *SplitDwarfPtr = DebugInfoNames.Allocate<char>(SplitDwarfFile.length());
369 memcpy(SplitDwarfPtr, SplitDwarfFile.c_str(), SplitDwarfFile.length());
370 StringRef SplitDwarfFilename(SplitDwarfPtr, SplitDwarfFile.length());
Eric Christopher6537f082013-05-16 00:45:12 +0000371
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000372 unsigned LangTag;
373 const LangOptions &LO = CGM.getLangOpts();
374 if (LO.CPlusPlus) {
375 if (LO.ObjC1)
376 LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
377 else
378 LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
379 } else if (LO.ObjC1) {
380 LangTag = llvm::dwarf::DW_LANG_ObjC;
381 } else if (LO.C99) {
382 LangTag = llvm::dwarf::DW_LANG_C99;
383 } else {
384 LangTag = llvm::dwarf::DW_LANG_C89;
385 }
386
387 std::string Producer = getClangFullVersion();
388
389 // Figure out which version of the ObjC runtime we have.
390 unsigned RuntimeVers = 0;
391 if (LO.ObjC1)
392 RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
393
394 // Create new compile unit.
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000395 // FIXME - Eliminate TheCU.
Eric Christopher8fed3f42013-07-19 00:51:58 +0000396 TheCU = DBuilder.createCompileUnit(LangTag, Filename, getCurrentDirname(),
397 Producer, LO.Optimize,
398 CGM.getCodeGenOpts().DwarfDebugFlags,
399 RuntimeVers, SplitDwarfFilename);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000400}
401
402/// CreateType - Get the Basic type from the cache or create a new
403/// one if necessary.
404llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT) {
405 unsigned Encoding = 0;
406 StringRef BTName;
407 switch (BT->getKind()) {
408#define BUILTIN_TYPE(Id, SingletonId)
409#define PLACEHOLDER_TYPE(Id, SingletonId) \
410 case BuiltinType::Id:
411#include "clang/AST/BuiltinTypes.def"
412 case BuiltinType::Dependent:
413 llvm_unreachable("Unexpected builtin type");
414 case BuiltinType::NullPtr:
Peter Collingbourne24118f52013-06-27 22:51:01 +0000415 return DBuilder.createNullPtrType();
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000416 case BuiltinType::Void:
417 return llvm::DIType();
418 case BuiltinType::ObjCClass:
Eric Christopherb2d13922013-07-18 00:52:50 +0000419 if (ClassTy)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000420 return ClassTy;
421 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
422 "objc_class", TheCU,
423 getOrCreateMainFile(), 0);
424 return ClassTy;
425 case BuiltinType::ObjCId: {
426 // typedef struct objc_class *Class;
427 // typedef struct objc_object {
428 // Class isa;
429 // } *id;
430
Eric Christopherb2d13922013-07-18 00:52:50 +0000431 if (ObjTy)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000432 return ObjTy;
433
Eric Christopherb2d13922013-07-18 00:52:50 +0000434 if (!ClassTy)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000435 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
436 "objc_class", TheCU,
437 getOrCreateMainFile(), 0);
438
439 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
Eric Christopher6537f082013-05-16 00:45:12 +0000440
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000441 llvm::DIType ISATy = DBuilder.createPointerType(ClassTy, Size);
442
Eric Christopherf068c922013-04-02 22:59:11 +0000443 ObjTy =
David Blaikiec1d0af12013-02-25 01:07:08 +0000444 DBuilder.createStructType(TheCU, "objc_object", getOrCreateMainFile(),
445 0, 0, 0, 0, llvm::DIType(), llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000446
Eric Christopherf068c922013-04-02 22:59:11 +0000447 ObjTy.setTypeArray(DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
448 ObjTy, "isa", getOrCreateMainFile(), 0, Size, 0, 0, 0, ISATy)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000449 return ObjTy;
450 }
451 case BuiltinType::ObjCSel: {
Eric Christopherb2d13922013-07-18 00:52:50 +0000452 if (SelTy)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000453 return SelTy;
454 SelTy =
455 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
456 "objc_selector", TheCU, getOrCreateMainFile(),
457 0);
458 return SelTy;
459 }
Guy Benyeib13621d2012-12-18 14:38:23 +0000460
461 case BuiltinType::OCLImage1d:
462 return getOrCreateStructPtrType("opencl_image1d_t",
463 OCLImage1dDITy);
464 case BuiltinType::OCLImage1dArray:
Eric Christopher6537f082013-05-16 00:45:12 +0000465 return getOrCreateStructPtrType("opencl_image1d_array_t",
Guy Benyeib13621d2012-12-18 14:38:23 +0000466 OCLImage1dArrayDITy);
467 case BuiltinType::OCLImage1dBuffer:
468 return getOrCreateStructPtrType("opencl_image1d_buffer_t",
469 OCLImage1dBufferDITy);
470 case BuiltinType::OCLImage2d:
471 return getOrCreateStructPtrType("opencl_image2d_t",
472 OCLImage2dDITy);
473 case BuiltinType::OCLImage2dArray:
474 return getOrCreateStructPtrType("opencl_image2d_array_t",
475 OCLImage2dArrayDITy);
476 case BuiltinType::OCLImage3d:
477 return getOrCreateStructPtrType("opencl_image3d_t",
478 OCLImage3dDITy);
Guy Benyei21f18c42013-02-07 10:55:47 +0000479 case BuiltinType::OCLSampler:
480 return DBuilder.createBasicType("opencl_sampler_t",
481 CGM.getContext().getTypeSize(BT),
482 CGM.getContext().getTypeAlign(BT),
483 llvm::dwarf::DW_ATE_unsigned);
Guy Benyeie6b9d802013-01-20 12:31:11 +0000484 case BuiltinType::OCLEvent:
485 return getOrCreateStructPtrType("opencl_event_t",
486 OCLEventDITy);
Guy Benyeib13621d2012-12-18 14:38:23 +0000487
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000488 case BuiltinType::UChar:
489 case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
490 case BuiltinType::Char_S:
491 case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
492 case BuiltinType::Char16:
493 case BuiltinType::Char32: Encoding = llvm::dwarf::DW_ATE_UTF; break;
494 case BuiltinType::UShort:
495 case BuiltinType::UInt:
496 case BuiltinType::UInt128:
497 case BuiltinType::ULong:
498 case BuiltinType::WChar_U:
499 case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
500 case BuiltinType::Short:
501 case BuiltinType::Int:
502 case BuiltinType::Int128:
503 case BuiltinType::Long:
504 case BuiltinType::WChar_S:
505 case BuiltinType::LongLong: Encoding = llvm::dwarf::DW_ATE_signed; break;
506 case BuiltinType::Bool: Encoding = llvm::dwarf::DW_ATE_boolean; break;
507 case BuiltinType::Half:
508 case BuiltinType::Float:
509 case BuiltinType::LongDouble:
510 case BuiltinType::Double: Encoding = llvm::dwarf::DW_ATE_float; break;
511 }
512
513 switch (BT->getKind()) {
514 case BuiltinType::Long: BTName = "long int"; break;
515 case BuiltinType::LongLong: BTName = "long long int"; break;
516 case BuiltinType::ULong: BTName = "long unsigned int"; break;
517 case BuiltinType::ULongLong: BTName = "long long unsigned int"; break;
518 default:
519 BTName = BT->getName(CGM.getLangOpts());
520 break;
521 }
522 // Bit size, align and offset of the type.
523 uint64_t Size = CGM.getContext().getTypeSize(BT);
524 uint64_t Align = CGM.getContext().getTypeAlign(BT);
Eric Christopher6537f082013-05-16 00:45:12 +0000525 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000526 DBuilder.createBasicType(BTName, Size, Align, Encoding);
527 return DbgTy;
528}
529
530llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty) {
531 // Bit size, align and offset of the type.
532 unsigned Encoding = llvm::dwarf::DW_ATE_complex_float;
533 if (Ty->isComplexIntegerType())
534 Encoding = llvm::dwarf::DW_ATE_lo_user;
535
536 uint64_t Size = CGM.getContext().getTypeSize(Ty);
537 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
Eric Christopher6537f082013-05-16 00:45:12 +0000538 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000539 DBuilder.createBasicType("complex", Size, Align, Encoding);
540
541 return DbgTy;
542}
543
544/// CreateCVRType - Get the qualified type from the cache or create
545/// a new one if necessary.
Eric Christopher56b108a2013-06-07 22:54:39 +0000546llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit,
547 bool Declaration) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000548 QualifierCollector Qc;
549 const Type *T = Qc.strip(Ty);
550
551 // Ignore these qualifiers for now.
552 Qc.removeObjCGCAttr();
553 Qc.removeAddressSpace();
554 Qc.removeObjCLifetime();
555
556 // We will create one Derived type for one qualifier and recurse to handle any
557 // additional ones.
558 unsigned Tag;
559 if (Qc.hasConst()) {
560 Tag = llvm::dwarf::DW_TAG_const_type;
561 Qc.removeConst();
562 } else if (Qc.hasVolatile()) {
563 Tag = llvm::dwarf::DW_TAG_volatile_type;
564 Qc.removeVolatile();
565 } else if (Qc.hasRestrict()) {
566 Tag = llvm::dwarf::DW_TAG_restrict_type;
567 Qc.removeRestrict();
568 } else {
569 assert(Qc.empty() && "Unknown type qualifier for debug info");
570 return getOrCreateType(QualType(T, 0), Unit);
571 }
572
Eric Christopher56b108a2013-06-07 22:54:39 +0000573 llvm::DIType FromTy =
574 getOrCreateType(Qc.apply(CGM.getContext(), T), Unit, Declaration);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000575
576 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
577 // CVR derived types.
578 llvm::DIType DbgTy = DBuilder.createQualifiedType(Tag, FromTy);
Eric Christopher6537f082013-05-16 00:45:12 +0000579
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000580 return DbgTy;
581}
582
583llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
584 llvm::DIFile Unit) {
Fariborz Jahanian05f8ff12013-02-21 20:42:11 +0000585
586 // The frontend treats 'id' as a typedef to an ObjCObjectType,
587 // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
588 // debug info, we want to emit 'id' in both cases.
589 if (Ty->isObjCQualifiedIdType())
590 return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
591
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000592 llvm::DIType DbgTy =
Eric Christopher6537f082013-05-16 00:45:12 +0000593 CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000594 Ty->getPointeeType(), Unit);
595 return DbgTy;
596}
597
598llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
599 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +0000600 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000601 Ty->getPointeeType(), Unit);
602}
603
604// Creates a forward declaration for a RecordDecl in the given context.
David Blaikieeaacc882013-08-20 21:03:29 +0000605llvm::DICompositeType
606CGDebugInfo::getOrCreateRecordFwdDecl(const RecordDecl *RD,
607 llvm::DIDescriptor Ctx) {
David Blaikiec5cd1a72013-08-15 20:17:25 +0000608 if (llvm::DIType T = getTypeOrNull(CGM.getContext().getRecordType(RD)))
David Blaikieeaacc882013-08-20 21:03:29 +0000609 return llvm::DICompositeType(T);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000610 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
611 unsigned Line = getLineNumber(RD->getLocation());
612 StringRef RDName = getClassName(RD);
613
614 unsigned Tag = 0;
615 if (RD->isStruct() || RD->isInterface())
616 Tag = llvm::dwarf::DW_TAG_structure_type;
617 else if (RD->isUnion())
618 Tag = llvm::dwarf::DW_TAG_union_type;
619 else {
620 assert(RD->isClass());
621 Tag = llvm::dwarf::DW_TAG_class_type;
622 }
623
624 // Create the type.
625 return DBuilder.createForwardDecl(Tag, RDName, Ctx, DefUnit, Line);
626}
627
628// Walk up the context chain and create forward decls for record decls,
629// and normal descriptors for namespaces.
630llvm::DIDescriptor CGDebugInfo::createContextChain(const Decl *Context) {
631 if (!Context)
632 return TheCU;
633
634 // See if we already have the parent.
635 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
636 I = RegionMap.find(Context);
637 if (I != RegionMap.end()) {
638 llvm::Value *V = I->second;
639 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
640 }
Eric Christopher6537f082013-05-16 00:45:12 +0000641
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000642 // Check namespace.
643 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
644 return llvm::DIDescriptor(getOrCreateNameSpace(NSDecl));
645
David Blaikieeaacc882013-08-20 21:03:29 +0000646 if (const RecordDecl *RD = dyn_cast<RecordDecl>(Context))
647 if (!RD->isDependentType())
648 return getOrCreateLimitedType(
David Blaikie5434fc22013-08-20 01:28:15 +0000649 CGM.getContext().getRecordType(RD)->castAs<RecordType>(),
David Blaikieeaacc882013-08-20 21:03:29 +0000650 getOrCreateMainFile());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000651 return TheCU;
652}
653
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000654llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag,
Eric Christopher6537f082013-05-16 00:45:12 +0000655 const Type *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000656 QualType PointeeTy,
657 llvm::DIFile Unit) {
658 if (Tag == llvm::dwarf::DW_TAG_reference_type ||
659 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
David Blaikieb0f77b02013-05-24 21:33:22 +0000660 return DBuilder.createReferenceType(
David Blaikieb3c23772013-08-12 23:14:36 +0000661 Tag, getOrCreateType(PointeeTy, Unit, true));
Fariborz Jahanian05f8ff12013-02-21 20:42:11 +0000662
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000663 // Bit size, align and offset of the type.
664 // Size is always the size of a pointer. We can't use getTypeSize here
665 // because that does not return the correct value for references.
666 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCall64aa4b32013-04-16 22:48:15 +0000667 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000668 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
669
David Blaikieb3c23772013-08-12 23:14:36 +0000670 return DBuilder.createPointerType(getOrCreateType(PointeeTy, Unit, true),
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000671 Size, Align);
672}
673
Eric Christopherf0890c42013-05-16 00:52:20 +0000674llvm::DIType CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
675 llvm::DIType &Cache) {
Eric Christopherb2d13922013-07-18 00:52:50 +0000676 if (Cache)
Guy Benyeib13621d2012-12-18 14:38:23 +0000677 return Cache;
David Blaikie1e97c1e2013-05-21 17:58:54 +0000678 Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
679 TheCU, getOrCreateMainFile(), 0);
680 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
681 Cache = DBuilder.createPointerType(Cache, Size);
682 return Cache;
Guy Benyeib13621d2012-12-18 14:38:23 +0000683}
684
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000685llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
686 llvm::DIFile Unit) {
Eric Christopherb2d13922013-07-18 00:52:50 +0000687 if (BlockLiteralGeneric)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000688 return BlockLiteralGeneric;
689
690 SmallVector<llvm::Value *, 8> EltTys;
691 llvm::DIType FieldTy;
692 QualType FType;
693 uint64_t FieldSize, FieldOffset;
694 unsigned FieldAlign;
695 llvm::DIArray Elements;
696 llvm::DIType EltTy, DescTy;
697
698 FieldOffset = 0;
699 FType = CGM.getContext().UnsignedLongTy;
700 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
701 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
702
703 Elements = DBuilder.getOrCreateArray(EltTys);
704 EltTys.clear();
705
706 unsigned Flags = llvm::DIDescriptor::FlagAppleBlock;
707 unsigned LineNo = getLineNumber(CurLoc);
708
709 EltTy = DBuilder.createStructType(Unit, "__block_descriptor",
710 Unit, LineNo, FieldOffset, 0,
David Blaikiec1d0af12013-02-25 01:07:08 +0000711 Flags, llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000712
713 // Bit size, align and offset of the type.
714 uint64_t Size = CGM.getContext().getTypeSize(Ty);
715
716 DescTy = DBuilder.createPointerType(EltTy, Size);
717
718 FieldOffset = 0;
719 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
720 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
721 FType = CGM.getContext().IntTy;
722 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
723 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
724 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
725 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
726
727 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
728 FieldTy = DescTy;
729 FieldSize = CGM.getContext().getTypeSize(Ty);
730 FieldAlign = CGM.getContext().getTypeAlign(Ty);
731 FieldTy = DBuilder.createMemberType(Unit, "__descriptor", Unit,
732 LineNo, FieldSize, FieldAlign,
733 FieldOffset, 0, FieldTy);
734 EltTys.push_back(FieldTy);
735
736 FieldOffset += FieldSize;
737 Elements = DBuilder.getOrCreateArray(EltTys);
738
739 EltTy = DBuilder.createStructType(Unit, "__block_literal_generic",
740 Unit, LineNo, FieldOffset, 0,
David Blaikiec1d0af12013-02-25 01:07:08 +0000741 Flags, llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000742
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000743 BlockLiteralGeneric = DBuilder.createPointerType(EltTy, Size);
744 return BlockLiteralGeneric;
745}
746
David Blaikie5f6e2f42013-06-05 05:32:23 +0000747llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty, llvm::DIFile Unit,
748 bool Declaration) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000749 // Typedefs are derived from some other type. If we have a typedef of a
750 // typedef, make sure to emit the whole chain.
David Blaikieb0f77b02013-05-24 21:33:22 +0000751 llvm::DIType Src =
David Blaikie5f6e2f42013-06-05 05:32:23 +0000752 getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit, Declaration);
Eric Christopherb2d13922013-07-18 00:52:50 +0000753 if (!Src)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000754 return llvm::DIType();
755 // We don't set size information, but do specify where the typedef was
756 // declared.
757 unsigned Line = getLineNumber(Ty->getDecl()->getLocation());
758 const TypedefNameDecl *TyDecl = Ty->getDecl();
Eric Christopher6537f082013-05-16 00:45:12 +0000759
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000760 llvm::DIDescriptor TypedefContext =
761 getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext()));
Eric Christopher6537f082013-05-16 00:45:12 +0000762
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000763 return
764 DBuilder.createTypedef(Src, TyDecl->getName(), Unit, Line, TypedefContext);
765}
766
767llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
768 llvm::DIFile Unit) {
769 SmallVector<llvm::Value *, 16> EltTys;
770
771 // Add the result type at least.
David Blaikie55a2b3d2013-08-21 23:23:07 +0000772 EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit, true));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000773
774 // Set up remainder of arguments if there is a prototype.
775 // FIXME: IF NOT, HOW IS THIS REPRESENTED? llvm-gcc doesn't represent '...'!
776 if (isa<FunctionNoProtoType>(Ty))
777 EltTys.push_back(DBuilder.createUnspecifiedParameter());
778 else if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Ty)) {
779 for (unsigned i = 0, e = FPT->getNumArgs(); i != e; ++i)
David Blaikie55a2b3d2013-08-21 23:23:07 +0000780 EltTys.push_back(getOrCreateType(FPT->getArgType(i), Unit, true));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000781 }
782
783 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
784 return DBuilder.createSubroutineType(Unit, EltTypeArray);
785}
786
787
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000788llvm::DIType CGDebugInfo::createFieldType(StringRef name,
789 QualType type,
790 uint64_t sizeInBitsOverride,
791 SourceLocation loc,
792 AccessSpecifier AS,
793 uint64_t offsetInBits,
794 llvm::DIFile tunit,
795 llvm::DIDescriptor scope) {
796 llvm::DIType debugType = getOrCreateType(type, tunit);
797
798 // Get the location for the field.
799 llvm::DIFile file = getOrCreateFile(loc);
800 unsigned line = getLineNumber(loc);
801
802 uint64_t sizeInBits = 0;
803 unsigned alignInBits = 0;
804 if (!type->isIncompleteArrayType()) {
805 llvm::tie(sizeInBits, alignInBits) = CGM.getContext().getTypeInfo(type);
806
807 if (sizeInBitsOverride)
808 sizeInBits = sizeInBitsOverride;
809 }
810
811 unsigned flags = 0;
812 if (AS == clang::AS_private)
813 flags |= llvm::DIDescriptor::FlagPrivate;
814 else if (AS == clang::AS_protected)
815 flags |= llvm::DIDescriptor::FlagProtected;
816
817 return DBuilder.createMemberType(scope, name, file, line, sizeInBits,
818 alignInBits, offsetInBits, flags, debugType);
819}
820
Eric Christopher0395de32013-01-16 01:22:32 +0000821/// CollectRecordLambdaFields - Helper for CollectRecordFields.
822void CGDebugInfo::
823CollectRecordLambdaFields(const CXXRecordDecl *CXXDecl,
824 SmallVectorImpl<llvm::Value *> &elements,
825 llvm::DIType RecordTy) {
826 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
827 // has the name and the location of the variable so we should iterate over
828 // both concurrently.
829 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
830 RecordDecl::field_iterator Field = CXXDecl->field_begin();
831 unsigned fieldno = 0;
832 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
833 E = CXXDecl->captures_end(); I != E; ++I, ++Field, ++fieldno) {
834 const LambdaExpr::Capture C = *I;
835 if (C.capturesVariable()) {
836 VarDecl *V = C.getCapturedVar();
837 llvm::DIFile VUnit = getOrCreateFile(C.getLocation());
838 StringRef VName = V->getName();
839 uint64_t SizeInBitsOverride = 0;
840 if (Field->isBitField()) {
841 SizeInBitsOverride = Field->getBitWidthValue(CGM.getContext());
842 assert(SizeInBitsOverride && "found named 0-width bitfield");
843 }
844 llvm::DIType fieldType
845 = createFieldType(VName, Field->getType(), SizeInBitsOverride,
846 C.getLocation(), Field->getAccess(),
847 layout.getFieldOffset(fieldno), VUnit, RecordTy);
848 elements.push_back(fieldType);
849 } else {
850 // TODO: Need to handle 'this' in some way by probably renaming the
851 // this of the lambda class and having a field member of 'this' or
852 // by using AT_object_pointer for the function and having that be
853 // used as 'this' for semantic references.
854 assert(C.capturesThis() && "Field that isn't captured and isn't this?");
855 FieldDecl *f = *Field;
856 llvm::DIFile VUnit = getOrCreateFile(f->getLocation());
857 QualType type = f->getType();
858 llvm::DIType fieldType
859 = createFieldType("this", type, 0, f->getLocation(), f->getAccess(),
860 layout.getFieldOffset(fieldno), VUnit, RecordTy);
861
862 elements.push_back(fieldType);
863 }
864 }
865}
866
David Blaikie5434fc22013-08-20 01:28:15 +0000867/// Helper for CollectRecordFields.
David Blaikiecbcb0302013-08-15 22:50:29 +0000868llvm::DIDerivedType
869CGDebugInfo::CreateRecordStaticField(const VarDecl *Var,
870 llvm::DIType RecordTy) {
Eric Christopher0395de32013-01-16 01:22:32 +0000871 // Create the descriptor for the static variable, with or without
872 // constant initializers.
873 llvm::DIFile VUnit = getOrCreateFile(Var->getLocation());
874 llvm::DIType VTy = getOrCreateType(Var->getType(), VUnit);
875
Eric Christopher0395de32013-01-16 01:22:32 +0000876 unsigned LineNumber = getLineNumber(Var->getLocation());
877 StringRef VName = Var->getName();
David Blaikiea89701b2013-01-20 01:19:17 +0000878 llvm::Constant *C = NULL;
Eric Christopher0395de32013-01-16 01:22:32 +0000879 if (Var->getInit()) {
880 const APValue *Value = Var->evaluateValue();
David Blaikiea89701b2013-01-20 01:19:17 +0000881 if (Value) {
882 if (Value->isInt())
883 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
884 if (Value->isFloat())
885 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
886 }
Eric Christopher0395de32013-01-16 01:22:32 +0000887 }
888
889 unsigned Flags = 0;
890 AccessSpecifier Access = Var->getAccess();
891 if (Access == clang::AS_private)
892 Flags |= llvm::DIDescriptor::FlagPrivate;
893 else if (Access == clang::AS_protected)
894 Flags |= llvm::DIDescriptor::FlagProtected;
895
David Blaikiecbcb0302013-08-15 22:50:29 +0000896 llvm::DIDerivedType GV = DBuilder.createStaticMemberType(
897 RecordTy, VName, VUnit, LineNumber, VTy, Flags, C);
Eric Christopher0395de32013-01-16 01:22:32 +0000898 StaticDataMemberCache[Var->getCanonicalDecl()] = llvm::WeakVH(GV);
David Blaikiecbcb0302013-08-15 22:50:29 +0000899 return GV;
Eric Christopher0395de32013-01-16 01:22:32 +0000900}
901
902/// CollectRecordNormalField - Helper for CollectRecordFields.
903void CGDebugInfo::
904CollectRecordNormalField(const FieldDecl *field, uint64_t OffsetInBits,
905 llvm::DIFile tunit,
906 SmallVectorImpl<llvm::Value *> &elements,
907 llvm::DIType RecordTy) {
908 StringRef name = field->getName();
909 QualType type = field->getType();
910
911 // Ignore unnamed fields unless they're anonymous structs/unions.
912 if (name.empty() && !type->isRecordType())
913 return;
914
915 uint64_t SizeInBitsOverride = 0;
916 if (field->isBitField()) {
917 SizeInBitsOverride = field->getBitWidthValue(CGM.getContext());
918 assert(SizeInBitsOverride && "found named 0-width bitfield");
919 }
920
921 llvm::DIType fieldType
922 = createFieldType(name, type, SizeInBitsOverride,
923 field->getLocation(), field->getAccess(),
924 OffsetInBits, tunit, RecordTy);
925
926 elements.push_back(fieldType);
927}
928
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000929/// CollectRecordFields - A helper function to collect debug info for
930/// record fields. This is used while creating debug info entry for a Record.
David Blaikie841fd112013-08-16 20:40:25 +0000931void CGDebugInfo::CollectRecordFields(const RecordDecl *record,
932 llvm::DIFile tunit,
933 SmallVectorImpl<llvm::Value *> &elements,
934 llvm::DICompositeType RecordTy) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000935 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(record);
936
Eric Christopher0395de32013-01-16 01:22:32 +0000937 if (CXXDecl && CXXDecl->isLambda())
938 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
939 else {
940 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000941
Eric Christopher0395de32013-01-16 01:22:32 +0000942 // Field number for non-static fields.
Eric Christopherfd5ac0d2013-01-04 17:59:07 +0000943 unsigned fieldNo = 0;
Eric Christopher0395de32013-01-16 01:22:32 +0000944
Eric Christopher0395de32013-01-16 01:22:32 +0000945 // Static and non-static members should appear in the same order as
946 // the corresponding declarations in the source program.
947 for (RecordDecl::decl_iterator I = record->decls_begin(),
948 E = record->decls_end(); I != E; ++I)
David Blaikie5e6937b2013-08-20 21:49:21 +0000949 if (const VarDecl *V = dyn_cast<VarDecl>(*I)) {
950 // Reuse the existing static member declaration if one exists
951 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator MI =
952 StaticDataMemberCache.find(V->getCanonicalDecl());
953 if (MI != StaticDataMemberCache.end()) {
954 assert(MI->second &&
955 "Static data member declaration should still exist");
956 elements.push_back(
957 llvm::DIDerivedType(cast<llvm::MDNode>(MI->second)));
958 } else
959 elements.push_back(CreateRecordStaticField(V, RecordTy));
960 } else if (FieldDecl *field = dyn_cast<FieldDecl>(*I)) {
Eric Christopher0395de32013-01-16 01:22:32 +0000961 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo),
962 tunit, elements, RecordTy);
963
964 // Bump field number for next field.
965 ++fieldNo;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000966 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000967 }
968}
969
970/// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
971/// function type is not updated to include implicit "this" pointer. Use this
972/// routine to get a method type which includes "this" pointer.
David Blaikie9a845292013-05-22 23:22:42 +0000973llvm::DICompositeType
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000974CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
975 llvm::DIFile Unit) {
David Blaikie9c78f9b2013-01-07 23:06:35 +0000976 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
David Blaikie67f8b5e2013-01-07 22:24:59 +0000977 if (Method->isStatic())
David Blaikie9a845292013-05-22 23:22:42 +0000978 return llvm::DICompositeType(getOrCreateType(QualType(Func, 0), Unit));
David Blaikie9c78f9b2013-01-07 23:06:35 +0000979 return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()),
980 Func, Unit);
981}
David Blaikie67f8b5e2013-01-07 22:24:59 +0000982
David Blaikie9a845292013-05-22 23:22:42 +0000983llvm::DICompositeType CGDebugInfo::getOrCreateInstanceMethodType(
David Blaikie9c78f9b2013-01-07 23:06:35 +0000984 QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile Unit) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000985 // Add "this" pointer.
David Blaikie9c78f9b2013-01-07 23:06:35 +0000986 llvm::DIArray Args = llvm::DICompositeType(
987 getOrCreateType(QualType(Func, 0), Unit)).getTypeArray();
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000988 assert (Args.getNumElements() && "Invalid number of arguments!");
989
990 SmallVector<llvm::Value *, 16> Elts;
991
992 // First element is always return type. For 'void' functions it is NULL.
993 Elts.push_back(Args.getElement(0));
994
David Blaikie67f8b5e2013-01-07 22:24:59 +0000995 // "this" pointer is always first argument.
David Blaikie9c78f9b2013-01-07 23:06:35 +0000996 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
David Blaikie67f8b5e2013-01-07 22:24:59 +0000997 if (isa<ClassTemplateSpecializationDecl>(RD)) {
998 // Create pointer type directly in this case.
999 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
1000 QualType PointeeTy = ThisPtrTy->getPointeeType();
1001 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCall64aa4b32013-04-16 22:48:15 +00001002 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
David Blaikie67f8b5e2013-01-07 22:24:59 +00001003 uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy);
1004 llvm::DIType PointeeType = getOrCreateType(PointeeTy, Unit);
Eric Christopherf0890c42013-05-16 00:52:20 +00001005 llvm::DIType ThisPtrType =
1006 DBuilder.createPointerType(PointeeType, Size, Align);
David Blaikie67f8b5e2013-01-07 22:24:59 +00001007 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
1008 // TODO: This and the artificial type below are misleading, the
1009 // types aren't artificial the argument is, but the current
1010 // metadata doesn't represent that.
1011 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1012 Elts.push_back(ThisPtrType);
1013 } else {
1014 llvm::DIType ThisPtrType = getOrCreateType(ThisPtr, Unit);
1015 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
1016 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1017 Elts.push_back(ThisPtrType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001018 }
1019
1020 // Copy rest of the arguments.
1021 for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
1022 Elts.push_back(Args.getElement(i));
1023
1024 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
1025
1026 return DBuilder.createSubroutineType(Unit, EltTypeArray);
1027}
1028
Eric Christopher6537f082013-05-16 00:45:12 +00001029/// isFunctionLocalClass - Return true if CXXRecordDecl is defined
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001030/// inside a function.
1031static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
1032 if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
1033 return isFunctionLocalClass(NRD);
1034 if (isa<FunctionDecl>(RD->getDeclContext()))
1035 return true;
1036 return false;
1037}
1038
1039/// CreateCXXMemberFunction - A helper function to create a DISubprogram for
1040/// a single member function GlobalDecl.
1041llvm::DISubprogram
1042CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
1043 llvm::DIFile Unit,
1044 llvm::DIType RecordTy) {
Eric Christopher6537f082013-05-16 00:45:12 +00001045 bool IsCtorOrDtor =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001046 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
Eric Christopher6537f082013-05-16 00:45:12 +00001047
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001048 StringRef MethodName = getFunctionName(Method);
David Blaikie9a845292013-05-22 23:22:42 +00001049 llvm::DICompositeType MethodTy = getOrCreateMethodType(Method, Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001050
1051 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1052 // make sense to give a single ctor/dtor a linkage name.
1053 StringRef MethodLinkageName;
1054 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1055 MethodLinkageName = CGM.getMangledName(Method);
1056
1057 // Get the location for the method.
David Blaikiefc946272013-08-19 03:37:48 +00001058 llvm::DIFile MethodDefUnit;
1059 unsigned MethodLine = 0;
1060 if (!Method->isImplicit()) {
1061 MethodDefUnit = getOrCreateFile(Method->getLocation());
1062 MethodLine = getLineNumber(Method->getLocation());
1063 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001064
1065 // Collect virtual method info.
1066 llvm::DIType ContainingType;
Eric Christopher6537f082013-05-16 00:45:12 +00001067 unsigned Virtuality = 0;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001068 unsigned VIndex = 0;
Eric Christopher6537f082013-05-16 00:45:12 +00001069
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001070 if (Method->isVirtual()) {
1071 if (Method->isPure())
1072 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
1073 else
1074 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
Eric Christopher6537f082013-05-16 00:45:12 +00001075
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001076 // It doesn't make sense to give a virtual destructor a vtable index,
1077 // since a single destructor has two entries in the vtable.
1078 if (!isa<CXXDestructorDecl>(Method))
1079 VIndex = CGM.getVTableContext().getMethodVTableIndex(Method);
1080 ContainingType = RecordTy;
1081 }
1082
1083 unsigned Flags = 0;
1084 if (Method->isImplicit())
1085 Flags |= llvm::DIDescriptor::FlagArtificial;
1086 AccessSpecifier Access = Method->getAccess();
1087 if (Access == clang::AS_private)
1088 Flags |= llvm::DIDescriptor::FlagPrivate;
1089 else if (Access == clang::AS_protected)
1090 Flags |= llvm::DIDescriptor::FlagProtected;
1091 if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1092 if (CXXC->isExplicit())
1093 Flags |= llvm::DIDescriptor::FlagExplicit;
Eric Christopher6537f082013-05-16 00:45:12 +00001094 } else if (const CXXConversionDecl *CXXC =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001095 dyn_cast<CXXConversionDecl>(Method)) {
1096 if (CXXC->isExplicit())
1097 Flags |= llvm::DIDescriptor::FlagExplicit;
1098 }
1099 if (Method->hasPrototype())
1100 Flags |= llvm::DIDescriptor::FlagPrototyped;
1101
1102 llvm::DIArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1103 llvm::DISubprogram SP =
Eric Christopher6537f082013-05-16 00:45:12 +00001104 DBuilder.createMethod(RecordTy, MethodName, MethodLinkageName,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001105 MethodDefUnit, MethodLine,
Eric Christopher6537f082013-05-16 00:45:12 +00001106 MethodTy, /*isLocalToUnit=*/false,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001107 /* isDefinition=*/ false,
1108 Virtuality, VIndex, ContainingType,
1109 Flags, CGM.getLangOpts().Optimize, NULL,
1110 TParamsArray);
Eric Christopher6537f082013-05-16 00:45:12 +00001111
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001112 SPCache[Method->getCanonicalDecl()] = llvm::WeakVH(SP);
1113
1114 return SP;
1115}
1116
1117/// CollectCXXMemberFunctions - A helper function to collect debug info for
Eric Christopher6537f082013-05-16 00:45:12 +00001118/// C++ member functions. This is used while creating debug info entry for
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001119/// a Record.
1120void CGDebugInfo::
1121CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
1122 SmallVectorImpl<llvm::Value *> &EltTys,
1123 llvm::DIType RecordTy) {
1124
1125 // Since we want more than just the individual member decls if we
1126 // have templated functions iterate over every declaration to gather
1127 // the functions.
1128 for(DeclContext::decl_iterator I = RD->decls_begin(),
1129 E = RD->decls_end(); I != E; ++I) {
1130 Decl *D = *I;
David Blaikied6d5d692013-08-09 17:20:05 +00001131 if (D->isImplicit())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001132 continue;
1133
David Blaikie5434fc22013-08-20 01:28:15 +00001134 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
David Blaikie5e6937b2013-08-20 21:49:21 +00001135 // Reuse the existing member function declaration if it exists
David Blaikie5434fc22013-08-20 01:28:15 +00001136 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator MI =
1137 SPCache.find(Method->getCanonicalDecl());
1138 if (MI == SPCache.end())
1139 EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
1140 else
1141 EltTys.push_back(MI->second);
1142 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001143 }
Eric Christopher6537f082013-05-16 00:45:12 +00001144}
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001145
1146/// CollectCXXFriends - A helper function to collect debug info for
1147/// C++ base classes. This is used while creating debug info entry for
1148/// a Record.
1149void CGDebugInfo::
1150CollectCXXFriends(const CXXRecordDecl *RD, llvm::DIFile Unit,
1151 SmallVectorImpl<llvm::Value *> &EltTys,
1152 llvm::DIType RecordTy) {
1153 for (CXXRecordDecl::friend_iterator BI = RD->friend_begin(),
1154 BE = RD->friend_end(); BI != BE; ++BI) {
1155 if ((*BI)->isUnsupportedFriend())
1156 continue;
1157 if (TypeSourceInfo *TInfo = (*BI)->getFriendType())
David Blaikie3de73f02013-08-18 04:50:23 +00001158 EltTys.push_back(DBuilder.createFriend(
1159 RecordTy, getOrCreateType(TInfo->getType(), Unit, true)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001160 }
1161}
1162
1163/// CollectCXXBases - A helper function to collect debug info for
Eric Christopher6537f082013-05-16 00:45:12 +00001164/// C++ base classes. This is used while creating debug info entry for
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001165/// a Record.
1166void CGDebugInfo::
1167CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
1168 SmallVectorImpl<llvm::Value *> &EltTys,
1169 llvm::DIType RecordTy) {
1170
1171 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1172 for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
1173 BE = RD->bases_end(); BI != BE; ++BI) {
1174 unsigned BFlags = 0;
1175 uint64_t BaseOffset;
Eric Christopher6537f082013-05-16 00:45:12 +00001176
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001177 const CXXRecordDecl *Base =
1178 cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl());
Eric Christopher6537f082013-05-16 00:45:12 +00001179
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001180 if (BI->isVirtual()) {
1181 // virtual base offset offset is -ve. The code generator emits dwarf
1182 // expression where it expects +ve number.
Eric Christopher6537f082013-05-16 00:45:12 +00001183 BaseOffset =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001184 0 - CGM.getVTableContext()
1185 .getVirtualBaseOffsetOffset(RD, Base).getQuantity();
1186 BFlags = llvm::DIDescriptor::FlagVirtual;
1187 } else
1188 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1189 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1190 // BI->isVirtual() and bits when not.
Eric Christopher6537f082013-05-16 00:45:12 +00001191
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001192 AccessSpecifier Access = BI->getAccessSpecifier();
1193 if (Access == clang::AS_private)
1194 BFlags |= llvm::DIDescriptor::FlagPrivate;
1195 else if (Access == clang::AS_protected)
1196 BFlags |= llvm::DIDescriptor::FlagProtected;
Eric Christopher6537f082013-05-16 00:45:12 +00001197
1198 llvm::DIType DTy =
1199 DBuilder.createInheritance(RecordTy,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001200 getOrCreateType(BI->getType(), Unit),
1201 BaseOffset, BFlags);
1202 EltTys.push_back(DTy);
1203 }
1204}
1205
1206/// CollectTemplateParams - A helper function to collect template parameters.
1207llvm::DIArray CGDebugInfo::
1208CollectTemplateParams(const TemplateParameterList *TPList,
David Blaikie35178dc2013-06-22 18:59:18 +00001209 ArrayRef<TemplateArgument> TAList,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001210 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +00001211 SmallVector<llvm::Value *, 16> TemplateParams;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001212 for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1213 const TemplateArgument &TA = TAList[i];
David Blaikie35178dc2013-06-22 18:59:18 +00001214 StringRef Name;
1215 if (TPList)
1216 Name = TPList->getParam(i)->getName();
David Blaikie9dfd2432013-05-10 21:53:14 +00001217 switch (TA.getKind()) {
1218 case TemplateArgument::Type: {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001219 llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit);
1220 llvm::DITemplateTypeParameter TTP =
David Blaikie35178dc2013-06-22 18:59:18 +00001221 DBuilder.createTemplateTypeParameter(TheCU, Name, TTy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001222 TemplateParams.push_back(TTP);
David Blaikie9dfd2432013-05-10 21:53:14 +00001223 } break;
1224 case TemplateArgument::Integral: {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001225 llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit);
1226 llvm::DITemplateValueParameter TVP =
David Blaikie9dfd2432013-05-10 21:53:14 +00001227 DBuilder.createTemplateValueParameter(
David Blaikie35178dc2013-06-22 18:59:18 +00001228 TheCU, Name, TTy,
David Blaikie9dfd2432013-05-10 21:53:14 +00001229 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral()));
1230 TemplateParams.push_back(TVP);
1231 } break;
1232 case TemplateArgument::Declaration: {
1233 const ValueDecl *D = TA.getAsDecl();
1234 bool InstanceMember = D->isCXXInstanceMember();
1235 QualType T = InstanceMember
1236 ? CGM.getContext().getMemberPointerType(
1237 D->getType(), cast<RecordDecl>(D->getDeclContext())
1238 ->getTypeForDecl())
1239 : CGM.getContext().getPointerType(D->getType());
1240 llvm::DIType TTy = getOrCreateType(T, Unit);
1241 llvm::Value *V = 0;
1242 // Variable pointer template parameters have a value that is the address
1243 // of the variable.
1244 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1245 V = CGM.GetAddrOfGlobalVar(VD);
1246 // Member function pointers have special support for building them, though
1247 // this is currently unsupported in LLVM CodeGen.
David Blaikief8aa1552013-05-13 06:57:50 +00001248 if (InstanceMember) {
David Blaikie9dfd2432013-05-10 21:53:14 +00001249 if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(D))
1250 V = CGM.getCXXABI().EmitMemberPointer(method);
David Blaikief8aa1552013-05-13 06:57:50 +00001251 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1252 V = CGM.GetAddrOfFunction(FD);
David Blaikie9dfd2432013-05-10 21:53:14 +00001253 // Member data pointers have special handling too to compute the fixed
1254 // offset within the object.
1255 if (isa<FieldDecl>(D)) {
1256 // These five lines (& possibly the above member function pointer
1257 // handling) might be able to be refactored to use similar code in
1258 // CodeGenModule::getMemberPointerConstant
1259 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
1260 CharUnits chars =
1261 CGM.getContext().toCharUnitsFromBits((int64_t) fieldOffset);
1262 V = CGM.getCXXABI().EmitMemberDataPointer(
1263 cast<MemberPointerType>(T.getTypePtr()), chars);
1264 }
1265 llvm::DITemplateValueParameter TVP =
David Blaikie35178dc2013-06-22 18:59:18 +00001266 DBuilder.createTemplateValueParameter(TheCU, Name, TTy, V);
David Blaikie9dfd2432013-05-10 21:53:14 +00001267 TemplateParams.push_back(TVP);
1268 } break;
1269 case TemplateArgument::NullPtr: {
1270 QualType T = TA.getNullPtrType();
1271 llvm::DIType TTy = getOrCreateType(T, Unit);
1272 llvm::Value *V = 0;
1273 // Special case member data pointer null values since they're actually -1
1274 // instead of zero.
1275 if (const MemberPointerType *MPT =
1276 dyn_cast<MemberPointerType>(T.getTypePtr()))
1277 // But treat member function pointers as simple zero integers because
1278 // it's easier than having a special case in LLVM's CodeGen. If LLVM
1279 // CodeGen grows handling for values of non-null member function
1280 // pointers then perhaps we could remove this special case and rely on
1281 // EmitNullMemberPointer for member function pointers.
1282 if (MPT->isMemberDataPointer())
1283 V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1284 if (!V)
1285 V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
1286 llvm::DITemplateValueParameter TVP =
David Blaikie35178dc2013-06-22 18:59:18 +00001287 DBuilder.createTemplateValueParameter(TheCU, Name, TTy, V);
David Blaikie9dfd2432013-05-10 21:53:14 +00001288 TemplateParams.push_back(TVP);
1289 } break;
David Blaikie35178dc2013-06-22 18:59:18 +00001290 case TemplateArgument::Template: {
1291 llvm::DITemplateValueParameter TVP =
1292 DBuilder.createTemplateTemplateParameter(
1293 TheCU, Name, llvm::DIType(),
1294 TA.getAsTemplate().getAsTemplateDecl()
1295 ->getQualifiedNameAsString());
1296 TemplateParams.push_back(TVP);
1297 } break;
1298 case TemplateArgument::Pack: {
1299 llvm::DITemplateValueParameter TVP =
1300 DBuilder.createTemplateParameterPack(
1301 TheCU, Name, llvm::DIType(),
1302 CollectTemplateParams(NULL, TA.getPackAsArray(), Unit));
1303 TemplateParams.push_back(TVP);
1304 } break;
David Blaikiee8065122013-05-10 23:36:06 +00001305 // And the following should never occur:
David Blaikie9dfd2432013-05-10 21:53:14 +00001306 case TemplateArgument::Expression:
1307 case TemplateArgument::TemplateExpansion:
David Blaikie9dfd2432013-05-10 21:53:14 +00001308 case TemplateArgument::Null:
1309 llvm_unreachable(
1310 "These argument types shouldn't exist in concrete types");
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001311 }
1312 }
1313 return DBuilder.getOrCreateArray(TemplateParams);
1314}
1315
1316/// CollectFunctionTemplateParams - A helper function to collect debug
1317/// info for function template parameters.
1318llvm::DIArray CGDebugInfo::
1319CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) {
1320 if (FD->getTemplatedKind() ==
1321 FunctionDecl::TK_FunctionTemplateSpecialization) {
1322 const TemplateParameterList *TList =
1323 FD->getTemplateSpecializationInfo()->getTemplate()
1324 ->getTemplateParameters();
David Blaikie35178dc2013-06-22 18:59:18 +00001325 return CollectTemplateParams(
1326 TList, FD->getTemplateSpecializationArgs()->asArray(), Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001327 }
1328 return llvm::DIArray();
1329}
1330
1331/// CollectCXXTemplateParams - A helper function to collect debug info for
1332/// template parameters.
1333llvm::DIArray CGDebugInfo::
1334CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial,
1335 llvm::DIFile Unit) {
1336 llvm::PointerUnion<ClassTemplateDecl *,
1337 ClassTemplatePartialSpecializationDecl *>
1338 PU = TSpecial->getSpecializedTemplateOrPartial();
Eric Christopher6537f082013-05-16 00:45:12 +00001339
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001340 TemplateParameterList *TPList = PU.is<ClassTemplateDecl *>() ?
1341 PU.get<ClassTemplateDecl *>()->getTemplateParameters() :
1342 PU.get<ClassTemplatePartialSpecializationDecl *>()->getTemplateParameters();
1343 const TemplateArgumentList &TAList = TSpecial->getTemplateInstantiationArgs();
David Blaikie35178dc2013-06-22 18:59:18 +00001344 return CollectTemplateParams(TPList, TAList.asArray(), Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001345}
1346
1347/// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
1348llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
1349 if (VTablePtrType.isValid())
1350 return VTablePtrType;
1351
1352 ASTContext &Context = CGM.getContext();
1353
1354 /* Function type */
1355 llvm::Value *STy = getOrCreateType(Context.IntTy, Unit);
1356 llvm::DIArray SElements = DBuilder.getOrCreateArray(STy);
1357 llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements);
1358 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1359 llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0,
1360 "__vtbl_ptr_type");
1361 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1362 return VTablePtrType;
1363}
1364
1365/// getVTableName - Get vtable name for the given Class.
1366StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
1367 // Construct gdb compatible name name.
1368 std::string Name = "_vptr$" + RD->getNameAsString();
1369
1370 // Copy this name on the side and use its reference.
1371 char *StrPtr = DebugInfoNames.Allocate<char>(Name.length());
1372 memcpy(StrPtr, Name.data(), Name.length());
1373 return StringRef(StrPtr, Name.length());
1374}
1375
1376
1377/// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
1378/// debug info entry in EltTys vector.
1379void CGDebugInfo::
1380CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
1381 SmallVectorImpl<llvm::Value *> &EltTys) {
1382 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1383
1384 // If there is a primary base then it will hold vtable info.
1385 if (RL.getPrimaryBase())
1386 return;
1387
1388 // If this class is not dynamic then there is not any vtable info to collect.
1389 if (!RD->isDynamicClass())
1390 return;
1391
1392 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1393 llvm::DIType VPTR
1394 = DBuilder.createMemberType(Unit, getVTableName(RD), Unit,
Eric Christopherf0890c42013-05-16 00:52:20 +00001395 0, Size, 0, 0,
1396 llvm::DIDescriptor::FlagArtificial,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001397 getOrCreateVTablePtrType(Unit));
1398 EltTys.push_back(VPTR);
1399}
1400
Eric Christopher6537f082013-05-16 00:45:12 +00001401/// getOrCreateRecordType - Emit record type's standalone debug info.
1402llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001403 SourceLocation Loc) {
Eric Christopher13c97672013-05-16 00:45:23 +00001404 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001405 llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc));
1406 return T;
1407}
1408
1409/// getOrCreateInterfaceType - Emit an objective c interface type standalone
1410/// debug info.
1411llvm::DIType CGDebugInfo::getOrCreateInterfaceType(QualType D,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001412 SourceLocation Loc) {
Eric Christopher13c97672013-05-16 00:45:23 +00001413 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001414 llvm::DIType T = getOrCreateType(D, getOrCreateFile(Loc));
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001415 RetainedTypes.push_back(D.getAsOpaquePtr());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001416 return T;
1417}
1418
David Blaikie27804892013-08-15 20:49:17 +00001419void CGDebugInfo::completeType(const RecordDecl *RD) {
1420 if (DebugKind > CodeGenOptions::LimitedDebugInfo ||
1421 !CGM.getLangOpts().CPlusPlus)
1422 completeRequiredType(RD);
1423}
1424
1425void CGDebugInfo::completeRequiredType(const RecordDecl *RD) {
David Blaikie5434fc22013-08-20 01:28:15 +00001426 if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
1427 if (CXXDecl->isDynamicClass())
1428 return;
1429
David Blaikie27804892013-08-15 20:49:17 +00001430 QualType Ty = CGM.getContext().getRecordType(RD);
1431 llvm::DIType T = getTypeOrNull(Ty);
David Blaikie5434fc22013-08-20 01:28:15 +00001432 if (T && T.isForwardDecl())
1433 completeClassData(RD);
1434}
1435
1436void CGDebugInfo::completeClassData(const RecordDecl *RD) {
1437 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
Michael Gottesman90e55232013-08-19 18:46:16 +00001438 return;
David Blaikie5434fc22013-08-20 01:28:15 +00001439 QualType Ty = CGM.getContext().getRecordType(RD);
David Blaikie27804892013-08-15 20:49:17 +00001440 void* TyPtr = Ty.getAsOpaquePtr();
1441 if (CompletedTypeCache.count(TyPtr))
1442 return;
1443 llvm::DIType Res = CreateTypeDefinition(Ty->castAs<RecordType>());
1444 assert(!Res.isForwardDecl());
1445 CompletedTypeCache[TyPtr] = Res;
1446 TypeCache[TyPtr] = Res;
1447}
1448
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001449/// CreateType - get structure or union type.
David Blaikie5f6e2f42013-06-05 05:32:23 +00001450llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty, bool Declaration) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001451 RecordDecl *RD = Ty->getDecl();
David Blaikie5434fc22013-08-20 01:28:15 +00001452 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
Adrian Prantl776bfa12013-06-18 23:32:21 +00001453 // Limited debug info should only remove struct definitions that can
1454 // safely be replaced by a forward declaration in the source code.
David Blaikie5434fc22013-08-20 01:28:15 +00001455 if ((DebugKind <= CodeGenOptions::LimitedDebugInfo && Declaration &&
1456 !RD->isCompleteDefinitionRequired() && CGM.getLangOpts().CPlusPlus) ||
1457 (CXXDecl && CXXDecl->hasDefinition() && CXXDecl->isDynamicClass())) {
David Blaikie5f6e2f42013-06-05 05:32:23 +00001458 llvm::DIDescriptor FDContext =
1459 getContextDescriptor(cast<Decl>(RD->getDeclContext()));
David Blaikie951094b2013-08-15 18:59:40 +00001460 llvm::DIType RetTy = getOrCreateRecordFwdDecl(RD, FDContext);
David Blaikie5434fc22013-08-20 01:28:15 +00001461 // FIXME: This is conservatively correct. If we return a non-forward decl
1462 // that's not a full definition (such as those created by
1463 // createContextChain) then getOrCreateType will record is as a complete
1464 // type and we'll never record all its members. But this means we're
1465 // emitting full debug info in TUs where GCC successfully emits a partial
1466 // definition of the type.
1467 if (RetTy.isForwardDecl())
1468 return RetTy;
David Blaikie5f6e2f42013-06-05 05:32:23 +00001469 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001470
David Blaikie27804892013-08-15 20:49:17 +00001471 return CreateTypeDefinition(Ty);
1472}
1473
1474llvm::DIType CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {
1475 RecordDecl *RD = Ty->getDecl();
1476
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001477 // Get overall information about the record type for the debug info.
1478 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1479
1480 // Records and classes and unions can all be recursive. To handle them, we
1481 // first generate a debug descriptor for the struct as a forward declaration.
1482 // Then (if it is a definition) we go through and get debug info for all of
1483 // its members. Finally, we create a descriptor for the complete type (which
1484 // may refer to the forward decl if the struct is recursive) and replace all
1485 // uses of the forward declaration with the final definition.
1486
David Blaikie4a077162013-08-12 22:24:20 +00001487 llvm::DICompositeType FwdDecl(getOrCreateLimitedType(Ty, DefUnit));
Manman Renb6b0a712013-07-02 19:01:53 +00001488 assert(FwdDecl.isCompositeType() &&
David Blaikie9a845292013-05-22 23:22:42 +00001489 "The debug type of a RecordType should be a llvm::DICompositeType");
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001490
1491 if (FwdDecl.isForwardDecl())
1492 return FwdDecl;
1493
David Blaikie498298d2013-08-18 16:55:33 +00001494 if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
1495 CollectContainingType(CXXDecl, FwdDecl);
1496
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001497 // Push the struct on region stack.
Eric Christopherf068c922013-04-02 22:59:11 +00001498 LexicalBlockStack.push_back(&*FwdDecl);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001499 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1500
Adrian Prantl4919de62013-03-06 22:03:30 +00001501 // Add this to the completed-type cache while we're completing it recursively.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001502 CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1503
1504 // Convert all the elements.
1505 SmallVector<llvm::Value *, 16> EltTys;
David Blaikie5434fc22013-08-20 01:28:15 +00001506 // what about nested types?
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001507
1508 // Note: The split of CXXDecl information here is intentional, the
1509 // gdb tests will depend on a certain ordering at printout. The debug
1510 // information offsets are still correct if we merge them all together
1511 // though.
1512 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1513 if (CXXDecl) {
1514 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1515 CollectVTableInfo(CXXDecl, DefUnit, EltTys);
1516 }
1517
Eric Christopher0395de32013-01-16 01:22:32 +00001518 // Collect data fields (including static variables and any initializers).
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001519 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001520 if (CXXDecl) {
1521 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
1522 CollectCXXFriends(CXXDecl, DefUnit, EltTys, FwdDecl);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001523 }
1524
1525 LexicalBlockStack.pop_back();
1526 RegionMap.erase(Ty->getDecl());
1527
1528 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
David Blaikie80588332013-08-01 20:31:40 +00001529 FwdDecl.setTypeArray(Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001530
Eric Christopherf068c922013-04-02 22:59:11 +00001531 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1532 return FwdDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001533}
1534
1535/// CreateType - get objective-c object type.
1536llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1537 llvm::DIFile Unit) {
1538 // Ignore protocols.
1539 return getOrCreateType(Ty->getBaseType(), Unit);
1540}
1541
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001542
1543/// \return true if Getter has the default name for the property PD.
1544static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
1545 const ObjCMethodDecl *Getter) {
1546 assert(PD);
1547 if (!Getter)
1548 return true;
1549
1550 assert(Getter->getDeclName().isObjCZeroArgSelector());
1551 return PD->getName() ==
1552 Getter->getDeclName().getObjCSelector().getNameForSlot(0);
1553}
1554
1555/// \return true if Setter has the default name for the property PD.
1556static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
1557 const ObjCMethodDecl *Setter) {
1558 assert(PD);
1559 if (!Setter)
1560 return true;
1561
1562 assert(Setter->getDeclName().isObjCOneArgSelector());
Adrian Prantl80e8ea92013-06-07 22:29:12 +00001563 return SelectorTable::constructSetterName(PD->getName()) ==
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001564 Setter->getDeclName().getObjCSelector().getNameForSlot(0);
1565}
1566
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001567/// CreateType - get objective-c interface type.
1568llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1569 llvm::DIFile Unit) {
1570 ObjCInterfaceDecl *ID = Ty->getDecl();
1571 if (!ID)
1572 return llvm::DIType();
1573
1574 // Get overall information about the record type for the debug info.
1575 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1576 unsigned Line = getLineNumber(ID->getLocation());
1577 unsigned RuntimeLang = TheCU.getLanguage();
1578
1579 // If this is just a forward declaration return a special forward-declaration
1580 // debug type since we won't be able to lay out the entire type.
1581 ObjCInterfaceDecl *Def = ID->getDefinition();
1582 if (!Def) {
1583 llvm::DIType FwdDecl =
1584 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001585 ID->getName(), TheCU, DefUnit, Line,
1586 RuntimeLang);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001587 return FwdDecl;
1588 }
1589
1590 ID = Def;
1591
1592 // Bit size, align and offset of the type.
1593 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1594 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1595
1596 unsigned Flags = 0;
1597 if (ID->getImplementation())
1598 Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
1599
Eric Christopherf068c922013-04-02 22:59:11 +00001600 llvm::DICompositeType RealDecl =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001601 DBuilder.createStructType(Unit, ID->getName(), DefUnit,
1602 Line, Size, Align, Flags,
David Blaikiec1d0af12013-02-25 01:07:08 +00001603 llvm::DIType(), llvm::DIArray(), RuntimeLang);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001604
1605 // Otherwise, insert it into the CompletedTypeCache so that recursive uses
1606 // will find it and we're emitting the complete type.
Adrian Prantl4919de62013-03-06 22:03:30 +00001607 QualType QualTy = QualType(Ty, 0);
1608 CompletedTypeCache[QualTy.getAsOpaquePtr()] = RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001609
Eric Christopherd3003dc2013-07-14 21:00:07 +00001610 // Push the struct on region stack.
Eric Christopherf068c922013-04-02 22:59:11 +00001611 LexicalBlockStack.push_back(static_cast<llvm::MDNode*>(RealDecl));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001612 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1613
1614 // Convert all the elements.
1615 SmallVector<llvm::Value *, 16> EltTys;
1616
1617 ObjCInterfaceDecl *SClass = ID->getSuperClass();
1618 if (SClass) {
1619 llvm::DIType SClassTy =
1620 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1621 if (!SClassTy.isValid())
1622 return llvm::DIType();
Eric Christopher6537f082013-05-16 00:45:12 +00001623
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001624 llvm::DIType InhTag =
1625 DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
1626 EltTys.push_back(InhTag);
1627 }
1628
Eric Christopherd3003dc2013-07-14 21:00:07 +00001629 // Create entries for all of the properties.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001630 for (ObjCContainerDecl::prop_iterator I = ID->prop_begin(),
1631 E = ID->prop_end(); I != E; ++I) {
1632 const ObjCPropertyDecl *PD = *I;
1633 SourceLocation Loc = PD->getLocation();
1634 llvm::DIFile PUnit = getOrCreateFile(Loc);
1635 unsigned PLine = getLineNumber(Loc);
1636 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1637 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1638 llvm::MDNode *PropertyNode =
1639 DBuilder.createObjCProperty(PD->getName(),
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001640 PUnit, PLine,
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001641 hasDefaultGetterName(PD, Getter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001642 getSelectorName(PD->getGetterName()),
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001643 hasDefaultSetterName(PD, Setter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001644 getSelectorName(PD->getSetterName()),
1645 PD->getPropertyAttributes(),
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001646 getOrCreateType(PD->getType(), PUnit));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001647 EltTys.push_back(PropertyNode);
1648 }
1649
1650 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1651 unsigned FieldNo = 0;
1652 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1653 Field = Field->getNextIvar(), ++FieldNo) {
1654 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1655 if (!FieldTy.isValid())
1656 return llvm::DIType();
Eric Christopher6537f082013-05-16 00:45:12 +00001657
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001658 StringRef FieldName = Field->getName();
1659
1660 // Ignore unnamed fields.
1661 if (FieldName.empty())
1662 continue;
1663
1664 // Get the location for the field.
1665 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1666 unsigned FieldLine = getLineNumber(Field->getLocation());
1667 QualType FType = Field->getType();
1668 uint64_t FieldSize = 0;
1669 unsigned FieldAlign = 0;
1670
1671 if (!FType->isIncompleteArrayType()) {
1672
1673 // Bit size, align and offset of the type.
1674 FieldSize = Field->isBitField()
Eric Christopherd3003dc2013-07-14 21:00:07 +00001675 ? Field->getBitWidthValue(CGM.getContext())
1676 : CGM.getContext().getTypeSize(FType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001677 FieldAlign = CGM.getContext().getTypeAlign(FType);
1678 }
1679
1680 uint64_t FieldOffset;
1681 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1682 // We don't know the runtime offset of an ivar if we're using the
1683 // non-fragile ABI. For bitfields, use the bit offset into the first
1684 // byte of storage of the bitfield. For other fields, use zero.
1685 if (Field->isBitField()) {
1686 FieldOffset = CGM.getObjCRuntime().ComputeBitfieldBitOffset(
1687 CGM, ID, Field);
1688 FieldOffset %= CGM.getContext().getCharWidth();
1689 } else {
1690 FieldOffset = 0;
1691 }
1692 } else {
1693 FieldOffset = RL.getFieldOffset(FieldNo);
1694 }
1695
1696 unsigned Flags = 0;
1697 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1698 Flags = llvm::DIDescriptor::FlagProtected;
1699 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1700 Flags = llvm::DIDescriptor::FlagPrivate;
1701
1702 llvm::MDNode *PropertyNode = NULL;
1703 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
Eric Christopher6537f082013-05-16 00:45:12 +00001704 if (ObjCPropertyImplDecl *PImpD =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001705 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
1706 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001707 SourceLocation Loc = PD->getLocation();
1708 llvm::DIFile PUnit = getOrCreateFile(Loc);
1709 unsigned PLine = getLineNumber(Loc);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001710 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1711 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1712 PropertyNode =
1713 DBuilder.createObjCProperty(PD->getName(),
1714 PUnit, PLine,
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001715 hasDefaultGetterName(PD, Getter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001716 getSelectorName(PD->getGetterName()),
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001717 hasDefaultSetterName(PD, Setter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001718 getSelectorName(PD->getSetterName()),
1719 PD->getPropertyAttributes(),
1720 getOrCreateType(PD->getType(), PUnit));
1721 }
1722 }
1723 }
1724 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
1725 FieldLine, FieldSize, FieldAlign,
1726 FieldOffset, Flags, FieldTy,
1727 PropertyNode);
1728 EltTys.push_back(FieldTy);
1729 }
1730
1731 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopherf068c922013-04-02 22:59:11 +00001732 RealDecl.setTypeArray(Elements);
Adrian Prantl4919de62013-03-06 22:03:30 +00001733
1734 // If the implementation is not yet set, we do not want to mark it
1735 // as complete. An implementation may declare additional
1736 // private ivars that we would miss otherwise.
1737 if (ID->getImplementation() == 0)
1738 CompletedTypeCache.erase(QualTy.getAsOpaquePtr());
Eric Christopher6537f082013-05-16 00:45:12 +00001739
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001740 LexicalBlockStack.pop_back();
Eric Christopherf068c922013-04-02 22:59:11 +00001741 return RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001742}
1743
1744llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) {
1745 llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1746 int64_t Count = Ty->getNumElements();
1747 if (Count == 0)
1748 // If number of elements are not known then this is an unbounded array.
1749 // Use Count == -1 to express such arrays.
1750 Count = -1;
1751
1752 llvm::Value *Subscript = DBuilder.getOrCreateSubrange(0, Count);
1753 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1754
1755 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1756 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1757
1758 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1759}
1760
1761llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1762 llvm::DIFile Unit) {
1763 uint64_t Size;
1764 uint64_t Align;
1765
1766 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1767 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1768 Size = 0;
1769 Align =
1770 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1771 } else if (Ty->isIncompleteArrayType()) {
1772 Size = 0;
1773 if (Ty->getElementType()->isIncompleteType())
1774 Align = 0;
1775 else
1776 Align = CGM.getContext().getTypeAlign(Ty->getElementType());
David Blaikie089db2e2013-05-09 20:48:12 +00001777 } else if (Ty->isIncompleteType()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001778 Size = 0;
1779 Align = 0;
1780 } else {
1781 // Size and align of the whole array, not the element type.
1782 Size = CGM.getContext().getTypeSize(Ty);
1783 Align = CGM.getContext().getTypeAlign(Ty);
1784 }
1785
1786 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
1787 // interior arrays, do we care? Why aren't nested arrays represented the
1788 // obvious/recursive way?
1789 SmallVector<llvm::Value *, 8> Subscripts;
1790 QualType EltTy(Ty, 0);
1791 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1792 // If the number of elements is known, then count is that number. Otherwise,
1793 // it's -1. This allows us to represent a subrange with an array of 0
1794 // elements, like this:
1795 //
1796 // struct foo {
1797 // int x[0];
1798 // };
1799 int64_t Count = -1; // Count == -1 is an unbounded array.
1800 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1801 Count = CAT->getSize().getZExtValue();
Eric Christopher6537f082013-05-16 00:45:12 +00001802
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001803 // FIXME: Verify this is right for VLAs.
1804 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
1805 EltTy = Ty->getElementType();
1806 }
1807
1808 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1809
Eric Christopher6537f082013-05-16 00:45:12 +00001810 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001811 DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1812 SubscriptArray);
1813 return DbgTy;
1814}
1815
Eric Christopher6537f082013-05-16 00:45:12 +00001816llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001817 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +00001818 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001819 Ty, Ty->getPointeeType(), Unit);
1820}
1821
Eric Christopher6537f082013-05-16 00:45:12 +00001822llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001823 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +00001824 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001825 Ty, Ty->getPointeeType(), Unit);
1826}
1827
Eric Christopher6537f082013-05-16 00:45:12 +00001828llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001829 llvm::DIFile U) {
David Blaikiee8d75142013-01-19 19:20:56 +00001830 llvm::DIType ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
1831 if (!Ty->getPointeeType()->isFunctionType())
1832 return DBuilder.createMemberPointerType(
David Blaikieb3c23772013-08-12 23:14:36 +00001833 getOrCreateType(Ty->getPointeeType(), U, true), ClassType);
David Blaikiee8d75142013-01-19 19:20:56 +00001834 return DBuilder.createMemberPointerType(getOrCreateInstanceMethodType(
1835 CGM.getContext().getPointerType(
1836 QualType(Ty->getClass(), Ty->getPointeeType().getCVRQualifiers())),
1837 Ty->getPointeeType()->getAs<FunctionProtoType>(), U),
1838 ClassType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001839}
1840
Eric Christopher6537f082013-05-16 00:45:12 +00001841llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001842 llvm::DIFile U) {
1843 // Ignore the atomic wrapping
1844 // FIXME: What is the correct representation?
1845 return getOrCreateType(Ty->getValueType(), U);
1846}
1847
1848/// CreateEnumType - get enumeration type.
1849llvm::DIType CGDebugInfo::CreateEnumType(const EnumDecl *ED) {
1850 uint64_t Size = 0;
1851 uint64_t Align = 0;
1852 if (!ED->getTypeForDecl()->isIncompleteType()) {
1853 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1854 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1855 }
1856
1857 // If this is just a forward declaration, construct an appropriately
1858 // marked node and just return it.
1859 if (!ED->getDefinition()) {
1860 llvm::DIDescriptor EDContext;
1861 EDContext = getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1862 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1863 unsigned Line = getLineNumber(ED->getLocation());
1864 StringRef EDName = ED->getName();
1865 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_enumeration_type,
1866 EDName, EDContext, DefUnit, Line, 0,
1867 Size, Align);
1868 }
1869
1870 // Create DIEnumerator elements for each enumerator.
1871 SmallVector<llvm::Value *, 16> Enumerators;
1872 ED = ED->getDefinition();
1873 for (EnumDecl::enumerator_iterator
1874 Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
1875 Enum != EnumEnd; ++Enum) {
1876 Enumerators.push_back(
1877 DBuilder.createEnumerator(Enum->getName(),
David Blaikieac8f43c2013-06-24 07:13:13 +00001878 Enum->getInitVal().getSExtValue()));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001879 }
1880
1881 // Return a CompositeType for the enum itself.
1882 llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1883
1884 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1885 unsigned Line = getLineNumber(ED->getLocation());
Eric Christopher6537f082013-05-16 00:45:12 +00001886 llvm::DIDescriptor EnumContext =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001887 getContextDescriptor(cast<Decl>(ED->getDeclContext()));
Adrian Prantl59d6a712013-04-19 19:56:39 +00001888 llvm::DIType ClassTy = ED->isFixed() ?
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001889 getOrCreateType(ED->getIntegerType(), DefUnit) : llvm::DIType();
Eric Christopher6537f082013-05-16 00:45:12 +00001890 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001891 DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1892 Size, Align, EltArray,
1893 ClassTy);
1894 return DbgTy;
1895}
1896
David Blaikie4b12be62013-01-21 04:37:12 +00001897static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
1898 Qualifiers Quals;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001899 do {
David Blaikie4b12be62013-01-21 04:37:12 +00001900 Quals += T.getLocalQualifiers();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001901 QualType LastT = T;
1902 switch (T->getTypeClass()) {
1903 default:
David Blaikie4b12be62013-01-21 04:37:12 +00001904 return C.getQualifiedType(T.getTypePtr(), Quals);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001905 case Type::TemplateSpecialization:
1906 T = cast<TemplateSpecializationType>(T)->desugar();
1907 break;
1908 case Type::TypeOfExpr:
1909 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1910 break;
1911 case Type::TypeOf:
1912 T = cast<TypeOfType>(T)->getUnderlyingType();
1913 break;
1914 case Type::Decltype:
1915 T = cast<DecltypeType>(T)->getUnderlyingType();
1916 break;
1917 case Type::UnaryTransform:
1918 T = cast<UnaryTransformType>(T)->getUnderlyingType();
1919 break;
1920 case Type::Attributed:
1921 T = cast<AttributedType>(T)->getEquivalentType();
1922 break;
1923 case Type::Elaborated:
1924 T = cast<ElaboratedType>(T)->getNamedType();
1925 break;
1926 case Type::Paren:
1927 T = cast<ParenType>(T)->getInnerType();
1928 break;
David Blaikie4b12be62013-01-21 04:37:12 +00001929 case Type::SubstTemplateTypeParm:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001930 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001931 break;
1932 case Type::Auto:
David Blaikie91296482013-05-24 21:24:35 +00001933 QualType DT = cast<AutoType>(T)->getDeducedType();
1934 if (DT.isNull())
1935 return T;
1936 T = DT;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001937 break;
1938 }
Eric Christopher6537f082013-05-16 00:45:12 +00001939
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001940 assert(T != LastT && "Type unwrapping failed to unwrap!");
NAKAMURA Takumid24c9ab2013-01-21 10:51:28 +00001941 (void)LastT;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001942 } while (true);
1943}
1944
Eric Christopherf0890c42013-05-16 00:52:20 +00001945/// getType - Get the type from the cache or return null type if it doesn't
1946/// exist.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001947llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) {
1948
1949 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00001950 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Eric Christopher6537f082013-05-16 00:45:12 +00001951
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001952 // Check for existing entry.
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001953 if (Ty->getTypeClass() == Type::ObjCInterface) {
1954 llvm::Value *V = getCachedInterfaceTypeOrNull(Ty);
1955 if (V)
1956 return llvm::DIType(cast<llvm::MDNode>(V));
1957 else return llvm::DIType();
1958 }
1959
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001960 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1961 TypeCache.find(Ty.getAsOpaquePtr());
1962 if (it != TypeCache.end()) {
1963 // Verify that the debug info still exists.
1964 if (llvm::Value *V = it->second)
1965 return llvm::DIType(cast<llvm::MDNode>(V));
1966 }
1967
1968 return llvm::DIType();
1969}
1970
1971/// getCompletedTypeOrNull - Get the type from the cache or return null if it
1972/// doesn't exist.
1973llvm::DIType CGDebugInfo::getCompletedTypeOrNull(QualType Ty) {
1974
1975 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00001976 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001977
1978 // Check for existing entry.
Adrian Prantl4919de62013-03-06 22:03:30 +00001979 llvm::Value *V = 0;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001980 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1981 CompletedTypeCache.find(Ty.getAsOpaquePtr());
Adrian Prantl4919de62013-03-06 22:03:30 +00001982 if (it != CompletedTypeCache.end())
1983 V = it->second;
1984 else {
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001985 V = getCachedInterfaceTypeOrNull(Ty);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001986 }
1987
Adrian Prantl4919de62013-03-06 22:03:30 +00001988 // Verify that any cached debug info still exists.
David Blaikie00383082013-08-13 04:21:38 +00001989 return llvm::DIType(cast_or_null<llvm::MDNode>(V));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001990}
1991
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001992/// getCachedInterfaceTypeOrNull - Get the type from the interface
1993/// cache, unless it needs to regenerated. Otherwise return null.
1994llvm::Value *CGDebugInfo::getCachedInterfaceTypeOrNull(QualType Ty) {
1995 // Is there a cached interface that hasn't changed?
1996 llvm::DenseMap<void *, std::pair<llvm::WeakVH, unsigned > >
1997 ::iterator it1 = ObjCInterfaceCache.find(Ty.getAsOpaquePtr());
1998
1999 if (it1 != ObjCInterfaceCache.end())
2000 if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty))
2001 if (Checksum(Decl) == it1->second.second)
2002 // Return cached forward declaration.
2003 return it1->second.first;
2004
2005 return 0;
2006}
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002007
2008/// getOrCreateType - Get the type from the cache or create a new
2009/// one if necessary.
Eric Christopher56b108a2013-06-07 22:54:39 +00002010llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit,
2011 bool Declaration) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002012 if (Ty.isNull())
2013 return llvm::DIType();
2014
2015 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00002016 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002017
David Blaikie00383082013-08-13 04:21:38 +00002018 if (llvm::DIType T = getCompletedTypeOrNull(Ty)) {
David Blaikief0c31d92013-06-21 21:03:11 +00002019 // If we're looking for a definition, make sure we have definitions of any
2020 // underlying types.
2021 if (const TypedefType* TTy = dyn_cast<TypedefType>(Ty))
2022 getOrCreateType(TTy->getDecl()->getUnderlyingType(), Unit, Declaration);
2023 if (Ty.hasLocalQualifiers())
2024 getOrCreateType(QualType(Ty.getTypePtr(), 0), Unit, Declaration);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002025 return T;
David Blaikief0c31d92013-06-21 21:03:11 +00002026 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002027
2028 // Otherwise create the type.
David Blaikie5f6e2f42013-06-05 05:32:23 +00002029 llvm::DIType Res = CreateTypeNode(Ty, Unit, Declaration);
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002030 void* TyPtr = Ty.getAsOpaquePtr();
2031
2032 // And update the type cache.
2033 TypeCache[TyPtr] = Res;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002034
David Blaikie492b1022013-08-15 21:21:19 +00002035 // FIXME: this getTypeOrNull call seems silly when we just inserted the type
2036 // into the cache - but getTypeOrNull has a special case for cached interface
2037 // types. We should probably just pull that out as a special case for the
2038 // "else" block below & skip the otherwise needless lookup.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002039 llvm::DIType TC = getTypeOrNull(Ty);
Eric Christopherb2d13922013-07-18 00:52:50 +00002040 if (TC && TC.isForwardDecl())
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002041 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
2042 else if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty)) {
2043 // Interface types may have elements added to them by a
2044 // subsequent implementation or extension, so we keep them in
2045 // the ObjCInterfaceCache together with a checksum. Instead of
Adrian Prantlf06989b2013-05-08 23:37:22 +00002046 // the (possibly) incomplete interface type, we return a forward
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002047 // declaration that gets RAUW'd in CGDebugInfo::finalize().
David Blaikiee2eb89a2013-05-21 18:29:40 +00002048 std::pair<llvm::WeakVH, unsigned> &V = ObjCInterfaceCache[TyPtr];
2049 if (V.first)
2050 return llvm::DIType(cast<llvm::MDNode>(V.first));
2051 TC = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
2052 Decl->getName(), TheCU, Unit,
2053 getLineNumber(Decl->getLocation()),
2054 TheCU.getLanguage());
2055 // Store the forward declaration in the cache.
2056 V.first = TC;
2057 V.second = Checksum(Decl);
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002058
David Blaikiee2eb89a2013-05-21 18:29:40 +00002059 // Register the type for replacement in finalize().
2060 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
2061
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002062 return TC;
Adrian Prantl4919de62013-03-06 22:03:30 +00002063 }
2064
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002065 if (!Res.isForwardDecl())
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002066 CompletedTypeCache[TyPtr] = Res;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002067
2068 return Res;
2069}
2070
Adrian Prantlb5a50072013-06-07 01:10:41 +00002071/// Currently the checksum of an interface includes the number of
2072/// ivars and property accessors.
Eric Christopher56b108a2013-06-07 22:54:39 +00002073unsigned CGDebugInfo::Checksum(const ObjCInterfaceDecl *ID) {
Adrian Prantl4f97f852013-06-07 01:10:48 +00002074 // The assumption is that the number of ivars can only increase
2075 // monotonically, so it is safe to just use their current number as
2076 // a checksum.
Adrian Prantlb5a50072013-06-07 01:10:41 +00002077 unsigned Sum = 0;
2078 for (const ObjCIvarDecl *Ivar = ID->all_declared_ivar_begin();
2079 Ivar != 0; Ivar = Ivar->getNextIvar())
2080 ++Sum;
2081
2082 return Sum;
Adrian Prantl4919de62013-03-06 22:03:30 +00002083}
2084
2085ObjCInterfaceDecl *CGDebugInfo::getObjCInterfaceDecl(QualType Ty) {
2086 switch (Ty->getTypeClass()) {
2087 case Type::ObjCObjectPointer:
Eric Christopherf0890c42013-05-16 00:52:20 +00002088 return getObjCInterfaceDecl(cast<ObjCObjectPointerType>(Ty)
2089 ->getPointeeType());
Adrian Prantl4919de62013-03-06 22:03:30 +00002090 case Type::ObjCInterface:
2091 return cast<ObjCInterfaceType>(Ty)->getDecl();
2092 default:
2093 return 0;
2094 }
2095}
2096
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002097/// CreateTypeNode - Create a new debug type node.
Eric Christopher56b108a2013-06-07 22:54:39 +00002098llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit,
2099 bool Declaration) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002100 // Handle qualifiers, which recursively handles what they refer to.
2101 if (Ty.hasLocalQualifiers())
David Blaikie5f6e2f42013-06-05 05:32:23 +00002102 return CreateQualifiedType(Ty, Unit, Declaration);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002103
2104 const char *Diag = 0;
Eric Christopher6537f082013-05-16 00:45:12 +00002105
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002106 // Work out details of type.
2107 switch (Ty->getTypeClass()) {
2108#define TYPE(Class, Base)
2109#define ABSTRACT_TYPE(Class, Base)
2110#define NON_CANONICAL_TYPE(Class, Base)
2111#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2112#include "clang/AST/TypeNodes.def"
2113 llvm_unreachable("Dependent types cannot show up in debug information");
2114
2115 case Type::ExtVector:
2116 case Type::Vector:
2117 return CreateType(cast<VectorType>(Ty), Unit);
2118 case Type::ObjCObjectPointer:
2119 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
2120 case Type::ObjCObject:
2121 return CreateType(cast<ObjCObjectType>(Ty), Unit);
2122 case Type::ObjCInterface:
2123 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
2124 case Type::Builtin:
2125 return CreateType(cast<BuiltinType>(Ty));
2126 case Type::Complex:
2127 return CreateType(cast<ComplexType>(Ty));
2128 case Type::Pointer:
2129 return CreateType(cast<PointerType>(Ty), Unit);
Reid Kleckner12df2462013-06-24 17:51:48 +00002130 case Type::Decayed:
2131 // Decayed types are just pointers in LLVM and DWARF.
2132 return CreateType(
2133 cast<PointerType>(cast<DecayedType>(Ty)->getDecayedType()), Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002134 case Type::BlockPointer:
2135 return CreateType(cast<BlockPointerType>(Ty), Unit);
2136 case Type::Typedef:
David Blaikie5f6e2f42013-06-05 05:32:23 +00002137 return CreateType(cast<TypedefType>(Ty), Unit, Declaration);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002138 case Type::Record:
David Blaikie5f6e2f42013-06-05 05:32:23 +00002139 return CreateType(cast<RecordType>(Ty), Declaration);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002140 case Type::Enum:
2141 return CreateEnumType(cast<EnumType>(Ty)->getDecl());
2142 case Type::FunctionProto:
2143 case Type::FunctionNoProto:
2144 return CreateType(cast<FunctionType>(Ty), Unit);
2145 case Type::ConstantArray:
2146 case Type::VariableArray:
2147 case Type::IncompleteArray:
2148 return CreateType(cast<ArrayType>(Ty), Unit);
2149
2150 case Type::LValueReference:
2151 return CreateType(cast<LValueReferenceType>(Ty), Unit);
2152 case Type::RValueReference:
2153 return CreateType(cast<RValueReferenceType>(Ty), Unit);
2154
2155 case Type::MemberPointer:
2156 return CreateType(cast<MemberPointerType>(Ty), Unit);
2157
2158 case Type::Atomic:
2159 return CreateType(cast<AtomicType>(Ty), Unit);
2160
2161 case Type::Attributed:
2162 case Type::TemplateSpecialization:
2163 case Type::Elaborated:
2164 case Type::Paren:
2165 case Type::SubstTemplateTypeParm:
2166 case Type::TypeOfExpr:
2167 case Type::TypeOf:
2168 case Type::Decltype:
2169 case Type::UnaryTransform:
David Blaikie226399c2013-07-13 21:08:08 +00002170 case Type::PackExpansion:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002171 llvm_unreachable("type should have been unwrapped!");
David Blaikie91296482013-05-24 21:24:35 +00002172 case Type::Auto:
2173 Diag = "auto";
2174 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002175 }
Eric Christopher6537f082013-05-16 00:45:12 +00002176
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002177 assert(Diag && "Fall through without a diagnostic?");
2178 unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error,
2179 "debug information for %0 is not yet supported");
2180 CGM.getDiags().Report(DiagID)
2181 << Diag;
2182 return llvm::DIType();
2183}
2184
2185/// getOrCreateLimitedType - Get the type from the cache or create a new
2186/// limited type if necessary.
David Blaikie4a077162013-08-12 22:24:20 +00002187llvm::DIType CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002188 llvm::DIFile Unit) {
David Blaikie4a077162013-08-12 22:24:20 +00002189 QualType QTy(Ty, 0);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002190
David Blaikieeaacc882013-08-20 21:03:29 +00002191 llvm::DICompositeType T(getTypeOrNull(QTy));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002192
2193 // We may have cached a forward decl when we could have created
2194 // a non-forward decl. Go ahead and create a non-forward decl
2195 // now.
Eric Christopherb2d13922013-07-18 00:52:50 +00002196 if (T && !T.isForwardDecl()) return T;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002197
2198 // Otherwise create the type.
David Blaikieeaacc882013-08-20 21:03:29 +00002199 llvm::DICompositeType Res = CreateLimitedType(Ty);
2200
2201 // Propagate members from the declaration to the definition
2202 // CreateType(const RecordType*) will overwrite this with the members in the
2203 // correct order if the full type is needed.
2204 Res.setTypeArray(T.getTypeArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002205
Eric Christopherb2d13922013-07-18 00:52:50 +00002206 if (T && T.isForwardDecl())
David Blaikie4a077162013-08-12 22:24:20 +00002207 ReplaceMap.push_back(
2208 std::make_pair(QTy.getAsOpaquePtr(), static_cast<llvm::Value *>(T)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002209
2210 // And update the type cache.
David Blaikie4a077162013-08-12 22:24:20 +00002211 TypeCache[QTy.getAsOpaquePtr()] = Res;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002212 return Res;
2213}
2214
2215// TODO: Currently used for context chains when limiting debug info.
David Blaikieeaacc882013-08-20 21:03:29 +00002216llvm::DICompositeType CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002217 RecordDecl *RD = Ty->getDecl();
Eric Christopher6537f082013-05-16 00:45:12 +00002218
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002219 // Get overall information about the record type for the debug info.
2220 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
2221 unsigned Line = getLineNumber(RD->getLocation());
2222 StringRef RDName = getClassName(RD);
2223
2224 llvm::DIDescriptor RDContext;
Eric Christopher13c97672013-05-16 00:45:23 +00002225 if (DebugKind == CodeGenOptions::LimitedDebugInfo)
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002226 RDContext = createContextChain(cast<Decl>(RD->getDeclContext()));
2227 else
2228 RDContext = getContextDescriptor(cast<Decl>(RD->getDeclContext()));
2229
David Blaikiec138ff52013-08-18 17:36:19 +00002230 // If we ended up creating the type during the context chain construction,
2231 // just return that.
2232 // FIXME: this could be dealt with better if the type was recorded as
2233 // completed before we started this (see the CompletedTypeCache usage in
2234 // CGDebugInfo::CreateTypeDefinition(const RecordType*) - that would need to
2235 // be pushed to before context creation, but after it was known to be
2236 // destined for completion (might still have an issue if this caller only
2237 // required a declaration but the context construction ended up creating a
2238 // definition)
David Blaikieeaacc882013-08-20 21:03:29 +00002239 llvm::DICompositeType T(getTypeOrNull(CGM.getContext().getRecordType(RD)));
2240 if (T && (!T.isForwardDecl() || !RD->getDefinition()))
David Blaikiec138ff52013-08-18 17:36:19 +00002241 return T;
2242
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002243 // If this is just a forward declaration, construct an appropriately
2244 // marked node and just return it.
2245 if (!RD->getDefinition())
David Blaikie951094b2013-08-15 18:59:40 +00002246 return getOrCreateRecordFwdDecl(RD, RDContext);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002247
2248 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2249 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
David Blaikie2fcadbe2013-03-26 23:47:35 +00002250 llvm::DICompositeType RealDecl;
Eric Christopher6537f082013-05-16 00:45:12 +00002251
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002252 if (RD->isUnion())
2253 RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002254 Size, Align, 0, llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002255 else if (RD->isClass()) {
2256 // FIXME: This could be a struct type giving a default visibility different
2257 // than C++ class type, but needs llvm metadata changes first.
2258 RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002259 Size, Align, 0, 0, llvm::DIType(),
2260 llvm::DIArray(), llvm::DIType(),
2261 llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002262 } else
2263 RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line,
Eric Christopherf0890c42013-05-16 00:52:20 +00002264 Size, Align, 0, llvm::DIType(),
2265 llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002266
2267 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
David Blaikie2fcadbe2013-03-26 23:47:35 +00002268 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002269
David Blaikie498298d2013-08-18 16:55:33 +00002270 if (const ClassTemplateSpecializationDecl *TSpecial =
2271 dyn_cast<ClassTemplateSpecializationDecl>(RD))
2272 RealDecl.setTypeArray(llvm::DIArray(),
2273 CollectCXXTemplateParams(TSpecial, DefUnit));
David Blaikiefab829d2013-08-15 22:42:12 +00002274 return RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002275}
2276
David Blaikie498298d2013-08-18 16:55:33 +00002277void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,
2278 llvm::DICompositeType RealDecl) {
2279 // A class's primary base or the class itself contains the vtable.
2280 llvm::DICompositeType ContainingType;
2281 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2282 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
2283 // Seek non virtual primary base root.
2284 while (1) {
2285 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
2286 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
2287 if (PBT && !BRL.isPrimaryBaseVirtual())
2288 PBase = PBT;
2289 else
2290 break;
2291 }
2292 ContainingType = llvm::DICompositeType(
2293 getOrCreateType(QualType(PBase->getTypeForDecl(), 0),
2294 getOrCreateFile(RD->getLocation())));
2295 } else if (RD->isDynamicClass())
2296 ContainingType = RealDecl;
2297
2298 RealDecl.setContainingType(ContainingType);
2299}
2300
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002301/// CreateMemberType - Create new member and increase Offset by FType's size.
2302llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
2303 StringRef Name,
2304 uint64_t *Offset) {
2305 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2306 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
2307 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
2308 llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0,
2309 FieldSize, FieldAlign,
2310 *Offset, 0, FieldTy);
2311 *Offset += FieldSize;
2312 return Ty;
2313}
2314
David Blaikie9faebd22013-05-20 04:58:53 +00002315llvm::DIDescriptor CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
2316 // We only need a declaration (not a definition) of the type - so use whatever
2317 // we would otherwise do to get a type for a pointee. (forward declarations in
2318 // limited debug info, full definitions (if the type definition is available)
2319 // in unlimited debug info)
David Blaikieb3c23772013-08-12 23:14:36 +00002320 if (const TypeDecl *TD = dyn_cast<TypeDecl>(D))
2321 return getOrCreateType(CGM.getContext().getTypeDeclType(TD),
2322 getOrCreateFile(TD->getLocation()), true);
David Blaikie9faebd22013-05-20 04:58:53 +00002323 // Otherwise fall back to a fairly rudimentary cache of existing declarations.
2324 // This doesn't handle providing declarations (for functions or variables) for
2325 // entities without definitions in this TU, nor when the definition proceeds
2326 // the call to this function.
2327 // FIXME: This should be split out into more specific maps with support for
2328 // emitting forward declarations and merging definitions with declarations,
2329 // the same way as we do for types.
2330 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator I =
2331 DeclCache.find(D->getCanonicalDecl());
2332 if (I == DeclCache.end())
2333 return llvm::DIDescriptor();
2334 llvm::Value *V = I->second;
2335 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
2336}
2337
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002338/// getFunctionDeclaration - Return debug info descriptor to describe method
2339/// declaration for the given method definition.
2340llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
David Blaikie23e66db2013-06-22 00:09:36 +00002341 if (!D || DebugKind == CodeGenOptions::DebugLineTablesOnly)
2342 return llvm::DISubprogram();
2343
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002344 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
2345 if (!FD) return llvm::DISubprogram();
2346
2347 // Setup context.
David Blaikied6d5d692013-08-09 17:20:05 +00002348 llvm::DIScope S = getContextDescriptor(cast<Decl>(D->getDeclContext()));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002349
2350 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2351 MI = SPCache.find(FD->getCanonicalDecl());
David Blaikied6d5d692013-08-09 17:20:05 +00002352 if (MI == SPCache.end()) {
David Blaikie5434fc22013-08-20 01:28:15 +00002353 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
David Blaikied6d5d692013-08-09 17:20:05 +00002354 llvm::DICompositeType T(S);
2355 llvm::DISubprogram SP = CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()), T);
2356 T.addMember(SP);
2357 return SP;
2358 }
2359 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002360 if (MI != SPCache.end()) {
2361 llvm::Value *V = MI->second;
2362 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
David Blaikie23e66db2013-06-22 00:09:36 +00002363 if (SP.isSubprogram() && !SP.isDefinition())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002364 return SP;
2365 }
2366
2367 for (FunctionDecl::redecl_iterator I = FD->redecls_begin(),
2368 E = FD->redecls_end(); I != E; ++I) {
2369 const FunctionDecl *NextFD = *I;
2370 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2371 MI = SPCache.find(NextFD->getCanonicalDecl());
2372 if (MI != SPCache.end()) {
2373 llvm::Value *V = MI->second;
2374 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
David Blaikie23e66db2013-06-22 00:09:36 +00002375 if (SP.isSubprogram() && !SP.isDefinition())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002376 return SP;
2377 }
2378 }
2379 return llvm::DISubprogram();
2380}
2381
2382// getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
2383// implicit parameter "this".
David Blaikie9a845292013-05-22 23:22:42 +00002384llvm::DICompositeType CGDebugInfo::getOrCreateFunctionType(const Decl *D,
2385 QualType FnType,
2386 llvm::DIFile F) {
David Blaikie23e66db2013-06-22 00:09:36 +00002387 if (!D || DebugKind == CodeGenOptions::DebugLineTablesOnly)
2388 // Create fake but valid subroutine type. Otherwise
2389 // llvm::DISubprogram::Verify() would return false, and
2390 // subprogram DIE will miss DW_AT_decl_file and
2391 // DW_AT_decl_line fields.
2392 return DBuilder.createSubroutineType(F, DBuilder.getOrCreateArray(None));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002393
2394 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
2395 return getOrCreateMethodType(Method, F);
2396 if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
2397 // Add "self" and "_cmd"
2398 SmallVector<llvm::Value *, 16> Elts;
2399
2400 // First element is always return type. For 'void' functions it is NULL.
Adrian Prantl0cb00022013-05-22 21:37:49 +00002401 QualType ResultTy = OMethod->getResultType();
2402
2403 // Replace the instancetype keyword with the actual type.
2404 if (ResultTy == CGM.getContext().getObjCInstanceType())
2405 ResultTy = CGM.getContext().getPointerType(
2406 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
2407
Adrian Prantl566a9c32013-05-10 21:08:31 +00002408 Elts.push_back(getOrCreateType(ResultTy, F));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002409 // "self" pointer is always first argument.
Adrian Prantle86fcc42013-03-29 19:20:29 +00002410 QualType SelfDeclTy = OMethod->getSelfDecl()->getType();
2411 llvm::DIType SelfTy = getOrCreateType(SelfDeclTy, F);
2412 Elts.push_back(CreateSelfType(SelfDeclTy, SelfTy));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002413 // "_cmd" pointer is always second argument.
2414 llvm::DIType CmdTy = getOrCreateType(OMethod->getCmdDecl()->getType(), F);
2415 Elts.push_back(DBuilder.createArtificialType(CmdTy));
2416 // Get rest of the arguments.
Eric Christopher6537f082013-05-16 00:45:12 +00002417 for (ObjCMethodDecl::param_const_iterator PI = OMethod->param_begin(),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002418 PE = OMethod->param_end(); PI != PE; ++PI)
2419 Elts.push_back(getOrCreateType((*PI)->getType(), F));
2420
2421 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2422 return DBuilder.createSubroutineType(F, EltTypeArray);
2423 }
David Blaikie9a845292013-05-22 23:22:42 +00002424 return llvm::DICompositeType(getOrCreateType(FnType, F));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002425}
2426
2427/// EmitFunctionStart - Constructs the debug code for entering a function.
2428void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
2429 llvm::Function *Fn,
2430 CGBuilderTy &Builder) {
2431
2432 StringRef Name;
2433 StringRef LinkageName;
2434
2435 FnBeginRegionCount.push_back(LexicalBlockStack.size());
2436
2437 const Decl *D = GD.getDecl();
2438 // Function may lack declaration in source code if it is created by Clang
2439 // CodeGen (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
2440 bool HasDecl = (D != 0);
2441 // Use the location of the declaration.
2442 SourceLocation Loc;
2443 if (HasDecl)
2444 Loc = D->getLocation();
2445
2446 unsigned Flags = 0;
2447 llvm::DIFile Unit = getOrCreateFile(Loc);
2448 llvm::DIDescriptor FDContext(Unit);
2449 llvm::DIArray TParamsArray;
2450 if (!HasDecl) {
2451 // Use llvm function name.
2452 Name = Fn->getName();
2453 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2454 // If there is a DISubprogram for this function available then use it.
2455 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2456 FI = SPCache.find(FD->getCanonicalDecl());
2457 if (FI != SPCache.end()) {
2458 llvm::Value *V = FI->second;
2459 llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(V));
2460 if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
2461 llvm::MDNode *SPN = SP;
2462 LexicalBlockStack.push_back(SPN);
2463 RegionMap[D] = llvm::WeakVH(SP);
2464 return;
2465 }
2466 }
2467 Name = getFunctionName(FD);
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002468 // Use mangled name as linkage name for C/C++ functions.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002469 if (FD->hasPrototype()) {
2470 LinkageName = CGM.getMangledName(GD);
2471 Flags |= llvm::DIDescriptor::FlagPrototyped;
2472 }
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002473 // No need to replicate the linkage name if it isn't different from the
2474 // subprogram name, no need to have it at all unless coverage is enabled or
2475 // debug is set to more than just line tables.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002476 if (LinkageName == Name ||
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002477 (!CGM.getCodeGenOpts().EmitGcovArcs &&
2478 !CGM.getCodeGenOpts().EmitGcovNotes &&
Eric Christopher13c97672013-05-16 00:45:23 +00002479 DebugKind <= CodeGenOptions::DebugLineTablesOnly))
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002480 LinkageName = StringRef();
2481
Eric Christopher13c97672013-05-16 00:45:23 +00002482 if (DebugKind >= CodeGenOptions::LimitedDebugInfo) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002483 if (const NamespaceDecl *NSDecl =
2484 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
2485 FDContext = getOrCreateNameSpace(NSDecl);
2486 else if (const RecordDecl *RDecl =
2487 dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
2488 FDContext = getContextDescriptor(cast<Decl>(RDecl->getDeclContext()));
2489
2490 // Collect template parameters.
2491 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
2492 }
2493 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
2494 Name = getObjCMethodName(OMD);
2495 Flags |= llvm::DIDescriptor::FlagPrototyped;
2496 } else {
2497 // Use llvm function name.
2498 Name = Fn->getName();
2499 Flags |= llvm::DIDescriptor::FlagPrototyped;
2500 }
2501 if (!Name.empty() && Name[0] == '\01')
2502 Name = Name.substr(1);
2503
2504 unsigned LineNo = getLineNumber(Loc);
2505 if (!HasDecl || D->isImplicit())
2506 Flags |= llvm::DIDescriptor::FlagArtificial;
2507
David Blaikie23e66db2013-06-22 00:09:36 +00002508 llvm::DISubprogram SP = DBuilder.createFunction(
2509 FDContext, Name, LinkageName, Unit, LineNo,
2510 getOrCreateFunctionType(D, FnType, Unit), Fn->hasInternalLinkage(),
2511 true /*definition*/, getLineNumber(CurLoc), Flags,
2512 CGM.getLangOpts().Optimize, Fn, TParamsArray, getFunctionDeclaration(D));
David Blaikie9faebd22013-05-20 04:58:53 +00002513 if (HasDecl)
2514 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(SP)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002515
2516 // Push function on region stack.
2517 llvm::MDNode *SPN = SP;
2518 LexicalBlockStack.push_back(SPN);
2519 if (HasDecl)
2520 RegionMap[D] = llvm::WeakVH(SP);
2521}
2522
2523/// EmitLocation - Emit metadata to indicate a change in line/column
Adrian Prantl18a0cd52013-07-18 00:27:59 +00002524/// information in the source file. If the location is invalid, the
2525/// previous location will be reused.
Adrian Prantl00df5ea2013-03-12 20:43:25 +00002526void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc,
2527 bool ForceColumnInfo) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002528 // Update our current location
2529 setLocation(Loc);
2530
2531 if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
2532
2533 // Don't bother if things are the same as last time.
2534 SourceManager &SM = CGM.getContext().getSourceManager();
2535 if (CurLoc == PrevLoc ||
2536 SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc))
2537 // New Builder may not be in sync with CGDebugInfo.
David Blaikie0a0f93c2013-02-01 19:09:49 +00002538 if (!Builder.getCurrentDebugLocation().isUnknown() &&
2539 Builder.getCurrentDebugLocation().getScope(CGM.getLLVMContext()) ==
2540 LexicalBlockStack.back())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002541 return;
Eric Christopher6537f082013-05-16 00:45:12 +00002542
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002543 // Update last state.
2544 PrevLoc = CurLoc;
2545
2546 llvm::MDNode *Scope = LexicalBlockStack.back();
Adrian Prantl00df5ea2013-03-12 20:43:25 +00002547 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get
2548 (getLineNumber(CurLoc),
2549 getColumnNumber(CurLoc, ForceColumnInfo),
2550 Scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002551}
2552
2553/// CreateLexicalBlock - Creates a new lexical block node and pushes it on
2554/// the stack.
2555void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
2556 llvm::DIDescriptor D =
2557 DBuilder.createLexicalBlock(LexicalBlockStack.empty() ?
2558 llvm::DIDescriptor() :
2559 llvm::DIDescriptor(LexicalBlockStack.back()),
2560 getOrCreateFile(CurLoc),
2561 getLineNumber(CurLoc),
2562 getColumnNumber(CurLoc));
2563 llvm::MDNode *DN = D;
2564 LexicalBlockStack.push_back(DN);
2565}
2566
2567/// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
2568/// region - beginning of a DW_TAG_lexical_block.
Eric Christopherf0890c42013-05-16 00:52:20 +00002569void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
2570 SourceLocation Loc) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002571 // Set our current location.
2572 setLocation(Loc);
2573
2574 // Create a new lexical block and push it on the stack.
2575 CreateLexicalBlock(Loc);
2576
2577 // Emit a line table change for the current location inside the new scope.
2578 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc),
2579 getColumnNumber(Loc),
2580 LexicalBlockStack.back()));
2581}
2582
2583/// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative
2584/// region - end of a DW_TAG_lexical_block.
Eric Christopherf0890c42013-05-16 00:52:20 +00002585void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
2586 SourceLocation Loc) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002587 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2588
2589 // Provide an entry in the line table for the end of the block.
2590 EmitLocation(Builder, Loc);
2591
2592 LexicalBlockStack.pop_back();
2593}
2594
2595/// EmitFunctionEnd - Constructs the debug code for exiting a function.
2596void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
2597 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2598 unsigned RCount = FnBeginRegionCount.back();
2599 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
2600
2601 // Pop all regions for this function.
2602 while (LexicalBlockStack.size() != RCount)
2603 EmitLexicalBlockEnd(Builder, CurLoc);
2604 FnBeginRegionCount.pop_back();
2605}
2606
Eric Christopher6537f082013-05-16 00:45:12 +00002607// EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002608// See BuildByRefType.
2609llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
2610 uint64_t *XOffset) {
2611
2612 SmallVector<llvm::Value *, 5> EltTys;
2613 QualType FType;
2614 uint64_t FieldSize, FieldOffset;
2615 unsigned FieldAlign;
Eric Christopher6537f082013-05-16 00:45:12 +00002616
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002617 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
Eric Christopher6537f082013-05-16 00:45:12 +00002618 QualType Type = VD->getType();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002619
2620 FieldOffset = 0;
2621 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2622 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
2623 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
2624 FType = CGM.getContext().IntTy;
2625 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
2626 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
2627
2628 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
2629 if (HasCopyAndDispose) {
2630 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2631 EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
2632 &FieldOffset));
2633 EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
2634 &FieldOffset));
2635 }
2636 bool HasByrefExtendedLayout;
2637 Qualifiers::ObjCLifetime Lifetime;
2638 if (CGM.getContext().getByrefLifetime(Type,
2639 Lifetime, HasByrefExtendedLayout)
Adrian Prantl1f437912013-07-23 00:12:14 +00002640 && HasByrefExtendedLayout) {
2641 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002642 EltTys.push_back(CreateMemberType(Unit, FType,
2643 "__byref_variable_layout",
2644 &FieldOffset));
Adrian Prantl1f437912013-07-23 00:12:14 +00002645 }
Eric Christopher6537f082013-05-16 00:45:12 +00002646
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002647 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2648 if (Align > CGM.getContext().toCharUnitsFromBits(
John McCall64aa4b32013-04-16 22:48:15 +00002649 CGM.getTarget().getPointerAlign(0))) {
Eric Christopher6537f082013-05-16 00:45:12 +00002650 CharUnits FieldOffsetInBytes
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002651 = CGM.getContext().toCharUnitsFromBits(FieldOffset);
2652 CharUnits AlignedOffsetInBytes
2653 = FieldOffsetInBytes.RoundUpToAlignment(Align);
2654 CharUnits NumPaddingBytes
2655 = AlignedOffsetInBytes - FieldOffsetInBytes;
Eric Christopher6537f082013-05-16 00:45:12 +00002656
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002657 if (NumPaddingBytes.isPositive()) {
2658 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
2659 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
2660 pad, ArrayType::Normal, 0);
2661 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
2662 }
2663 }
Eric Christopher6537f082013-05-16 00:45:12 +00002664
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002665 FType = Type;
2666 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2667 FieldSize = CGM.getContext().getTypeSize(FType);
2668 FieldAlign = CGM.getContext().toBits(Align);
2669
Eric Christopher6537f082013-05-16 00:45:12 +00002670 *XOffset = FieldOffset;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002671 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit,
2672 0, FieldSize, FieldAlign,
2673 FieldOffset, 0, FieldTy);
2674 EltTys.push_back(FieldTy);
2675 FieldOffset += FieldSize;
Eric Christopher6537f082013-05-16 00:45:12 +00002676
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002677 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopher6537f082013-05-16 00:45:12 +00002678
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002679 unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
Eric Christopher6537f082013-05-16 00:45:12 +00002680
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002681 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
David Blaikiec1d0af12013-02-25 01:07:08 +00002682 llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002683}
2684
2685/// EmitDeclare - Emit local variable declaration debug info.
2686void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
Eric Christopher6537f082013-05-16 00:45:12 +00002687 llvm::Value *Storage,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002688 unsigned ArgNo, CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002689 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002690 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2691
David Blaikiefc946272013-08-19 03:37:48 +00002692 bool Unwritten =
2693 VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) &&
2694 cast<Decl>(VD->getDeclContext())->isImplicit());
2695 llvm::DIFile Unit;
2696 if (!Unwritten)
2697 Unit = getOrCreateFile(VD->getLocation());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002698 llvm::DIType Ty;
2699 uint64_t XOffset = 0;
2700 if (VD->hasAttr<BlocksAttr>())
2701 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopher6537f082013-05-16 00:45:12 +00002702 else
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002703 Ty = getOrCreateType(VD->getType(), Unit);
2704
2705 // If there is no debug info for this type then do not emit debug info
2706 // for this variable.
2707 if (!Ty)
2708 return;
2709
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002710 // Get location information.
David Blaikiefc946272013-08-19 03:37:48 +00002711 unsigned Line = 0;
2712 unsigned Column = 0;
2713 if (!Unwritten) {
2714 Line = getLineNumber(VD->getLocation());
2715 Column = getColumnNumber(VD->getLocation());
2716 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002717 unsigned Flags = 0;
2718 if (VD->isImplicit())
2719 Flags |= llvm::DIDescriptor::FlagArtificial;
2720 // If this is the first argument and it is implicit then
2721 // give it an object pointer flag.
2722 // FIXME: There has to be a better way to do this, but for static
2723 // functions there won't be an implicit param at arg1 and
2724 // otherwise it is 'self' or 'this'.
2725 if (isa<ImplicitParamDecl>(VD) && ArgNo == 1)
2726 Flags |= llvm::DIDescriptor::FlagObjectPointer;
David Blaikie41c9bae2013-06-19 21:53:53 +00002727 if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage))
Eric Christopher7dab97b2013-07-17 22:52:53 +00002728 if (Arg->getType()->isPointerTy() && !Arg->hasByValAttr() &&
2729 !VD->getType()->isPointerType())
David Blaikie41c9bae2013-06-19 21:53:53 +00002730 Flags |= llvm::DIDescriptor::FlagIndirectVariable;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002731
2732 llvm::MDNode *Scope = LexicalBlockStack.back();
2733
2734 StringRef Name = VD->getName();
2735 if (!Name.empty()) {
2736 if (VD->hasAttr<BlocksAttr>()) {
2737 CharUnits offset = CharUnits::fromQuantity(32);
2738 SmallVector<llvm::Value *, 9> addr;
2739 llvm::Type *Int64Ty = CGM.Int64Ty;
2740 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2741 // offset of __forwarding field
2742 offset = CGM.getContext().toCharUnitsFromBits(
John McCall64aa4b32013-04-16 22:48:15 +00002743 CGM.getTarget().getPointerWidth(0));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002744 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2745 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2746 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2747 // offset of x field
2748 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2749 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2750
2751 // Create the descriptor for the variable.
2752 llvm::DIVariable D =
Eric Christopher6537f082013-05-16 00:45:12 +00002753 DBuilder.createComplexVariable(Tag,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002754 llvm::DIDescriptor(Scope),
2755 VD->getName(), Unit, Line, Ty,
2756 addr, ArgNo);
Eric Christopher6537f082013-05-16 00:45:12 +00002757
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002758 // Insert an llvm.dbg.declare into the current block.
2759 llvm::Instruction *Call =
2760 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2761 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2762 return;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002763 }
David Blaikie436653b2013-01-05 05:58:35 +00002764 } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2765 // If VD is an anonymous union then Storage represents value for
2766 // all union fields.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002767 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
David Blaikied8180cf2013-01-05 20:03:07 +00002768 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002769 for (RecordDecl::field_iterator I = RD->field_begin(),
2770 E = RD->field_end();
2771 I != E; ++I) {
2772 FieldDecl *Field = *I;
2773 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2774 StringRef FieldName = Field->getName();
Eric Christopher6537f082013-05-16 00:45:12 +00002775
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002776 // Ignore unnamed fields. Do not ignore unnamed records.
2777 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2778 continue;
Eric Christopher6537f082013-05-16 00:45:12 +00002779
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002780 // Use VarDecl's Tag, Scope and Line number.
2781 llvm::DIVariable D =
2782 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
Eric Christopher6537f082013-05-16 00:45:12 +00002783 FieldName, Unit, Line, FieldTy,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002784 CGM.getLangOpts().Optimize, Flags,
2785 ArgNo);
Eric Christopher6537f082013-05-16 00:45:12 +00002786
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002787 // Insert an llvm.dbg.declare into the current block.
2788 llvm::Instruction *Call =
2789 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2790 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2791 }
David Blaikied8180cf2013-01-05 20:03:07 +00002792 return;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002793 }
2794 }
David Blaikie436653b2013-01-05 05:58:35 +00002795
2796 // Create the descriptor for the variable.
2797 llvm::DIVariable D =
2798 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2799 Name, Unit, Line, Ty,
2800 CGM.getLangOpts().Optimize, Flags, ArgNo);
2801
2802 // Insert an llvm.dbg.declare into the current block.
2803 llvm::Instruction *Call =
2804 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2805 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002806}
2807
2808void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2809 llvm::Value *Storage,
2810 CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002811 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002812 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2813}
2814
Adrian Prantle86fcc42013-03-29 19:20:29 +00002815/// Look up the completed type for a self pointer in the TypeCache and
2816/// create a copy of it with the ObjectPointer and Artificial flags
2817/// set. If the type is not cached, a new one is created. This should
2818/// never happen though, since creating a type for the implicit self
2819/// argument implies that we already parsed the interface definition
2820/// and the ivar declarations in the implementation.
Eric Christopherf0890c42013-05-16 00:52:20 +00002821llvm::DIType CGDebugInfo::CreateSelfType(const QualType &QualTy,
2822 llvm::DIType Ty) {
Adrian Prantle86fcc42013-03-29 19:20:29 +00002823 llvm::DIType CachedTy = getTypeOrNull(QualTy);
Eric Christopherb2d13922013-07-18 00:52:50 +00002824 if (CachedTy) Ty = CachedTy;
Adrian Prantle86fcc42013-03-29 19:20:29 +00002825 else DEBUG(llvm::dbgs() << "No cached type for self.");
2826 return DBuilder.createObjectPointerType(Ty);
2827}
2828
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002829void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(const VarDecl *VD,
2830 llvm::Value *Storage,
2831 CGBuilderTy &Builder,
2832 const CGBlockInfo &blockInfo) {
Eric Christopher13c97672013-05-16 00:45:23 +00002833 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002834 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
Eric Christopher6537f082013-05-16 00:45:12 +00002835
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002836 if (Builder.GetInsertBlock() == 0)
2837 return;
Eric Christopher6537f082013-05-16 00:45:12 +00002838
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002839 bool isByRef = VD->hasAttr<BlocksAttr>();
Eric Christopher6537f082013-05-16 00:45:12 +00002840
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002841 uint64_t XOffset = 0;
2842 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2843 llvm::DIType Ty;
2844 if (isByRef)
2845 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopher6537f082013-05-16 00:45:12 +00002846 else
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002847 Ty = getOrCreateType(VD->getType(), Unit);
2848
2849 // Self is passed along as an implicit non-arg variable in a
2850 // block. Mark it as the object pointer.
2851 if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self")
Adrian Prantle86fcc42013-03-29 19:20:29 +00002852 Ty = CreateSelfType(VD->getType(), Ty);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002853
2854 // Get location information.
2855 unsigned Line = getLineNumber(VD->getLocation());
2856 unsigned Column = getColumnNumber(VD->getLocation());
2857
2858 const llvm::DataLayout &target = CGM.getDataLayout();
2859
2860 CharUnits offset = CharUnits::fromQuantity(
2861 target.getStructLayout(blockInfo.StructureType)
2862 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2863
2864 SmallVector<llvm::Value *, 9> addr;
2865 llvm::Type *Int64Ty = CGM.Int64Ty;
Adrian Prantl9b97adf2013-03-29 19:20:35 +00002866 if (isa<llvm::AllocaInst>(Storage))
2867 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002868 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2869 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2870 if (isByRef) {
2871 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2872 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2873 // offset of __forwarding field
2874 offset = CGM.getContext()
2875 .toCharUnitsFromBits(target.getPointerSizeInBits(0));
2876 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2877 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2878 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2879 // offset of x field
2880 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2881 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2882 }
2883
2884 // Create the descriptor for the variable.
2885 llvm::DIVariable D =
Eric Christopher6537f082013-05-16 00:45:12 +00002886 DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002887 llvm::DIDescriptor(LexicalBlockStack.back()),
2888 VD->getName(), Unit, Line, Ty, addr);
Adrian Prantl9b97adf2013-03-29 19:20:35 +00002889
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002890 // Insert an llvm.dbg.declare into the current block.
2891 llvm::Instruction *Call =
2892 DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
2893 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column,
2894 LexicalBlockStack.back()));
2895}
2896
2897/// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2898/// variable declaration.
2899void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2900 unsigned ArgNo,
2901 CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002902 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002903 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2904}
2905
2906namespace {
2907 struct BlockLayoutChunk {
2908 uint64_t OffsetInBits;
2909 const BlockDecl::Capture *Capture;
2910 };
2911 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2912 return l.OffsetInBits < r.OffsetInBits;
2913 }
2914}
2915
2916void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
Adrian Prantl836e7c92013-03-14 17:53:33 +00002917 llvm::Value *Arg,
2918 llvm::Value *LocalAddr,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002919 CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002920 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002921 ASTContext &C = CGM.getContext();
2922 const BlockDecl *blockDecl = block.getBlockDecl();
2923
2924 // Collect some general information about the block's location.
2925 SourceLocation loc = blockDecl->getCaretLocation();
2926 llvm::DIFile tunit = getOrCreateFile(loc);
2927 unsigned line = getLineNumber(loc);
2928 unsigned column = getColumnNumber(loc);
Eric Christopher6537f082013-05-16 00:45:12 +00002929
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002930 // Build the debug-info type for the block literal.
2931 getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
2932
2933 const llvm::StructLayout *blockLayout =
2934 CGM.getDataLayout().getStructLayout(block.StructureType);
2935
2936 SmallVector<llvm::Value*, 16> fields;
2937 fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
2938 blockLayout->getElementOffsetInBits(0),
2939 tunit, tunit));
2940 fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
2941 blockLayout->getElementOffsetInBits(1),
2942 tunit, tunit));
2943 fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
2944 blockLayout->getElementOffsetInBits(2),
2945 tunit, tunit));
2946 fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
2947 blockLayout->getElementOffsetInBits(3),
2948 tunit, tunit));
2949 fields.push_back(createFieldType("__descriptor",
2950 C.getPointerType(block.NeedsCopyDispose ?
2951 C.getBlockDescriptorExtendedType() :
2952 C.getBlockDescriptorType()),
2953 0, loc, AS_public,
2954 blockLayout->getElementOffsetInBits(4),
2955 tunit, tunit));
2956
2957 // We want to sort the captures by offset, not because DWARF
2958 // requires this, but because we're paranoid about debuggers.
2959 SmallVector<BlockLayoutChunk, 8> chunks;
2960
2961 // 'this' capture.
2962 if (blockDecl->capturesCXXThis()) {
2963 BlockLayoutChunk chunk;
2964 chunk.OffsetInBits =
2965 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
2966 chunk.Capture = 0;
2967 chunks.push_back(chunk);
2968 }
2969
2970 // Variable captures.
2971 for (BlockDecl::capture_const_iterator
2972 i = blockDecl->capture_begin(), e = blockDecl->capture_end();
2973 i != e; ++i) {
2974 const BlockDecl::Capture &capture = *i;
2975 const VarDecl *variable = capture.getVariable();
2976 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
2977
2978 // Ignore constant captures.
2979 if (captureInfo.isConstant())
2980 continue;
2981
2982 BlockLayoutChunk chunk;
2983 chunk.OffsetInBits =
2984 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
2985 chunk.Capture = &capture;
2986 chunks.push_back(chunk);
2987 }
2988
2989 // Sort by offset.
2990 llvm::array_pod_sort(chunks.begin(), chunks.end());
2991
2992 for (SmallVectorImpl<BlockLayoutChunk>::iterator
2993 i = chunks.begin(), e = chunks.end(); i != e; ++i) {
2994 uint64_t offsetInBits = i->OffsetInBits;
2995 const BlockDecl::Capture *capture = i->Capture;
2996
2997 // If we have a null capture, this must be the C++ 'this' capture.
2998 if (!capture) {
2999 const CXXMethodDecl *method =
3000 cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
3001 QualType type = method->getThisType(C);
3002
3003 fields.push_back(createFieldType("this", type, 0, loc, AS_public,
3004 offsetInBits, tunit, tunit));
3005 continue;
3006 }
3007
3008 const VarDecl *variable = capture->getVariable();
3009 StringRef name = variable->getName();
3010
3011 llvm::DIType fieldType;
3012 if (capture->isByRef()) {
3013 std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
3014
3015 // FIXME: this creates a second copy of this type!
3016 uint64_t xoffset;
3017 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
3018 fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
3019 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
3020 ptrInfo.first, ptrInfo.second,
3021 offsetInBits, 0, fieldType);
3022 } else {
3023 fieldType = createFieldType(name, variable->getType(), 0,
3024 loc, AS_public, offsetInBits, tunit, tunit);
3025 }
3026 fields.push_back(fieldType);
3027 }
3028
3029 SmallString<36> typeName;
3030 llvm::raw_svector_ostream(typeName)
3031 << "__block_literal_" << CGM.getUniqueBlockCount();
3032
3033 llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
3034
3035 llvm::DIType type =
3036 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
3037 CGM.getContext().toBits(block.BlockSize),
3038 CGM.getContext().toBits(block.BlockAlign),
David Blaikiec1d0af12013-02-25 01:07:08 +00003039 0, llvm::DIType(), fieldsArray);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003040 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
3041
3042 // Get overall information about the block.
3043 unsigned flags = llvm::DIDescriptor::FlagArtificial;
3044 llvm::MDNode *scope = LexicalBlockStack.back();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003045
3046 // Create the descriptor for the parameter.
3047 llvm::DIVariable debugVar =
3048 DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
Eric Christopher6537f082013-05-16 00:45:12 +00003049 llvm::DIDescriptor(scope),
Adrian Prantl836e7c92013-03-14 17:53:33 +00003050 Arg->getName(), tunit, line, type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003051 CGM.getLangOpts().Optimize, flags,
Adrian Prantl836e7c92013-03-14 17:53:33 +00003052 cast<llvm::Argument>(Arg)->getArgNo() + 1);
3053
Adrian Prantlbea407c2013-03-14 21:52:59 +00003054 if (LocalAddr) {
Adrian Prantl836e7c92013-03-14 17:53:33 +00003055 // Insert an llvm.dbg.value into the current block.
Adrian Prantlbea407c2013-03-14 21:52:59 +00003056 llvm::Instruction *DbgVal =
3057 DBuilder.insertDbgValueIntrinsic(LocalAddr, 0, debugVar,
Eric Christopherf068c922013-04-02 22:59:11 +00003058 Builder.GetInsertBlock());
Adrian Prantlbea407c2013-03-14 21:52:59 +00003059 DbgVal->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
3060 }
Adrian Prantl836e7c92013-03-14 17:53:33 +00003061
Adrian Prantlbea407c2013-03-14 21:52:59 +00003062 // Insert an llvm.dbg.declare into the current block.
3063 llvm::Instruction *DbgDecl =
3064 DBuilder.insertDeclare(Arg, debugVar, Builder.GetInsertBlock());
3065 DbgDecl->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003066}
3067
David Blaikie5434fc22013-08-20 01:28:15 +00003068/// If D is an out-of-class definition of a static data member of a class, find
3069/// its corresponding in-class declaration.
3070llvm::DIDerivedType
3071CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {
3072 if (!D->isStaticDataMember())
3073 return llvm::DIDerivedType();
3074 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator MI =
3075 StaticDataMemberCache.find(D->getCanonicalDecl());
3076 if (MI != StaticDataMemberCache.end()) {
3077 assert(MI->second && "Static data member declaration should still exist");
3078 return llvm::DIDerivedType(cast<llvm::MDNode>(MI->second));
Evgeniy Stepanov045a9f62013-08-16 10:35:31 +00003079 }
David Blaikie5e6937b2013-08-20 21:49:21 +00003080
3081 // If the member wasn't found in the cache, lazily construct and add it to the
3082 // type (used when a limited form of the type is emitted).
David Blaikie5434fc22013-08-20 01:28:15 +00003083 llvm::DICompositeType Ctxt(
3084 getContextDescriptor(cast<Decl>(D->getDeclContext())));
3085 llvm::DIDerivedType T = CreateRecordStaticField(D, Ctxt);
3086 Ctxt.addMember(T);
3087 return T;
3088}
3089
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003090/// EmitGlobalVariable - Emit information about a global variable.
3091void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
3092 const VarDecl *D) {
Eric Christopher13c97672013-05-16 00:45:23 +00003093 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003094 // Create global variable debug descriptor.
3095 llvm::DIFile Unit = getOrCreateFile(D->getLocation());
3096 unsigned LineNo = getLineNumber(D->getLocation());
3097
3098 setLocation(D->getLocation());
3099
3100 QualType T = D->getType();
3101 if (T->isIncompleteArrayType()) {
3102
3103 // CodeGen turns int[] into int[1] so we'll do the same here.
3104 llvm::APInt ConstVal(32, 1);
3105 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3106
3107 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3108 ArrayType::Normal, 0);
3109 }
3110 StringRef DeclName = D->getName();
3111 StringRef LinkageName;
3112 if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext())
3113 && !isa<ObjCMethodDecl>(D->getDeclContext()))
3114 LinkageName = Var->getName();
3115 if (LinkageName == DeclName)
3116 LinkageName = StringRef();
Eric Christopher6537f082013-05-16 00:45:12 +00003117 llvm::DIDescriptor DContext =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003118 getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
David Blaikie5434fc22013-08-20 01:28:15 +00003119 llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(
3120 DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
3121 Var->hasInternalLinkage(), Var,
3122 getOrCreateStaticDataMemberDeclarationOrNull(D));
David Blaikie9faebd22013-05-20 04:58:53 +00003123 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(GV)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003124}
3125
3126/// EmitGlobalVariable - Emit information about an objective-c interface.
3127void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
3128 ObjCInterfaceDecl *ID) {
Eric Christopher13c97672013-05-16 00:45:23 +00003129 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003130 // Create global variable debug descriptor.
3131 llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
3132 unsigned LineNo = getLineNumber(ID->getLocation());
3133
3134 StringRef Name = ID->getName();
3135
3136 QualType T = CGM.getContext().getObjCInterfaceType(ID);
3137 if (T->isIncompleteArrayType()) {
3138
3139 // CodeGen turns int[] into int[1] so we'll do the same here.
3140 llvm::APInt ConstVal(32, 1);
3141 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3142
3143 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3144 ArrayType::Normal, 0);
3145 }
3146
3147 DBuilder.createGlobalVariable(Name, Unit, LineNo,
3148 getOrCreateType(T, Unit),
3149 Var->hasInternalLinkage(), Var);
3150}
3151
3152/// EmitGlobalVariable - Emit global variable's debug info.
Eric Christopher6537f082013-05-16 00:45:12 +00003153void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003154 llvm::Constant *Init) {
Eric Christopher13c97672013-05-16 00:45:23 +00003155 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003156 // Create the descriptor for the variable.
3157 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
3158 StringRef Name = VD->getName();
3159 llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
3160 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
3161 const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext());
3162 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
3163 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
3164 }
3165 // Do not use DIGlobalVariable for enums.
3166 if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
3167 return;
David Blaikie27ab0362013-08-15 21:42:43 +00003168 llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(
3169 Unit, Name, Name, Unit, getLineNumber(VD->getLocation()), Ty, true, Init,
David Blaikie5434fc22013-08-20 01:28:15 +00003170 getOrCreateStaticDataMemberDeclarationOrNull(cast<VarDecl>(VD)));
David Blaikie9faebd22013-05-20 04:58:53 +00003171 DeclCache.insert(std::make_pair(VD->getCanonicalDecl(), llvm::WeakVH(GV)));
3172}
3173
3174llvm::DIScope CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
3175 if (!LexicalBlockStack.empty())
3176 return llvm::DIScope(LexicalBlockStack.back());
3177 return getContextDescriptor(D);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003178}
3179
David Blaikie957dac52013-04-22 06:13:21 +00003180void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
David Blaikie9faebd22013-05-20 04:58:53 +00003181 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3182 return;
David Blaikie957dac52013-04-22 06:13:21 +00003183 DBuilder.createImportedModule(
David Blaikie9faebd22013-05-20 04:58:53 +00003184 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
3185 getOrCreateNameSpace(UD.getNominatedNamespace()),
David Blaikie957dac52013-04-22 06:13:21 +00003186 getLineNumber(UD.getLocation()));
3187}
3188
David Blaikie9faebd22013-05-20 04:58:53 +00003189void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
3190 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3191 return;
3192 assert(UD.shadow_size() &&
3193 "We shouldn't be codegening an invalid UsingDecl containing no decls");
3194 // Emitting one decl is sufficient - debuggers can detect that this is an
3195 // overloaded name & provide lookup for all the overloads.
3196 const UsingShadowDecl &USD = **UD.shadow_begin();
Eric Christopher56b108a2013-06-07 22:54:39 +00003197 if (llvm::DIDescriptor Target =
3198 getDeclarationOrDefinition(USD.getUnderlyingDecl()))
David Blaikie9faebd22013-05-20 04:58:53 +00003199 DBuilder.createImportedDeclaration(
3200 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
3201 getLineNumber(USD.getLocation()));
3202}
3203
David Blaikiefc46ebc2013-05-20 22:50:41 +00003204llvm::DIImportedEntity
3205CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
3206 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3207 return llvm::DIImportedEntity(0);
3208 llvm::WeakVH &VH = NamespaceAliasCache[&NA];
3209 if (VH)
3210 return llvm::DIImportedEntity(cast<llvm::MDNode>(VH));
3211 llvm::DIImportedEntity R(0);
3212 if (const NamespaceAliasDecl *Underlying =
3213 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
3214 // This could cache & dedup here rather than relying on metadata deduping.
3215 R = DBuilder.createImportedModule(
3216 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3217 EmitNamespaceAlias(*Underlying), getLineNumber(NA.getLocation()),
3218 NA.getName());
3219 else
3220 R = DBuilder.createImportedModule(
3221 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3222 getOrCreateNameSpace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
3223 getLineNumber(NA.getLocation()), NA.getName());
3224 VH = R;
3225 return R;
3226}
3227
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003228/// getOrCreateNamesSpace - Return namespace descriptor for the given
3229/// namespace decl.
Eric Christopher6537f082013-05-16 00:45:12 +00003230llvm::DINameSpace
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003231CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
David Blaikie8863e6b2013-08-16 22:52:07 +00003232 NSDecl = NSDecl->getCanonicalDecl();
Eric Christopher6537f082013-05-16 00:45:12 +00003233 llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003234 NameSpaceCache.find(NSDecl);
3235 if (I != NameSpaceCache.end())
3236 return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
Eric Christopher6537f082013-05-16 00:45:12 +00003237
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003238 unsigned LineNo = getLineNumber(NSDecl->getLocation());
3239 llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
Eric Christopher6537f082013-05-16 00:45:12 +00003240 llvm::DIDescriptor Context =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003241 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
3242 llvm::DINameSpace NS =
3243 DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
3244 NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
3245 return NS;
3246}
3247
3248void CGDebugInfo::finalize() {
3249 for (std::vector<std::pair<void *, llvm::WeakVH> >::const_iterator VI
3250 = ReplaceMap.begin(), VE = ReplaceMap.end(); VI != VE; ++VI) {
3251 llvm::DIType Ty, RepTy;
3252 // Verify that the debug info still exists.
3253 if (llvm::Value *V = VI->second)
3254 Ty = llvm::DIType(cast<llvm::MDNode>(V));
Eric Christopher6537f082013-05-16 00:45:12 +00003255
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003256 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
3257 TypeCache.find(VI->first);
3258 if (it != TypeCache.end()) {
3259 // Verify that the debug info still exists.
3260 if (llvm::Value *V = it->second)
3261 RepTy = llvm::DIType(cast<llvm::MDNode>(V));
3262 }
Adrian Prantlebbd7e02013-03-11 18:33:46 +00003263
Eric Christopherb2d13922013-07-18 00:52:50 +00003264 if (Ty && Ty.isForwardDecl() && RepTy)
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003265 Ty.replaceAllUsesWith(RepTy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003266 }
Adrian Prantlebbd7e02013-03-11 18:33:46 +00003267
3268 // We keep our own list of retained types, because we need to look
3269 // up the final type in the type cache.
3270 for (std::vector<void *>::const_iterator RI = RetainedTypes.begin(),
3271 RE = RetainedTypes.end(); RI != RE; ++RI)
3272 DBuilder.retainType(llvm::DIType(cast<llvm::MDNode>(TypeCache[*RI])));
3273
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003274 DBuilder.finalize();
3275}