blob: 7177fe2cc326312aa6d0ed2e26f4355c6d856c9c [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 Blaikiec5cd1a72013-08-15 20:17:25 +0000605llvm::DIType CGDebugInfo::getOrCreateRecordFwdDecl(const RecordDecl *RD,
606 llvm::DIDescriptor Ctx) {
607 if (llvm::DIType T = getTypeOrNull(CGM.getContext().getRecordType(RD)))
David Blaikie951094b2013-08-15 18:59:40 +0000608 return T;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000609 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
610 unsigned Line = getLineNumber(RD->getLocation());
611 StringRef RDName = getClassName(RD);
612
613 unsigned Tag = 0;
614 if (RD->isStruct() || RD->isInterface())
615 Tag = llvm::dwarf::DW_TAG_structure_type;
616 else if (RD->isUnion())
617 Tag = llvm::dwarf::DW_TAG_union_type;
618 else {
619 assert(RD->isClass());
620 Tag = llvm::dwarf::DW_TAG_class_type;
621 }
622
623 // Create the type.
624 return DBuilder.createForwardDecl(Tag, RDName, Ctx, DefUnit, Line);
625}
626
627// Walk up the context chain and create forward decls for record decls,
628// and normal descriptors for namespaces.
629llvm::DIDescriptor CGDebugInfo::createContextChain(const Decl *Context) {
630 if (!Context)
631 return TheCU;
632
633 // See if we already have the parent.
634 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
635 I = RegionMap.find(Context);
636 if (I != RegionMap.end()) {
637 llvm::Value *V = I->second;
638 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
639 }
Eric Christopher6537f082013-05-16 00:45:12 +0000640
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000641 // Check namespace.
642 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
643 return llvm::DIDescriptor(getOrCreateNameSpace(NSDecl));
644
645 if (const RecordDecl *RD = dyn_cast<RecordDecl>(Context)) {
646 if (!RD->isDependentType()) {
David Blaikie5434fc22013-08-20 01:28:15 +0000647 llvm::DICompositeType T(getTypeOrNull(CGM.getContext().getRecordType(RD)));
648 llvm::DICompositeType Ty(getOrCreateLimitedType(
649 CGM.getContext().getRecordType(RD)->castAs<RecordType>(),
650 getOrCreateMainFile()));
651 if (!Ty.getTypeArray().getNumElements()) {
652 if (T) {
653 llvm::DIArray PrevMem = T.getTypeArray();
654 unsigned NumElements = PrevMem.getNumElements();
655 if (NumElements == 1 && !PrevMem.getElement(0))
656 NumElements = 0;
657 SmallVector<llvm::Value *, 16> EltTys;
658 EltTys.reserve(NumElements);
659 for (unsigned i = 0; i != NumElements; ++i)
660 EltTys.push_back(PrevMem.getElement(i));
661 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
662 Ty.setTypeArray(Elements);
663 }
664 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000665 return llvm::DIDescriptor(Ty);
666 }
667 }
668 return TheCU;
669}
670
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000671llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag,
Eric Christopher6537f082013-05-16 00:45:12 +0000672 const Type *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000673 QualType PointeeTy,
674 llvm::DIFile Unit) {
675 if (Tag == llvm::dwarf::DW_TAG_reference_type ||
676 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
David Blaikieb0f77b02013-05-24 21:33:22 +0000677 return DBuilder.createReferenceType(
David Blaikieb3c23772013-08-12 23:14:36 +0000678 Tag, getOrCreateType(PointeeTy, Unit, true));
Fariborz Jahanian05f8ff12013-02-21 20:42:11 +0000679
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000680 // Bit size, align and offset of the type.
681 // Size is always the size of a pointer. We can't use getTypeSize here
682 // because that does not return the correct value for references.
683 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCall64aa4b32013-04-16 22:48:15 +0000684 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000685 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
686
David Blaikieb3c23772013-08-12 23:14:36 +0000687 return DBuilder.createPointerType(getOrCreateType(PointeeTy, Unit, true),
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000688 Size, Align);
689}
690
Eric Christopherf0890c42013-05-16 00:52:20 +0000691llvm::DIType CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
692 llvm::DIType &Cache) {
Eric Christopherb2d13922013-07-18 00:52:50 +0000693 if (Cache)
Guy Benyeib13621d2012-12-18 14:38:23 +0000694 return Cache;
David Blaikie1e97c1e2013-05-21 17:58:54 +0000695 Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
696 TheCU, getOrCreateMainFile(), 0);
697 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
698 Cache = DBuilder.createPointerType(Cache, Size);
699 return Cache;
Guy Benyeib13621d2012-12-18 14:38:23 +0000700}
701
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000702llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
703 llvm::DIFile Unit) {
Eric Christopherb2d13922013-07-18 00:52:50 +0000704 if (BlockLiteralGeneric)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000705 return BlockLiteralGeneric;
706
707 SmallVector<llvm::Value *, 8> EltTys;
708 llvm::DIType FieldTy;
709 QualType FType;
710 uint64_t FieldSize, FieldOffset;
711 unsigned FieldAlign;
712 llvm::DIArray Elements;
713 llvm::DIType EltTy, DescTy;
714
715 FieldOffset = 0;
716 FType = CGM.getContext().UnsignedLongTy;
717 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
718 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
719
720 Elements = DBuilder.getOrCreateArray(EltTys);
721 EltTys.clear();
722
723 unsigned Flags = llvm::DIDescriptor::FlagAppleBlock;
724 unsigned LineNo = getLineNumber(CurLoc);
725
726 EltTy = DBuilder.createStructType(Unit, "__block_descriptor",
727 Unit, LineNo, FieldOffset, 0,
David Blaikiec1d0af12013-02-25 01:07:08 +0000728 Flags, llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000729
730 // Bit size, align and offset of the type.
731 uint64_t Size = CGM.getContext().getTypeSize(Ty);
732
733 DescTy = DBuilder.createPointerType(EltTy, Size);
734
735 FieldOffset = 0;
736 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
737 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
738 FType = CGM.getContext().IntTy;
739 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
740 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
741 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
742 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
743
744 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
745 FieldTy = DescTy;
746 FieldSize = CGM.getContext().getTypeSize(Ty);
747 FieldAlign = CGM.getContext().getTypeAlign(Ty);
748 FieldTy = DBuilder.createMemberType(Unit, "__descriptor", Unit,
749 LineNo, FieldSize, FieldAlign,
750 FieldOffset, 0, FieldTy);
751 EltTys.push_back(FieldTy);
752
753 FieldOffset += FieldSize;
754 Elements = DBuilder.getOrCreateArray(EltTys);
755
756 EltTy = DBuilder.createStructType(Unit, "__block_literal_generic",
757 Unit, LineNo, FieldOffset, 0,
David Blaikiec1d0af12013-02-25 01:07:08 +0000758 Flags, llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000759
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000760 BlockLiteralGeneric = DBuilder.createPointerType(EltTy, Size);
761 return BlockLiteralGeneric;
762}
763
David Blaikie5f6e2f42013-06-05 05:32:23 +0000764llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty, llvm::DIFile Unit,
765 bool Declaration) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000766 // Typedefs are derived from some other type. If we have a typedef of a
767 // typedef, make sure to emit the whole chain.
David Blaikieb0f77b02013-05-24 21:33:22 +0000768 llvm::DIType Src =
David Blaikie5f6e2f42013-06-05 05:32:23 +0000769 getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit, Declaration);
Eric Christopherb2d13922013-07-18 00:52:50 +0000770 if (!Src)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000771 return llvm::DIType();
772 // We don't set size information, but do specify where the typedef was
773 // declared.
774 unsigned Line = getLineNumber(Ty->getDecl()->getLocation());
775 const TypedefNameDecl *TyDecl = Ty->getDecl();
Eric Christopher6537f082013-05-16 00:45:12 +0000776
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000777 llvm::DIDescriptor TypedefContext =
778 getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext()));
Eric Christopher6537f082013-05-16 00:45:12 +0000779
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000780 return
781 DBuilder.createTypedef(Src, TyDecl->getName(), Unit, Line, TypedefContext);
782}
783
784llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
785 llvm::DIFile Unit) {
786 SmallVector<llvm::Value *, 16> EltTys;
787
788 // Add the result type at least.
789 EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit));
790
791 // Set up remainder of arguments if there is a prototype.
792 // FIXME: IF NOT, HOW IS THIS REPRESENTED? llvm-gcc doesn't represent '...'!
793 if (isa<FunctionNoProtoType>(Ty))
794 EltTys.push_back(DBuilder.createUnspecifiedParameter());
795 else if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Ty)) {
796 for (unsigned i = 0, e = FPT->getNumArgs(); i != e; ++i)
797 EltTys.push_back(getOrCreateType(FPT->getArgType(i), Unit));
798 }
799
800 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
801 return DBuilder.createSubroutineType(Unit, EltTypeArray);
802}
803
804
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000805llvm::DIType CGDebugInfo::createFieldType(StringRef name,
806 QualType type,
807 uint64_t sizeInBitsOverride,
808 SourceLocation loc,
809 AccessSpecifier AS,
810 uint64_t offsetInBits,
811 llvm::DIFile tunit,
812 llvm::DIDescriptor scope) {
813 llvm::DIType debugType = getOrCreateType(type, tunit);
814
815 // Get the location for the field.
816 llvm::DIFile file = getOrCreateFile(loc);
817 unsigned line = getLineNumber(loc);
818
819 uint64_t sizeInBits = 0;
820 unsigned alignInBits = 0;
821 if (!type->isIncompleteArrayType()) {
822 llvm::tie(sizeInBits, alignInBits) = CGM.getContext().getTypeInfo(type);
823
824 if (sizeInBitsOverride)
825 sizeInBits = sizeInBitsOverride;
826 }
827
828 unsigned flags = 0;
829 if (AS == clang::AS_private)
830 flags |= llvm::DIDescriptor::FlagPrivate;
831 else if (AS == clang::AS_protected)
832 flags |= llvm::DIDescriptor::FlagProtected;
833
834 return DBuilder.createMemberType(scope, name, file, line, sizeInBits,
835 alignInBits, offsetInBits, flags, debugType);
836}
837
Eric Christopher0395de32013-01-16 01:22:32 +0000838/// CollectRecordLambdaFields - Helper for CollectRecordFields.
839void CGDebugInfo::
840CollectRecordLambdaFields(const CXXRecordDecl *CXXDecl,
841 SmallVectorImpl<llvm::Value *> &elements,
842 llvm::DIType RecordTy) {
843 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
844 // has the name and the location of the variable so we should iterate over
845 // both concurrently.
846 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
847 RecordDecl::field_iterator Field = CXXDecl->field_begin();
848 unsigned fieldno = 0;
849 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
850 E = CXXDecl->captures_end(); I != E; ++I, ++Field, ++fieldno) {
851 const LambdaExpr::Capture C = *I;
852 if (C.capturesVariable()) {
853 VarDecl *V = C.getCapturedVar();
854 llvm::DIFile VUnit = getOrCreateFile(C.getLocation());
855 StringRef VName = V->getName();
856 uint64_t SizeInBitsOverride = 0;
857 if (Field->isBitField()) {
858 SizeInBitsOverride = Field->getBitWidthValue(CGM.getContext());
859 assert(SizeInBitsOverride && "found named 0-width bitfield");
860 }
861 llvm::DIType fieldType
862 = createFieldType(VName, Field->getType(), SizeInBitsOverride,
863 C.getLocation(), Field->getAccess(),
864 layout.getFieldOffset(fieldno), VUnit, RecordTy);
865 elements.push_back(fieldType);
866 } else {
867 // TODO: Need to handle 'this' in some way by probably renaming the
868 // this of the lambda class and having a field member of 'this' or
869 // by using AT_object_pointer for the function and having that be
870 // used as 'this' for semantic references.
871 assert(C.capturesThis() && "Field that isn't captured and isn't this?");
872 FieldDecl *f = *Field;
873 llvm::DIFile VUnit = getOrCreateFile(f->getLocation());
874 QualType type = f->getType();
875 llvm::DIType fieldType
876 = createFieldType("this", type, 0, f->getLocation(), f->getAccess(),
877 layout.getFieldOffset(fieldno), VUnit, RecordTy);
878
879 elements.push_back(fieldType);
880 }
881 }
882}
883
David Blaikie5434fc22013-08-20 01:28:15 +0000884/// Helper for CollectRecordFields.
David Blaikiecbcb0302013-08-15 22:50:29 +0000885llvm::DIDerivedType
886CGDebugInfo::CreateRecordStaticField(const VarDecl *Var,
887 llvm::DIType RecordTy) {
Eric Christopher0395de32013-01-16 01:22:32 +0000888 // Create the descriptor for the static variable, with or without
889 // constant initializers.
890 llvm::DIFile VUnit = getOrCreateFile(Var->getLocation());
891 llvm::DIType VTy = getOrCreateType(Var->getType(), VUnit);
892
Eric Christopher0395de32013-01-16 01:22:32 +0000893 unsigned LineNumber = getLineNumber(Var->getLocation());
894 StringRef VName = Var->getName();
David Blaikiea89701b2013-01-20 01:19:17 +0000895 llvm::Constant *C = NULL;
Eric Christopher0395de32013-01-16 01:22:32 +0000896 if (Var->getInit()) {
897 const APValue *Value = Var->evaluateValue();
David Blaikiea89701b2013-01-20 01:19:17 +0000898 if (Value) {
899 if (Value->isInt())
900 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
901 if (Value->isFloat())
902 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
903 }
Eric Christopher0395de32013-01-16 01:22:32 +0000904 }
905
906 unsigned Flags = 0;
907 AccessSpecifier Access = Var->getAccess();
908 if (Access == clang::AS_private)
909 Flags |= llvm::DIDescriptor::FlagPrivate;
910 else if (Access == clang::AS_protected)
911 Flags |= llvm::DIDescriptor::FlagProtected;
912
David Blaikiecbcb0302013-08-15 22:50:29 +0000913 llvm::DIDerivedType GV = DBuilder.createStaticMemberType(
914 RecordTy, VName, VUnit, LineNumber, VTy, Flags, C);
Eric Christopher0395de32013-01-16 01:22:32 +0000915 StaticDataMemberCache[Var->getCanonicalDecl()] = llvm::WeakVH(GV);
David Blaikiecbcb0302013-08-15 22:50:29 +0000916 return GV;
Eric Christopher0395de32013-01-16 01:22:32 +0000917}
918
919/// CollectRecordNormalField - Helper for CollectRecordFields.
920void CGDebugInfo::
921CollectRecordNormalField(const FieldDecl *field, uint64_t OffsetInBits,
922 llvm::DIFile tunit,
923 SmallVectorImpl<llvm::Value *> &elements,
924 llvm::DIType RecordTy) {
925 StringRef name = field->getName();
926 QualType type = field->getType();
927
928 // Ignore unnamed fields unless they're anonymous structs/unions.
929 if (name.empty() && !type->isRecordType())
930 return;
931
932 uint64_t SizeInBitsOverride = 0;
933 if (field->isBitField()) {
934 SizeInBitsOverride = field->getBitWidthValue(CGM.getContext());
935 assert(SizeInBitsOverride && "found named 0-width bitfield");
936 }
937
938 llvm::DIType fieldType
939 = createFieldType(name, type, SizeInBitsOverride,
940 field->getLocation(), field->getAccess(),
941 OffsetInBits, tunit, RecordTy);
942
943 elements.push_back(fieldType);
944}
945
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000946/// CollectRecordFields - A helper function to collect debug info for
947/// record fields. This is used while creating debug info entry for a Record.
David Blaikie841fd112013-08-16 20:40:25 +0000948void CGDebugInfo::CollectRecordFields(const RecordDecl *record,
949 llvm::DIFile tunit,
950 SmallVectorImpl<llvm::Value *> &elements,
951 llvm::DICompositeType RecordTy) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000952 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(record);
953
Eric Christopher0395de32013-01-16 01:22:32 +0000954 if (CXXDecl && CXXDecl->isLambda())
955 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
956 else {
957 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000958
Eric Christopher0395de32013-01-16 01:22:32 +0000959 // Field number for non-static fields.
Eric Christopherfd5ac0d2013-01-04 17:59:07 +0000960 unsigned fieldNo = 0;
Eric Christopher0395de32013-01-16 01:22:32 +0000961
Eric Christopher0395de32013-01-16 01:22:32 +0000962 // Static and non-static members should appear in the same order as
963 // the corresponding declarations in the source program.
964 for (RecordDecl::decl_iterator I = record->decls_begin(),
965 E = record->decls_end(); I != E; ++I)
966 if (const VarDecl *V = dyn_cast<VarDecl>(*I))
David Blaikie5434fc22013-08-20 01:28:15 +0000967 elements.push_back(getOrCreateStaticDataMemberDeclaration(V, RecordTy));
Eric Christopher0395de32013-01-16 01:22:32 +0000968 else if (FieldDecl *field = dyn_cast<FieldDecl>(*I)) {
Eric Christopher0395de32013-01-16 01:22:32 +0000969 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo),
970 tunit, elements, RecordTy);
971
972 // Bump field number for next field.
973 ++fieldNo;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000974 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000975 }
976}
977
978/// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
979/// function type is not updated to include implicit "this" pointer. Use this
980/// routine to get a method type which includes "this" pointer.
David Blaikie9a845292013-05-22 23:22:42 +0000981llvm::DICompositeType
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000982CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
983 llvm::DIFile Unit) {
David Blaikie9c78f9b2013-01-07 23:06:35 +0000984 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
David Blaikie67f8b5e2013-01-07 22:24:59 +0000985 if (Method->isStatic())
David Blaikie9a845292013-05-22 23:22:42 +0000986 return llvm::DICompositeType(getOrCreateType(QualType(Func, 0), Unit));
David Blaikie9c78f9b2013-01-07 23:06:35 +0000987 return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()),
988 Func, Unit);
989}
David Blaikie67f8b5e2013-01-07 22:24:59 +0000990
David Blaikie9a845292013-05-22 23:22:42 +0000991llvm::DICompositeType CGDebugInfo::getOrCreateInstanceMethodType(
David Blaikie9c78f9b2013-01-07 23:06:35 +0000992 QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile Unit) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000993 // Add "this" pointer.
David Blaikie9c78f9b2013-01-07 23:06:35 +0000994 llvm::DIArray Args = llvm::DICompositeType(
995 getOrCreateType(QualType(Func, 0), Unit)).getTypeArray();
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000996 assert (Args.getNumElements() && "Invalid number of arguments!");
997
998 SmallVector<llvm::Value *, 16> Elts;
999
1000 // First element is always return type. For 'void' functions it is NULL.
1001 Elts.push_back(Args.getElement(0));
1002
David Blaikie67f8b5e2013-01-07 22:24:59 +00001003 // "this" pointer is always first argument.
David Blaikie9c78f9b2013-01-07 23:06:35 +00001004 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
David Blaikie67f8b5e2013-01-07 22:24:59 +00001005 if (isa<ClassTemplateSpecializationDecl>(RD)) {
1006 // Create pointer type directly in this case.
1007 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
1008 QualType PointeeTy = ThisPtrTy->getPointeeType();
1009 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCall64aa4b32013-04-16 22:48:15 +00001010 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
David Blaikie67f8b5e2013-01-07 22:24:59 +00001011 uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy);
1012 llvm::DIType PointeeType = getOrCreateType(PointeeTy, Unit);
Eric Christopherf0890c42013-05-16 00:52:20 +00001013 llvm::DIType ThisPtrType =
1014 DBuilder.createPointerType(PointeeType, Size, Align);
David Blaikie67f8b5e2013-01-07 22:24:59 +00001015 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
1016 // TODO: This and the artificial type below are misleading, the
1017 // types aren't artificial the argument is, but the current
1018 // metadata doesn't represent that.
1019 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1020 Elts.push_back(ThisPtrType);
1021 } else {
1022 llvm::DIType ThisPtrType = getOrCreateType(ThisPtr, Unit);
1023 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
1024 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1025 Elts.push_back(ThisPtrType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001026 }
1027
1028 // Copy rest of the arguments.
1029 for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
1030 Elts.push_back(Args.getElement(i));
1031
1032 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
1033
1034 return DBuilder.createSubroutineType(Unit, EltTypeArray);
1035}
1036
Eric Christopher6537f082013-05-16 00:45:12 +00001037/// isFunctionLocalClass - Return true if CXXRecordDecl is defined
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001038/// inside a function.
1039static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
1040 if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
1041 return isFunctionLocalClass(NRD);
1042 if (isa<FunctionDecl>(RD->getDeclContext()))
1043 return true;
1044 return false;
1045}
1046
1047/// CreateCXXMemberFunction - A helper function to create a DISubprogram for
1048/// a single member function GlobalDecl.
1049llvm::DISubprogram
1050CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
1051 llvm::DIFile Unit,
1052 llvm::DIType RecordTy) {
Eric Christopher6537f082013-05-16 00:45:12 +00001053 bool IsCtorOrDtor =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001054 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
Eric Christopher6537f082013-05-16 00:45:12 +00001055
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001056 StringRef MethodName = getFunctionName(Method);
David Blaikie9a845292013-05-22 23:22:42 +00001057 llvm::DICompositeType MethodTy = getOrCreateMethodType(Method, Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001058
1059 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1060 // make sense to give a single ctor/dtor a linkage name.
1061 StringRef MethodLinkageName;
1062 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1063 MethodLinkageName = CGM.getMangledName(Method);
1064
1065 // Get the location for the method.
David Blaikiefc946272013-08-19 03:37:48 +00001066 llvm::DIFile MethodDefUnit;
1067 unsigned MethodLine = 0;
1068 if (!Method->isImplicit()) {
1069 MethodDefUnit = getOrCreateFile(Method->getLocation());
1070 MethodLine = getLineNumber(Method->getLocation());
1071 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001072
1073 // Collect virtual method info.
1074 llvm::DIType ContainingType;
Eric Christopher6537f082013-05-16 00:45:12 +00001075 unsigned Virtuality = 0;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001076 unsigned VIndex = 0;
Eric Christopher6537f082013-05-16 00:45:12 +00001077
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001078 if (Method->isVirtual()) {
1079 if (Method->isPure())
1080 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
1081 else
1082 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
Eric Christopher6537f082013-05-16 00:45:12 +00001083
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001084 // It doesn't make sense to give a virtual destructor a vtable index,
1085 // since a single destructor has two entries in the vtable.
1086 if (!isa<CXXDestructorDecl>(Method))
1087 VIndex = CGM.getVTableContext().getMethodVTableIndex(Method);
1088 ContainingType = RecordTy;
1089 }
1090
1091 unsigned Flags = 0;
1092 if (Method->isImplicit())
1093 Flags |= llvm::DIDescriptor::FlagArtificial;
1094 AccessSpecifier Access = Method->getAccess();
1095 if (Access == clang::AS_private)
1096 Flags |= llvm::DIDescriptor::FlagPrivate;
1097 else if (Access == clang::AS_protected)
1098 Flags |= llvm::DIDescriptor::FlagProtected;
1099 if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1100 if (CXXC->isExplicit())
1101 Flags |= llvm::DIDescriptor::FlagExplicit;
Eric Christopher6537f082013-05-16 00:45:12 +00001102 } else if (const CXXConversionDecl *CXXC =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001103 dyn_cast<CXXConversionDecl>(Method)) {
1104 if (CXXC->isExplicit())
1105 Flags |= llvm::DIDescriptor::FlagExplicit;
1106 }
1107 if (Method->hasPrototype())
1108 Flags |= llvm::DIDescriptor::FlagPrototyped;
1109
1110 llvm::DIArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1111 llvm::DISubprogram SP =
Eric Christopher6537f082013-05-16 00:45:12 +00001112 DBuilder.createMethod(RecordTy, MethodName, MethodLinkageName,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001113 MethodDefUnit, MethodLine,
Eric Christopher6537f082013-05-16 00:45:12 +00001114 MethodTy, /*isLocalToUnit=*/false,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001115 /* isDefinition=*/ false,
1116 Virtuality, VIndex, ContainingType,
1117 Flags, CGM.getLangOpts().Optimize, NULL,
1118 TParamsArray);
Eric Christopher6537f082013-05-16 00:45:12 +00001119
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001120 SPCache[Method->getCanonicalDecl()] = llvm::WeakVH(SP);
1121
1122 return SP;
1123}
1124
1125/// CollectCXXMemberFunctions - A helper function to collect debug info for
Eric Christopher6537f082013-05-16 00:45:12 +00001126/// C++ member functions. This is used while creating debug info entry for
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001127/// a Record.
1128void CGDebugInfo::
1129CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
1130 SmallVectorImpl<llvm::Value *> &EltTys,
1131 llvm::DIType RecordTy) {
1132
1133 // Since we want more than just the individual member decls if we
1134 // have templated functions iterate over every declaration to gather
1135 // the functions.
1136 for(DeclContext::decl_iterator I = RD->decls_begin(),
1137 E = RD->decls_end(); I != E; ++I) {
1138 Decl *D = *I;
David Blaikied6d5d692013-08-09 17:20:05 +00001139 if (D->isImplicit())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001140 continue;
1141
David Blaikie5434fc22013-08-20 01:28:15 +00001142 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
1143 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator MI =
1144 SPCache.find(Method->getCanonicalDecl());
1145 if (MI == SPCache.end())
1146 EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
1147 else
1148 EltTys.push_back(MI->second);
1149 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001150 }
Eric Christopher6537f082013-05-16 00:45:12 +00001151}
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001152
1153/// CollectCXXFriends - A helper function to collect debug info for
1154/// C++ base classes. This is used while creating debug info entry for
1155/// a Record.
1156void CGDebugInfo::
1157CollectCXXFriends(const CXXRecordDecl *RD, llvm::DIFile Unit,
1158 SmallVectorImpl<llvm::Value *> &EltTys,
1159 llvm::DIType RecordTy) {
1160 for (CXXRecordDecl::friend_iterator BI = RD->friend_begin(),
1161 BE = RD->friend_end(); BI != BE; ++BI) {
1162 if ((*BI)->isUnsupportedFriend())
1163 continue;
1164 if (TypeSourceInfo *TInfo = (*BI)->getFriendType())
David Blaikie3de73f02013-08-18 04:50:23 +00001165 EltTys.push_back(DBuilder.createFriend(
1166 RecordTy, getOrCreateType(TInfo->getType(), Unit, true)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001167 }
1168}
1169
1170/// CollectCXXBases - A helper function to collect debug info for
Eric Christopher6537f082013-05-16 00:45:12 +00001171/// C++ base classes. This is used while creating debug info entry for
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001172/// a Record.
1173void CGDebugInfo::
1174CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
1175 SmallVectorImpl<llvm::Value *> &EltTys,
1176 llvm::DIType RecordTy) {
1177
1178 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1179 for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
1180 BE = RD->bases_end(); BI != BE; ++BI) {
1181 unsigned BFlags = 0;
1182 uint64_t BaseOffset;
Eric Christopher6537f082013-05-16 00:45:12 +00001183
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001184 const CXXRecordDecl *Base =
1185 cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl());
Eric Christopher6537f082013-05-16 00:45:12 +00001186
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001187 if (BI->isVirtual()) {
1188 // virtual base offset offset is -ve. The code generator emits dwarf
1189 // expression where it expects +ve number.
Eric Christopher6537f082013-05-16 00:45:12 +00001190 BaseOffset =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001191 0 - CGM.getVTableContext()
1192 .getVirtualBaseOffsetOffset(RD, Base).getQuantity();
1193 BFlags = llvm::DIDescriptor::FlagVirtual;
1194 } else
1195 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1196 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1197 // BI->isVirtual() and bits when not.
Eric Christopher6537f082013-05-16 00:45:12 +00001198
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001199 AccessSpecifier Access = BI->getAccessSpecifier();
1200 if (Access == clang::AS_private)
1201 BFlags |= llvm::DIDescriptor::FlagPrivate;
1202 else if (Access == clang::AS_protected)
1203 BFlags |= llvm::DIDescriptor::FlagProtected;
Eric Christopher6537f082013-05-16 00:45:12 +00001204
1205 llvm::DIType DTy =
1206 DBuilder.createInheritance(RecordTy,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001207 getOrCreateType(BI->getType(), Unit),
1208 BaseOffset, BFlags);
1209 EltTys.push_back(DTy);
1210 }
1211}
1212
1213/// CollectTemplateParams - A helper function to collect template parameters.
1214llvm::DIArray CGDebugInfo::
1215CollectTemplateParams(const TemplateParameterList *TPList,
David Blaikie35178dc2013-06-22 18:59:18 +00001216 ArrayRef<TemplateArgument> TAList,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001217 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +00001218 SmallVector<llvm::Value *, 16> TemplateParams;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001219 for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1220 const TemplateArgument &TA = TAList[i];
David Blaikie35178dc2013-06-22 18:59:18 +00001221 StringRef Name;
1222 if (TPList)
1223 Name = TPList->getParam(i)->getName();
David Blaikie9dfd2432013-05-10 21:53:14 +00001224 switch (TA.getKind()) {
1225 case TemplateArgument::Type: {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001226 llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit);
1227 llvm::DITemplateTypeParameter TTP =
David Blaikie35178dc2013-06-22 18:59:18 +00001228 DBuilder.createTemplateTypeParameter(TheCU, Name, TTy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001229 TemplateParams.push_back(TTP);
David Blaikie9dfd2432013-05-10 21:53:14 +00001230 } break;
1231 case TemplateArgument::Integral: {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001232 llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit);
1233 llvm::DITemplateValueParameter TVP =
David Blaikie9dfd2432013-05-10 21:53:14 +00001234 DBuilder.createTemplateValueParameter(
David Blaikie35178dc2013-06-22 18:59:18 +00001235 TheCU, Name, TTy,
David Blaikie9dfd2432013-05-10 21:53:14 +00001236 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral()));
1237 TemplateParams.push_back(TVP);
1238 } break;
1239 case TemplateArgument::Declaration: {
1240 const ValueDecl *D = TA.getAsDecl();
1241 bool InstanceMember = D->isCXXInstanceMember();
1242 QualType T = InstanceMember
1243 ? CGM.getContext().getMemberPointerType(
1244 D->getType(), cast<RecordDecl>(D->getDeclContext())
1245 ->getTypeForDecl())
1246 : CGM.getContext().getPointerType(D->getType());
1247 llvm::DIType TTy = getOrCreateType(T, Unit);
1248 llvm::Value *V = 0;
1249 // Variable pointer template parameters have a value that is the address
1250 // of the variable.
1251 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1252 V = CGM.GetAddrOfGlobalVar(VD);
1253 // Member function pointers have special support for building them, though
1254 // this is currently unsupported in LLVM CodeGen.
David Blaikief8aa1552013-05-13 06:57:50 +00001255 if (InstanceMember) {
David Blaikie9dfd2432013-05-10 21:53:14 +00001256 if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(D))
1257 V = CGM.getCXXABI().EmitMemberPointer(method);
David Blaikief8aa1552013-05-13 06:57:50 +00001258 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1259 V = CGM.GetAddrOfFunction(FD);
David Blaikie9dfd2432013-05-10 21:53:14 +00001260 // Member data pointers have special handling too to compute the fixed
1261 // offset within the object.
1262 if (isa<FieldDecl>(D)) {
1263 // These five lines (& possibly the above member function pointer
1264 // handling) might be able to be refactored to use similar code in
1265 // CodeGenModule::getMemberPointerConstant
1266 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
1267 CharUnits chars =
1268 CGM.getContext().toCharUnitsFromBits((int64_t) fieldOffset);
1269 V = CGM.getCXXABI().EmitMemberDataPointer(
1270 cast<MemberPointerType>(T.getTypePtr()), chars);
1271 }
1272 llvm::DITemplateValueParameter TVP =
David Blaikie35178dc2013-06-22 18:59:18 +00001273 DBuilder.createTemplateValueParameter(TheCU, Name, TTy, V);
David Blaikie9dfd2432013-05-10 21:53:14 +00001274 TemplateParams.push_back(TVP);
1275 } break;
1276 case TemplateArgument::NullPtr: {
1277 QualType T = TA.getNullPtrType();
1278 llvm::DIType TTy = getOrCreateType(T, Unit);
1279 llvm::Value *V = 0;
1280 // Special case member data pointer null values since they're actually -1
1281 // instead of zero.
1282 if (const MemberPointerType *MPT =
1283 dyn_cast<MemberPointerType>(T.getTypePtr()))
1284 // But treat member function pointers as simple zero integers because
1285 // it's easier than having a special case in LLVM's CodeGen. If LLVM
1286 // CodeGen grows handling for values of non-null member function
1287 // pointers then perhaps we could remove this special case and rely on
1288 // EmitNullMemberPointer for member function pointers.
1289 if (MPT->isMemberDataPointer())
1290 V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1291 if (!V)
1292 V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
1293 llvm::DITemplateValueParameter TVP =
David Blaikie35178dc2013-06-22 18:59:18 +00001294 DBuilder.createTemplateValueParameter(TheCU, Name, TTy, V);
David Blaikie9dfd2432013-05-10 21:53:14 +00001295 TemplateParams.push_back(TVP);
1296 } break;
David Blaikie35178dc2013-06-22 18:59:18 +00001297 case TemplateArgument::Template: {
1298 llvm::DITemplateValueParameter TVP =
1299 DBuilder.createTemplateTemplateParameter(
1300 TheCU, Name, llvm::DIType(),
1301 TA.getAsTemplate().getAsTemplateDecl()
1302 ->getQualifiedNameAsString());
1303 TemplateParams.push_back(TVP);
1304 } break;
1305 case TemplateArgument::Pack: {
1306 llvm::DITemplateValueParameter TVP =
1307 DBuilder.createTemplateParameterPack(
1308 TheCU, Name, llvm::DIType(),
1309 CollectTemplateParams(NULL, TA.getPackAsArray(), Unit));
1310 TemplateParams.push_back(TVP);
1311 } break;
David Blaikiee8065122013-05-10 23:36:06 +00001312 // And the following should never occur:
David Blaikie9dfd2432013-05-10 21:53:14 +00001313 case TemplateArgument::Expression:
1314 case TemplateArgument::TemplateExpansion:
David Blaikie9dfd2432013-05-10 21:53:14 +00001315 case TemplateArgument::Null:
1316 llvm_unreachable(
1317 "These argument types shouldn't exist in concrete types");
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001318 }
1319 }
1320 return DBuilder.getOrCreateArray(TemplateParams);
1321}
1322
1323/// CollectFunctionTemplateParams - A helper function to collect debug
1324/// info for function template parameters.
1325llvm::DIArray CGDebugInfo::
1326CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) {
1327 if (FD->getTemplatedKind() ==
1328 FunctionDecl::TK_FunctionTemplateSpecialization) {
1329 const TemplateParameterList *TList =
1330 FD->getTemplateSpecializationInfo()->getTemplate()
1331 ->getTemplateParameters();
David Blaikie35178dc2013-06-22 18:59:18 +00001332 return CollectTemplateParams(
1333 TList, FD->getTemplateSpecializationArgs()->asArray(), Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001334 }
1335 return llvm::DIArray();
1336}
1337
1338/// CollectCXXTemplateParams - A helper function to collect debug info for
1339/// template parameters.
1340llvm::DIArray CGDebugInfo::
1341CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial,
1342 llvm::DIFile Unit) {
1343 llvm::PointerUnion<ClassTemplateDecl *,
1344 ClassTemplatePartialSpecializationDecl *>
1345 PU = TSpecial->getSpecializedTemplateOrPartial();
Eric Christopher6537f082013-05-16 00:45:12 +00001346
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001347 TemplateParameterList *TPList = PU.is<ClassTemplateDecl *>() ?
1348 PU.get<ClassTemplateDecl *>()->getTemplateParameters() :
1349 PU.get<ClassTemplatePartialSpecializationDecl *>()->getTemplateParameters();
1350 const TemplateArgumentList &TAList = TSpecial->getTemplateInstantiationArgs();
David Blaikie35178dc2013-06-22 18:59:18 +00001351 return CollectTemplateParams(TPList, TAList.asArray(), Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001352}
1353
1354/// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
1355llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
1356 if (VTablePtrType.isValid())
1357 return VTablePtrType;
1358
1359 ASTContext &Context = CGM.getContext();
1360
1361 /* Function type */
1362 llvm::Value *STy = getOrCreateType(Context.IntTy, Unit);
1363 llvm::DIArray SElements = DBuilder.getOrCreateArray(STy);
1364 llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements);
1365 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1366 llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0,
1367 "__vtbl_ptr_type");
1368 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1369 return VTablePtrType;
1370}
1371
1372/// getVTableName - Get vtable name for the given Class.
1373StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
1374 // Construct gdb compatible name name.
1375 std::string Name = "_vptr$" + RD->getNameAsString();
1376
1377 // Copy this name on the side and use its reference.
1378 char *StrPtr = DebugInfoNames.Allocate<char>(Name.length());
1379 memcpy(StrPtr, Name.data(), Name.length());
1380 return StringRef(StrPtr, Name.length());
1381}
1382
1383
1384/// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
1385/// debug info entry in EltTys vector.
1386void CGDebugInfo::
1387CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
1388 SmallVectorImpl<llvm::Value *> &EltTys) {
1389 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1390
1391 // If there is a primary base then it will hold vtable info.
1392 if (RL.getPrimaryBase())
1393 return;
1394
1395 // If this class is not dynamic then there is not any vtable info to collect.
1396 if (!RD->isDynamicClass())
1397 return;
1398
1399 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1400 llvm::DIType VPTR
1401 = DBuilder.createMemberType(Unit, getVTableName(RD), Unit,
Eric Christopherf0890c42013-05-16 00:52:20 +00001402 0, Size, 0, 0,
1403 llvm::DIDescriptor::FlagArtificial,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001404 getOrCreateVTablePtrType(Unit));
1405 EltTys.push_back(VPTR);
1406}
1407
Eric Christopher6537f082013-05-16 00:45:12 +00001408/// getOrCreateRecordType - Emit record type's standalone debug info.
1409llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001410 SourceLocation Loc) {
Eric Christopher13c97672013-05-16 00:45:23 +00001411 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001412 llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc));
1413 return T;
1414}
1415
1416/// getOrCreateInterfaceType - Emit an objective c interface type standalone
1417/// debug info.
1418llvm::DIType CGDebugInfo::getOrCreateInterfaceType(QualType D,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001419 SourceLocation Loc) {
Eric Christopher13c97672013-05-16 00:45:23 +00001420 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001421 llvm::DIType T = getOrCreateType(D, getOrCreateFile(Loc));
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001422 RetainedTypes.push_back(D.getAsOpaquePtr());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001423 return T;
1424}
1425
David Blaikie27804892013-08-15 20:49:17 +00001426void CGDebugInfo::completeType(const RecordDecl *RD) {
1427 if (DebugKind > CodeGenOptions::LimitedDebugInfo ||
1428 !CGM.getLangOpts().CPlusPlus)
1429 completeRequiredType(RD);
1430}
1431
1432void CGDebugInfo::completeRequiredType(const RecordDecl *RD) {
David Blaikie5434fc22013-08-20 01:28:15 +00001433 if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
1434 if (CXXDecl->isDynamicClass())
1435 return;
1436
David Blaikie27804892013-08-15 20:49:17 +00001437 QualType Ty = CGM.getContext().getRecordType(RD);
1438 llvm::DIType T = getTypeOrNull(Ty);
David Blaikie5434fc22013-08-20 01:28:15 +00001439 if (T && T.isForwardDecl())
1440 completeClassData(RD);
1441}
1442
1443void CGDebugInfo::completeClassData(const RecordDecl *RD) {
1444 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
Michael Gottesman90e55232013-08-19 18:46:16 +00001445 return;
David Blaikie5434fc22013-08-20 01:28:15 +00001446 QualType Ty = CGM.getContext().getRecordType(RD);
David Blaikie27804892013-08-15 20:49:17 +00001447 void* TyPtr = Ty.getAsOpaquePtr();
1448 if (CompletedTypeCache.count(TyPtr))
1449 return;
1450 llvm::DIType Res = CreateTypeDefinition(Ty->castAs<RecordType>());
1451 assert(!Res.isForwardDecl());
1452 CompletedTypeCache[TyPtr] = Res;
1453 TypeCache[TyPtr] = Res;
1454}
1455
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001456/// CreateType - get structure or union type.
David Blaikie5f6e2f42013-06-05 05:32:23 +00001457llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty, bool Declaration) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001458 RecordDecl *RD = Ty->getDecl();
David Blaikie5434fc22013-08-20 01:28:15 +00001459 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
Adrian Prantl776bfa12013-06-18 23:32:21 +00001460 // Limited debug info should only remove struct definitions that can
1461 // safely be replaced by a forward declaration in the source code.
David Blaikie5434fc22013-08-20 01:28:15 +00001462 if ((DebugKind <= CodeGenOptions::LimitedDebugInfo && Declaration &&
1463 !RD->isCompleteDefinitionRequired() && CGM.getLangOpts().CPlusPlus) ||
1464 (CXXDecl && CXXDecl->hasDefinition() && CXXDecl->isDynamicClass())) {
David Blaikie5f6e2f42013-06-05 05:32:23 +00001465 llvm::DIDescriptor FDContext =
1466 getContextDescriptor(cast<Decl>(RD->getDeclContext()));
David Blaikie951094b2013-08-15 18:59:40 +00001467 llvm::DIType RetTy = getOrCreateRecordFwdDecl(RD, FDContext);
David Blaikie5434fc22013-08-20 01:28:15 +00001468 // FIXME: This is conservatively correct. If we return a non-forward decl
1469 // that's not a full definition (such as those created by
1470 // createContextChain) then getOrCreateType will record is as a complete
1471 // type and we'll never record all its members. But this means we're
1472 // emitting full debug info in TUs where GCC successfully emits a partial
1473 // definition of the type.
1474 if (RetTy.isForwardDecl())
1475 return RetTy;
David Blaikie5f6e2f42013-06-05 05:32:23 +00001476 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001477
David Blaikie27804892013-08-15 20:49:17 +00001478 return CreateTypeDefinition(Ty);
1479}
1480
1481llvm::DIType CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {
1482 RecordDecl *RD = Ty->getDecl();
1483
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001484 // Get overall information about the record type for the debug info.
1485 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1486
1487 // Records and classes and unions can all be recursive. To handle them, we
1488 // first generate a debug descriptor for the struct as a forward declaration.
1489 // Then (if it is a definition) we go through and get debug info for all of
1490 // its members. Finally, we create a descriptor for the complete type (which
1491 // may refer to the forward decl if the struct is recursive) and replace all
1492 // uses of the forward declaration with the final definition.
1493
David Blaikie4a077162013-08-12 22:24:20 +00001494 llvm::DICompositeType FwdDecl(getOrCreateLimitedType(Ty, DefUnit));
Manman Renb6b0a712013-07-02 19:01:53 +00001495 assert(FwdDecl.isCompositeType() &&
David Blaikie9a845292013-05-22 23:22:42 +00001496 "The debug type of a RecordType should be a llvm::DICompositeType");
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001497
1498 if (FwdDecl.isForwardDecl())
1499 return FwdDecl;
1500
David Blaikie498298d2013-08-18 16:55:33 +00001501 if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
1502 CollectContainingType(CXXDecl, FwdDecl);
1503
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001504 // Push the struct on region stack.
Eric Christopherf068c922013-04-02 22:59:11 +00001505 LexicalBlockStack.push_back(&*FwdDecl);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001506 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1507
Adrian Prantl4919de62013-03-06 22:03:30 +00001508 // Add this to the completed-type cache while we're completing it recursively.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001509 CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1510
1511 // Convert all the elements.
1512 SmallVector<llvm::Value *, 16> EltTys;
David Blaikie5434fc22013-08-20 01:28:15 +00001513 // what about nested types?
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001514
1515 // Note: The split of CXXDecl information here is intentional, the
1516 // gdb tests will depend on a certain ordering at printout. The debug
1517 // information offsets are still correct if we merge them all together
1518 // though.
1519 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1520 if (CXXDecl) {
1521 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1522 CollectVTableInfo(CXXDecl, DefUnit, EltTys);
1523 }
1524
Eric Christopher0395de32013-01-16 01:22:32 +00001525 // Collect data fields (including static variables and any initializers).
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001526 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001527 if (CXXDecl) {
1528 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
1529 CollectCXXFriends(CXXDecl, DefUnit, EltTys, FwdDecl);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001530 }
1531
1532 LexicalBlockStack.pop_back();
1533 RegionMap.erase(Ty->getDecl());
1534
1535 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
David Blaikie80588332013-08-01 20:31:40 +00001536 FwdDecl.setTypeArray(Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001537
Eric Christopherf068c922013-04-02 22:59:11 +00001538 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1539 return FwdDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001540}
1541
1542/// CreateType - get objective-c object type.
1543llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1544 llvm::DIFile Unit) {
1545 // Ignore protocols.
1546 return getOrCreateType(Ty->getBaseType(), Unit);
1547}
1548
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001549
1550/// \return true if Getter has the default name for the property PD.
1551static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
1552 const ObjCMethodDecl *Getter) {
1553 assert(PD);
1554 if (!Getter)
1555 return true;
1556
1557 assert(Getter->getDeclName().isObjCZeroArgSelector());
1558 return PD->getName() ==
1559 Getter->getDeclName().getObjCSelector().getNameForSlot(0);
1560}
1561
1562/// \return true if Setter has the default name for the property PD.
1563static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
1564 const ObjCMethodDecl *Setter) {
1565 assert(PD);
1566 if (!Setter)
1567 return true;
1568
1569 assert(Setter->getDeclName().isObjCOneArgSelector());
Adrian Prantl80e8ea92013-06-07 22:29:12 +00001570 return SelectorTable::constructSetterName(PD->getName()) ==
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001571 Setter->getDeclName().getObjCSelector().getNameForSlot(0);
1572}
1573
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001574/// CreateType - get objective-c interface type.
1575llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1576 llvm::DIFile Unit) {
1577 ObjCInterfaceDecl *ID = Ty->getDecl();
1578 if (!ID)
1579 return llvm::DIType();
1580
1581 // Get overall information about the record type for the debug info.
1582 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1583 unsigned Line = getLineNumber(ID->getLocation());
1584 unsigned RuntimeLang = TheCU.getLanguage();
1585
1586 // If this is just a forward declaration return a special forward-declaration
1587 // debug type since we won't be able to lay out the entire type.
1588 ObjCInterfaceDecl *Def = ID->getDefinition();
1589 if (!Def) {
1590 llvm::DIType FwdDecl =
1591 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001592 ID->getName(), TheCU, DefUnit, Line,
1593 RuntimeLang);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001594 return FwdDecl;
1595 }
1596
1597 ID = Def;
1598
1599 // Bit size, align and offset of the type.
1600 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1601 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1602
1603 unsigned Flags = 0;
1604 if (ID->getImplementation())
1605 Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
1606
Eric Christopherf068c922013-04-02 22:59:11 +00001607 llvm::DICompositeType RealDecl =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001608 DBuilder.createStructType(Unit, ID->getName(), DefUnit,
1609 Line, Size, Align, Flags,
David Blaikiec1d0af12013-02-25 01:07:08 +00001610 llvm::DIType(), llvm::DIArray(), RuntimeLang);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001611
1612 // Otherwise, insert it into the CompletedTypeCache so that recursive uses
1613 // will find it and we're emitting the complete type.
Adrian Prantl4919de62013-03-06 22:03:30 +00001614 QualType QualTy = QualType(Ty, 0);
1615 CompletedTypeCache[QualTy.getAsOpaquePtr()] = RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001616
Eric Christopherd3003dc2013-07-14 21:00:07 +00001617 // Push the struct on region stack.
Eric Christopherf068c922013-04-02 22:59:11 +00001618 LexicalBlockStack.push_back(static_cast<llvm::MDNode*>(RealDecl));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001619 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1620
1621 // Convert all the elements.
1622 SmallVector<llvm::Value *, 16> EltTys;
1623
1624 ObjCInterfaceDecl *SClass = ID->getSuperClass();
1625 if (SClass) {
1626 llvm::DIType SClassTy =
1627 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1628 if (!SClassTy.isValid())
1629 return llvm::DIType();
Eric Christopher6537f082013-05-16 00:45:12 +00001630
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001631 llvm::DIType InhTag =
1632 DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
1633 EltTys.push_back(InhTag);
1634 }
1635
Eric Christopherd3003dc2013-07-14 21:00:07 +00001636 // Create entries for all of the properties.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001637 for (ObjCContainerDecl::prop_iterator I = ID->prop_begin(),
1638 E = ID->prop_end(); I != E; ++I) {
1639 const ObjCPropertyDecl *PD = *I;
1640 SourceLocation Loc = PD->getLocation();
1641 llvm::DIFile PUnit = getOrCreateFile(Loc);
1642 unsigned PLine = getLineNumber(Loc);
1643 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1644 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1645 llvm::MDNode *PropertyNode =
1646 DBuilder.createObjCProperty(PD->getName(),
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001647 PUnit, PLine,
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001648 hasDefaultGetterName(PD, Getter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001649 getSelectorName(PD->getGetterName()),
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001650 hasDefaultSetterName(PD, Setter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001651 getSelectorName(PD->getSetterName()),
1652 PD->getPropertyAttributes(),
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001653 getOrCreateType(PD->getType(), PUnit));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001654 EltTys.push_back(PropertyNode);
1655 }
1656
1657 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1658 unsigned FieldNo = 0;
1659 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1660 Field = Field->getNextIvar(), ++FieldNo) {
1661 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1662 if (!FieldTy.isValid())
1663 return llvm::DIType();
Eric Christopher6537f082013-05-16 00:45:12 +00001664
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001665 StringRef FieldName = Field->getName();
1666
1667 // Ignore unnamed fields.
1668 if (FieldName.empty())
1669 continue;
1670
1671 // Get the location for the field.
1672 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1673 unsigned FieldLine = getLineNumber(Field->getLocation());
1674 QualType FType = Field->getType();
1675 uint64_t FieldSize = 0;
1676 unsigned FieldAlign = 0;
1677
1678 if (!FType->isIncompleteArrayType()) {
1679
1680 // Bit size, align and offset of the type.
1681 FieldSize = Field->isBitField()
Eric Christopherd3003dc2013-07-14 21:00:07 +00001682 ? Field->getBitWidthValue(CGM.getContext())
1683 : CGM.getContext().getTypeSize(FType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001684 FieldAlign = CGM.getContext().getTypeAlign(FType);
1685 }
1686
1687 uint64_t FieldOffset;
1688 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1689 // We don't know the runtime offset of an ivar if we're using the
1690 // non-fragile ABI. For bitfields, use the bit offset into the first
1691 // byte of storage of the bitfield. For other fields, use zero.
1692 if (Field->isBitField()) {
1693 FieldOffset = CGM.getObjCRuntime().ComputeBitfieldBitOffset(
1694 CGM, ID, Field);
1695 FieldOffset %= CGM.getContext().getCharWidth();
1696 } else {
1697 FieldOffset = 0;
1698 }
1699 } else {
1700 FieldOffset = RL.getFieldOffset(FieldNo);
1701 }
1702
1703 unsigned Flags = 0;
1704 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1705 Flags = llvm::DIDescriptor::FlagProtected;
1706 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1707 Flags = llvm::DIDescriptor::FlagPrivate;
1708
1709 llvm::MDNode *PropertyNode = NULL;
1710 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
Eric Christopher6537f082013-05-16 00:45:12 +00001711 if (ObjCPropertyImplDecl *PImpD =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001712 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
1713 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001714 SourceLocation Loc = PD->getLocation();
1715 llvm::DIFile PUnit = getOrCreateFile(Loc);
1716 unsigned PLine = getLineNumber(Loc);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001717 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1718 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1719 PropertyNode =
1720 DBuilder.createObjCProperty(PD->getName(),
1721 PUnit, PLine,
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001722 hasDefaultGetterName(PD, Getter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001723 getSelectorName(PD->getGetterName()),
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001724 hasDefaultSetterName(PD, Setter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001725 getSelectorName(PD->getSetterName()),
1726 PD->getPropertyAttributes(),
1727 getOrCreateType(PD->getType(), PUnit));
1728 }
1729 }
1730 }
1731 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
1732 FieldLine, FieldSize, FieldAlign,
1733 FieldOffset, Flags, FieldTy,
1734 PropertyNode);
1735 EltTys.push_back(FieldTy);
1736 }
1737
1738 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopherf068c922013-04-02 22:59:11 +00001739 RealDecl.setTypeArray(Elements);
Adrian Prantl4919de62013-03-06 22:03:30 +00001740
1741 // If the implementation is not yet set, we do not want to mark it
1742 // as complete. An implementation may declare additional
1743 // private ivars that we would miss otherwise.
1744 if (ID->getImplementation() == 0)
1745 CompletedTypeCache.erase(QualTy.getAsOpaquePtr());
Eric Christopher6537f082013-05-16 00:45:12 +00001746
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001747 LexicalBlockStack.pop_back();
Eric Christopherf068c922013-04-02 22:59:11 +00001748 return RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001749}
1750
1751llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) {
1752 llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1753 int64_t Count = Ty->getNumElements();
1754 if (Count == 0)
1755 // If number of elements are not known then this is an unbounded array.
1756 // Use Count == -1 to express such arrays.
1757 Count = -1;
1758
1759 llvm::Value *Subscript = DBuilder.getOrCreateSubrange(0, Count);
1760 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1761
1762 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1763 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1764
1765 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1766}
1767
1768llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1769 llvm::DIFile Unit) {
1770 uint64_t Size;
1771 uint64_t Align;
1772
1773 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1774 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1775 Size = 0;
1776 Align =
1777 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1778 } else if (Ty->isIncompleteArrayType()) {
1779 Size = 0;
1780 if (Ty->getElementType()->isIncompleteType())
1781 Align = 0;
1782 else
1783 Align = CGM.getContext().getTypeAlign(Ty->getElementType());
David Blaikie089db2e2013-05-09 20:48:12 +00001784 } else if (Ty->isIncompleteType()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001785 Size = 0;
1786 Align = 0;
1787 } else {
1788 // Size and align of the whole array, not the element type.
1789 Size = CGM.getContext().getTypeSize(Ty);
1790 Align = CGM.getContext().getTypeAlign(Ty);
1791 }
1792
1793 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
1794 // interior arrays, do we care? Why aren't nested arrays represented the
1795 // obvious/recursive way?
1796 SmallVector<llvm::Value *, 8> Subscripts;
1797 QualType EltTy(Ty, 0);
1798 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1799 // If the number of elements is known, then count is that number. Otherwise,
1800 // it's -1. This allows us to represent a subrange with an array of 0
1801 // elements, like this:
1802 //
1803 // struct foo {
1804 // int x[0];
1805 // };
1806 int64_t Count = -1; // Count == -1 is an unbounded array.
1807 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1808 Count = CAT->getSize().getZExtValue();
Eric Christopher6537f082013-05-16 00:45:12 +00001809
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001810 // FIXME: Verify this is right for VLAs.
1811 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
1812 EltTy = Ty->getElementType();
1813 }
1814
1815 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1816
Eric Christopher6537f082013-05-16 00:45:12 +00001817 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001818 DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1819 SubscriptArray);
1820 return DbgTy;
1821}
1822
Eric Christopher6537f082013-05-16 00:45:12 +00001823llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001824 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +00001825 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001826 Ty, Ty->getPointeeType(), Unit);
1827}
1828
Eric Christopher6537f082013-05-16 00:45:12 +00001829llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001830 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +00001831 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001832 Ty, Ty->getPointeeType(), Unit);
1833}
1834
Eric Christopher6537f082013-05-16 00:45:12 +00001835llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001836 llvm::DIFile U) {
David Blaikiee8d75142013-01-19 19:20:56 +00001837 llvm::DIType ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
1838 if (!Ty->getPointeeType()->isFunctionType())
1839 return DBuilder.createMemberPointerType(
David Blaikieb3c23772013-08-12 23:14:36 +00001840 getOrCreateType(Ty->getPointeeType(), U, true), ClassType);
David Blaikiee8d75142013-01-19 19:20:56 +00001841 return DBuilder.createMemberPointerType(getOrCreateInstanceMethodType(
1842 CGM.getContext().getPointerType(
1843 QualType(Ty->getClass(), Ty->getPointeeType().getCVRQualifiers())),
1844 Ty->getPointeeType()->getAs<FunctionProtoType>(), U),
1845 ClassType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001846}
1847
Eric Christopher6537f082013-05-16 00:45:12 +00001848llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001849 llvm::DIFile U) {
1850 // Ignore the atomic wrapping
1851 // FIXME: What is the correct representation?
1852 return getOrCreateType(Ty->getValueType(), U);
1853}
1854
1855/// CreateEnumType - get enumeration type.
1856llvm::DIType CGDebugInfo::CreateEnumType(const EnumDecl *ED) {
1857 uint64_t Size = 0;
1858 uint64_t Align = 0;
1859 if (!ED->getTypeForDecl()->isIncompleteType()) {
1860 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1861 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1862 }
1863
1864 // If this is just a forward declaration, construct an appropriately
1865 // marked node and just return it.
1866 if (!ED->getDefinition()) {
1867 llvm::DIDescriptor EDContext;
1868 EDContext = getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1869 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1870 unsigned Line = getLineNumber(ED->getLocation());
1871 StringRef EDName = ED->getName();
1872 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_enumeration_type,
1873 EDName, EDContext, DefUnit, Line, 0,
1874 Size, Align);
1875 }
1876
1877 // Create DIEnumerator elements for each enumerator.
1878 SmallVector<llvm::Value *, 16> Enumerators;
1879 ED = ED->getDefinition();
1880 for (EnumDecl::enumerator_iterator
1881 Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
1882 Enum != EnumEnd; ++Enum) {
1883 Enumerators.push_back(
1884 DBuilder.createEnumerator(Enum->getName(),
David Blaikieac8f43c2013-06-24 07:13:13 +00001885 Enum->getInitVal().getSExtValue()));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001886 }
1887
1888 // Return a CompositeType for the enum itself.
1889 llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1890
1891 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1892 unsigned Line = getLineNumber(ED->getLocation());
Eric Christopher6537f082013-05-16 00:45:12 +00001893 llvm::DIDescriptor EnumContext =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001894 getContextDescriptor(cast<Decl>(ED->getDeclContext()));
Adrian Prantl59d6a712013-04-19 19:56:39 +00001895 llvm::DIType ClassTy = ED->isFixed() ?
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001896 getOrCreateType(ED->getIntegerType(), DefUnit) : llvm::DIType();
Eric Christopher6537f082013-05-16 00:45:12 +00001897 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001898 DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1899 Size, Align, EltArray,
1900 ClassTy);
1901 return DbgTy;
1902}
1903
David Blaikie4b12be62013-01-21 04:37:12 +00001904static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
1905 Qualifiers Quals;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001906 do {
David Blaikie4b12be62013-01-21 04:37:12 +00001907 Quals += T.getLocalQualifiers();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001908 QualType LastT = T;
1909 switch (T->getTypeClass()) {
1910 default:
David Blaikie4b12be62013-01-21 04:37:12 +00001911 return C.getQualifiedType(T.getTypePtr(), Quals);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001912 case Type::TemplateSpecialization:
1913 T = cast<TemplateSpecializationType>(T)->desugar();
1914 break;
1915 case Type::TypeOfExpr:
1916 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1917 break;
1918 case Type::TypeOf:
1919 T = cast<TypeOfType>(T)->getUnderlyingType();
1920 break;
1921 case Type::Decltype:
1922 T = cast<DecltypeType>(T)->getUnderlyingType();
1923 break;
1924 case Type::UnaryTransform:
1925 T = cast<UnaryTransformType>(T)->getUnderlyingType();
1926 break;
1927 case Type::Attributed:
1928 T = cast<AttributedType>(T)->getEquivalentType();
1929 break;
1930 case Type::Elaborated:
1931 T = cast<ElaboratedType>(T)->getNamedType();
1932 break;
1933 case Type::Paren:
1934 T = cast<ParenType>(T)->getInnerType();
1935 break;
David Blaikie4b12be62013-01-21 04:37:12 +00001936 case Type::SubstTemplateTypeParm:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001937 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001938 break;
1939 case Type::Auto:
David Blaikie91296482013-05-24 21:24:35 +00001940 QualType DT = cast<AutoType>(T)->getDeducedType();
1941 if (DT.isNull())
1942 return T;
1943 T = DT;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001944 break;
1945 }
Eric Christopher6537f082013-05-16 00:45:12 +00001946
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001947 assert(T != LastT && "Type unwrapping failed to unwrap!");
NAKAMURA Takumid24c9ab2013-01-21 10:51:28 +00001948 (void)LastT;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001949 } while (true);
1950}
1951
Eric Christopherf0890c42013-05-16 00:52:20 +00001952/// getType - Get the type from the cache or return null type if it doesn't
1953/// exist.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001954llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) {
1955
1956 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00001957 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Eric Christopher6537f082013-05-16 00:45:12 +00001958
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001959 // Check for existing entry.
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001960 if (Ty->getTypeClass() == Type::ObjCInterface) {
1961 llvm::Value *V = getCachedInterfaceTypeOrNull(Ty);
1962 if (V)
1963 return llvm::DIType(cast<llvm::MDNode>(V));
1964 else return llvm::DIType();
1965 }
1966
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001967 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1968 TypeCache.find(Ty.getAsOpaquePtr());
1969 if (it != TypeCache.end()) {
1970 // Verify that the debug info still exists.
1971 if (llvm::Value *V = it->second)
1972 return llvm::DIType(cast<llvm::MDNode>(V));
1973 }
1974
1975 return llvm::DIType();
1976}
1977
1978/// getCompletedTypeOrNull - Get the type from the cache or return null if it
1979/// doesn't exist.
1980llvm::DIType CGDebugInfo::getCompletedTypeOrNull(QualType Ty) {
1981
1982 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00001983 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001984
1985 // Check for existing entry.
Adrian Prantl4919de62013-03-06 22:03:30 +00001986 llvm::Value *V = 0;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001987 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1988 CompletedTypeCache.find(Ty.getAsOpaquePtr());
Adrian Prantl4919de62013-03-06 22:03:30 +00001989 if (it != CompletedTypeCache.end())
1990 V = it->second;
1991 else {
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001992 V = getCachedInterfaceTypeOrNull(Ty);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001993 }
1994
Adrian Prantl4919de62013-03-06 22:03:30 +00001995 // Verify that any cached debug info still exists.
David Blaikie00383082013-08-13 04:21:38 +00001996 return llvm::DIType(cast_or_null<llvm::MDNode>(V));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001997}
1998
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001999/// getCachedInterfaceTypeOrNull - Get the type from the interface
2000/// cache, unless it needs to regenerated. Otherwise return null.
2001llvm::Value *CGDebugInfo::getCachedInterfaceTypeOrNull(QualType Ty) {
2002 // Is there a cached interface that hasn't changed?
2003 llvm::DenseMap<void *, std::pair<llvm::WeakVH, unsigned > >
2004 ::iterator it1 = ObjCInterfaceCache.find(Ty.getAsOpaquePtr());
2005
2006 if (it1 != ObjCInterfaceCache.end())
2007 if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty))
2008 if (Checksum(Decl) == it1->second.second)
2009 // Return cached forward declaration.
2010 return it1->second.first;
2011
2012 return 0;
2013}
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002014
2015/// getOrCreateType - Get the type from the cache or create a new
2016/// one if necessary.
Eric Christopher56b108a2013-06-07 22:54:39 +00002017llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit,
2018 bool Declaration) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002019 if (Ty.isNull())
2020 return llvm::DIType();
2021
2022 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00002023 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002024
David Blaikie00383082013-08-13 04:21:38 +00002025 if (llvm::DIType T = getCompletedTypeOrNull(Ty)) {
David Blaikief0c31d92013-06-21 21:03:11 +00002026 // If we're looking for a definition, make sure we have definitions of any
2027 // underlying types.
2028 if (const TypedefType* TTy = dyn_cast<TypedefType>(Ty))
2029 getOrCreateType(TTy->getDecl()->getUnderlyingType(), Unit, Declaration);
2030 if (Ty.hasLocalQualifiers())
2031 getOrCreateType(QualType(Ty.getTypePtr(), 0), Unit, Declaration);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002032 return T;
David Blaikief0c31d92013-06-21 21:03:11 +00002033 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002034
2035 // Otherwise create the type.
David Blaikie5f6e2f42013-06-05 05:32:23 +00002036 llvm::DIType Res = CreateTypeNode(Ty, Unit, Declaration);
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002037 void* TyPtr = Ty.getAsOpaquePtr();
2038
2039 // And update the type cache.
2040 TypeCache[TyPtr] = Res;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002041
David Blaikie492b1022013-08-15 21:21:19 +00002042 // FIXME: this getTypeOrNull call seems silly when we just inserted the type
2043 // into the cache - but getTypeOrNull has a special case for cached interface
2044 // types. We should probably just pull that out as a special case for the
2045 // "else" block below & skip the otherwise needless lookup.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002046 llvm::DIType TC = getTypeOrNull(Ty);
Eric Christopherb2d13922013-07-18 00:52:50 +00002047 if (TC && TC.isForwardDecl())
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002048 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
2049 else if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty)) {
2050 // Interface types may have elements added to them by a
2051 // subsequent implementation or extension, so we keep them in
2052 // the ObjCInterfaceCache together with a checksum. Instead of
Adrian Prantlf06989b2013-05-08 23:37:22 +00002053 // the (possibly) incomplete interface type, we return a forward
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002054 // declaration that gets RAUW'd in CGDebugInfo::finalize().
David Blaikiee2eb89a2013-05-21 18:29:40 +00002055 std::pair<llvm::WeakVH, unsigned> &V = ObjCInterfaceCache[TyPtr];
2056 if (V.first)
2057 return llvm::DIType(cast<llvm::MDNode>(V.first));
2058 TC = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
2059 Decl->getName(), TheCU, Unit,
2060 getLineNumber(Decl->getLocation()),
2061 TheCU.getLanguage());
2062 // Store the forward declaration in the cache.
2063 V.first = TC;
2064 V.second = Checksum(Decl);
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002065
David Blaikiee2eb89a2013-05-21 18:29:40 +00002066 // Register the type for replacement in finalize().
2067 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
2068
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002069 return TC;
Adrian Prantl4919de62013-03-06 22:03:30 +00002070 }
2071
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002072 if (!Res.isForwardDecl())
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002073 CompletedTypeCache[TyPtr] = Res;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002074
2075 return Res;
2076}
2077
Adrian Prantlb5a50072013-06-07 01:10:41 +00002078/// Currently the checksum of an interface includes the number of
2079/// ivars and property accessors.
Eric Christopher56b108a2013-06-07 22:54:39 +00002080unsigned CGDebugInfo::Checksum(const ObjCInterfaceDecl *ID) {
Adrian Prantl4f97f852013-06-07 01:10:48 +00002081 // The assumption is that the number of ivars can only increase
2082 // monotonically, so it is safe to just use their current number as
2083 // a checksum.
Adrian Prantlb5a50072013-06-07 01:10:41 +00002084 unsigned Sum = 0;
2085 for (const ObjCIvarDecl *Ivar = ID->all_declared_ivar_begin();
2086 Ivar != 0; Ivar = Ivar->getNextIvar())
2087 ++Sum;
2088
2089 return Sum;
Adrian Prantl4919de62013-03-06 22:03:30 +00002090}
2091
2092ObjCInterfaceDecl *CGDebugInfo::getObjCInterfaceDecl(QualType Ty) {
2093 switch (Ty->getTypeClass()) {
2094 case Type::ObjCObjectPointer:
Eric Christopherf0890c42013-05-16 00:52:20 +00002095 return getObjCInterfaceDecl(cast<ObjCObjectPointerType>(Ty)
2096 ->getPointeeType());
Adrian Prantl4919de62013-03-06 22:03:30 +00002097 case Type::ObjCInterface:
2098 return cast<ObjCInterfaceType>(Ty)->getDecl();
2099 default:
2100 return 0;
2101 }
2102}
2103
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002104/// CreateTypeNode - Create a new debug type node.
Eric Christopher56b108a2013-06-07 22:54:39 +00002105llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit,
2106 bool Declaration) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002107 // Handle qualifiers, which recursively handles what they refer to.
2108 if (Ty.hasLocalQualifiers())
David Blaikie5f6e2f42013-06-05 05:32:23 +00002109 return CreateQualifiedType(Ty, Unit, Declaration);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002110
2111 const char *Diag = 0;
Eric Christopher6537f082013-05-16 00:45:12 +00002112
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002113 // Work out details of type.
2114 switch (Ty->getTypeClass()) {
2115#define TYPE(Class, Base)
2116#define ABSTRACT_TYPE(Class, Base)
2117#define NON_CANONICAL_TYPE(Class, Base)
2118#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2119#include "clang/AST/TypeNodes.def"
2120 llvm_unreachable("Dependent types cannot show up in debug information");
2121
2122 case Type::ExtVector:
2123 case Type::Vector:
2124 return CreateType(cast<VectorType>(Ty), Unit);
2125 case Type::ObjCObjectPointer:
2126 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
2127 case Type::ObjCObject:
2128 return CreateType(cast<ObjCObjectType>(Ty), Unit);
2129 case Type::ObjCInterface:
2130 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
2131 case Type::Builtin:
2132 return CreateType(cast<BuiltinType>(Ty));
2133 case Type::Complex:
2134 return CreateType(cast<ComplexType>(Ty));
2135 case Type::Pointer:
2136 return CreateType(cast<PointerType>(Ty), Unit);
Reid Kleckner12df2462013-06-24 17:51:48 +00002137 case Type::Decayed:
2138 // Decayed types are just pointers in LLVM and DWARF.
2139 return CreateType(
2140 cast<PointerType>(cast<DecayedType>(Ty)->getDecayedType()), Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002141 case Type::BlockPointer:
2142 return CreateType(cast<BlockPointerType>(Ty), Unit);
2143 case Type::Typedef:
David Blaikie5f6e2f42013-06-05 05:32:23 +00002144 return CreateType(cast<TypedefType>(Ty), Unit, Declaration);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002145 case Type::Record:
David Blaikie5f6e2f42013-06-05 05:32:23 +00002146 return CreateType(cast<RecordType>(Ty), Declaration);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002147 case Type::Enum:
2148 return CreateEnumType(cast<EnumType>(Ty)->getDecl());
2149 case Type::FunctionProto:
2150 case Type::FunctionNoProto:
2151 return CreateType(cast<FunctionType>(Ty), Unit);
2152 case Type::ConstantArray:
2153 case Type::VariableArray:
2154 case Type::IncompleteArray:
2155 return CreateType(cast<ArrayType>(Ty), Unit);
2156
2157 case Type::LValueReference:
2158 return CreateType(cast<LValueReferenceType>(Ty), Unit);
2159 case Type::RValueReference:
2160 return CreateType(cast<RValueReferenceType>(Ty), Unit);
2161
2162 case Type::MemberPointer:
2163 return CreateType(cast<MemberPointerType>(Ty), Unit);
2164
2165 case Type::Atomic:
2166 return CreateType(cast<AtomicType>(Ty), Unit);
2167
2168 case Type::Attributed:
2169 case Type::TemplateSpecialization:
2170 case Type::Elaborated:
2171 case Type::Paren:
2172 case Type::SubstTemplateTypeParm:
2173 case Type::TypeOfExpr:
2174 case Type::TypeOf:
2175 case Type::Decltype:
2176 case Type::UnaryTransform:
David Blaikie226399c2013-07-13 21:08:08 +00002177 case Type::PackExpansion:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002178 llvm_unreachable("type should have been unwrapped!");
David Blaikie91296482013-05-24 21:24:35 +00002179 case Type::Auto:
2180 Diag = "auto";
2181 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002182 }
Eric Christopher6537f082013-05-16 00:45:12 +00002183
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002184 assert(Diag && "Fall through without a diagnostic?");
2185 unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error,
2186 "debug information for %0 is not yet supported");
2187 CGM.getDiags().Report(DiagID)
2188 << Diag;
2189 return llvm::DIType();
2190}
2191
2192/// getOrCreateLimitedType - Get the type from the cache or create a new
2193/// limited type if necessary.
David Blaikie4a077162013-08-12 22:24:20 +00002194llvm::DIType CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002195 llvm::DIFile Unit) {
David Blaikie4a077162013-08-12 22:24:20 +00002196 QualType QTy(Ty, 0);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002197
David Blaikie4a077162013-08-12 22:24:20 +00002198 llvm::DIType T = getTypeOrNull(QTy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002199
2200 // We may have cached a forward decl when we could have created
2201 // a non-forward decl. Go ahead and create a non-forward decl
2202 // now.
Eric Christopherb2d13922013-07-18 00:52:50 +00002203 if (T && !T.isForwardDecl()) return T;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002204
2205 // Otherwise create the type.
David Blaikie4a077162013-08-12 22:24:20 +00002206 llvm::DIType Res = CreateLimitedType(Ty);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002207
Eric Christopherb2d13922013-07-18 00:52:50 +00002208 if (T && T.isForwardDecl())
David Blaikie4a077162013-08-12 22:24:20 +00002209 ReplaceMap.push_back(
2210 std::make_pair(QTy.getAsOpaquePtr(), static_cast<llvm::Value *>(T)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002211
2212 // And update the type cache.
David Blaikie4a077162013-08-12 22:24:20 +00002213 TypeCache[QTy.getAsOpaquePtr()] = Res;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002214 return Res;
2215}
2216
2217// TODO: Currently used for context chains when limiting debug info.
2218llvm::DIType CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
2219 RecordDecl *RD = Ty->getDecl();
Eric Christopher6537f082013-05-16 00:45:12 +00002220
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002221 // Get overall information about the record type for the debug info.
2222 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
2223 unsigned Line = getLineNumber(RD->getLocation());
2224 StringRef RDName = getClassName(RD);
2225
2226 llvm::DIDescriptor RDContext;
Eric Christopher13c97672013-05-16 00:45:23 +00002227 if (DebugKind == CodeGenOptions::LimitedDebugInfo)
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002228 RDContext = createContextChain(cast<Decl>(RD->getDeclContext()));
2229 else
2230 RDContext = getContextDescriptor(cast<Decl>(RD->getDeclContext()));
2231
David Blaikiec138ff52013-08-18 17:36:19 +00002232 // If we ended up creating the type during the context chain construction,
2233 // just return that.
2234 // FIXME: this could be dealt with better if the type was recorded as
2235 // completed before we started this (see the CompletedTypeCache usage in
2236 // CGDebugInfo::CreateTypeDefinition(const RecordType*) - that would need to
2237 // be pushed to before context creation, but after it was known to be
2238 // destined for completion (might still have an issue if this caller only
2239 // required a declaration but the context construction ended up creating a
2240 // definition)
2241 if (llvm::DIType T = getTypeOrNull(CGM.getContext().getRecordType(RD)))
2242 if (!T.isForwardDecl() || !RD->getDefinition())
2243 return T;
2244
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002245 // If this is just a forward declaration, construct an appropriately
2246 // marked node and just return it.
2247 if (!RD->getDefinition())
David Blaikie951094b2013-08-15 18:59:40 +00002248 return getOrCreateRecordFwdDecl(RD, RDContext);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002249
2250 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2251 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
David Blaikie2fcadbe2013-03-26 23:47:35 +00002252 llvm::DICompositeType RealDecl;
Eric Christopher6537f082013-05-16 00:45:12 +00002253
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002254 if (RD->isUnion())
2255 RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002256 Size, Align, 0, llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002257 else if (RD->isClass()) {
2258 // FIXME: This could be a struct type giving a default visibility different
2259 // than C++ class type, but needs llvm metadata changes first.
2260 RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002261 Size, Align, 0, 0, llvm::DIType(),
2262 llvm::DIArray(), llvm::DIType(),
2263 llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002264 } else
2265 RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line,
Eric Christopherf0890c42013-05-16 00:52:20 +00002266 Size, Align, 0, llvm::DIType(),
2267 llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002268
2269 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
David Blaikie2fcadbe2013-03-26 23:47:35 +00002270 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002271
David Blaikie498298d2013-08-18 16:55:33 +00002272 if (const ClassTemplateSpecializationDecl *TSpecial =
2273 dyn_cast<ClassTemplateSpecializationDecl>(RD))
2274 RealDecl.setTypeArray(llvm::DIArray(),
2275 CollectCXXTemplateParams(TSpecial, DefUnit));
David Blaikiefab829d2013-08-15 22:42:12 +00002276 return RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002277}
2278
David Blaikie498298d2013-08-18 16:55:33 +00002279void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,
2280 llvm::DICompositeType RealDecl) {
2281 // A class's primary base or the class itself contains the vtable.
2282 llvm::DICompositeType ContainingType;
2283 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2284 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
2285 // Seek non virtual primary base root.
2286 while (1) {
2287 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
2288 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
2289 if (PBT && !BRL.isPrimaryBaseVirtual())
2290 PBase = PBT;
2291 else
2292 break;
2293 }
2294 ContainingType = llvm::DICompositeType(
2295 getOrCreateType(QualType(PBase->getTypeForDecl(), 0),
2296 getOrCreateFile(RD->getLocation())));
2297 } else if (RD->isDynamicClass())
2298 ContainingType = RealDecl;
2299
2300 RealDecl.setContainingType(ContainingType);
2301}
2302
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002303/// CreateMemberType - Create new member and increase Offset by FType's size.
2304llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
2305 StringRef Name,
2306 uint64_t *Offset) {
2307 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2308 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
2309 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
2310 llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0,
2311 FieldSize, FieldAlign,
2312 *Offset, 0, FieldTy);
2313 *Offset += FieldSize;
2314 return Ty;
2315}
2316
David Blaikie9faebd22013-05-20 04:58:53 +00002317llvm::DIDescriptor CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
2318 // We only need a declaration (not a definition) of the type - so use whatever
2319 // we would otherwise do to get a type for a pointee. (forward declarations in
2320 // limited debug info, full definitions (if the type definition is available)
2321 // in unlimited debug info)
David Blaikieb3c23772013-08-12 23:14:36 +00002322 if (const TypeDecl *TD = dyn_cast<TypeDecl>(D))
2323 return getOrCreateType(CGM.getContext().getTypeDeclType(TD),
2324 getOrCreateFile(TD->getLocation()), true);
David Blaikie9faebd22013-05-20 04:58:53 +00002325 // Otherwise fall back to a fairly rudimentary cache of existing declarations.
2326 // This doesn't handle providing declarations (for functions or variables) for
2327 // entities without definitions in this TU, nor when the definition proceeds
2328 // the call to this function.
2329 // FIXME: This should be split out into more specific maps with support for
2330 // emitting forward declarations and merging definitions with declarations,
2331 // the same way as we do for types.
2332 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator I =
2333 DeclCache.find(D->getCanonicalDecl());
2334 if (I == DeclCache.end())
2335 return llvm::DIDescriptor();
2336 llvm::Value *V = I->second;
2337 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
2338}
2339
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002340/// getFunctionDeclaration - Return debug info descriptor to describe method
2341/// declaration for the given method definition.
2342llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
David Blaikie23e66db2013-06-22 00:09:36 +00002343 if (!D || DebugKind == CodeGenOptions::DebugLineTablesOnly)
2344 return llvm::DISubprogram();
2345
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002346 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
2347 if (!FD) return llvm::DISubprogram();
2348
2349 // Setup context.
David Blaikied6d5d692013-08-09 17:20:05 +00002350 llvm::DIScope S = getContextDescriptor(cast<Decl>(D->getDeclContext()));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002351
2352 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2353 MI = SPCache.find(FD->getCanonicalDecl());
David Blaikied6d5d692013-08-09 17:20:05 +00002354 if (MI == SPCache.end()) {
David Blaikie5434fc22013-08-20 01:28:15 +00002355 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
David Blaikied6d5d692013-08-09 17:20:05 +00002356 llvm::DICompositeType T(S);
2357 llvm::DISubprogram SP = CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()), T);
2358 T.addMember(SP);
2359 return SP;
2360 }
2361 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002362 if (MI != SPCache.end()) {
2363 llvm::Value *V = MI->second;
2364 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
David Blaikie23e66db2013-06-22 00:09:36 +00002365 if (SP.isSubprogram() && !SP.isDefinition())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002366 return SP;
2367 }
2368
2369 for (FunctionDecl::redecl_iterator I = FD->redecls_begin(),
2370 E = FD->redecls_end(); I != E; ++I) {
2371 const FunctionDecl *NextFD = *I;
2372 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2373 MI = SPCache.find(NextFD->getCanonicalDecl());
2374 if (MI != SPCache.end()) {
2375 llvm::Value *V = MI->second;
2376 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
David Blaikie23e66db2013-06-22 00:09:36 +00002377 if (SP.isSubprogram() && !SP.isDefinition())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002378 return SP;
2379 }
2380 }
2381 return llvm::DISubprogram();
2382}
2383
2384// getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
2385// implicit parameter "this".
David Blaikie9a845292013-05-22 23:22:42 +00002386llvm::DICompositeType CGDebugInfo::getOrCreateFunctionType(const Decl *D,
2387 QualType FnType,
2388 llvm::DIFile F) {
David Blaikie23e66db2013-06-22 00:09:36 +00002389 if (!D || DebugKind == CodeGenOptions::DebugLineTablesOnly)
2390 // Create fake but valid subroutine type. Otherwise
2391 // llvm::DISubprogram::Verify() would return false, and
2392 // subprogram DIE will miss DW_AT_decl_file and
2393 // DW_AT_decl_line fields.
2394 return DBuilder.createSubroutineType(F, DBuilder.getOrCreateArray(None));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002395
2396 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
2397 return getOrCreateMethodType(Method, F);
2398 if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
2399 // Add "self" and "_cmd"
2400 SmallVector<llvm::Value *, 16> Elts;
2401
2402 // First element is always return type. For 'void' functions it is NULL.
Adrian Prantl0cb00022013-05-22 21:37:49 +00002403 QualType ResultTy = OMethod->getResultType();
2404
2405 // Replace the instancetype keyword with the actual type.
2406 if (ResultTy == CGM.getContext().getObjCInstanceType())
2407 ResultTy = CGM.getContext().getPointerType(
2408 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
2409
Adrian Prantl566a9c32013-05-10 21:08:31 +00002410 Elts.push_back(getOrCreateType(ResultTy, F));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002411 // "self" pointer is always first argument.
Adrian Prantle86fcc42013-03-29 19:20:29 +00002412 QualType SelfDeclTy = OMethod->getSelfDecl()->getType();
2413 llvm::DIType SelfTy = getOrCreateType(SelfDeclTy, F);
2414 Elts.push_back(CreateSelfType(SelfDeclTy, SelfTy));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002415 // "_cmd" pointer is always second argument.
2416 llvm::DIType CmdTy = getOrCreateType(OMethod->getCmdDecl()->getType(), F);
2417 Elts.push_back(DBuilder.createArtificialType(CmdTy));
2418 // Get rest of the arguments.
Eric Christopher6537f082013-05-16 00:45:12 +00002419 for (ObjCMethodDecl::param_const_iterator PI = OMethod->param_begin(),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002420 PE = OMethod->param_end(); PI != PE; ++PI)
2421 Elts.push_back(getOrCreateType((*PI)->getType(), F));
2422
2423 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2424 return DBuilder.createSubroutineType(F, EltTypeArray);
2425 }
David Blaikie9a845292013-05-22 23:22:42 +00002426 return llvm::DICompositeType(getOrCreateType(FnType, F));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002427}
2428
2429/// EmitFunctionStart - Constructs the debug code for entering a function.
2430void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
2431 llvm::Function *Fn,
2432 CGBuilderTy &Builder) {
2433
2434 StringRef Name;
2435 StringRef LinkageName;
2436
2437 FnBeginRegionCount.push_back(LexicalBlockStack.size());
2438
2439 const Decl *D = GD.getDecl();
2440 // Function may lack declaration in source code if it is created by Clang
2441 // CodeGen (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
2442 bool HasDecl = (D != 0);
2443 // Use the location of the declaration.
2444 SourceLocation Loc;
2445 if (HasDecl)
2446 Loc = D->getLocation();
2447
2448 unsigned Flags = 0;
2449 llvm::DIFile Unit = getOrCreateFile(Loc);
2450 llvm::DIDescriptor FDContext(Unit);
2451 llvm::DIArray TParamsArray;
2452 if (!HasDecl) {
2453 // Use llvm function name.
2454 Name = Fn->getName();
2455 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2456 // If there is a DISubprogram for this function available then use it.
2457 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2458 FI = SPCache.find(FD->getCanonicalDecl());
2459 if (FI != SPCache.end()) {
2460 llvm::Value *V = FI->second;
2461 llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(V));
2462 if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
2463 llvm::MDNode *SPN = SP;
2464 LexicalBlockStack.push_back(SPN);
2465 RegionMap[D] = llvm::WeakVH(SP);
2466 return;
2467 }
2468 }
2469 Name = getFunctionName(FD);
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002470 // Use mangled name as linkage name for C/C++ functions.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002471 if (FD->hasPrototype()) {
2472 LinkageName = CGM.getMangledName(GD);
2473 Flags |= llvm::DIDescriptor::FlagPrototyped;
2474 }
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002475 // No need to replicate the linkage name if it isn't different from the
2476 // subprogram name, no need to have it at all unless coverage is enabled or
2477 // debug is set to more than just line tables.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002478 if (LinkageName == Name ||
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002479 (!CGM.getCodeGenOpts().EmitGcovArcs &&
2480 !CGM.getCodeGenOpts().EmitGcovNotes &&
Eric Christopher13c97672013-05-16 00:45:23 +00002481 DebugKind <= CodeGenOptions::DebugLineTablesOnly))
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002482 LinkageName = StringRef();
2483
Eric Christopher13c97672013-05-16 00:45:23 +00002484 if (DebugKind >= CodeGenOptions::LimitedDebugInfo) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002485 if (const NamespaceDecl *NSDecl =
2486 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
2487 FDContext = getOrCreateNameSpace(NSDecl);
2488 else if (const RecordDecl *RDecl =
2489 dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
2490 FDContext = getContextDescriptor(cast<Decl>(RDecl->getDeclContext()));
2491
2492 // Collect template parameters.
2493 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
2494 }
2495 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
2496 Name = getObjCMethodName(OMD);
2497 Flags |= llvm::DIDescriptor::FlagPrototyped;
2498 } else {
2499 // Use llvm function name.
2500 Name = Fn->getName();
2501 Flags |= llvm::DIDescriptor::FlagPrototyped;
2502 }
2503 if (!Name.empty() && Name[0] == '\01')
2504 Name = Name.substr(1);
2505
2506 unsigned LineNo = getLineNumber(Loc);
2507 if (!HasDecl || D->isImplicit())
2508 Flags |= llvm::DIDescriptor::FlagArtificial;
2509
David Blaikie23e66db2013-06-22 00:09:36 +00002510 llvm::DISubprogram SP = DBuilder.createFunction(
2511 FDContext, Name, LinkageName, Unit, LineNo,
2512 getOrCreateFunctionType(D, FnType, Unit), Fn->hasInternalLinkage(),
2513 true /*definition*/, getLineNumber(CurLoc), Flags,
2514 CGM.getLangOpts().Optimize, Fn, TParamsArray, getFunctionDeclaration(D));
David Blaikie9faebd22013-05-20 04:58:53 +00002515 if (HasDecl)
2516 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(SP)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002517
2518 // Push function on region stack.
2519 llvm::MDNode *SPN = SP;
2520 LexicalBlockStack.push_back(SPN);
2521 if (HasDecl)
2522 RegionMap[D] = llvm::WeakVH(SP);
2523}
2524
2525/// EmitLocation - Emit metadata to indicate a change in line/column
Adrian Prantl18a0cd52013-07-18 00:27:59 +00002526/// information in the source file. If the location is invalid, the
2527/// previous location will be reused.
Adrian Prantl00df5ea2013-03-12 20:43:25 +00002528void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc,
2529 bool ForceColumnInfo) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002530 // Update our current location
2531 setLocation(Loc);
2532
2533 if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
2534
2535 // Don't bother if things are the same as last time.
2536 SourceManager &SM = CGM.getContext().getSourceManager();
2537 if (CurLoc == PrevLoc ||
2538 SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc))
2539 // New Builder may not be in sync with CGDebugInfo.
David Blaikie0a0f93c2013-02-01 19:09:49 +00002540 if (!Builder.getCurrentDebugLocation().isUnknown() &&
2541 Builder.getCurrentDebugLocation().getScope(CGM.getLLVMContext()) ==
2542 LexicalBlockStack.back())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002543 return;
Eric Christopher6537f082013-05-16 00:45:12 +00002544
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002545 // Update last state.
2546 PrevLoc = CurLoc;
2547
2548 llvm::MDNode *Scope = LexicalBlockStack.back();
Adrian Prantl00df5ea2013-03-12 20:43:25 +00002549 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get
2550 (getLineNumber(CurLoc),
2551 getColumnNumber(CurLoc, ForceColumnInfo),
2552 Scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002553}
2554
2555/// CreateLexicalBlock - Creates a new lexical block node and pushes it on
2556/// the stack.
2557void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
2558 llvm::DIDescriptor D =
2559 DBuilder.createLexicalBlock(LexicalBlockStack.empty() ?
2560 llvm::DIDescriptor() :
2561 llvm::DIDescriptor(LexicalBlockStack.back()),
2562 getOrCreateFile(CurLoc),
2563 getLineNumber(CurLoc),
2564 getColumnNumber(CurLoc));
2565 llvm::MDNode *DN = D;
2566 LexicalBlockStack.push_back(DN);
2567}
2568
2569/// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
2570/// region - beginning of a DW_TAG_lexical_block.
Eric Christopherf0890c42013-05-16 00:52:20 +00002571void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
2572 SourceLocation Loc) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002573 // Set our current location.
2574 setLocation(Loc);
2575
2576 // Create a new lexical block and push it on the stack.
2577 CreateLexicalBlock(Loc);
2578
2579 // Emit a line table change for the current location inside the new scope.
2580 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc),
2581 getColumnNumber(Loc),
2582 LexicalBlockStack.back()));
2583}
2584
2585/// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative
2586/// region - end of a DW_TAG_lexical_block.
Eric Christopherf0890c42013-05-16 00:52:20 +00002587void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
2588 SourceLocation Loc) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002589 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2590
2591 // Provide an entry in the line table for the end of the block.
2592 EmitLocation(Builder, Loc);
2593
2594 LexicalBlockStack.pop_back();
2595}
2596
2597/// EmitFunctionEnd - Constructs the debug code for exiting a function.
2598void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
2599 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2600 unsigned RCount = FnBeginRegionCount.back();
2601 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
2602
2603 // Pop all regions for this function.
2604 while (LexicalBlockStack.size() != RCount)
2605 EmitLexicalBlockEnd(Builder, CurLoc);
2606 FnBeginRegionCount.pop_back();
2607}
2608
Eric Christopher6537f082013-05-16 00:45:12 +00002609// EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002610// See BuildByRefType.
2611llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
2612 uint64_t *XOffset) {
2613
2614 SmallVector<llvm::Value *, 5> EltTys;
2615 QualType FType;
2616 uint64_t FieldSize, FieldOffset;
2617 unsigned FieldAlign;
Eric Christopher6537f082013-05-16 00:45:12 +00002618
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002619 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
Eric Christopher6537f082013-05-16 00:45:12 +00002620 QualType Type = VD->getType();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002621
2622 FieldOffset = 0;
2623 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2624 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
2625 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
2626 FType = CGM.getContext().IntTy;
2627 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
2628 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
2629
2630 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
2631 if (HasCopyAndDispose) {
2632 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2633 EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
2634 &FieldOffset));
2635 EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
2636 &FieldOffset));
2637 }
2638 bool HasByrefExtendedLayout;
2639 Qualifiers::ObjCLifetime Lifetime;
2640 if (CGM.getContext().getByrefLifetime(Type,
2641 Lifetime, HasByrefExtendedLayout)
Adrian Prantl1f437912013-07-23 00:12:14 +00002642 && HasByrefExtendedLayout) {
2643 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002644 EltTys.push_back(CreateMemberType(Unit, FType,
2645 "__byref_variable_layout",
2646 &FieldOffset));
Adrian Prantl1f437912013-07-23 00:12:14 +00002647 }
Eric Christopher6537f082013-05-16 00:45:12 +00002648
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002649 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2650 if (Align > CGM.getContext().toCharUnitsFromBits(
John McCall64aa4b32013-04-16 22:48:15 +00002651 CGM.getTarget().getPointerAlign(0))) {
Eric Christopher6537f082013-05-16 00:45:12 +00002652 CharUnits FieldOffsetInBytes
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002653 = CGM.getContext().toCharUnitsFromBits(FieldOffset);
2654 CharUnits AlignedOffsetInBytes
2655 = FieldOffsetInBytes.RoundUpToAlignment(Align);
2656 CharUnits NumPaddingBytes
2657 = AlignedOffsetInBytes - FieldOffsetInBytes;
Eric Christopher6537f082013-05-16 00:45:12 +00002658
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002659 if (NumPaddingBytes.isPositive()) {
2660 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
2661 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
2662 pad, ArrayType::Normal, 0);
2663 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
2664 }
2665 }
Eric Christopher6537f082013-05-16 00:45:12 +00002666
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002667 FType = Type;
2668 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2669 FieldSize = CGM.getContext().getTypeSize(FType);
2670 FieldAlign = CGM.getContext().toBits(Align);
2671
Eric Christopher6537f082013-05-16 00:45:12 +00002672 *XOffset = FieldOffset;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002673 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit,
2674 0, FieldSize, FieldAlign,
2675 FieldOffset, 0, FieldTy);
2676 EltTys.push_back(FieldTy);
2677 FieldOffset += FieldSize;
Eric Christopher6537f082013-05-16 00:45:12 +00002678
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002679 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopher6537f082013-05-16 00:45:12 +00002680
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002681 unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
Eric Christopher6537f082013-05-16 00:45:12 +00002682
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002683 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
David Blaikiec1d0af12013-02-25 01:07:08 +00002684 llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002685}
2686
2687/// EmitDeclare - Emit local variable declaration debug info.
2688void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
Eric Christopher6537f082013-05-16 00:45:12 +00002689 llvm::Value *Storage,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002690 unsigned ArgNo, CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002691 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002692 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2693
David Blaikiefc946272013-08-19 03:37:48 +00002694 bool Unwritten =
2695 VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) &&
2696 cast<Decl>(VD->getDeclContext())->isImplicit());
2697 llvm::DIFile Unit;
2698 if (!Unwritten)
2699 Unit = getOrCreateFile(VD->getLocation());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002700 llvm::DIType Ty;
2701 uint64_t XOffset = 0;
2702 if (VD->hasAttr<BlocksAttr>())
2703 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopher6537f082013-05-16 00:45:12 +00002704 else
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002705 Ty = getOrCreateType(VD->getType(), Unit);
2706
2707 // If there is no debug info for this type then do not emit debug info
2708 // for this variable.
2709 if (!Ty)
2710 return;
2711
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002712 // Get location information.
David Blaikiefc946272013-08-19 03:37:48 +00002713 unsigned Line = 0;
2714 unsigned Column = 0;
2715 if (!Unwritten) {
2716 Line = getLineNumber(VD->getLocation());
2717 Column = getColumnNumber(VD->getLocation());
2718 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002719 unsigned Flags = 0;
2720 if (VD->isImplicit())
2721 Flags |= llvm::DIDescriptor::FlagArtificial;
2722 // If this is the first argument and it is implicit then
2723 // give it an object pointer flag.
2724 // FIXME: There has to be a better way to do this, but for static
2725 // functions there won't be an implicit param at arg1 and
2726 // otherwise it is 'self' or 'this'.
2727 if (isa<ImplicitParamDecl>(VD) && ArgNo == 1)
2728 Flags |= llvm::DIDescriptor::FlagObjectPointer;
David Blaikie41c9bae2013-06-19 21:53:53 +00002729 if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage))
Eric Christopher7dab97b2013-07-17 22:52:53 +00002730 if (Arg->getType()->isPointerTy() && !Arg->hasByValAttr() &&
2731 !VD->getType()->isPointerType())
David Blaikie41c9bae2013-06-19 21:53:53 +00002732 Flags |= llvm::DIDescriptor::FlagIndirectVariable;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002733
2734 llvm::MDNode *Scope = LexicalBlockStack.back();
2735
2736 StringRef Name = VD->getName();
2737 if (!Name.empty()) {
2738 if (VD->hasAttr<BlocksAttr>()) {
2739 CharUnits offset = CharUnits::fromQuantity(32);
2740 SmallVector<llvm::Value *, 9> addr;
2741 llvm::Type *Int64Ty = CGM.Int64Ty;
2742 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2743 // offset of __forwarding field
2744 offset = CGM.getContext().toCharUnitsFromBits(
John McCall64aa4b32013-04-16 22:48:15 +00002745 CGM.getTarget().getPointerWidth(0));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002746 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2747 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2748 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2749 // offset of x field
2750 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2751 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2752
2753 // Create the descriptor for the variable.
2754 llvm::DIVariable D =
Eric Christopher6537f082013-05-16 00:45:12 +00002755 DBuilder.createComplexVariable(Tag,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002756 llvm::DIDescriptor(Scope),
2757 VD->getName(), Unit, Line, Ty,
2758 addr, ArgNo);
Eric Christopher6537f082013-05-16 00:45:12 +00002759
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002760 // Insert an llvm.dbg.declare into the current block.
2761 llvm::Instruction *Call =
2762 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2763 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2764 return;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002765 }
David Blaikie436653b2013-01-05 05:58:35 +00002766 } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2767 // If VD is an anonymous union then Storage represents value for
2768 // all union fields.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002769 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
David Blaikied8180cf2013-01-05 20:03:07 +00002770 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002771 for (RecordDecl::field_iterator I = RD->field_begin(),
2772 E = RD->field_end();
2773 I != E; ++I) {
2774 FieldDecl *Field = *I;
2775 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2776 StringRef FieldName = Field->getName();
Eric Christopher6537f082013-05-16 00:45:12 +00002777
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002778 // Ignore unnamed fields. Do not ignore unnamed records.
2779 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2780 continue;
Eric Christopher6537f082013-05-16 00:45:12 +00002781
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002782 // Use VarDecl's Tag, Scope and Line number.
2783 llvm::DIVariable D =
2784 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
Eric Christopher6537f082013-05-16 00:45:12 +00002785 FieldName, Unit, Line, FieldTy,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002786 CGM.getLangOpts().Optimize, Flags,
2787 ArgNo);
Eric Christopher6537f082013-05-16 00:45:12 +00002788
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002789 // Insert an llvm.dbg.declare into the current block.
2790 llvm::Instruction *Call =
2791 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2792 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2793 }
David Blaikied8180cf2013-01-05 20:03:07 +00002794 return;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002795 }
2796 }
David Blaikie436653b2013-01-05 05:58:35 +00002797
2798 // Create the descriptor for the variable.
2799 llvm::DIVariable D =
2800 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2801 Name, Unit, Line, Ty,
2802 CGM.getLangOpts().Optimize, Flags, ArgNo);
2803
2804 // Insert an llvm.dbg.declare into the current block.
2805 llvm::Instruction *Call =
2806 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2807 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002808}
2809
2810void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2811 llvm::Value *Storage,
2812 CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002813 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002814 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2815}
2816
Adrian Prantle86fcc42013-03-29 19:20:29 +00002817/// Look up the completed type for a self pointer in the TypeCache and
2818/// create a copy of it with the ObjectPointer and Artificial flags
2819/// set. If the type is not cached, a new one is created. This should
2820/// never happen though, since creating a type for the implicit self
2821/// argument implies that we already parsed the interface definition
2822/// and the ivar declarations in the implementation.
Eric Christopherf0890c42013-05-16 00:52:20 +00002823llvm::DIType CGDebugInfo::CreateSelfType(const QualType &QualTy,
2824 llvm::DIType Ty) {
Adrian Prantle86fcc42013-03-29 19:20:29 +00002825 llvm::DIType CachedTy = getTypeOrNull(QualTy);
Eric Christopherb2d13922013-07-18 00:52:50 +00002826 if (CachedTy) Ty = CachedTy;
Adrian Prantle86fcc42013-03-29 19:20:29 +00002827 else DEBUG(llvm::dbgs() << "No cached type for self.");
2828 return DBuilder.createObjectPointerType(Ty);
2829}
2830
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002831void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(const VarDecl *VD,
2832 llvm::Value *Storage,
2833 CGBuilderTy &Builder,
2834 const CGBlockInfo &blockInfo) {
Eric Christopher13c97672013-05-16 00:45:23 +00002835 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002836 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
Eric Christopher6537f082013-05-16 00:45:12 +00002837
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002838 if (Builder.GetInsertBlock() == 0)
2839 return;
Eric Christopher6537f082013-05-16 00:45:12 +00002840
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002841 bool isByRef = VD->hasAttr<BlocksAttr>();
Eric Christopher6537f082013-05-16 00:45:12 +00002842
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002843 uint64_t XOffset = 0;
2844 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2845 llvm::DIType Ty;
2846 if (isByRef)
2847 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopher6537f082013-05-16 00:45:12 +00002848 else
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002849 Ty = getOrCreateType(VD->getType(), Unit);
2850
2851 // Self is passed along as an implicit non-arg variable in a
2852 // block. Mark it as the object pointer.
2853 if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self")
Adrian Prantle86fcc42013-03-29 19:20:29 +00002854 Ty = CreateSelfType(VD->getType(), Ty);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002855
2856 // Get location information.
2857 unsigned Line = getLineNumber(VD->getLocation());
2858 unsigned Column = getColumnNumber(VD->getLocation());
2859
2860 const llvm::DataLayout &target = CGM.getDataLayout();
2861
2862 CharUnits offset = CharUnits::fromQuantity(
2863 target.getStructLayout(blockInfo.StructureType)
2864 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2865
2866 SmallVector<llvm::Value *, 9> addr;
2867 llvm::Type *Int64Ty = CGM.Int64Ty;
Adrian Prantl9b97adf2013-03-29 19:20:35 +00002868 if (isa<llvm::AllocaInst>(Storage))
2869 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002870 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2871 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2872 if (isByRef) {
2873 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2874 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2875 // offset of __forwarding field
2876 offset = CGM.getContext()
2877 .toCharUnitsFromBits(target.getPointerSizeInBits(0));
2878 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2879 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2880 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2881 // offset of x field
2882 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2883 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2884 }
2885
2886 // Create the descriptor for the variable.
2887 llvm::DIVariable D =
Eric Christopher6537f082013-05-16 00:45:12 +00002888 DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002889 llvm::DIDescriptor(LexicalBlockStack.back()),
2890 VD->getName(), Unit, Line, Ty, addr);
Adrian Prantl9b97adf2013-03-29 19:20:35 +00002891
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002892 // Insert an llvm.dbg.declare into the current block.
2893 llvm::Instruction *Call =
2894 DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
2895 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column,
2896 LexicalBlockStack.back()));
2897}
2898
2899/// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2900/// variable declaration.
2901void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2902 unsigned ArgNo,
2903 CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002904 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002905 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2906}
2907
2908namespace {
2909 struct BlockLayoutChunk {
2910 uint64_t OffsetInBits;
2911 const BlockDecl::Capture *Capture;
2912 };
2913 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2914 return l.OffsetInBits < r.OffsetInBits;
2915 }
2916}
2917
2918void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
Adrian Prantl836e7c92013-03-14 17:53:33 +00002919 llvm::Value *Arg,
2920 llvm::Value *LocalAddr,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002921 CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002922 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002923 ASTContext &C = CGM.getContext();
2924 const BlockDecl *blockDecl = block.getBlockDecl();
2925
2926 // Collect some general information about the block's location.
2927 SourceLocation loc = blockDecl->getCaretLocation();
2928 llvm::DIFile tunit = getOrCreateFile(loc);
2929 unsigned line = getLineNumber(loc);
2930 unsigned column = getColumnNumber(loc);
Eric Christopher6537f082013-05-16 00:45:12 +00002931
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002932 // Build the debug-info type for the block literal.
2933 getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
2934
2935 const llvm::StructLayout *blockLayout =
2936 CGM.getDataLayout().getStructLayout(block.StructureType);
2937
2938 SmallVector<llvm::Value*, 16> fields;
2939 fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
2940 blockLayout->getElementOffsetInBits(0),
2941 tunit, tunit));
2942 fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
2943 blockLayout->getElementOffsetInBits(1),
2944 tunit, tunit));
2945 fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
2946 blockLayout->getElementOffsetInBits(2),
2947 tunit, tunit));
2948 fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
2949 blockLayout->getElementOffsetInBits(3),
2950 tunit, tunit));
2951 fields.push_back(createFieldType("__descriptor",
2952 C.getPointerType(block.NeedsCopyDispose ?
2953 C.getBlockDescriptorExtendedType() :
2954 C.getBlockDescriptorType()),
2955 0, loc, AS_public,
2956 blockLayout->getElementOffsetInBits(4),
2957 tunit, tunit));
2958
2959 // We want to sort the captures by offset, not because DWARF
2960 // requires this, but because we're paranoid about debuggers.
2961 SmallVector<BlockLayoutChunk, 8> chunks;
2962
2963 // 'this' capture.
2964 if (blockDecl->capturesCXXThis()) {
2965 BlockLayoutChunk chunk;
2966 chunk.OffsetInBits =
2967 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
2968 chunk.Capture = 0;
2969 chunks.push_back(chunk);
2970 }
2971
2972 // Variable captures.
2973 for (BlockDecl::capture_const_iterator
2974 i = blockDecl->capture_begin(), e = blockDecl->capture_end();
2975 i != e; ++i) {
2976 const BlockDecl::Capture &capture = *i;
2977 const VarDecl *variable = capture.getVariable();
2978 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
2979
2980 // Ignore constant captures.
2981 if (captureInfo.isConstant())
2982 continue;
2983
2984 BlockLayoutChunk chunk;
2985 chunk.OffsetInBits =
2986 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
2987 chunk.Capture = &capture;
2988 chunks.push_back(chunk);
2989 }
2990
2991 // Sort by offset.
2992 llvm::array_pod_sort(chunks.begin(), chunks.end());
2993
2994 for (SmallVectorImpl<BlockLayoutChunk>::iterator
2995 i = chunks.begin(), e = chunks.end(); i != e; ++i) {
2996 uint64_t offsetInBits = i->OffsetInBits;
2997 const BlockDecl::Capture *capture = i->Capture;
2998
2999 // If we have a null capture, this must be the C++ 'this' capture.
3000 if (!capture) {
3001 const CXXMethodDecl *method =
3002 cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
3003 QualType type = method->getThisType(C);
3004
3005 fields.push_back(createFieldType("this", type, 0, loc, AS_public,
3006 offsetInBits, tunit, tunit));
3007 continue;
3008 }
3009
3010 const VarDecl *variable = capture->getVariable();
3011 StringRef name = variable->getName();
3012
3013 llvm::DIType fieldType;
3014 if (capture->isByRef()) {
3015 std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
3016
3017 // FIXME: this creates a second copy of this type!
3018 uint64_t xoffset;
3019 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
3020 fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
3021 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
3022 ptrInfo.first, ptrInfo.second,
3023 offsetInBits, 0, fieldType);
3024 } else {
3025 fieldType = createFieldType(name, variable->getType(), 0,
3026 loc, AS_public, offsetInBits, tunit, tunit);
3027 }
3028 fields.push_back(fieldType);
3029 }
3030
3031 SmallString<36> typeName;
3032 llvm::raw_svector_ostream(typeName)
3033 << "__block_literal_" << CGM.getUniqueBlockCount();
3034
3035 llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
3036
3037 llvm::DIType type =
3038 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
3039 CGM.getContext().toBits(block.BlockSize),
3040 CGM.getContext().toBits(block.BlockAlign),
David Blaikiec1d0af12013-02-25 01:07:08 +00003041 0, llvm::DIType(), fieldsArray);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003042 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
3043
3044 // Get overall information about the block.
3045 unsigned flags = llvm::DIDescriptor::FlagArtificial;
3046 llvm::MDNode *scope = LexicalBlockStack.back();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003047
3048 // Create the descriptor for the parameter.
3049 llvm::DIVariable debugVar =
3050 DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
Eric Christopher6537f082013-05-16 00:45:12 +00003051 llvm::DIDescriptor(scope),
Adrian Prantl836e7c92013-03-14 17:53:33 +00003052 Arg->getName(), tunit, line, type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003053 CGM.getLangOpts().Optimize, flags,
Adrian Prantl836e7c92013-03-14 17:53:33 +00003054 cast<llvm::Argument>(Arg)->getArgNo() + 1);
3055
Adrian Prantlbea407c2013-03-14 21:52:59 +00003056 if (LocalAddr) {
Adrian Prantl836e7c92013-03-14 17:53:33 +00003057 // Insert an llvm.dbg.value into the current block.
Adrian Prantlbea407c2013-03-14 21:52:59 +00003058 llvm::Instruction *DbgVal =
3059 DBuilder.insertDbgValueIntrinsic(LocalAddr, 0, debugVar,
Eric Christopherf068c922013-04-02 22:59:11 +00003060 Builder.GetInsertBlock());
Adrian Prantlbea407c2013-03-14 21:52:59 +00003061 DbgVal->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
3062 }
Adrian Prantl836e7c92013-03-14 17:53:33 +00003063
Adrian Prantlbea407c2013-03-14 21:52:59 +00003064 // Insert an llvm.dbg.declare into the current block.
3065 llvm::Instruction *DbgDecl =
3066 DBuilder.insertDeclare(Arg, debugVar, Builder.GetInsertBlock());
3067 DbgDecl->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003068}
3069
David Blaikie5434fc22013-08-20 01:28:15 +00003070/// If D is an out-of-class definition of a static data member of a class, find
3071/// its corresponding in-class declaration.
3072llvm::DIDerivedType
3073CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {
3074 if (!D->isStaticDataMember())
3075 return llvm::DIDerivedType();
3076 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator MI =
3077 StaticDataMemberCache.find(D->getCanonicalDecl());
3078 if (MI != StaticDataMemberCache.end()) {
3079 assert(MI->second && "Static data member declaration should still exist");
3080 return llvm::DIDerivedType(cast<llvm::MDNode>(MI->second));
Evgeniy Stepanov045a9f62013-08-16 10:35:31 +00003081 }
David Blaikie5434fc22013-08-20 01:28:15 +00003082 llvm::DICompositeType Ctxt(
3083 getContextDescriptor(cast<Decl>(D->getDeclContext())));
3084 llvm::DIDerivedType T = CreateRecordStaticField(D, Ctxt);
3085 Ctxt.addMember(T);
3086 return T;
3087}
3088
3089llvm::DIDerivedType
3090CGDebugInfo::getOrCreateStaticDataMemberDeclaration(const VarDecl *D,
3091 llvm::DICompositeType Ctxt) {
3092 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator MI =
3093 StaticDataMemberCache.find(D->getCanonicalDecl());
3094 if (MI != StaticDataMemberCache.end()) {
3095 assert(MI->second && "Static data member declaration should still exist");
3096 return llvm::DIDerivedType(cast<llvm::MDNode>(MI->second));
3097 }
3098 return CreateRecordStaticField(D, Ctxt);
Eric Christopher0395de32013-01-16 01:22:32 +00003099}
3100
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003101/// EmitGlobalVariable - Emit information about a global variable.
3102void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
3103 const VarDecl *D) {
Eric Christopher13c97672013-05-16 00:45:23 +00003104 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003105 // Create global variable debug descriptor.
3106 llvm::DIFile Unit = getOrCreateFile(D->getLocation());
3107 unsigned LineNo = getLineNumber(D->getLocation());
3108
3109 setLocation(D->getLocation());
3110
3111 QualType T = D->getType();
3112 if (T->isIncompleteArrayType()) {
3113
3114 // CodeGen turns int[] into int[1] so we'll do the same here.
3115 llvm::APInt ConstVal(32, 1);
3116 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3117
3118 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3119 ArrayType::Normal, 0);
3120 }
3121 StringRef DeclName = D->getName();
3122 StringRef LinkageName;
3123 if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext())
3124 && !isa<ObjCMethodDecl>(D->getDeclContext()))
3125 LinkageName = Var->getName();
3126 if (LinkageName == DeclName)
3127 LinkageName = StringRef();
Eric Christopher6537f082013-05-16 00:45:12 +00003128 llvm::DIDescriptor DContext =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003129 getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
David Blaikie5434fc22013-08-20 01:28:15 +00003130 llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(
3131 DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
3132 Var->hasInternalLinkage(), Var,
3133 getOrCreateStaticDataMemberDeclarationOrNull(D));
David Blaikie9faebd22013-05-20 04:58:53 +00003134 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(GV)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003135}
3136
3137/// EmitGlobalVariable - Emit information about an objective-c interface.
3138void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
3139 ObjCInterfaceDecl *ID) {
Eric Christopher13c97672013-05-16 00:45:23 +00003140 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003141 // Create global variable debug descriptor.
3142 llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
3143 unsigned LineNo = getLineNumber(ID->getLocation());
3144
3145 StringRef Name = ID->getName();
3146
3147 QualType T = CGM.getContext().getObjCInterfaceType(ID);
3148 if (T->isIncompleteArrayType()) {
3149
3150 // CodeGen turns int[] into int[1] so we'll do the same here.
3151 llvm::APInt ConstVal(32, 1);
3152 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3153
3154 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3155 ArrayType::Normal, 0);
3156 }
3157
3158 DBuilder.createGlobalVariable(Name, Unit, LineNo,
3159 getOrCreateType(T, Unit),
3160 Var->hasInternalLinkage(), Var);
3161}
3162
3163/// EmitGlobalVariable - Emit global variable's debug info.
Eric Christopher6537f082013-05-16 00:45:12 +00003164void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003165 llvm::Constant *Init) {
Eric Christopher13c97672013-05-16 00:45:23 +00003166 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003167 // Create the descriptor for the variable.
3168 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
3169 StringRef Name = VD->getName();
3170 llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
3171 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
3172 const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext());
3173 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
3174 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
3175 }
3176 // Do not use DIGlobalVariable for enums.
3177 if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
3178 return;
David Blaikie27ab0362013-08-15 21:42:43 +00003179 llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(
3180 Unit, Name, Name, Unit, getLineNumber(VD->getLocation()), Ty, true, Init,
David Blaikie5434fc22013-08-20 01:28:15 +00003181 getOrCreateStaticDataMemberDeclarationOrNull(cast<VarDecl>(VD)));
David Blaikie9faebd22013-05-20 04:58:53 +00003182 DeclCache.insert(std::make_pair(VD->getCanonicalDecl(), llvm::WeakVH(GV)));
3183}
3184
3185llvm::DIScope CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
3186 if (!LexicalBlockStack.empty())
3187 return llvm::DIScope(LexicalBlockStack.back());
3188 return getContextDescriptor(D);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003189}
3190
David Blaikie957dac52013-04-22 06:13:21 +00003191void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
David Blaikie9faebd22013-05-20 04:58:53 +00003192 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3193 return;
David Blaikie957dac52013-04-22 06:13:21 +00003194 DBuilder.createImportedModule(
David Blaikie9faebd22013-05-20 04:58:53 +00003195 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
3196 getOrCreateNameSpace(UD.getNominatedNamespace()),
David Blaikie957dac52013-04-22 06:13:21 +00003197 getLineNumber(UD.getLocation()));
3198}
3199
David Blaikie9faebd22013-05-20 04:58:53 +00003200void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
3201 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3202 return;
3203 assert(UD.shadow_size() &&
3204 "We shouldn't be codegening an invalid UsingDecl containing no decls");
3205 // Emitting one decl is sufficient - debuggers can detect that this is an
3206 // overloaded name & provide lookup for all the overloads.
3207 const UsingShadowDecl &USD = **UD.shadow_begin();
Eric Christopher56b108a2013-06-07 22:54:39 +00003208 if (llvm::DIDescriptor Target =
3209 getDeclarationOrDefinition(USD.getUnderlyingDecl()))
David Blaikie9faebd22013-05-20 04:58:53 +00003210 DBuilder.createImportedDeclaration(
3211 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
3212 getLineNumber(USD.getLocation()));
3213}
3214
David Blaikiefc46ebc2013-05-20 22:50:41 +00003215llvm::DIImportedEntity
3216CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
3217 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3218 return llvm::DIImportedEntity(0);
3219 llvm::WeakVH &VH = NamespaceAliasCache[&NA];
3220 if (VH)
3221 return llvm::DIImportedEntity(cast<llvm::MDNode>(VH));
3222 llvm::DIImportedEntity R(0);
3223 if (const NamespaceAliasDecl *Underlying =
3224 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
3225 // This could cache & dedup here rather than relying on metadata deduping.
3226 R = DBuilder.createImportedModule(
3227 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3228 EmitNamespaceAlias(*Underlying), getLineNumber(NA.getLocation()),
3229 NA.getName());
3230 else
3231 R = DBuilder.createImportedModule(
3232 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3233 getOrCreateNameSpace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
3234 getLineNumber(NA.getLocation()), NA.getName());
3235 VH = R;
3236 return R;
3237}
3238
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003239/// getOrCreateNamesSpace - Return namespace descriptor for the given
3240/// namespace decl.
Eric Christopher6537f082013-05-16 00:45:12 +00003241llvm::DINameSpace
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003242CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
David Blaikie8863e6b2013-08-16 22:52:07 +00003243 NSDecl = NSDecl->getCanonicalDecl();
Eric Christopher6537f082013-05-16 00:45:12 +00003244 llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003245 NameSpaceCache.find(NSDecl);
3246 if (I != NameSpaceCache.end())
3247 return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
Eric Christopher6537f082013-05-16 00:45:12 +00003248
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003249 unsigned LineNo = getLineNumber(NSDecl->getLocation());
3250 llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
Eric Christopher6537f082013-05-16 00:45:12 +00003251 llvm::DIDescriptor Context =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003252 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
3253 llvm::DINameSpace NS =
3254 DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
3255 NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
3256 return NS;
3257}
3258
3259void CGDebugInfo::finalize() {
3260 for (std::vector<std::pair<void *, llvm::WeakVH> >::const_iterator VI
3261 = ReplaceMap.begin(), VE = ReplaceMap.end(); VI != VE; ++VI) {
3262 llvm::DIType Ty, RepTy;
3263 // Verify that the debug info still exists.
3264 if (llvm::Value *V = VI->second)
3265 Ty = llvm::DIType(cast<llvm::MDNode>(V));
Eric Christopher6537f082013-05-16 00:45:12 +00003266
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003267 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
3268 TypeCache.find(VI->first);
3269 if (it != TypeCache.end()) {
3270 // Verify that the debug info still exists.
3271 if (llvm::Value *V = it->second)
3272 RepTy = llvm::DIType(cast<llvm::MDNode>(V));
3273 }
Adrian Prantlebbd7e02013-03-11 18:33:46 +00003274
Eric Christopherb2d13922013-07-18 00:52:50 +00003275 if (Ty && Ty.isForwardDecl() && RepTy)
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003276 Ty.replaceAllUsesWith(RepTy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003277 }
Adrian Prantlebbd7e02013-03-11 18:33:46 +00003278
3279 // We keep our own list of retained types, because we need to look
3280 // up the final type in the type cache.
3281 for (std::vector<void *>::const_iterator RI = RetainedTypes.begin(),
3282 RE = RetainedTypes.end(); RI != RE; ++RI)
3283 DBuilder.retainType(llvm::DIType(cast<llvm::MDNode>(TypeCache[*RI])));
3284
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003285 DBuilder.finalize();
3286}