blob: fd495fe77336d29b95cffe03e0061521750e431f [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.
David Blaikie47251962013-08-22 13:36:01 +0000546llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000547 QualifierCollector Qc;
548 const Type *T = Qc.strip(Ty);
549
550 // Ignore these qualifiers for now.
551 Qc.removeObjCGCAttr();
552 Qc.removeAddressSpace();
553 Qc.removeObjCLifetime();
554
555 // We will create one Derived type for one qualifier and recurse to handle any
556 // additional ones.
557 unsigned Tag;
558 if (Qc.hasConst()) {
559 Tag = llvm::dwarf::DW_TAG_const_type;
560 Qc.removeConst();
561 } else if (Qc.hasVolatile()) {
562 Tag = llvm::dwarf::DW_TAG_volatile_type;
563 Qc.removeVolatile();
564 } else if (Qc.hasRestrict()) {
565 Tag = llvm::dwarf::DW_TAG_restrict_type;
566 Qc.removeRestrict();
567 } else {
568 assert(Qc.empty() && "Unknown type qualifier for debug info");
569 return getOrCreateType(QualType(T, 0), Unit);
570 }
571
David Blaikie47251962013-08-22 13:36:01 +0000572 llvm::DIType FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000573
574 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
575 // CVR derived types.
576 llvm::DIType DbgTy = DBuilder.createQualifiedType(Tag, FromTy);
Eric Christopher6537f082013-05-16 00:45:12 +0000577
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000578 return DbgTy;
579}
580
581llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
582 llvm::DIFile Unit) {
Fariborz Jahanian05f8ff12013-02-21 20:42:11 +0000583
584 // The frontend treats 'id' as a typedef to an ObjCObjectType,
585 // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
586 // debug info, we want to emit 'id' in both cases.
587 if (Ty->isObjCQualifiedIdType())
588 return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
589
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000590 llvm::DIType DbgTy =
Eric Christopher6537f082013-05-16 00:45:12 +0000591 CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000592 Ty->getPointeeType(), Unit);
593 return DbgTy;
594}
595
596llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
597 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +0000598 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000599 Ty->getPointeeType(), Unit);
600}
601
602// Creates a forward declaration for a RecordDecl in the given context.
David Blaikieeaacc882013-08-20 21:03:29 +0000603llvm::DICompositeType
Manman Renf3327332013-08-28 21:20:28 +0000604CGDebugInfo::getOrCreateRecordFwdDecl(const RecordType *Ty,
David Blaikieeaacc882013-08-20 21:03:29 +0000605 llvm::DIDescriptor Ctx) {
Manman Renf3327332013-08-28 21:20:28 +0000606 const RecordDecl *RD = Ty->getDecl();
David Blaikiec5cd1a72013-08-15 20:17:25 +0000607 if (llvm::DIType T = getTypeOrNull(CGM.getContext().getRecordType(RD)))
David Blaikieeaacc882013-08-20 21:03:29 +0000608 return llvm::DICompositeType(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.
Manman Ren18760452013-08-29 20:48:48 +0000624 return DBuilder.createForwardDecl(Tag, RDName, Ctx, DefUnit, Line);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000625}
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
David Blaikieeaacc882013-08-20 21:03:29 +0000645 if (const RecordDecl *RD = dyn_cast<RecordDecl>(Context))
646 if (!RD->isDependentType())
647 return getOrCreateLimitedType(
David Blaikie5434fc22013-08-20 01:28:15 +0000648 CGM.getContext().getRecordType(RD)->castAs<RecordType>(),
David Blaikieeaacc882013-08-20 21:03:29 +0000649 getOrCreateMainFile());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000650 return TheCU;
651}
652
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000653llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag,
Eric Christopher6537f082013-05-16 00:45:12 +0000654 const Type *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000655 QualType PointeeTy,
656 llvm::DIFile Unit) {
657 if (Tag == llvm::dwarf::DW_TAG_reference_type ||
658 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
David Blaikie47251962013-08-22 13:36:01 +0000659 return DBuilder.createReferenceType(Tag, getOrCreateType(PointeeTy, Unit));
Fariborz Jahanian05f8ff12013-02-21 20:42:11 +0000660
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000661 // Bit size, align and offset of the type.
662 // Size is always the size of a pointer. We can't use getTypeSize here
663 // because that does not return the correct value for references.
664 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCall64aa4b32013-04-16 22:48:15 +0000665 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000666 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
667
David Blaikie47251962013-08-22 13:36:01 +0000668 return DBuilder.createPointerType(getOrCreateType(PointeeTy, Unit), Size,
669 Align);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000670}
671
Eric Christopherf0890c42013-05-16 00:52:20 +0000672llvm::DIType CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
673 llvm::DIType &Cache) {
Eric Christopherb2d13922013-07-18 00:52:50 +0000674 if (Cache)
Guy Benyeib13621d2012-12-18 14:38:23 +0000675 return Cache;
David Blaikie1e97c1e2013-05-21 17:58:54 +0000676 Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
677 TheCU, getOrCreateMainFile(), 0);
678 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
679 Cache = DBuilder.createPointerType(Cache, Size);
680 return Cache;
Guy Benyeib13621d2012-12-18 14:38:23 +0000681}
682
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000683llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
684 llvm::DIFile Unit) {
Eric Christopherb2d13922013-07-18 00:52:50 +0000685 if (BlockLiteralGeneric)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000686 return BlockLiteralGeneric;
687
688 SmallVector<llvm::Value *, 8> EltTys;
689 llvm::DIType FieldTy;
690 QualType FType;
691 uint64_t FieldSize, FieldOffset;
692 unsigned FieldAlign;
693 llvm::DIArray Elements;
694 llvm::DIType EltTy, DescTy;
695
696 FieldOffset = 0;
697 FType = CGM.getContext().UnsignedLongTy;
698 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
699 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
700
701 Elements = DBuilder.getOrCreateArray(EltTys);
702 EltTys.clear();
703
704 unsigned Flags = llvm::DIDescriptor::FlagAppleBlock;
705 unsigned LineNo = getLineNumber(CurLoc);
706
707 EltTy = DBuilder.createStructType(Unit, "__block_descriptor",
708 Unit, LineNo, FieldOffset, 0,
David Blaikiec1d0af12013-02-25 01:07:08 +0000709 Flags, llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000710
711 // Bit size, align and offset of the type.
712 uint64_t Size = CGM.getContext().getTypeSize(Ty);
713
714 DescTy = DBuilder.createPointerType(EltTy, Size);
715
716 FieldOffset = 0;
717 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
718 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
719 FType = CGM.getContext().IntTy;
720 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
721 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
722 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
723 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
724
725 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
726 FieldTy = DescTy;
727 FieldSize = CGM.getContext().getTypeSize(Ty);
728 FieldAlign = CGM.getContext().getTypeAlign(Ty);
729 FieldTy = DBuilder.createMemberType(Unit, "__descriptor", Unit,
730 LineNo, FieldSize, FieldAlign,
731 FieldOffset, 0, FieldTy);
732 EltTys.push_back(FieldTy);
733
734 FieldOffset += FieldSize;
735 Elements = DBuilder.getOrCreateArray(EltTys);
736
737 EltTy = DBuilder.createStructType(Unit, "__block_literal_generic",
738 Unit, LineNo, FieldOffset, 0,
David Blaikiec1d0af12013-02-25 01:07:08 +0000739 Flags, llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000740
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000741 BlockLiteralGeneric = DBuilder.createPointerType(EltTy, Size);
742 return BlockLiteralGeneric;
743}
744
David Blaikie47251962013-08-22 13:36:01 +0000745llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty, llvm::DIFile Unit) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000746 // Typedefs are derived from some other type. If we have a typedef of a
747 // typedef, make sure to emit the whole chain.
David Blaikie47251962013-08-22 13:36:01 +0000748 llvm::DIType Src = getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
Eric Christopherb2d13922013-07-18 00:52:50 +0000749 if (!Src)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000750 return llvm::DIType();
751 // We don't set size information, but do specify where the typedef was
752 // declared.
753 unsigned Line = getLineNumber(Ty->getDecl()->getLocation());
754 const TypedefNameDecl *TyDecl = Ty->getDecl();
Eric Christopher6537f082013-05-16 00:45:12 +0000755
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000756 llvm::DIDescriptor TypedefContext =
757 getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext()));
Eric Christopher6537f082013-05-16 00:45:12 +0000758
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000759 return
760 DBuilder.createTypedef(Src, TyDecl->getName(), Unit, Line, TypedefContext);
761}
762
763llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
764 llvm::DIFile Unit) {
765 SmallVector<llvm::Value *, 16> EltTys;
766
767 // Add the result type at least.
David Blaikie47251962013-08-22 13:36:01 +0000768 EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000769
770 // Set up remainder of arguments if there is a prototype.
771 // FIXME: IF NOT, HOW IS THIS REPRESENTED? llvm-gcc doesn't represent '...'!
772 if (isa<FunctionNoProtoType>(Ty))
773 EltTys.push_back(DBuilder.createUnspecifiedParameter());
774 else if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Ty)) {
775 for (unsigned i = 0, e = FPT->getNumArgs(); i != e; ++i)
David Blaikie47251962013-08-22 13:36:01 +0000776 EltTys.push_back(getOrCreateType(FPT->getArgType(i), Unit));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000777 }
778
779 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
780 return DBuilder.createSubroutineType(Unit, EltTypeArray);
781}
782
783
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000784llvm::DIType CGDebugInfo::createFieldType(StringRef name,
785 QualType type,
786 uint64_t sizeInBitsOverride,
787 SourceLocation loc,
788 AccessSpecifier AS,
789 uint64_t offsetInBits,
790 llvm::DIFile tunit,
791 llvm::DIDescriptor scope) {
792 llvm::DIType debugType = getOrCreateType(type, tunit);
793
794 // Get the location for the field.
795 llvm::DIFile file = getOrCreateFile(loc);
796 unsigned line = getLineNumber(loc);
797
798 uint64_t sizeInBits = 0;
799 unsigned alignInBits = 0;
800 if (!type->isIncompleteArrayType()) {
801 llvm::tie(sizeInBits, alignInBits) = CGM.getContext().getTypeInfo(type);
802
803 if (sizeInBitsOverride)
804 sizeInBits = sizeInBitsOverride;
805 }
806
807 unsigned flags = 0;
808 if (AS == clang::AS_private)
809 flags |= llvm::DIDescriptor::FlagPrivate;
810 else if (AS == clang::AS_protected)
811 flags |= llvm::DIDescriptor::FlagProtected;
812
813 return DBuilder.createMemberType(scope, name, file, line, sizeInBits,
814 alignInBits, offsetInBits, flags, debugType);
815}
816
Eric Christopher0395de32013-01-16 01:22:32 +0000817/// CollectRecordLambdaFields - Helper for CollectRecordFields.
818void CGDebugInfo::
819CollectRecordLambdaFields(const CXXRecordDecl *CXXDecl,
820 SmallVectorImpl<llvm::Value *> &elements,
821 llvm::DIType RecordTy) {
822 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
823 // has the name and the location of the variable so we should iterate over
824 // both concurrently.
825 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
826 RecordDecl::field_iterator Field = CXXDecl->field_begin();
827 unsigned fieldno = 0;
828 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
829 E = CXXDecl->captures_end(); I != E; ++I, ++Field, ++fieldno) {
830 const LambdaExpr::Capture C = *I;
831 if (C.capturesVariable()) {
832 VarDecl *V = C.getCapturedVar();
833 llvm::DIFile VUnit = getOrCreateFile(C.getLocation());
834 StringRef VName = V->getName();
835 uint64_t SizeInBitsOverride = 0;
836 if (Field->isBitField()) {
837 SizeInBitsOverride = Field->getBitWidthValue(CGM.getContext());
838 assert(SizeInBitsOverride && "found named 0-width bitfield");
839 }
840 llvm::DIType fieldType
841 = createFieldType(VName, Field->getType(), SizeInBitsOverride,
842 C.getLocation(), Field->getAccess(),
843 layout.getFieldOffset(fieldno), VUnit, RecordTy);
844 elements.push_back(fieldType);
845 } else {
846 // TODO: Need to handle 'this' in some way by probably renaming the
847 // this of the lambda class and having a field member of 'this' or
848 // by using AT_object_pointer for the function and having that be
849 // used as 'this' for semantic references.
850 assert(C.capturesThis() && "Field that isn't captured and isn't this?");
851 FieldDecl *f = *Field;
852 llvm::DIFile VUnit = getOrCreateFile(f->getLocation());
853 QualType type = f->getType();
854 llvm::DIType fieldType
855 = createFieldType("this", type, 0, f->getLocation(), f->getAccess(),
856 layout.getFieldOffset(fieldno), VUnit, RecordTy);
857
858 elements.push_back(fieldType);
859 }
860 }
861}
862
David Blaikie5434fc22013-08-20 01:28:15 +0000863/// Helper for CollectRecordFields.
David Blaikiecbcb0302013-08-15 22:50:29 +0000864llvm::DIDerivedType
865CGDebugInfo::CreateRecordStaticField(const VarDecl *Var,
866 llvm::DIType RecordTy) {
Eric Christopher0395de32013-01-16 01:22:32 +0000867 // Create the descriptor for the static variable, with or without
868 // constant initializers.
869 llvm::DIFile VUnit = getOrCreateFile(Var->getLocation());
870 llvm::DIType VTy = getOrCreateType(Var->getType(), VUnit);
871
Eric Christopher0395de32013-01-16 01:22:32 +0000872 unsigned LineNumber = getLineNumber(Var->getLocation());
873 StringRef VName = Var->getName();
David Blaikiea89701b2013-01-20 01:19:17 +0000874 llvm::Constant *C = NULL;
Eric Christopher0395de32013-01-16 01:22:32 +0000875 if (Var->getInit()) {
876 const APValue *Value = Var->evaluateValue();
David Blaikiea89701b2013-01-20 01:19:17 +0000877 if (Value) {
878 if (Value->isInt())
879 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
880 if (Value->isFloat())
881 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
882 }
Eric Christopher0395de32013-01-16 01:22:32 +0000883 }
884
885 unsigned Flags = 0;
886 AccessSpecifier Access = Var->getAccess();
887 if (Access == clang::AS_private)
888 Flags |= llvm::DIDescriptor::FlagPrivate;
889 else if (Access == clang::AS_protected)
890 Flags |= llvm::DIDescriptor::FlagProtected;
891
David Blaikiecbcb0302013-08-15 22:50:29 +0000892 llvm::DIDerivedType GV = DBuilder.createStaticMemberType(
893 RecordTy, VName, VUnit, LineNumber, VTy, Flags, C);
Eric Christopher0395de32013-01-16 01:22:32 +0000894 StaticDataMemberCache[Var->getCanonicalDecl()] = llvm::WeakVH(GV);
David Blaikiecbcb0302013-08-15 22:50:29 +0000895 return GV;
Eric Christopher0395de32013-01-16 01:22:32 +0000896}
897
898/// CollectRecordNormalField - Helper for CollectRecordFields.
899void CGDebugInfo::
900CollectRecordNormalField(const FieldDecl *field, uint64_t OffsetInBits,
901 llvm::DIFile tunit,
902 SmallVectorImpl<llvm::Value *> &elements,
903 llvm::DIType RecordTy) {
904 StringRef name = field->getName();
905 QualType type = field->getType();
906
907 // Ignore unnamed fields unless they're anonymous structs/unions.
908 if (name.empty() && !type->isRecordType())
909 return;
910
911 uint64_t SizeInBitsOverride = 0;
912 if (field->isBitField()) {
913 SizeInBitsOverride = field->getBitWidthValue(CGM.getContext());
914 assert(SizeInBitsOverride && "found named 0-width bitfield");
915 }
916
917 llvm::DIType fieldType
918 = createFieldType(name, type, SizeInBitsOverride,
919 field->getLocation(), field->getAccess(),
920 OffsetInBits, tunit, RecordTy);
921
922 elements.push_back(fieldType);
923}
924
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000925/// CollectRecordFields - A helper function to collect debug info for
926/// record fields. This is used while creating debug info entry for a Record.
David Blaikie841fd112013-08-16 20:40:25 +0000927void CGDebugInfo::CollectRecordFields(const RecordDecl *record,
928 llvm::DIFile tunit,
929 SmallVectorImpl<llvm::Value *> &elements,
930 llvm::DICompositeType RecordTy) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000931 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(record);
932
Eric Christopher0395de32013-01-16 01:22:32 +0000933 if (CXXDecl && CXXDecl->isLambda())
934 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
935 else {
936 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000937
Eric Christopher0395de32013-01-16 01:22:32 +0000938 // Field number for non-static fields.
Eric Christopherfd5ac0d2013-01-04 17:59:07 +0000939 unsigned fieldNo = 0;
Eric Christopher0395de32013-01-16 01:22:32 +0000940
Eric Christopher0395de32013-01-16 01:22:32 +0000941 // Static and non-static members should appear in the same order as
942 // the corresponding declarations in the source program.
943 for (RecordDecl::decl_iterator I = record->decls_begin(),
944 E = record->decls_end(); I != E; ++I)
David Blaikie5e6937b2013-08-20 21:49:21 +0000945 if (const VarDecl *V = dyn_cast<VarDecl>(*I)) {
946 // Reuse the existing static member declaration if one exists
947 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator MI =
948 StaticDataMemberCache.find(V->getCanonicalDecl());
949 if (MI != StaticDataMemberCache.end()) {
950 assert(MI->second &&
951 "Static data member declaration should still exist");
952 elements.push_back(
953 llvm::DIDerivedType(cast<llvm::MDNode>(MI->second)));
954 } else
955 elements.push_back(CreateRecordStaticField(V, RecordTy));
956 } else if (FieldDecl *field = dyn_cast<FieldDecl>(*I)) {
Eric Christopher0395de32013-01-16 01:22:32 +0000957 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo),
958 tunit, elements, RecordTy);
959
960 // Bump field number for next field.
961 ++fieldNo;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000962 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000963 }
964}
965
966/// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
967/// function type is not updated to include implicit "this" pointer. Use this
968/// routine to get a method type which includes "this" pointer.
David Blaikie9a845292013-05-22 23:22:42 +0000969llvm::DICompositeType
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000970CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
971 llvm::DIFile Unit) {
David Blaikie9c78f9b2013-01-07 23:06:35 +0000972 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
David Blaikie67f8b5e2013-01-07 22:24:59 +0000973 if (Method->isStatic())
David Blaikie9a845292013-05-22 23:22:42 +0000974 return llvm::DICompositeType(getOrCreateType(QualType(Func, 0), Unit));
David Blaikie9c78f9b2013-01-07 23:06:35 +0000975 return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()),
976 Func, Unit);
977}
David Blaikie67f8b5e2013-01-07 22:24:59 +0000978
David Blaikie9a845292013-05-22 23:22:42 +0000979llvm::DICompositeType CGDebugInfo::getOrCreateInstanceMethodType(
David Blaikie9c78f9b2013-01-07 23:06:35 +0000980 QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile Unit) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000981 // Add "this" pointer.
David Blaikie9c78f9b2013-01-07 23:06:35 +0000982 llvm::DIArray Args = llvm::DICompositeType(
983 getOrCreateType(QualType(Func, 0), Unit)).getTypeArray();
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000984 assert (Args.getNumElements() && "Invalid number of arguments!");
985
986 SmallVector<llvm::Value *, 16> Elts;
987
988 // First element is always return type. For 'void' functions it is NULL.
989 Elts.push_back(Args.getElement(0));
990
David Blaikie67f8b5e2013-01-07 22:24:59 +0000991 // "this" pointer is always first argument.
David Blaikie9c78f9b2013-01-07 23:06:35 +0000992 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
David Blaikie67f8b5e2013-01-07 22:24:59 +0000993 if (isa<ClassTemplateSpecializationDecl>(RD)) {
994 // Create pointer type directly in this case.
995 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
996 QualType PointeeTy = ThisPtrTy->getPointeeType();
997 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCall64aa4b32013-04-16 22:48:15 +0000998 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
David Blaikie67f8b5e2013-01-07 22:24:59 +0000999 uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy);
1000 llvm::DIType PointeeType = getOrCreateType(PointeeTy, Unit);
Eric Christopherf0890c42013-05-16 00:52:20 +00001001 llvm::DIType ThisPtrType =
1002 DBuilder.createPointerType(PointeeType, Size, Align);
David Blaikie67f8b5e2013-01-07 22:24:59 +00001003 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
1004 // TODO: This and the artificial type below are misleading, the
1005 // types aren't artificial the argument is, but the current
1006 // metadata doesn't represent that.
1007 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1008 Elts.push_back(ThisPtrType);
1009 } else {
1010 llvm::DIType ThisPtrType = getOrCreateType(ThisPtr, Unit);
1011 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
1012 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1013 Elts.push_back(ThisPtrType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001014 }
1015
1016 // Copy rest of the arguments.
1017 for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
1018 Elts.push_back(Args.getElement(i));
1019
1020 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
1021
1022 return DBuilder.createSubroutineType(Unit, EltTypeArray);
1023}
1024
Eric Christopher6537f082013-05-16 00:45:12 +00001025/// isFunctionLocalClass - Return true if CXXRecordDecl is defined
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001026/// inside a function.
1027static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
1028 if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
1029 return isFunctionLocalClass(NRD);
1030 if (isa<FunctionDecl>(RD->getDeclContext()))
1031 return true;
1032 return false;
1033}
1034
1035/// CreateCXXMemberFunction - A helper function to create a DISubprogram for
1036/// a single member function GlobalDecl.
1037llvm::DISubprogram
1038CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
1039 llvm::DIFile Unit,
1040 llvm::DIType RecordTy) {
Eric Christopher6537f082013-05-16 00:45:12 +00001041 bool IsCtorOrDtor =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001042 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
Eric Christopher6537f082013-05-16 00:45:12 +00001043
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001044 StringRef MethodName = getFunctionName(Method);
David Blaikie9a845292013-05-22 23:22:42 +00001045 llvm::DICompositeType MethodTy = getOrCreateMethodType(Method, Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001046
1047 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1048 // make sense to give a single ctor/dtor a linkage name.
1049 StringRef MethodLinkageName;
1050 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1051 MethodLinkageName = CGM.getMangledName(Method);
1052
1053 // Get the location for the method.
David Blaikiefc946272013-08-19 03:37:48 +00001054 llvm::DIFile MethodDefUnit;
1055 unsigned MethodLine = 0;
1056 if (!Method->isImplicit()) {
1057 MethodDefUnit = getOrCreateFile(Method->getLocation());
1058 MethodLine = getLineNumber(Method->getLocation());
1059 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001060
1061 // Collect virtual method info.
1062 llvm::DIType ContainingType;
Eric Christopher6537f082013-05-16 00:45:12 +00001063 unsigned Virtuality = 0;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001064 unsigned VIndex = 0;
Eric Christopher6537f082013-05-16 00:45:12 +00001065
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001066 if (Method->isVirtual()) {
1067 if (Method->isPure())
1068 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
1069 else
1070 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
Eric Christopher6537f082013-05-16 00:45:12 +00001071
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001072 // It doesn't make sense to give a virtual destructor a vtable index,
1073 // since a single destructor has two entries in the vtable.
1074 if (!isa<CXXDestructorDecl>(Method))
1075 VIndex = CGM.getVTableContext().getMethodVTableIndex(Method);
1076 ContainingType = RecordTy;
1077 }
1078
1079 unsigned Flags = 0;
1080 if (Method->isImplicit())
1081 Flags |= llvm::DIDescriptor::FlagArtificial;
1082 AccessSpecifier Access = Method->getAccess();
1083 if (Access == clang::AS_private)
1084 Flags |= llvm::DIDescriptor::FlagPrivate;
1085 else if (Access == clang::AS_protected)
1086 Flags |= llvm::DIDescriptor::FlagProtected;
1087 if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1088 if (CXXC->isExplicit())
1089 Flags |= llvm::DIDescriptor::FlagExplicit;
Eric Christopher6537f082013-05-16 00:45:12 +00001090 } else if (const CXXConversionDecl *CXXC =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001091 dyn_cast<CXXConversionDecl>(Method)) {
1092 if (CXXC->isExplicit())
1093 Flags |= llvm::DIDescriptor::FlagExplicit;
1094 }
1095 if (Method->hasPrototype())
1096 Flags |= llvm::DIDescriptor::FlagPrototyped;
1097
1098 llvm::DIArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1099 llvm::DISubprogram SP =
Eric Christopher6537f082013-05-16 00:45:12 +00001100 DBuilder.createMethod(RecordTy, MethodName, MethodLinkageName,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001101 MethodDefUnit, MethodLine,
Eric Christopher6537f082013-05-16 00:45:12 +00001102 MethodTy, /*isLocalToUnit=*/false,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001103 /* isDefinition=*/ false,
1104 Virtuality, VIndex, ContainingType,
1105 Flags, CGM.getLangOpts().Optimize, NULL,
1106 TParamsArray);
Eric Christopher6537f082013-05-16 00:45:12 +00001107
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001108 SPCache[Method->getCanonicalDecl()] = llvm::WeakVH(SP);
1109
1110 return SP;
1111}
1112
1113/// CollectCXXMemberFunctions - A helper function to collect debug info for
Eric Christopher6537f082013-05-16 00:45:12 +00001114/// C++ member functions. This is used while creating debug info entry for
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001115/// a Record.
1116void CGDebugInfo::
1117CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
1118 SmallVectorImpl<llvm::Value *> &EltTys,
1119 llvm::DIType RecordTy) {
1120
1121 // Since we want more than just the individual member decls if we
1122 // have templated functions iterate over every declaration to gather
1123 // the functions.
1124 for(DeclContext::decl_iterator I = RD->decls_begin(),
1125 E = RD->decls_end(); I != E; ++I) {
David Blaikiec5761272013-08-28 17:27:13 +00001126 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*I)) {
David Blaikiedd658022013-08-28 20:58:00 +00001127 // Reuse the existing member function declaration if it exists.
David Blaikie4a684912013-08-28 20:24:55 +00001128 // It may be associated with the declaration of the type & should be
1129 // reused as we're building the definition.
David Blaikiedd658022013-08-28 20:58:00 +00001130 //
1131 // This situation can arise in the vtable-based debug info reduction where
1132 // implicit members are emitted in a non-vtable TU.
David Blaikie5434fc22013-08-20 01:28:15 +00001133 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator MI =
1134 SPCache.find(Method->getCanonicalDecl());
David Blaikiec5761272013-08-28 17:27:13 +00001135 if (MI == SPCache.end()) {
David Blaikie4a684912013-08-28 20:24:55 +00001136 // If the member is implicit, lazily create it when we see the
1137 // definition, not before. (an ODR-used implicit default ctor that's
1138 // never actually code generated should not produce debug info)
David Blaikiec5761272013-08-28 17:27:13 +00001139 if (!Method->isImplicit())
1140 EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
1141 } else
David Blaikie5434fc22013-08-20 01:28:15 +00001142 EltTys.push_back(MI->second);
Eric Christopherac7c25f2013-08-28 23:12:10 +00001143 } else if (const FunctionTemplateDecl *FTD =
1144 dyn_cast<FunctionTemplateDecl>(*I)) {
David Blaikie11fa7512013-08-28 23:06:52 +00001145 // Add any template specializations that have already been seen. Like
1146 // implicit member functions, these may have been added to a declaration
1147 // in the case of vtable-based debug info reduction.
Eric Christopherac7c25f2013-08-28 23:12:10 +00001148 for (FunctionTemplateDecl::spec_iterator SI = FTD->spec_begin(),
1149 SE = FTD->spec_end();
1150 SI != SE; ++SI) {
David Blaikie11fa7512013-08-28 23:06:52 +00001151 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator MI =
1152 SPCache.find(cast<CXXMethodDecl>(*SI)->getCanonicalDecl());
1153 if (MI != SPCache.end())
1154 EltTys.push_back(MI->second);
1155 }
David Blaikie5434fc22013-08-20 01:28:15 +00001156 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001157 }
Eric Christopher6537f082013-05-16 00:45:12 +00001158}
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001159
1160/// CollectCXXFriends - A helper function to collect debug info for
1161/// C++ base classes. This is used while creating debug info entry for
1162/// a Record.
1163void CGDebugInfo::
1164CollectCXXFriends(const CXXRecordDecl *RD, llvm::DIFile Unit,
1165 SmallVectorImpl<llvm::Value *> &EltTys,
1166 llvm::DIType RecordTy) {
1167 for (CXXRecordDecl::friend_iterator BI = RD->friend_begin(),
1168 BE = RD->friend_end(); BI != BE; ++BI) {
1169 if ((*BI)->isUnsupportedFriend())
1170 continue;
1171 if (TypeSourceInfo *TInfo = (*BI)->getFriendType())
David Blaikie3de73f02013-08-18 04:50:23 +00001172 EltTys.push_back(DBuilder.createFriend(
David Blaikie47251962013-08-22 13:36:01 +00001173 RecordTy, getOrCreateType(TInfo->getType(), Unit)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001174 }
1175}
1176
1177/// CollectCXXBases - A helper function to collect debug info for
Eric Christopher6537f082013-05-16 00:45:12 +00001178/// C++ base classes. This is used while creating debug info entry for
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001179/// a Record.
1180void CGDebugInfo::
1181CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
1182 SmallVectorImpl<llvm::Value *> &EltTys,
1183 llvm::DIType RecordTy) {
1184
1185 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1186 for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
1187 BE = RD->bases_end(); BI != BE; ++BI) {
1188 unsigned BFlags = 0;
1189 uint64_t BaseOffset;
Eric Christopher6537f082013-05-16 00:45:12 +00001190
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001191 const CXXRecordDecl *Base =
1192 cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl());
Eric Christopher6537f082013-05-16 00:45:12 +00001193
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001194 if (BI->isVirtual()) {
1195 // virtual base offset offset is -ve. The code generator emits dwarf
1196 // expression where it expects +ve number.
Eric Christopher6537f082013-05-16 00:45:12 +00001197 BaseOffset =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001198 0 - CGM.getVTableContext()
1199 .getVirtualBaseOffsetOffset(RD, Base).getQuantity();
1200 BFlags = llvm::DIDescriptor::FlagVirtual;
1201 } else
1202 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1203 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1204 // BI->isVirtual() and bits when not.
Eric Christopher6537f082013-05-16 00:45:12 +00001205
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001206 AccessSpecifier Access = BI->getAccessSpecifier();
1207 if (Access == clang::AS_private)
1208 BFlags |= llvm::DIDescriptor::FlagPrivate;
1209 else if (Access == clang::AS_protected)
1210 BFlags |= llvm::DIDescriptor::FlagProtected;
Eric Christopher6537f082013-05-16 00:45:12 +00001211
1212 llvm::DIType DTy =
1213 DBuilder.createInheritance(RecordTy,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001214 getOrCreateType(BI->getType(), Unit),
1215 BaseOffset, BFlags);
1216 EltTys.push_back(DTy);
1217 }
1218}
1219
1220/// CollectTemplateParams - A helper function to collect template parameters.
1221llvm::DIArray CGDebugInfo::
1222CollectTemplateParams(const TemplateParameterList *TPList,
David Blaikie35178dc2013-06-22 18:59:18 +00001223 ArrayRef<TemplateArgument> TAList,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001224 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +00001225 SmallVector<llvm::Value *, 16> TemplateParams;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001226 for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1227 const TemplateArgument &TA = TAList[i];
David Blaikie35178dc2013-06-22 18:59:18 +00001228 StringRef Name;
1229 if (TPList)
1230 Name = TPList->getParam(i)->getName();
David Blaikie9dfd2432013-05-10 21:53:14 +00001231 switch (TA.getKind()) {
1232 case TemplateArgument::Type: {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001233 llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit);
1234 llvm::DITemplateTypeParameter TTP =
David Blaikie35178dc2013-06-22 18:59:18 +00001235 DBuilder.createTemplateTypeParameter(TheCU, Name, TTy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001236 TemplateParams.push_back(TTP);
David Blaikie9dfd2432013-05-10 21:53:14 +00001237 } break;
1238 case TemplateArgument::Integral: {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001239 llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit);
1240 llvm::DITemplateValueParameter TVP =
David Blaikie9dfd2432013-05-10 21:53:14 +00001241 DBuilder.createTemplateValueParameter(
David Blaikie35178dc2013-06-22 18:59:18 +00001242 TheCU, Name, TTy,
David Blaikie9dfd2432013-05-10 21:53:14 +00001243 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral()));
1244 TemplateParams.push_back(TVP);
1245 } break;
1246 case TemplateArgument::Declaration: {
1247 const ValueDecl *D = TA.getAsDecl();
1248 bool InstanceMember = D->isCXXInstanceMember();
1249 QualType T = InstanceMember
1250 ? CGM.getContext().getMemberPointerType(
1251 D->getType(), cast<RecordDecl>(D->getDeclContext())
1252 ->getTypeForDecl())
1253 : CGM.getContext().getPointerType(D->getType());
1254 llvm::DIType TTy = getOrCreateType(T, Unit);
1255 llvm::Value *V = 0;
1256 // Variable pointer template parameters have a value that is the address
1257 // of the variable.
1258 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1259 V = CGM.GetAddrOfGlobalVar(VD);
1260 // Member function pointers have special support for building them, though
1261 // this is currently unsupported in LLVM CodeGen.
David Blaikief8aa1552013-05-13 06:57:50 +00001262 if (InstanceMember) {
David Blaikie9dfd2432013-05-10 21:53:14 +00001263 if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(D))
1264 V = CGM.getCXXABI().EmitMemberPointer(method);
David Blaikief8aa1552013-05-13 06:57:50 +00001265 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1266 V = CGM.GetAddrOfFunction(FD);
David Blaikie9dfd2432013-05-10 21:53:14 +00001267 // Member data pointers have special handling too to compute the fixed
1268 // offset within the object.
1269 if (isa<FieldDecl>(D)) {
1270 // These five lines (& possibly the above member function pointer
1271 // handling) might be able to be refactored to use similar code in
1272 // CodeGenModule::getMemberPointerConstant
1273 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
1274 CharUnits chars =
1275 CGM.getContext().toCharUnitsFromBits((int64_t) fieldOffset);
1276 V = CGM.getCXXABI().EmitMemberDataPointer(
1277 cast<MemberPointerType>(T.getTypePtr()), chars);
1278 }
1279 llvm::DITemplateValueParameter TVP =
David Majnemer5db8b312013-08-25 22:13:27 +00001280 DBuilder.createTemplateValueParameter(TheCU, Name, TTy,
1281 V->stripPointerCasts());
David Blaikie9dfd2432013-05-10 21:53:14 +00001282 TemplateParams.push_back(TVP);
1283 } break;
1284 case TemplateArgument::NullPtr: {
1285 QualType T = TA.getNullPtrType();
1286 llvm::DIType TTy = getOrCreateType(T, Unit);
1287 llvm::Value *V = 0;
1288 // Special case member data pointer null values since they're actually -1
1289 // instead of zero.
1290 if (const MemberPointerType *MPT =
1291 dyn_cast<MemberPointerType>(T.getTypePtr()))
1292 // But treat member function pointers as simple zero integers because
1293 // it's easier than having a special case in LLVM's CodeGen. If LLVM
1294 // CodeGen grows handling for values of non-null member function
1295 // pointers then perhaps we could remove this special case and rely on
1296 // EmitNullMemberPointer for member function pointers.
1297 if (MPT->isMemberDataPointer())
1298 V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1299 if (!V)
1300 V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
1301 llvm::DITemplateValueParameter TVP =
David Blaikie35178dc2013-06-22 18:59:18 +00001302 DBuilder.createTemplateValueParameter(TheCU, Name, TTy, V);
David Blaikie9dfd2432013-05-10 21:53:14 +00001303 TemplateParams.push_back(TVP);
1304 } break;
David Blaikie35178dc2013-06-22 18:59:18 +00001305 case TemplateArgument::Template: {
1306 llvm::DITemplateValueParameter TVP =
1307 DBuilder.createTemplateTemplateParameter(
1308 TheCU, Name, llvm::DIType(),
1309 TA.getAsTemplate().getAsTemplateDecl()
1310 ->getQualifiedNameAsString());
1311 TemplateParams.push_back(TVP);
1312 } break;
1313 case TemplateArgument::Pack: {
1314 llvm::DITemplateValueParameter TVP =
1315 DBuilder.createTemplateParameterPack(
1316 TheCU, Name, llvm::DIType(),
1317 CollectTemplateParams(NULL, TA.getPackAsArray(), Unit));
1318 TemplateParams.push_back(TVP);
1319 } break;
David Majnemer87b1f6d2013-08-24 08:21:10 +00001320 case TemplateArgument::Expression: {
1321 const Expr *E = TA.getAsExpr();
1322 QualType T = E->getType();
1323 llvm::Value *V = CGM.EmitConstantExpr(E, T);
1324 assert(V && "Expression in template argument isn't constant");
1325 llvm::DIType TTy = getOrCreateType(T, Unit);
1326 llvm::DITemplateValueParameter TVP =
1327 DBuilder.createTemplateValueParameter(TheCU, Name, TTy,
1328 V->stripPointerCasts());
1329 TemplateParams.push_back(TVP);
1330 } break;
David Blaikiee8065122013-05-10 23:36:06 +00001331 // And the following should never occur:
David Blaikie9dfd2432013-05-10 21:53:14 +00001332 case TemplateArgument::TemplateExpansion:
David Blaikie9dfd2432013-05-10 21:53:14 +00001333 case TemplateArgument::Null:
1334 llvm_unreachable(
1335 "These argument types shouldn't exist in concrete types");
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001336 }
1337 }
1338 return DBuilder.getOrCreateArray(TemplateParams);
1339}
1340
1341/// CollectFunctionTemplateParams - A helper function to collect debug
1342/// info for function template parameters.
1343llvm::DIArray CGDebugInfo::
1344CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) {
1345 if (FD->getTemplatedKind() ==
1346 FunctionDecl::TK_FunctionTemplateSpecialization) {
1347 const TemplateParameterList *TList =
1348 FD->getTemplateSpecializationInfo()->getTemplate()
1349 ->getTemplateParameters();
David Blaikie35178dc2013-06-22 18:59:18 +00001350 return CollectTemplateParams(
1351 TList, FD->getTemplateSpecializationArgs()->asArray(), Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001352 }
1353 return llvm::DIArray();
1354}
1355
1356/// CollectCXXTemplateParams - A helper function to collect debug info for
1357/// template parameters.
1358llvm::DIArray CGDebugInfo::
1359CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial,
1360 llvm::DIFile Unit) {
1361 llvm::PointerUnion<ClassTemplateDecl *,
1362 ClassTemplatePartialSpecializationDecl *>
1363 PU = TSpecial->getSpecializedTemplateOrPartial();
Eric Christopher6537f082013-05-16 00:45:12 +00001364
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001365 TemplateParameterList *TPList = PU.is<ClassTemplateDecl *>() ?
1366 PU.get<ClassTemplateDecl *>()->getTemplateParameters() :
1367 PU.get<ClassTemplatePartialSpecializationDecl *>()->getTemplateParameters();
1368 const TemplateArgumentList &TAList = TSpecial->getTemplateInstantiationArgs();
David Blaikie35178dc2013-06-22 18:59:18 +00001369 return CollectTemplateParams(TPList, TAList.asArray(), Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001370}
1371
1372/// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
1373llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
1374 if (VTablePtrType.isValid())
1375 return VTablePtrType;
1376
1377 ASTContext &Context = CGM.getContext();
1378
1379 /* Function type */
1380 llvm::Value *STy = getOrCreateType(Context.IntTy, Unit);
1381 llvm::DIArray SElements = DBuilder.getOrCreateArray(STy);
1382 llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements);
1383 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1384 llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0,
1385 "__vtbl_ptr_type");
1386 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1387 return VTablePtrType;
1388}
1389
1390/// getVTableName - Get vtable name for the given Class.
1391StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
1392 // Construct gdb compatible name name.
1393 std::string Name = "_vptr$" + RD->getNameAsString();
1394
1395 // Copy this name on the side and use its reference.
1396 char *StrPtr = DebugInfoNames.Allocate<char>(Name.length());
1397 memcpy(StrPtr, Name.data(), Name.length());
1398 return StringRef(StrPtr, Name.length());
1399}
1400
1401
1402/// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
1403/// debug info entry in EltTys vector.
1404void CGDebugInfo::
1405CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
1406 SmallVectorImpl<llvm::Value *> &EltTys) {
1407 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1408
1409 // If there is a primary base then it will hold vtable info.
1410 if (RL.getPrimaryBase())
1411 return;
1412
1413 // If this class is not dynamic then there is not any vtable info to collect.
1414 if (!RD->isDynamicClass())
1415 return;
1416
1417 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1418 llvm::DIType VPTR
1419 = DBuilder.createMemberType(Unit, getVTableName(RD), Unit,
Eric Christopherf0890c42013-05-16 00:52:20 +00001420 0, Size, 0, 0,
1421 llvm::DIDescriptor::FlagArtificial,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001422 getOrCreateVTablePtrType(Unit));
1423 EltTys.push_back(VPTR);
1424}
1425
Eric Christopher6537f082013-05-16 00:45:12 +00001426/// getOrCreateRecordType - Emit record type's standalone debug info.
1427llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001428 SourceLocation Loc) {
Eric Christopher13c97672013-05-16 00:45:23 +00001429 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001430 llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc));
1431 return T;
1432}
1433
1434/// getOrCreateInterfaceType - Emit an objective c interface type standalone
1435/// debug info.
1436llvm::DIType CGDebugInfo::getOrCreateInterfaceType(QualType D,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001437 SourceLocation Loc) {
Eric Christopher13c97672013-05-16 00:45:23 +00001438 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001439 llvm::DIType T = getOrCreateType(D, getOrCreateFile(Loc));
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001440 RetainedTypes.push_back(D.getAsOpaquePtr());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001441 return T;
1442}
1443
David Blaikie27804892013-08-15 20:49:17 +00001444void CGDebugInfo::completeType(const RecordDecl *RD) {
1445 if (DebugKind > CodeGenOptions::LimitedDebugInfo ||
1446 !CGM.getLangOpts().CPlusPlus)
1447 completeRequiredType(RD);
1448}
1449
1450void CGDebugInfo::completeRequiredType(const RecordDecl *RD) {
David Blaikie5434fc22013-08-20 01:28:15 +00001451 if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
1452 if (CXXDecl->isDynamicClass())
1453 return;
1454
David Blaikie27804892013-08-15 20:49:17 +00001455 QualType Ty = CGM.getContext().getRecordType(RD);
1456 llvm::DIType T = getTypeOrNull(Ty);
David Blaikie5434fc22013-08-20 01:28:15 +00001457 if (T && T.isForwardDecl())
1458 completeClassData(RD);
1459}
1460
1461void CGDebugInfo::completeClassData(const RecordDecl *RD) {
1462 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
Michael Gottesman90e55232013-08-19 18:46:16 +00001463 return;
David Blaikie5434fc22013-08-20 01:28:15 +00001464 QualType Ty = CGM.getContext().getRecordType(RD);
David Blaikie27804892013-08-15 20:49:17 +00001465 void* TyPtr = Ty.getAsOpaquePtr();
1466 if (CompletedTypeCache.count(TyPtr))
1467 return;
1468 llvm::DIType Res = CreateTypeDefinition(Ty->castAs<RecordType>());
1469 assert(!Res.isForwardDecl());
1470 CompletedTypeCache[TyPtr] = Res;
1471 TypeCache[TyPtr] = Res;
1472}
1473
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001474/// CreateType - get structure or union type.
David Blaikie47251962013-08-22 13:36:01 +00001475llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001476 RecordDecl *RD = Ty->getDecl();
David Blaikie5434fc22013-08-20 01:28:15 +00001477 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
David Blaikie47251962013-08-22 13:36:01 +00001478 // Always emit declarations for types that aren't required to be complete when
1479 // in limit-debug-info mode. If the type is later found to be required to be
1480 // complete this declaration will be upgraded to a definition by
1481 // `completeRequiredType`.
1482 // If the type is dynamic, only emit the definition in TUs that require class
1483 // data. This is handled by `completeClassData`.
1484 if ((DebugKind <= CodeGenOptions::LimitedDebugInfo &&
David Blaikie5434fc22013-08-20 01:28:15 +00001485 !RD->isCompleteDefinitionRequired() && CGM.getLangOpts().CPlusPlus) ||
1486 (CXXDecl && CXXDecl->hasDefinition() && CXXDecl->isDynamicClass())) {
David Blaikie5f6e2f42013-06-05 05:32:23 +00001487 llvm::DIDescriptor FDContext =
1488 getContextDescriptor(cast<Decl>(RD->getDeclContext()));
Manman Renf3327332013-08-28 21:20:28 +00001489 llvm::DIType RetTy = getOrCreateRecordFwdDecl(Ty, FDContext);
David Blaikie5434fc22013-08-20 01:28:15 +00001490 // FIXME: This is conservatively correct. If we return a non-forward decl
1491 // that's not a full definition (such as those created by
1492 // createContextChain) then getOrCreateType will record is as a complete
1493 // type and we'll never record all its members. But this means we're
1494 // emitting full debug info in TUs where GCC successfully emits a partial
1495 // definition of the type.
1496 if (RetTy.isForwardDecl())
1497 return RetTy;
David Blaikie5f6e2f42013-06-05 05:32:23 +00001498 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001499
David Blaikie27804892013-08-15 20:49:17 +00001500 return CreateTypeDefinition(Ty);
1501}
1502
1503llvm::DIType CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {
1504 RecordDecl *RD = Ty->getDecl();
1505
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001506 // Get overall information about the record type for the debug info.
1507 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1508
1509 // Records and classes and unions can all be recursive. To handle them, we
1510 // first generate a debug descriptor for the struct as a forward declaration.
1511 // Then (if it is a definition) we go through and get debug info for all of
1512 // its members. Finally, we create a descriptor for the complete type (which
1513 // may refer to the forward decl if the struct is recursive) and replace all
1514 // uses of the forward declaration with the final definition.
1515
David Blaikie4a077162013-08-12 22:24:20 +00001516 llvm::DICompositeType FwdDecl(getOrCreateLimitedType(Ty, DefUnit));
Manman Renb6b0a712013-07-02 19:01:53 +00001517 assert(FwdDecl.isCompositeType() &&
David Blaikie9a845292013-05-22 23:22:42 +00001518 "The debug type of a RecordType should be a llvm::DICompositeType");
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001519
1520 if (FwdDecl.isForwardDecl())
1521 return FwdDecl;
1522
David Blaikie498298d2013-08-18 16:55:33 +00001523 if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
1524 CollectContainingType(CXXDecl, FwdDecl);
1525
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001526 // Push the struct on region stack.
Eric Christopherf068c922013-04-02 22:59:11 +00001527 LexicalBlockStack.push_back(&*FwdDecl);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001528 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1529
Adrian Prantl4919de62013-03-06 22:03:30 +00001530 // Add this to the completed-type cache while we're completing it recursively.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001531 CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1532
1533 // Convert all the elements.
1534 SmallVector<llvm::Value *, 16> EltTys;
David Blaikie5434fc22013-08-20 01:28:15 +00001535 // what about nested types?
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001536
1537 // Note: The split of CXXDecl information here is intentional, the
1538 // gdb tests will depend on a certain ordering at printout. The debug
1539 // information offsets are still correct if we merge them all together
1540 // though.
1541 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1542 if (CXXDecl) {
1543 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1544 CollectVTableInfo(CXXDecl, DefUnit, EltTys);
1545 }
1546
Eric Christopher0395de32013-01-16 01:22:32 +00001547 // Collect data fields (including static variables and any initializers).
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001548 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001549 if (CXXDecl) {
1550 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
1551 CollectCXXFriends(CXXDecl, DefUnit, EltTys, FwdDecl);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001552 }
1553
1554 LexicalBlockStack.pop_back();
1555 RegionMap.erase(Ty->getDecl());
1556
1557 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
David Blaikie80588332013-08-01 20:31:40 +00001558 FwdDecl.setTypeArray(Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001559
Eric Christopherf068c922013-04-02 22:59:11 +00001560 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1561 return FwdDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001562}
1563
1564/// CreateType - get objective-c object type.
1565llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1566 llvm::DIFile Unit) {
1567 // Ignore protocols.
1568 return getOrCreateType(Ty->getBaseType(), Unit);
1569}
1570
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001571
1572/// \return true if Getter has the default name for the property PD.
1573static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
1574 const ObjCMethodDecl *Getter) {
1575 assert(PD);
1576 if (!Getter)
1577 return true;
1578
1579 assert(Getter->getDeclName().isObjCZeroArgSelector());
1580 return PD->getName() ==
1581 Getter->getDeclName().getObjCSelector().getNameForSlot(0);
1582}
1583
1584/// \return true if Setter has the default name for the property PD.
1585static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
1586 const ObjCMethodDecl *Setter) {
1587 assert(PD);
1588 if (!Setter)
1589 return true;
1590
1591 assert(Setter->getDeclName().isObjCOneArgSelector());
Adrian Prantl80e8ea92013-06-07 22:29:12 +00001592 return SelectorTable::constructSetterName(PD->getName()) ==
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001593 Setter->getDeclName().getObjCSelector().getNameForSlot(0);
1594}
1595
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001596/// CreateType - get objective-c interface type.
1597llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1598 llvm::DIFile Unit) {
1599 ObjCInterfaceDecl *ID = Ty->getDecl();
1600 if (!ID)
1601 return llvm::DIType();
1602
1603 // Get overall information about the record type for the debug info.
1604 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1605 unsigned Line = getLineNumber(ID->getLocation());
1606 unsigned RuntimeLang = TheCU.getLanguage();
1607
1608 // If this is just a forward declaration return a special forward-declaration
1609 // debug type since we won't be able to lay out the entire type.
1610 ObjCInterfaceDecl *Def = ID->getDefinition();
1611 if (!Def) {
1612 llvm::DIType FwdDecl =
1613 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001614 ID->getName(), TheCU, DefUnit, Line,
1615 RuntimeLang);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001616 return FwdDecl;
1617 }
1618
1619 ID = Def;
1620
1621 // Bit size, align and offset of the type.
1622 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1623 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1624
1625 unsigned Flags = 0;
1626 if (ID->getImplementation())
1627 Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
1628
Eric Christopherf068c922013-04-02 22:59:11 +00001629 llvm::DICompositeType RealDecl =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001630 DBuilder.createStructType(Unit, ID->getName(), DefUnit,
1631 Line, Size, Align, Flags,
David Blaikiec1d0af12013-02-25 01:07:08 +00001632 llvm::DIType(), llvm::DIArray(), RuntimeLang);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001633
1634 // Otherwise, insert it into the CompletedTypeCache so that recursive uses
1635 // will find it and we're emitting the complete type.
Adrian Prantl4919de62013-03-06 22:03:30 +00001636 QualType QualTy = QualType(Ty, 0);
1637 CompletedTypeCache[QualTy.getAsOpaquePtr()] = RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001638
Eric Christopherd3003dc2013-07-14 21:00:07 +00001639 // Push the struct on region stack.
Eric Christopherf068c922013-04-02 22:59:11 +00001640 LexicalBlockStack.push_back(static_cast<llvm::MDNode*>(RealDecl));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001641 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1642
1643 // Convert all the elements.
1644 SmallVector<llvm::Value *, 16> EltTys;
1645
1646 ObjCInterfaceDecl *SClass = ID->getSuperClass();
1647 if (SClass) {
1648 llvm::DIType SClassTy =
1649 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1650 if (!SClassTy.isValid())
1651 return llvm::DIType();
Eric Christopher6537f082013-05-16 00:45:12 +00001652
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001653 llvm::DIType InhTag =
1654 DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
1655 EltTys.push_back(InhTag);
1656 }
1657
Eric Christopherd3003dc2013-07-14 21:00:07 +00001658 // Create entries for all of the properties.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001659 for (ObjCContainerDecl::prop_iterator I = ID->prop_begin(),
1660 E = ID->prop_end(); I != E; ++I) {
1661 const ObjCPropertyDecl *PD = *I;
1662 SourceLocation Loc = PD->getLocation();
1663 llvm::DIFile PUnit = getOrCreateFile(Loc);
1664 unsigned PLine = getLineNumber(Loc);
1665 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1666 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1667 llvm::MDNode *PropertyNode =
1668 DBuilder.createObjCProperty(PD->getName(),
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001669 PUnit, PLine,
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001670 hasDefaultGetterName(PD, Getter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001671 getSelectorName(PD->getGetterName()),
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001672 hasDefaultSetterName(PD, Setter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001673 getSelectorName(PD->getSetterName()),
1674 PD->getPropertyAttributes(),
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001675 getOrCreateType(PD->getType(), PUnit));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001676 EltTys.push_back(PropertyNode);
1677 }
1678
1679 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1680 unsigned FieldNo = 0;
1681 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1682 Field = Field->getNextIvar(), ++FieldNo) {
1683 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1684 if (!FieldTy.isValid())
1685 return llvm::DIType();
Eric Christopher6537f082013-05-16 00:45:12 +00001686
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001687 StringRef FieldName = Field->getName();
1688
1689 // Ignore unnamed fields.
1690 if (FieldName.empty())
1691 continue;
1692
1693 // Get the location for the field.
1694 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1695 unsigned FieldLine = getLineNumber(Field->getLocation());
1696 QualType FType = Field->getType();
1697 uint64_t FieldSize = 0;
1698 unsigned FieldAlign = 0;
1699
1700 if (!FType->isIncompleteArrayType()) {
1701
1702 // Bit size, align and offset of the type.
1703 FieldSize = Field->isBitField()
Eric Christopherd3003dc2013-07-14 21:00:07 +00001704 ? Field->getBitWidthValue(CGM.getContext())
1705 : CGM.getContext().getTypeSize(FType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001706 FieldAlign = CGM.getContext().getTypeAlign(FType);
1707 }
1708
1709 uint64_t FieldOffset;
1710 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1711 // We don't know the runtime offset of an ivar if we're using the
1712 // non-fragile ABI. For bitfields, use the bit offset into the first
1713 // byte of storage of the bitfield. For other fields, use zero.
1714 if (Field->isBitField()) {
1715 FieldOffset = CGM.getObjCRuntime().ComputeBitfieldBitOffset(
1716 CGM, ID, Field);
1717 FieldOffset %= CGM.getContext().getCharWidth();
1718 } else {
1719 FieldOffset = 0;
1720 }
1721 } else {
1722 FieldOffset = RL.getFieldOffset(FieldNo);
1723 }
1724
1725 unsigned Flags = 0;
1726 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1727 Flags = llvm::DIDescriptor::FlagProtected;
1728 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1729 Flags = llvm::DIDescriptor::FlagPrivate;
1730
1731 llvm::MDNode *PropertyNode = NULL;
1732 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
Eric Christopher6537f082013-05-16 00:45:12 +00001733 if (ObjCPropertyImplDecl *PImpD =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001734 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
1735 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001736 SourceLocation Loc = PD->getLocation();
1737 llvm::DIFile PUnit = getOrCreateFile(Loc);
1738 unsigned PLine = getLineNumber(Loc);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001739 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1740 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1741 PropertyNode =
1742 DBuilder.createObjCProperty(PD->getName(),
1743 PUnit, PLine,
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001744 hasDefaultGetterName(PD, Getter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001745 getSelectorName(PD->getGetterName()),
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001746 hasDefaultSetterName(PD, Setter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001747 getSelectorName(PD->getSetterName()),
1748 PD->getPropertyAttributes(),
1749 getOrCreateType(PD->getType(), PUnit));
1750 }
1751 }
1752 }
1753 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
1754 FieldLine, FieldSize, FieldAlign,
1755 FieldOffset, Flags, FieldTy,
1756 PropertyNode);
1757 EltTys.push_back(FieldTy);
1758 }
1759
1760 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopherf068c922013-04-02 22:59:11 +00001761 RealDecl.setTypeArray(Elements);
Adrian Prantl4919de62013-03-06 22:03:30 +00001762
1763 // If the implementation is not yet set, we do not want to mark it
1764 // as complete. An implementation may declare additional
1765 // private ivars that we would miss otherwise.
1766 if (ID->getImplementation() == 0)
1767 CompletedTypeCache.erase(QualTy.getAsOpaquePtr());
Eric Christopher6537f082013-05-16 00:45:12 +00001768
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001769 LexicalBlockStack.pop_back();
Eric Christopherf068c922013-04-02 22:59:11 +00001770 return RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001771}
1772
1773llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) {
1774 llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1775 int64_t Count = Ty->getNumElements();
1776 if (Count == 0)
1777 // If number of elements are not known then this is an unbounded array.
1778 // Use Count == -1 to express such arrays.
1779 Count = -1;
1780
1781 llvm::Value *Subscript = DBuilder.getOrCreateSubrange(0, Count);
1782 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1783
1784 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1785 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1786
1787 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1788}
1789
1790llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1791 llvm::DIFile Unit) {
1792 uint64_t Size;
1793 uint64_t Align;
1794
1795 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1796 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1797 Size = 0;
1798 Align =
1799 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1800 } else if (Ty->isIncompleteArrayType()) {
1801 Size = 0;
1802 if (Ty->getElementType()->isIncompleteType())
1803 Align = 0;
1804 else
1805 Align = CGM.getContext().getTypeAlign(Ty->getElementType());
David Blaikie089db2e2013-05-09 20:48:12 +00001806 } else if (Ty->isIncompleteType()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001807 Size = 0;
1808 Align = 0;
1809 } else {
1810 // Size and align of the whole array, not the element type.
1811 Size = CGM.getContext().getTypeSize(Ty);
1812 Align = CGM.getContext().getTypeAlign(Ty);
1813 }
1814
1815 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
1816 // interior arrays, do we care? Why aren't nested arrays represented the
1817 // obvious/recursive way?
1818 SmallVector<llvm::Value *, 8> Subscripts;
1819 QualType EltTy(Ty, 0);
1820 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1821 // If the number of elements is known, then count is that number. Otherwise,
1822 // it's -1. This allows us to represent a subrange with an array of 0
1823 // elements, like this:
1824 //
1825 // struct foo {
1826 // int x[0];
1827 // };
1828 int64_t Count = -1; // Count == -1 is an unbounded array.
1829 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1830 Count = CAT->getSize().getZExtValue();
Eric Christopher6537f082013-05-16 00:45:12 +00001831
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001832 // FIXME: Verify this is right for VLAs.
1833 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
1834 EltTy = Ty->getElementType();
1835 }
1836
1837 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1838
Eric Christopher6537f082013-05-16 00:45:12 +00001839 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001840 DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1841 SubscriptArray);
1842 return DbgTy;
1843}
1844
Eric Christopher6537f082013-05-16 00:45:12 +00001845llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001846 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +00001847 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001848 Ty, Ty->getPointeeType(), Unit);
1849}
1850
Eric Christopher6537f082013-05-16 00:45:12 +00001851llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001852 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +00001853 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001854 Ty, Ty->getPointeeType(), Unit);
1855}
1856
Eric Christopher6537f082013-05-16 00:45:12 +00001857llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001858 llvm::DIFile U) {
David Blaikiee8d75142013-01-19 19:20:56 +00001859 llvm::DIType ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
1860 if (!Ty->getPointeeType()->isFunctionType())
1861 return DBuilder.createMemberPointerType(
David Blaikie47251962013-08-22 13:36:01 +00001862 getOrCreateType(Ty->getPointeeType(), U), ClassType);
David Blaikiee8d75142013-01-19 19:20:56 +00001863 return DBuilder.createMemberPointerType(getOrCreateInstanceMethodType(
1864 CGM.getContext().getPointerType(
1865 QualType(Ty->getClass(), Ty->getPointeeType().getCVRQualifiers())),
1866 Ty->getPointeeType()->getAs<FunctionProtoType>(), U),
1867 ClassType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001868}
1869
Eric Christopher6537f082013-05-16 00:45:12 +00001870llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001871 llvm::DIFile U) {
1872 // Ignore the atomic wrapping
1873 // FIXME: What is the correct representation?
1874 return getOrCreateType(Ty->getValueType(), U);
1875}
1876
1877/// CreateEnumType - get enumeration type.
Manman Ren0a0be742013-08-28 21:46:36 +00001878llvm::DIType CGDebugInfo::CreateEnumType(const EnumType *Ty) {
Manman Renf3327332013-08-28 21:20:28 +00001879 const EnumDecl *ED = Ty->getDecl();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001880 uint64_t Size = 0;
1881 uint64_t Align = 0;
1882 if (!ED->getTypeForDecl()->isIncompleteType()) {
1883 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1884 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1885 }
1886
1887 // If this is just a forward declaration, construct an appropriately
1888 // marked node and just return it.
1889 if (!ED->getDefinition()) {
1890 llvm::DIDescriptor EDContext;
1891 EDContext = getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1892 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1893 unsigned Line = getLineNumber(ED->getLocation());
1894 StringRef EDName = ED->getName();
1895 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_enumeration_type,
1896 EDName, EDContext, DefUnit, Line, 0,
Manman Ren18760452013-08-29 20:48:48 +00001897 Size, Align);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001898 }
1899
1900 // Create DIEnumerator elements for each enumerator.
1901 SmallVector<llvm::Value *, 16> Enumerators;
1902 ED = ED->getDefinition();
1903 for (EnumDecl::enumerator_iterator
1904 Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
1905 Enum != EnumEnd; ++Enum) {
1906 Enumerators.push_back(
1907 DBuilder.createEnumerator(Enum->getName(),
David Blaikieac8f43c2013-06-24 07:13:13 +00001908 Enum->getInitVal().getSExtValue()));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001909 }
1910
1911 // Return a CompositeType for the enum itself.
1912 llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1913
1914 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1915 unsigned Line = getLineNumber(ED->getLocation());
Eric Christopher6537f082013-05-16 00:45:12 +00001916 llvm::DIDescriptor EnumContext =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001917 getContextDescriptor(cast<Decl>(ED->getDeclContext()));
Adrian Prantl59d6a712013-04-19 19:56:39 +00001918 llvm::DIType ClassTy = ED->isFixed() ?
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001919 getOrCreateType(ED->getIntegerType(), DefUnit) : llvm::DIType();
Eric Christopher6537f082013-05-16 00:45:12 +00001920 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001921 DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1922 Size, Align, EltArray,
Manman Ren18760452013-08-29 20:48:48 +00001923 ClassTy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001924 return DbgTy;
1925}
1926
David Blaikie4b12be62013-01-21 04:37:12 +00001927static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
1928 Qualifiers Quals;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001929 do {
David Blaikie4b12be62013-01-21 04:37:12 +00001930 Quals += T.getLocalQualifiers();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001931 QualType LastT = T;
1932 switch (T->getTypeClass()) {
1933 default:
David Blaikie4b12be62013-01-21 04:37:12 +00001934 return C.getQualifiedType(T.getTypePtr(), Quals);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001935 case Type::TemplateSpecialization:
1936 T = cast<TemplateSpecializationType>(T)->desugar();
1937 break;
1938 case Type::TypeOfExpr:
1939 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1940 break;
1941 case Type::TypeOf:
1942 T = cast<TypeOfType>(T)->getUnderlyingType();
1943 break;
1944 case Type::Decltype:
1945 T = cast<DecltypeType>(T)->getUnderlyingType();
1946 break;
1947 case Type::UnaryTransform:
1948 T = cast<UnaryTransformType>(T)->getUnderlyingType();
1949 break;
1950 case Type::Attributed:
1951 T = cast<AttributedType>(T)->getEquivalentType();
1952 break;
1953 case Type::Elaborated:
1954 T = cast<ElaboratedType>(T)->getNamedType();
1955 break;
1956 case Type::Paren:
1957 T = cast<ParenType>(T)->getInnerType();
1958 break;
David Blaikie4b12be62013-01-21 04:37:12 +00001959 case Type::SubstTemplateTypeParm:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001960 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001961 break;
1962 case Type::Auto:
David Blaikie91296482013-05-24 21:24:35 +00001963 QualType DT = cast<AutoType>(T)->getDeducedType();
1964 if (DT.isNull())
1965 return T;
1966 T = DT;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001967 break;
1968 }
Eric Christopher6537f082013-05-16 00:45:12 +00001969
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001970 assert(T != LastT && "Type unwrapping failed to unwrap!");
NAKAMURA Takumid24c9ab2013-01-21 10:51:28 +00001971 (void)LastT;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001972 } while (true);
1973}
1974
Eric Christopherf0890c42013-05-16 00:52:20 +00001975/// getType - Get the type from the cache or return null type if it doesn't
1976/// exist.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001977llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) {
1978
1979 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00001980 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Eric Christopher6537f082013-05-16 00:45:12 +00001981
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001982 // Check for existing entry.
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001983 if (Ty->getTypeClass() == Type::ObjCInterface) {
1984 llvm::Value *V = getCachedInterfaceTypeOrNull(Ty);
1985 if (V)
1986 return llvm::DIType(cast<llvm::MDNode>(V));
1987 else return llvm::DIType();
1988 }
1989
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001990 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1991 TypeCache.find(Ty.getAsOpaquePtr());
1992 if (it != TypeCache.end()) {
1993 // Verify that the debug info still exists.
1994 if (llvm::Value *V = it->second)
1995 return llvm::DIType(cast<llvm::MDNode>(V));
1996 }
1997
1998 return llvm::DIType();
1999}
2000
2001/// getCompletedTypeOrNull - Get the type from the cache or return null if it
2002/// doesn't exist.
2003llvm::DIType CGDebugInfo::getCompletedTypeOrNull(QualType Ty) {
2004
2005 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00002006 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002007
2008 // Check for existing entry.
Adrian Prantl4919de62013-03-06 22:03:30 +00002009 llvm::Value *V = 0;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002010 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
2011 CompletedTypeCache.find(Ty.getAsOpaquePtr());
Adrian Prantl4919de62013-03-06 22:03:30 +00002012 if (it != CompletedTypeCache.end())
2013 V = it->second;
2014 else {
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002015 V = getCachedInterfaceTypeOrNull(Ty);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002016 }
2017
Adrian Prantl4919de62013-03-06 22:03:30 +00002018 // Verify that any cached debug info still exists.
David Blaikie00383082013-08-13 04:21:38 +00002019 return llvm::DIType(cast_or_null<llvm::MDNode>(V));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002020}
2021
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002022/// getCachedInterfaceTypeOrNull - Get the type from the interface
2023/// cache, unless it needs to regenerated. Otherwise return null.
2024llvm::Value *CGDebugInfo::getCachedInterfaceTypeOrNull(QualType Ty) {
2025 // Is there a cached interface that hasn't changed?
2026 llvm::DenseMap<void *, std::pair<llvm::WeakVH, unsigned > >
2027 ::iterator it1 = ObjCInterfaceCache.find(Ty.getAsOpaquePtr());
2028
2029 if (it1 != ObjCInterfaceCache.end())
2030 if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty))
2031 if (Checksum(Decl) == it1->second.second)
2032 // Return cached forward declaration.
2033 return it1->second.first;
2034
2035 return 0;
2036}
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002037
2038/// getOrCreateType - Get the type from the cache or create a new
2039/// one if necessary.
David Blaikie47251962013-08-22 13:36:01 +00002040llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002041 if (Ty.isNull())
2042 return llvm::DIType();
2043
2044 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00002045 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002046
David Blaikie47251962013-08-22 13:36:01 +00002047 if (llvm::DIType T = getCompletedTypeOrNull(Ty))
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002048 return T;
2049
2050 // Otherwise create the type.
David Blaikie47251962013-08-22 13:36:01 +00002051 llvm::DIType Res = CreateTypeNode(Ty, Unit);
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002052 void* TyPtr = Ty.getAsOpaquePtr();
2053
2054 // And update the type cache.
2055 TypeCache[TyPtr] = Res;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002056
David Blaikie492b1022013-08-15 21:21:19 +00002057 // FIXME: this getTypeOrNull call seems silly when we just inserted the type
2058 // into the cache - but getTypeOrNull has a special case for cached interface
2059 // types. We should probably just pull that out as a special case for the
2060 // "else" block below & skip the otherwise needless lookup.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002061 llvm::DIType TC = getTypeOrNull(Ty);
Eric Christopherb2d13922013-07-18 00:52:50 +00002062 if (TC && TC.isForwardDecl())
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002063 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
2064 else if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty)) {
2065 // Interface types may have elements added to them by a
2066 // subsequent implementation or extension, so we keep them in
2067 // the ObjCInterfaceCache together with a checksum. Instead of
Adrian Prantlf06989b2013-05-08 23:37:22 +00002068 // the (possibly) incomplete interface type, we return a forward
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002069 // declaration that gets RAUW'd in CGDebugInfo::finalize().
David Blaikiee2eb89a2013-05-21 18:29:40 +00002070 std::pair<llvm::WeakVH, unsigned> &V = ObjCInterfaceCache[TyPtr];
2071 if (V.first)
2072 return llvm::DIType(cast<llvm::MDNode>(V.first));
2073 TC = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
2074 Decl->getName(), TheCU, Unit,
2075 getLineNumber(Decl->getLocation()),
2076 TheCU.getLanguage());
2077 // Store the forward declaration in the cache.
2078 V.first = TC;
2079 V.second = Checksum(Decl);
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002080
David Blaikiee2eb89a2013-05-21 18:29:40 +00002081 // Register the type for replacement in finalize().
2082 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
2083
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002084 return TC;
Adrian Prantl4919de62013-03-06 22:03:30 +00002085 }
2086
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002087 if (!Res.isForwardDecl())
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002088 CompletedTypeCache[TyPtr] = Res;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002089
2090 return Res;
2091}
2092
Adrian Prantlb5a50072013-06-07 01:10:41 +00002093/// Currently the checksum of an interface includes the number of
2094/// ivars and property accessors.
Eric Christopher56b108a2013-06-07 22:54:39 +00002095unsigned CGDebugInfo::Checksum(const ObjCInterfaceDecl *ID) {
Adrian Prantl4f97f852013-06-07 01:10:48 +00002096 // The assumption is that the number of ivars can only increase
2097 // monotonically, so it is safe to just use their current number as
2098 // a checksum.
Adrian Prantlb5a50072013-06-07 01:10:41 +00002099 unsigned Sum = 0;
2100 for (const ObjCIvarDecl *Ivar = ID->all_declared_ivar_begin();
2101 Ivar != 0; Ivar = Ivar->getNextIvar())
2102 ++Sum;
2103
2104 return Sum;
Adrian Prantl4919de62013-03-06 22:03:30 +00002105}
2106
2107ObjCInterfaceDecl *CGDebugInfo::getObjCInterfaceDecl(QualType Ty) {
2108 switch (Ty->getTypeClass()) {
2109 case Type::ObjCObjectPointer:
Eric Christopherf0890c42013-05-16 00:52:20 +00002110 return getObjCInterfaceDecl(cast<ObjCObjectPointerType>(Ty)
2111 ->getPointeeType());
Adrian Prantl4919de62013-03-06 22:03:30 +00002112 case Type::ObjCInterface:
2113 return cast<ObjCInterfaceType>(Ty)->getDecl();
2114 default:
2115 return 0;
2116 }
2117}
2118
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002119/// CreateTypeNode - Create a new debug type node.
David Blaikie47251962013-08-22 13:36:01 +00002120llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002121 // Handle qualifiers, which recursively handles what they refer to.
2122 if (Ty.hasLocalQualifiers())
David Blaikie47251962013-08-22 13:36:01 +00002123 return CreateQualifiedType(Ty, Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002124
2125 const char *Diag = 0;
Eric Christopher6537f082013-05-16 00:45:12 +00002126
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002127 // Work out details of type.
2128 switch (Ty->getTypeClass()) {
2129#define TYPE(Class, Base)
2130#define ABSTRACT_TYPE(Class, Base)
2131#define NON_CANONICAL_TYPE(Class, Base)
2132#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2133#include "clang/AST/TypeNodes.def"
2134 llvm_unreachable("Dependent types cannot show up in debug information");
2135
2136 case Type::ExtVector:
2137 case Type::Vector:
2138 return CreateType(cast<VectorType>(Ty), Unit);
2139 case Type::ObjCObjectPointer:
2140 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
2141 case Type::ObjCObject:
2142 return CreateType(cast<ObjCObjectType>(Ty), Unit);
2143 case Type::ObjCInterface:
2144 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
2145 case Type::Builtin:
2146 return CreateType(cast<BuiltinType>(Ty));
2147 case Type::Complex:
2148 return CreateType(cast<ComplexType>(Ty));
2149 case Type::Pointer:
2150 return CreateType(cast<PointerType>(Ty), Unit);
Reid Kleckner12df2462013-06-24 17:51:48 +00002151 case Type::Decayed:
2152 // Decayed types are just pointers in LLVM and DWARF.
2153 return CreateType(
2154 cast<PointerType>(cast<DecayedType>(Ty)->getDecayedType()), Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002155 case Type::BlockPointer:
2156 return CreateType(cast<BlockPointerType>(Ty), Unit);
2157 case Type::Typedef:
David Blaikie47251962013-08-22 13:36:01 +00002158 return CreateType(cast<TypedefType>(Ty), Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002159 case Type::Record:
David Blaikie47251962013-08-22 13:36:01 +00002160 return CreateType(cast<RecordType>(Ty));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002161 case Type::Enum:
Manman Renf3327332013-08-28 21:20:28 +00002162 return CreateEnumType(cast<EnumType>(Ty));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002163 case Type::FunctionProto:
2164 case Type::FunctionNoProto:
2165 return CreateType(cast<FunctionType>(Ty), Unit);
2166 case Type::ConstantArray:
2167 case Type::VariableArray:
2168 case Type::IncompleteArray:
2169 return CreateType(cast<ArrayType>(Ty), Unit);
2170
2171 case Type::LValueReference:
2172 return CreateType(cast<LValueReferenceType>(Ty), Unit);
2173 case Type::RValueReference:
2174 return CreateType(cast<RValueReferenceType>(Ty), Unit);
2175
2176 case Type::MemberPointer:
2177 return CreateType(cast<MemberPointerType>(Ty), Unit);
2178
2179 case Type::Atomic:
2180 return CreateType(cast<AtomicType>(Ty), Unit);
2181
2182 case Type::Attributed:
2183 case Type::TemplateSpecialization:
2184 case Type::Elaborated:
2185 case Type::Paren:
2186 case Type::SubstTemplateTypeParm:
2187 case Type::TypeOfExpr:
2188 case Type::TypeOf:
2189 case Type::Decltype:
2190 case Type::UnaryTransform:
David Blaikie226399c2013-07-13 21:08:08 +00002191 case Type::PackExpansion:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002192 llvm_unreachable("type should have been unwrapped!");
David Blaikie91296482013-05-24 21:24:35 +00002193 case Type::Auto:
2194 Diag = "auto";
2195 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002196 }
Eric Christopher6537f082013-05-16 00:45:12 +00002197
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002198 assert(Diag && "Fall through without a diagnostic?");
2199 unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error,
2200 "debug information for %0 is not yet supported");
2201 CGM.getDiags().Report(DiagID)
2202 << Diag;
2203 return llvm::DIType();
2204}
2205
2206/// getOrCreateLimitedType - Get the type from the cache or create a new
2207/// limited type if necessary.
David Blaikie4a077162013-08-12 22:24:20 +00002208llvm::DIType CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002209 llvm::DIFile Unit) {
David Blaikie4a077162013-08-12 22:24:20 +00002210 QualType QTy(Ty, 0);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002211
David Blaikieeaacc882013-08-20 21:03:29 +00002212 llvm::DICompositeType T(getTypeOrNull(QTy));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002213
2214 // We may have cached a forward decl when we could have created
2215 // a non-forward decl. Go ahead and create a non-forward decl
2216 // now.
Eric Christopherb2d13922013-07-18 00:52:50 +00002217 if (T && !T.isForwardDecl()) return T;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002218
2219 // Otherwise create the type.
David Blaikieeaacc882013-08-20 21:03:29 +00002220 llvm::DICompositeType Res = CreateLimitedType(Ty);
2221
2222 // Propagate members from the declaration to the definition
2223 // CreateType(const RecordType*) will overwrite this with the members in the
2224 // correct order if the full type is needed.
2225 Res.setTypeArray(T.getTypeArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002226
Eric Christopherb2d13922013-07-18 00:52:50 +00002227 if (T && T.isForwardDecl())
David Blaikie4a077162013-08-12 22:24:20 +00002228 ReplaceMap.push_back(
2229 std::make_pair(QTy.getAsOpaquePtr(), static_cast<llvm::Value *>(T)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002230
2231 // And update the type cache.
David Blaikie4a077162013-08-12 22:24:20 +00002232 TypeCache[QTy.getAsOpaquePtr()] = Res;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002233 return Res;
2234}
2235
2236// TODO: Currently used for context chains when limiting debug info.
David Blaikieeaacc882013-08-20 21:03:29 +00002237llvm::DICompositeType CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002238 RecordDecl *RD = Ty->getDecl();
Eric Christopher6537f082013-05-16 00:45:12 +00002239
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002240 // Get overall information about the record type for the debug info.
2241 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
2242 unsigned Line = getLineNumber(RD->getLocation());
2243 StringRef RDName = getClassName(RD);
2244
2245 llvm::DIDescriptor RDContext;
Eric Christopher13c97672013-05-16 00:45:23 +00002246 if (DebugKind == CodeGenOptions::LimitedDebugInfo)
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002247 RDContext = createContextChain(cast<Decl>(RD->getDeclContext()));
2248 else
2249 RDContext = getContextDescriptor(cast<Decl>(RD->getDeclContext()));
2250
David Blaikiec138ff52013-08-18 17:36:19 +00002251 // If we ended up creating the type during the context chain construction,
2252 // just return that.
2253 // FIXME: this could be dealt with better if the type was recorded as
2254 // completed before we started this (see the CompletedTypeCache usage in
2255 // CGDebugInfo::CreateTypeDefinition(const RecordType*) - that would need to
2256 // be pushed to before context creation, but after it was known to be
2257 // destined for completion (might still have an issue if this caller only
2258 // required a declaration but the context construction ended up creating a
2259 // definition)
David Blaikieeaacc882013-08-20 21:03:29 +00002260 llvm::DICompositeType T(getTypeOrNull(CGM.getContext().getRecordType(RD)));
2261 if (T && (!T.isForwardDecl() || !RD->getDefinition()))
David Blaikiec138ff52013-08-18 17:36:19 +00002262 return T;
2263
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002264 // If this is just a forward declaration, construct an appropriately
2265 // marked node and just return it.
2266 if (!RD->getDefinition())
Manman Renf3327332013-08-28 21:20:28 +00002267 return getOrCreateRecordFwdDecl(Ty, RDContext);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002268
2269 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2270 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
David Blaikie2fcadbe2013-03-26 23:47:35 +00002271 llvm::DICompositeType RealDecl;
Eric Christopher6537f082013-05-16 00:45:12 +00002272
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002273 if (RD->isUnion())
2274 RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
Manman Ren18760452013-08-29 20:48:48 +00002275 Size, Align, 0, llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002276 else if (RD->isClass()) {
2277 // FIXME: This could be a struct type giving a default visibility different
2278 // than C++ class type, but needs llvm metadata changes first.
2279 RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002280 Size, Align, 0, 0, llvm::DIType(),
2281 llvm::DIArray(), llvm::DIType(),
Manman Ren18760452013-08-29 20:48:48 +00002282 llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002283 } else
2284 RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line,
Eric Christopherf0890c42013-05-16 00:52:20 +00002285 Size, Align, 0, llvm::DIType(),
Manman Ren18760452013-08-29 20:48:48 +00002286 llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002287
2288 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
David Blaikie2fcadbe2013-03-26 23:47:35 +00002289 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002290
David Blaikie498298d2013-08-18 16:55:33 +00002291 if (const ClassTemplateSpecializationDecl *TSpecial =
2292 dyn_cast<ClassTemplateSpecializationDecl>(RD))
2293 RealDecl.setTypeArray(llvm::DIArray(),
2294 CollectCXXTemplateParams(TSpecial, DefUnit));
David Blaikiefab829d2013-08-15 22:42:12 +00002295 return RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002296}
2297
David Blaikie498298d2013-08-18 16:55:33 +00002298void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,
2299 llvm::DICompositeType RealDecl) {
2300 // A class's primary base or the class itself contains the vtable.
2301 llvm::DICompositeType ContainingType;
2302 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2303 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
2304 // Seek non virtual primary base root.
2305 while (1) {
2306 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
2307 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
2308 if (PBT && !BRL.isPrimaryBaseVirtual())
2309 PBase = PBT;
2310 else
2311 break;
2312 }
2313 ContainingType = llvm::DICompositeType(
2314 getOrCreateType(QualType(PBase->getTypeForDecl(), 0),
2315 getOrCreateFile(RD->getLocation())));
2316 } else if (RD->isDynamicClass())
2317 ContainingType = RealDecl;
2318
2319 RealDecl.setContainingType(ContainingType);
2320}
2321
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002322/// CreateMemberType - Create new member and increase Offset by FType's size.
2323llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
2324 StringRef Name,
2325 uint64_t *Offset) {
2326 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2327 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
2328 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
2329 llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0,
2330 FieldSize, FieldAlign,
2331 *Offset, 0, FieldTy);
2332 *Offset += FieldSize;
2333 return Ty;
2334}
2335
David Blaikie9faebd22013-05-20 04:58:53 +00002336llvm::DIDescriptor CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
2337 // We only need a declaration (not a definition) of the type - so use whatever
2338 // we would otherwise do to get a type for a pointee. (forward declarations in
2339 // limited debug info, full definitions (if the type definition is available)
2340 // in unlimited debug info)
David Blaikieb3c23772013-08-12 23:14:36 +00002341 if (const TypeDecl *TD = dyn_cast<TypeDecl>(D))
2342 return getOrCreateType(CGM.getContext().getTypeDeclType(TD),
David Blaikie47251962013-08-22 13:36:01 +00002343 getOrCreateFile(TD->getLocation()));
David Blaikie9faebd22013-05-20 04:58:53 +00002344 // Otherwise fall back to a fairly rudimentary cache of existing declarations.
2345 // This doesn't handle providing declarations (for functions or variables) for
2346 // entities without definitions in this TU, nor when the definition proceeds
2347 // the call to this function.
2348 // FIXME: This should be split out into more specific maps with support for
2349 // emitting forward declarations and merging definitions with declarations,
2350 // the same way as we do for types.
2351 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator I =
2352 DeclCache.find(D->getCanonicalDecl());
2353 if (I == DeclCache.end())
2354 return llvm::DIDescriptor();
2355 llvm::Value *V = I->second;
2356 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
2357}
2358
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002359/// getFunctionDeclaration - Return debug info descriptor to describe method
2360/// declaration for the given method definition.
2361llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
David Blaikie23e66db2013-06-22 00:09:36 +00002362 if (!D || DebugKind == CodeGenOptions::DebugLineTablesOnly)
2363 return llvm::DISubprogram();
2364
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002365 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
2366 if (!FD) return llvm::DISubprogram();
2367
2368 // Setup context.
David Blaikied6d5d692013-08-09 17:20:05 +00002369 llvm::DIScope S = getContextDescriptor(cast<Decl>(D->getDeclContext()));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002370
2371 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2372 MI = SPCache.find(FD->getCanonicalDecl());
David Blaikied6d5d692013-08-09 17:20:05 +00002373 if (MI == SPCache.end()) {
Eric Christopherac7c25f2013-08-28 23:12:10 +00002374 if (const CXXMethodDecl *MD =
2375 dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
David Blaikied6d5d692013-08-09 17:20:05 +00002376 llvm::DICompositeType T(S);
Eric Christopherac7c25f2013-08-28 23:12:10 +00002377 llvm::DISubprogram SP =
2378 CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()), T);
David Blaikied6d5d692013-08-09 17:20:05 +00002379 T.addMember(SP);
2380 return SP;
2381 }
2382 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002383 if (MI != SPCache.end()) {
2384 llvm::Value *V = MI->second;
2385 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
David Blaikie23e66db2013-06-22 00:09:36 +00002386 if (SP.isSubprogram() && !SP.isDefinition())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002387 return SP;
2388 }
2389
2390 for (FunctionDecl::redecl_iterator I = FD->redecls_begin(),
2391 E = FD->redecls_end(); I != E; ++I) {
2392 const FunctionDecl *NextFD = *I;
2393 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2394 MI = SPCache.find(NextFD->getCanonicalDecl());
2395 if (MI != SPCache.end()) {
2396 llvm::Value *V = MI->second;
2397 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
David Blaikie23e66db2013-06-22 00:09:36 +00002398 if (SP.isSubprogram() && !SP.isDefinition())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002399 return SP;
2400 }
2401 }
2402 return llvm::DISubprogram();
2403}
2404
2405// getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
2406// implicit parameter "this".
David Blaikie9a845292013-05-22 23:22:42 +00002407llvm::DICompositeType CGDebugInfo::getOrCreateFunctionType(const Decl *D,
2408 QualType FnType,
2409 llvm::DIFile F) {
David Blaikie23e66db2013-06-22 00:09:36 +00002410 if (!D || DebugKind == CodeGenOptions::DebugLineTablesOnly)
2411 // Create fake but valid subroutine type. Otherwise
2412 // llvm::DISubprogram::Verify() would return false, and
2413 // subprogram DIE will miss DW_AT_decl_file and
2414 // DW_AT_decl_line fields.
2415 return DBuilder.createSubroutineType(F, DBuilder.getOrCreateArray(None));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002416
2417 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
2418 return getOrCreateMethodType(Method, F);
2419 if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
2420 // Add "self" and "_cmd"
2421 SmallVector<llvm::Value *, 16> Elts;
2422
2423 // First element is always return type. For 'void' functions it is NULL.
Adrian Prantl0cb00022013-05-22 21:37:49 +00002424 QualType ResultTy = OMethod->getResultType();
2425
2426 // Replace the instancetype keyword with the actual type.
2427 if (ResultTy == CGM.getContext().getObjCInstanceType())
2428 ResultTy = CGM.getContext().getPointerType(
2429 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
2430
Adrian Prantl566a9c32013-05-10 21:08:31 +00002431 Elts.push_back(getOrCreateType(ResultTy, F));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002432 // "self" pointer is always first argument.
Adrian Prantle86fcc42013-03-29 19:20:29 +00002433 QualType SelfDeclTy = OMethod->getSelfDecl()->getType();
2434 llvm::DIType SelfTy = getOrCreateType(SelfDeclTy, F);
2435 Elts.push_back(CreateSelfType(SelfDeclTy, SelfTy));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002436 // "_cmd" pointer is always second argument.
2437 llvm::DIType CmdTy = getOrCreateType(OMethod->getCmdDecl()->getType(), F);
2438 Elts.push_back(DBuilder.createArtificialType(CmdTy));
2439 // Get rest of the arguments.
Eric Christopher6537f082013-05-16 00:45:12 +00002440 for (ObjCMethodDecl::param_const_iterator PI = OMethod->param_begin(),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002441 PE = OMethod->param_end(); PI != PE; ++PI)
2442 Elts.push_back(getOrCreateType((*PI)->getType(), F));
2443
2444 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2445 return DBuilder.createSubroutineType(F, EltTypeArray);
2446 }
David Blaikie9a845292013-05-22 23:22:42 +00002447 return llvm::DICompositeType(getOrCreateType(FnType, F));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002448}
2449
2450/// EmitFunctionStart - Constructs the debug code for entering a function.
2451void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
2452 llvm::Function *Fn,
2453 CGBuilderTy &Builder) {
2454
2455 StringRef Name;
2456 StringRef LinkageName;
2457
2458 FnBeginRegionCount.push_back(LexicalBlockStack.size());
2459
2460 const Decl *D = GD.getDecl();
2461 // Function may lack declaration in source code if it is created by Clang
2462 // CodeGen (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
2463 bool HasDecl = (D != 0);
2464 // Use the location of the declaration.
2465 SourceLocation Loc;
2466 if (HasDecl)
2467 Loc = D->getLocation();
2468
2469 unsigned Flags = 0;
2470 llvm::DIFile Unit = getOrCreateFile(Loc);
2471 llvm::DIDescriptor FDContext(Unit);
2472 llvm::DIArray TParamsArray;
2473 if (!HasDecl) {
2474 // Use llvm function name.
David Blaikiec7971a92013-08-27 23:57:18 +00002475 LinkageName = Fn->getName();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002476 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2477 // If there is a DISubprogram for this function available then use it.
2478 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2479 FI = SPCache.find(FD->getCanonicalDecl());
2480 if (FI != SPCache.end()) {
2481 llvm::Value *V = FI->second;
2482 llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(V));
2483 if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
2484 llvm::MDNode *SPN = SP;
2485 LexicalBlockStack.push_back(SPN);
2486 RegionMap[D] = llvm::WeakVH(SP);
2487 return;
2488 }
2489 }
2490 Name = getFunctionName(FD);
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002491 // Use mangled name as linkage name for C/C++ functions.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002492 if (FD->hasPrototype()) {
2493 LinkageName = CGM.getMangledName(GD);
2494 Flags |= llvm::DIDescriptor::FlagPrototyped;
2495 }
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002496 // No need to replicate the linkage name if it isn't different from the
2497 // subprogram name, no need to have it at all unless coverage is enabled or
2498 // debug is set to more than just line tables.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002499 if (LinkageName == Name ||
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002500 (!CGM.getCodeGenOpts().EmitGcovArcs &&
2501 !CGM.getCodeGenOpts().EmitGcovNotes &&
Eric Christopher13c97672013-05-16 00:45:23 +00002502 DebugKind <= CodeGenOptions::DebugLineTablesOnly))
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002503 LinkageName = StringRef();
2504
Eric Christopher13c97672013-05-16 00:45:23 +00002505 if (DebugKind >= CodeGenOptions::LimitedDebugInfo) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002506 if (const NamespaceDecl *NSDecl =
2507 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
2508 FDContext = getOrCreateNameSpace(NSDecl);
2509 else if (const RecordDecl *RDecl =
2510 dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
2511 FDContext = getContextDescriptor(cast<Decl>(RDecl->getDeclContext()));
2512
2513 // Collect template parameters.
2514 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
2515 }
2516 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
2517 Name = getObjCMethodName(OMD);
2518 Flags |= llvm::DIDescriptor::FlagPrototyped;
2519 } else {
2520 // Use llvm function name.
2521 Name = Fn->getName();
2522 Flags |= llvm::DIDescriptor::FlagPrototyped;
2523 }
2524 if (!Name.empty() && Name[0] == '\01')
2525 Name = Name.substr(1);
2526
2527 unsigned LineNo = getLineNumber(Loc);
2528 if (!HasDecl || D->isImplicit())
2529 Flags |= llvm::DIDescriptor::FlagArtificial;
2530
David Blaikie23e66db2013-06-22 00:09:36 +00002531 llvm::DISubprogram SP = DBuilder.createFunction(
2532 FDContext, Name, LinkageName, Unit, LineNo,
2533 getOrCreateFunctionType(D, FnType, Unit), Fn->hasInternalLinkage(),
2534 true /*definition*/, getLineNumber(CurLoc), Flags,
2535 CGM.getLangOpts().Optimize, Fn, TParamsArray, getFunctionDeclaration(D));
David Blaikie9faebd22013-05-20 04:58:53 +00002536 if (HasDecl)
2537 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(SP)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002538
2539 // Push function on region stack.
2540 llvm::MDNode *SPN = SP;
2541 LexicalBlockStack.push_back(SPN);
2542 if (HasDecl)
2543 RegionMap[D] = llvm::WeakVH(SP);
2544}
2545
2546/// EmitLocation - Emit metadata to indicate a change in line/column
Adrian Prantl18a0cd52013-07-18 00:27:59 +00002547/// information in the source file. If the location is invalid, the
2548/// previous location will be reused.
Adrian Prantl00df5ea2013-03-12 20:43:25 +00002549void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc,
2550 bool ForceColumnInfo) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002551 // Update our current location
2552 setLocation(Loc);
2553
2554 if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
2555
2556 // Don't bother if things are the same as last time.
2557 SourceManager &SM = CGM.getContext().getSourceManager();
2558 if (CurLoc == PrevLoc ||
2559 SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc))
2560 // New Builder may not be in sync with CGDebugInfo.
David Blaikie0a0f93c2013-02-01 19:09:49 +00002561 if (!Builder.getCurrentDebugLocation().isUnknown() &&
2562 Builder.getCurrentDebugLocation().getScope(CGM.getLLVMContext()) ==
2563 LexicalBlockStack.back())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002564 return;
Eric Christopher6537f082013-05-16 00:45:12 +00002565
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002566 // Update last state.
2567 PrevLoc = CurLoc;
2568
2569 llvm::MDNode *Scope = LexicalBlockStack.back();
Adrian Prantl00df5ea2013-03-12 20:43:25 +00002570 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get
2571 (getLineNumber(CurLoc),
2572 getColumnNumber(CurLoc, ForceColumnInfo),
2573 Scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002574}
2575
2576/// CreateLexicalBlock - Creates a new lexical block node and pushes it on
2577/// the stack.
2578void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
2579 llvm::DIDescriptor D =
2580 DBuilder.createLexicalBlock(LexicalBlockStack.empty() ?
2581 llvm::DIDescriptor() :
2582 llvm::DIDescriptor(LexicalBlockStack.back()),
2583 getOrCreateFile(CurLoc),
2584 getLineNumber(CurLoc),
2585 getColumnNumber(CurLoc));
2586 llvm::MDNode *DN = D;
2587 LexicalBlockStack.push_back(DN);
2588}
2589
2590/// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
2591/// region - beginning of a DW_TAG_lexical_block.
Eric Christopherf0890c42013-05-16 00:52:20 +00002592void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
2593 SourceLocation Loc) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002594 // Set our current location.
2595 setLocation(Loc);
2596
2597 // Create a new lexical block and push it on the stack.
2598 CreateLexicalBlock(Loc);
2599
2600 // Emit a line table change for the current location inside the new scope.
2601 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc),
2602 getColumnNumber(Loc),
2603 LexicalBlockStack.back()));
2604}
2605
2606/// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative
2607/// region - end of a DW_TAG_lexical_block.
Eric Christopherf0890c42013-05-16 00:52:20 +00002608void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
2609 SourceLocation Loc) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002610 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2611
2612 // Provide an entry in the line table for the end of the block.
2613 EmitLocation(Builder, Loc);
2614
2615 LexicalBlockStack.pop_back();
2616}
2617
2618/// EmitFunctionEnd - Constructs the debug code for exiting a function.
2619void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
2620 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2621 unsigned RCount = FnBeginRegionCount.back();
2622 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
2623
2624 // Pop all regions for this function.
2625 while (LexicalBlockStack.size() != RCount)
2626 EmitLexicalBlockEnd(Builder, CurLoc);
2627 FnBeginRegionCount.pop_back();
2628}
2629
Eric Christopher6537f082013-05-16 00:45:12 +00002630// EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002631// See BuildByRefType.
2632llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
2633 uint64_t *XOffset) {
2634
2635 SmallVector<llvm::Value *, 5> EltTys;
2636 QualType FType;
2637 uint64_t FieldSize, FieldOffset;
2638 unsigned FieldAlign;
Eric Christopher6537f082013-05-16 00:45:12 +00002639
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002640 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
Eric Christopher6537f082013-05-16 00:45:12 +00002641 QualType Type = VD->getType();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002642
2643 FieldOffset = 0;
2644 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2645 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
2646 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
2647 FType = CGM.getContext().IntTy;
2648 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
2649 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
2650
2651 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
2652 if (HasCopyAndDispose) {
2653 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2654 EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
2655 &FieldOffset));
2656 EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
2657 &FieldOffset));
2658 }
2659 bool HasByrefExtendedLayout;
2660 Qualifiers::ObjCLifetime Lifetime;
2661 if (CGM.getContext().getByrefLifetime(Type,
2662 Lifetime, HasByrefExtendedLayout)
Adrian Prantl1f437912013-07-23 00:12:14 +00002663 && HasByrefExtendedLayout) {
2664 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002665 EltTys.push_back(CreateMemberType(Unit, FType,
2666 "__byref_variable_layout",
2667 &FieldOffset));
Adrian Prantl1f437912013-07-23 00:12:14 +00002668 }
Eric Christopher6537f082013-05-16 00:45:12 +00002669
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002670 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2671 if (Align > CGM.getContext().toCharUnitsFromBits(
John McCall64aa4b32013-04-16 22:48:15 +00002672 CGM.getTarget().getPointerAlign(0))) {
Eric Christopher6537f082013-05-16 00:45:12 +00002673 CharUnits FieldOffsetInBytes
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002674 = CGM.getContext().toCharUnitsFromBits(FieldOffset);
2675 CharUnits AlignedOffsetInBytes
2676 = FieldOffsetInBytes.RoundUpToAlignment(Align);
2677 CharUnits NumPaddingBytes
2678 = AlignedOffsetInBytes - FieldOffsetInBytes;
Eric Christopher6537f082013-05-16 00:45:12 +00002679
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002680 if (NumPaddingBytes.isPositive()) {
2681 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
2682 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
2683 pad, ArrayType::Normal, 0);
2684 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
2685 }
2686 }
Eric Christopher6537f082013-05-16 00:45:12 +00002687
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002688 FType = Type;
2689 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2690 FieldSize = CGM.getContext().getTypeSize(FType);
2691 FieldAlign = CGM.getContext().toBits(Align);
2692
Eric Christopher6537f082013-05-16 00:45:12 +00002693 *XOffset = FieldOffset;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002694 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit,
2695 0, FieldSize, FieldAlign,
2696 FieldOffset, 0, FieldTy);
2697 EltTys.push_back(FieldTy);
2698 FieldOffset += FieldSize;
Eric Christopher6537f082013-05-16 00:45:12 +00002699
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002700 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopher6537f082013-05-16 00:45:12 +00002701
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002702 unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
Eric Christopher6537f082013-05-16 00:45:12 +00002703
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002704 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
David Blaikiec1d0af12013-02-25 01:07:08 +00002705 llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002706}
2707
2708/// EmitDeclare - Emit local variable declaration debug info.
2709void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
Eric Christopher6537f082013-05-16 00:45:12 +00002710 llvm::Value *Storage,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002711 unsigned ArgNo, CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002712 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002713 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2714
David Blaikiefc946272013-08-19 03:37:48 +00002715 bool Unwritten =
2716 VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) &&
2717 cast<Decl>(VD->getDeclContext())->isImplicit());
2718 llvm::DIFile Unit;
2719 if (!Unwritten)
2720 Unit = getOrCreateFile(VD->getLocation());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002721 llvm::DIType Ty;
2722 uint64_t XOffset = 0;
2723 if (VD->hasAttr<BlocksAttr>())
2724 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopher6537f082013-05-16 00:45:12 +00002725 else
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002726 Ty = getOrCreateType(VD->getType(), Unit);
2727
2728 // If there is no debug info for this type then do not emit debug info
2729 // for this variable.
2730 if (!Ty)
2731 return;
2732
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002733 // Get location information.
David Blaikiefc946272013-08-19 03:37:48 +00002734 unsigned Line = 0;
2735 unsigned Column = 0;
2736 if (!Unwritten) {
2737 Line = getLineNumber(VD->getLocation());
2738 Column = getColumnNumber(VD->getLocation());
2739 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002740 unsigned Flags = 0;
2741 if (VD->isImplicit())
2742 Flags |= llvm::DIDescriptor::FlagArtificial;
2743 // If this is the first argument and it is implicit then
2744 // give it an object pointer flag.
2745 // FIXME: There has to be a better way to do this, but for static
2746 // functions there won't be an implicit param at arg1 and
2747 // otherwise it is 'self' or 'this'.
2748 if (isa<ImplicitParamDecl>(VD) && ArgNo == 1)
2749 Flags |= llvm::DIDescriptor::FlagObjectPointer;
David Blaikie41c9bae2013-06-19 21:53:53 +00002750 if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage))
Eric Christopher7dab97b2013-07-17 22:52:53 +00002751 if (Arg->getType()->isPointerTy() && !Arg->hasByValAttr() &&
2752 !VD->getType()->isPointerType())
David Blaikie41c9bae2013-06-19 21:53:53 +00002753 Flags |= llvm::DIDescriptor::FlagIndirectVariable;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002754
2755 llvm::MDNode *Scope = LexicalBlockStack.back();
2756
2757 StringRef Name = VD->getName();
2758 if (!Name.empty()) {
2759 if (VD->hasAttr<BlocksAttr>()) {
2760 CharUnits offset = CharUnits::fromQuantity(32);
2761 SmallVector<llvm::Value *, 9> addr;
2762 llvm::Type *Int64Ty = CGM.Int64Ty;
2763 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2764 // offset of __forwarding field
2765 offset = CGM.getContext().toCharUnitsFromBits(
John McCall64aa4b32013-04-16 22:48:15 +00002766 CGM.getTarget().getPointerWidth(0));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002767 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2768 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2769 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2770 // offset of x field
2771 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2772 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2773
2774 // Create the descriptor for the variable.
2775 llvm::DIVariable D =
Eric Christopher6537f082013-05-16 00:45:12 +00002776 DBuilder.createComplexVariable(Tag,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002777 llvm::DIDescriptor(Scope),
2778 VD->getName(), Unit, Line, Ty,
2779 addr, ArgNo);
Eric Christopher6537f082013-05-16 00:45:12 +00002780
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002781 // Insert an llvm.dbg.declare into the current block.
2782 llvm::Instruction *Call =
2783 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2784 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2785 return;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002786 }
David Blaikie436653b2013-01-05 05:58:35 +00002787 } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2788 // If VD is an anonymous union then Storage represents value for
2789 // all union fields.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002790 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
David Blaikied8180cf2013-01-05 20:03:07 +00002791 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002792 for (RecordDecl::field_iterator I = RD->field_begin(),
2793 E = RD->field_end();
2794 I != E; ++I) {
2795 FieldDecl *Field = *I;
2796 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2797 StringRef FieldName = Field->getName();
Eric Christopher6537f082013-05-16 00:45:12 +00002798
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002799 // Ignore unnamed fields. Do not ignore unnamed records.
2800 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2801 continue;
Eric Christopher6537f082013-05-16 00:45:12 +00002802
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002803 // Use VarDecl's Tag, Scope and Line number.
2804 llvm::DIVariable D =
2805 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
Eric Christopher6537f082013-05-16 00:45:12 +00002806 FieldName, Unit, Line, FieldTy,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002807 CGM.getLangOpts().Optimize, Flags,
2808 ArgNo);
Eric Christopher6537f082013-05-16 00:45:12 +00002809
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002810 // Insert an llvm.dbg.declare into the current block.
2811 llvm::Instruction *Call =
2812 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2813 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2814 }
David Blaikied8180cf2013-01-05 20:03:07 +00002815 return;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002816 }
2817 }
David Blaikie436653b2013-01-05 05:58:35 +00002818
2819 // Create the descriptor for the variable.
2820 llvm::DIVariable D =
2821 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2822 Name, Unit, Line, Ty,
2823 CGM.getLangOpts().Optimize, Flags, ArgNo);
2824
2825 // Insert an llvm.dbg.declare into the current block.
2826 llvm::Instruction *Call =
2827 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2828 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002829}
2830
2831void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2832 llvm::Value *Storage,
2833 CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002834 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002835 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2836}
2837
Adrian Prantle86fcc42013-03-29 19:20:29 +00002838/// Look up the completed type for a self pointer in the TypeCache and
2839/// create a copy of it with the ObjectPointer and Artificial flags
2840/// set. If the type is not cached, a new one is created. This should
2841/// never happen though, since creating a type for the implicit self
2842/// argument implies that we already parsed the interface definition
2843/// and the ivar declarations in the implementation.
Eric Christopherf0890c42013-05-16 00:52:20 +00002844llvm::DIType CGDebugInfo::CreateSelfType(const QualType &QualTy,
2845 llvm::DIType Ty) {
Adrian Prantle86fcc42013-03-29 19:20:29 +00002846 llvm::DIType CachedTy = getTypeOrNull(QualTy);
Eric Christopherb2d13922013-07-18 00:52:50 +00002847 if (CachedTy) Ty = CachedTy;
Adrian Prantle86fcc42013-03-29 19:20:29 +00002848 else DEBUG(llvm::dbgs() << "No cached type for self.");
2849 return DBuilder.createObjectPointerType(Ty);
2850}
2851
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002852void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(const VarDecl *VD,
2853 llvm::Value *Storage,
2854 CGBuilderTy &Builder,
2855 const CGBlockInfo &blockInfo) {
Eric Christopher13c97672013-05-16 00:45:23 +00002856 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002857 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
Eric Christopher6537f082013-05-16 00:45:12 +00002858
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002859 if (Builder.GetInsertBlock() == 0)
2860 return;
Eric Christopher6537f082013-05-16 00:45:12 +00002861
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002862 bool isByRef = VD->hasAttr<BlocksAttr>();
Eric Christopher6537f082013-05-16 00:45:12 +00002863
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002864 uint64_t XOffset = 0;
2865 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2866 llvm::DIType Ty;
2867 if (isByRef)
2868 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopher6537f082013-05-16 00:45:12 +00002869 else
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002870 Ty = getOrCreateType(VD->getType(), Unit);
2871
2872 // Self is passed along as an implicit non-arg variable in a
2873 // block. Mark it as the object pointer.
2874 if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self")
Adrian Prantle86fcc42013-03-29 19:20:29 +00002875 Ty = CreateSelfType(VD->getType(), Ty);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002876
2877 // Get location information.
2878 unsigned Line = getLineNumber(VD->getLocation());
2879 unsigned Column = getColumnNumber(VD->getLocation());
2880
2881 const llvm::DataLayout &target = CGM.getDataLayout();
2882
2883 CharUnits offset = CharUnits::fromQuantity(
2884 target.getStructLayout(blockInfo.StructureType)
2885 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2886
2887 SmallVector<llvm::Value *, 9> addr;
2888 llvm::Type *Int64Ty = CGM.Int64Ty;
Adrian Prantl9b97adf2013-03-29 19:20:35 +00002889 if (isa<llvm::AllocaInst>(Storage))
2890 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002891 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2892 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2893 if (isByRef) {
2894 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2895 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2896 // offset of __forwarding field
2897 offset = CGM.getContext()
2898 .toCharUnitsFromBits(target.getPointerSizeInBits(0));
2899 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2900 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2901 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2902 // offset of x field
2903 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2904 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2905 }
2906
2907 // Create the descriptor for the variable.
2908 llvm::DIVariable D =
Eric Christopher6537f082013-05-16 00:45:12 +00002909 DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002910 llvm::DIDescriptor(LexicalBlockStack.back()),
2911 VD->getName(), Unit, Line, Ty, addr);
Adrian Prantl9b97adf2013-03-29 19:20:35 +00002912
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002913 // Insert an llvm.dbg.declare into the current block.
2914 llvm::Instruction *Call =
2915 DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
2916 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column,
2917 LexicalBlockStack.back()));
2918}
2919
2920/// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2921/// variable declaration.
2922void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2923 unsigned ArgNo,
2924 CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002925 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002926 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2927}
2928
2929namespace {
2930 struct BlockLayoutChunk {
2931 uint64_t OffsetInBits;
2932 const BlockDecl::Capture *Capture;
2933 };
2934 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2935 return l.OffsetInBits < r.OffsetInBits;
2936 }
2937}
2938
2939void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
Adrian Prantl836e7c92013-03-14 17:53:33 +00002940 llvm::Value *Arg,
2941 llvm::Value *LocalAddr,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002942 CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002943 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002944 ASTContext &C = CGM.getContext();
2945 const BlockDecl *blockDecl = block.getBlockDecl();
2946
2947 // Collect some general information about the block's location.
2948 SourceLocation loc = blockDecl->getCaretLocation();
2949 llvm::DIFile tunit = getOrCreateFile(loc);
2950 unsigned line = getLineNumber(loc);
2951 unsigned column = getColumnNumber(loc);
Eric Christopher6537f082013-05-16 00:45:12 +00002952
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002953 // Build the debug-info type for the block literal.
2954 getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
2955
2956 const llvm::StructLayout *blockLayout =
2957 CGM.getDataLayout().getStructLayout(block.StructureType);
2958
2959 SmallVector<llvm::Value*, 16> fields;
2960 fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
2961 blockLayout->getElementOffsetInBits(0),
2962 tunit, tunit));
2963 fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
2964 blockLayout->getElementOffsetInBits(1),
2965 tunit, tunit));
2966 fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
2967 blockLayout->getElementOffsetInBits(2),
2968 tunit, tunit));
2969 fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
2970 blockLayout->getElementOffsetInBits(3),
2971 tunit, tunit));
2972 fields.push_back(createFieldType("__descriptor",
2973 C.getPointerType(block.NeedsCopyDispose ?
2974 C.getBlockDescriptorExtendedType() :
2975 C.getBlockDescriptorType()),
2976 0, loc, AS_public,
2977 blockLayout->getElementOffsetInBits(4),
2978 tunit, tunit));
2979
2980 // We want to sort the captures by offset, not because DWARF
2981 // requires this, but because we're paranoid about debuggers.
2982 SmallVector<BlockLayoutChunk, 8> chunks;
2983
2984 // 'this' capture.
2985 if (blockDecl->capturesCXXThis()) {
2986 BlockLayoutChunk chunk;
2987 chunk.OffsetInBits =
2988 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
2989 chunk.Capture = 0;
2990 chunks.push_back(chunk);
2991 }
2992
2993 // Variable captures.
2994 for (BlockDecl::capture_const_iterator
2995 i = blockDecl->capture_begin(), e = blockDecl->capture_end();
2996 i != e; ++i) {
2997 const BlockDecl::Capture &capture = *i;
2998 const VarDecl *variable = capture.getVariable();
2999 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
3000
3001 // Ignore constant captures.
3002 if (captureInfo.isConstant())
3003 continue;
3004
3005 BlockLayoutChunk chunk;
3006 chunk.OffsetInBits =
3007 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
3008 chunk.Capture = &capture;
3009 chunks.push_back(chunk);
3010 }
3011
3012 // Sort by offset.
3013 llvm::array_pod_sort(chunks.begin(), chunks.end());
3014
3015 for (SmallVectorImpl<BlockLayoutChunk>::iterator
3016 i = chunks.begin(), e = chunks.end(); i != e; ++i) {
3017 uint64_t offsetInBits = i->OffsetInBits;
3018 const BlockDecl::Capture *capture = i->Capture;
3019
3020 // If we have a null capture, this must be the C++ 'this' capture.
3021 if (!capture) {
3022 const CXXMethodDecl *method =
3023 cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
3024 QualType type = method->getThisType(C);
3025
3026 fields.push_back(createFieldType("this", type, 0, loc, AS_public,
3027 offsetInBits, tunit, tunit));
3028 continue;
3029 }
3030
3031 const VarDecl *variable = capture->getVariable();
3032 StringRef name = variable->getName();
3033
3034 llvm::DIType fieldType;
3035 if (capture->isByRef()) {
3036 std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
3037
3038 // FIXME: this creates a second copy of this type!
3039 uint64_t xoffset;
3040 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
3041 fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
3042 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
3043 ptrInfo.first, ptrInfo.second,
3044 offsetInBits, 0, fieldType);
3045 } else {
3046 fieldType = createFieldType(name, variable->getType(), 0,
3047 loc, AS_public, offsetInBits, tunit, tunit);
3048 }
3049 fields.push_back(fieldType);
3050 }
3051
3052 SmallString<36> typeName;
3053 llvm::raw_svector_ostream(typeName)
3054 << "__block_literal_" << CGM.getUniqueBlockCount();
3055
3056 llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
3057
3058 llvm::DIType type =
3059 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
3060 CGM.getContext().toBits(block.BlockSize),
3061 CGM.getContext().toBits(block.BlockAlign),
David Blaikiec1d0af12013-02-25 01:07:08 +00003062 0, llvm::DIType(), fieldsArray);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003063 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
3064
3065 // Get overall information about the block.
3066 unsigned flags = llvm::DIDescriptor::FlagArtificial;
3067 llvm::MDNode *scope = LexicalBlockStack.back();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003068
3069 // Create the descriptor for the parameter.
3070 llvm::DIVariable debugVar =
3071 DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
Eric Christopher6537f082013-05-16 00:45:12 +00003072 llvm::DIDescriptor(scope),
Adrian Prantl836e7c92013-03-14 17:53:33 +00003073 Arg->getName(), tunit, line, type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003074 CGM.getLangOpts().Optimize, flags,
Adrian Prantl836e7c92013-03-14 17:53:33 +00003075 cast<llvm::Argument>(Arg)->getArgNo() + 1);
3076
Adrian Prantlbea407c2013-03-14 21:52:59 +00003077 if (LocalAddr) {
Adrian Prantl836e7c92013-03-14 17:53:33 +00003078 // Insert an llvm.dbg.value into the current block.
Adrian Prantlbea407c2013-03-14 21:52:59 +00003079 llvm::Instruction *DbgVal =
3080 DBuilder.insertDbgValueIntrinsic(LocalAddr, 0, debugVar,
Eric Christopherf068c922013-04-02 22:59:11 +00003081 Builder.GetInsertBlock());
Adrian Prantlbea407c2013-03-14 21:52:59 +00003082 DbgVal->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
3083 }
Adrian Prantl836e7c92013-03-14 17:53:33 +00003084
Adrian Prantlbea407c2013-03-14 21:52:59 +00003085 // Insert an llvm.dbg.declare into the current block.
3086 llvm::Instruction *DbgDecl =
3087 DBuilder.insertDeclare(Arg, debugVar, Builder.GetInsertBlock());
3088 DbgDecl->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003089}
3090
David Blaikie5434fc22013-08-20 01:28:15 +00003091/// If D is an out-of-class definition of a static data member of a class, find
3092/// its corresponding in-class declaration.
3093llvm::DIDerivedType
3094CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {
3095 if (!D->isStaticDataMember())
3096 return llvm::DIDerivedType();
3097 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator MI =
3098 StaticDataMemberCache.find(D->getCanonicalDecl());
3099 if (MI != StaticDataMemberCache.end()) {
3100 assert(MI->second && "Static data member declaration should still exist");
3101 return llvm::DIDerivedType(cast<llvm::MDNode>(MI->second));
Evgeniy Stepanov045a9f62013-08-16 10:35:31 +00003102 }
David Blaikie5e6937b2013-08-20 21:49:21 +00003103
3104 // If the member wasn't found in the cache, lazily construct and add it to the
3105 // type (used when a limited form of the type is emitted).
David Blaikie5434fc22013-08-20 01:28:15 +00003106 llvm::DICompositeType Ctxt(
3107 getContextDescriptor(cast<Decl>(D->getDeclContext())));
3108 llvm::DIDerivedType T = CreateRecordStaticField(D, Ctxt);
3109 Ctxt.addMember(T);
3110 return T;
3111}
3112
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003113/// EmitGlobalVariable - Emit information about a global variable.
3114void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
3115 const VarDecl *D) {
Eric Christopher13c97672013-05-16 00:45:23 +00003116 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003117 // Create global variable debug descriptor.
3118 llvm::DIFile Unit = getOrCreateFile(D->getLocation());
3119 unsigned LineNo = getLineNumber(D->getLocation());
3120
3121 setLocation(D->getLocation());
3122
3123 QualType T = D->getType();
3124 if (T->isIncompleteArrayType()) {
3125
3126 // CodeGen turns int[] into int[1] so we'll do the same here.
3127 llvm::APInt ConstVal(32, 1);
3128 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3129
3130 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3131 ArrayType::Normal, 0);
3132 }
3133 StringRef DeclName = D->getName();
3134 StringRef LinkageName;
3135 if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext())
3136 && !isa<ObjCMethodDecl>(D->getDeclContext()))
3137 LinkageName = Var->getName();
3138 if (LinkageName == DeclName)
3139 LinkageName = StringRef();
Eric Christopher6537f082013-05-16 00:45:12 +00003140 llvm::DIDescriptor DContext =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003141 getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
David Blaikie5434fc22013-08-20 01:28:15 +00003142 llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(
3143 DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
3144 Var->hasInternalLinkage(), Var,
3145 getOrCreateStaticDataMemberDeclarationOrNull(D));
David Blaikie9faebd22013-05-20 04:58:53 +00003146 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(GV)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003147}
3148
3149/// EmitGlobalVariable - Emit information about an objective-c interface.
3150void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
3151 ObjCInterfaceDecl *ID) {
Eric Christopher13c97672013-05-16 00:45:23 +00003152 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003153 // Create global variable debug descriptor.
3154 llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
3155 unsigned LineNo = getLineNumber(ID->getLocation());
3156
3157 StringRef Name = ID->getName();
3158
3159 QualType T = CGM.getContext().getObjCInterfaceType(ID);
3160 if (T->isIncompleteArrayType()) {
3161
3162 // CodeGen turns int[] into int[1] so we'll do the same here.
3163 llvm::APInt ConstVal(32, 1);
3164 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3165
3166 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3167 ArrayType::Normal, 0);
3168 }
3169
3170 DBuilder.createGlobalVariable(Name, Unit, LineNo,
3171 getOrCreateType(T, Unit),
3172 Var->hasInternalLinkage(), Var);
3173}
3174
3175/// EmitGlobalVariable - Emit global variable's debug info.
Eric Christopher6537f082013-05-16 00:45:12 +00003176void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003177 llvm::Constant *Init) {
Eric Christopher13c97672013-05-16 00:45:23 +00003178 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003179 // Create the descriptor for the variable.
3180 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
3181 StringRef Name = VD->getName();
3182 llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
3183 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
3184 const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext());
3185 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
3186 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
3187 }
3188 // Do not use DIGlobalVariable for enums.
3189 if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
3190 return;
David Blaikie27ab0362013-08-15 21:42:43 +00003191 llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(
3192 Unit, Name, Name, Unit, getLineNumber(VD->getLocation()), Ty, true, Init,
David Blaikie5434fc22013-08-20 01:28:15 +00003193 getOrCreateStaticDataMemberDeclarationOrNull(cast<VarDecl>(VD)));
David Blaikie9faebd22013-05-20 04:58:53 +00003194 DeclCache.insert(std::make_pair(VD->getCanonicalDecl(), llvm::WeakVH(GV)));
3195}
3196
3197llvm::DIScope CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
3198 if (!LexicalBlockStack.empty())
3199 return llvm::DIScope(LexicalBlockStack.back());
3200 return getContextDescriptor(D);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003201}
3202
David Blaikie957dac52013-04-22 06:13:21 +00003203void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
David Blaikie9faebd22013-05-20 04:58:53 +00003204 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3205 return;
David Blaikie957dac52013-04-22 06:13:21 +00003206 DBuilder.createImportedModule(
David Blaikie9faebd22013-05-20 04:58:53 +00003207 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
3208 getOrCreateNameSpace(UD.getNominatedNamespace()),
David Blaikie957dac52013-04-22 06:13:21 +00003209 getLineNumber(UD.getLocation()));
3210}
3211
David Blaikie9faebd22013-05-20 04:58:53 +00003212void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
3213 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3214 return;
3215 assert(UD.shadow_size() &&
3216 "We shouldn't be codegening an invalid UsingDecl containing no decls");
3217 // Emitting one decl is sufficient - debuggers can detect that this is an
3218 // overloaded name & provide lookup for all the overloads.
3219 const UsingShadowDecl &USD = **UD.shadow_begin();
Eric Christopher56b108a2013-06-07 22:54:39 +00003220 if (llvm::DIDescriptor Target =
3221 getDeclarationOrDefinition(USD.getUnderlyingDecl()))
David Blaikie9faebd22013-05-20 04:58:53 +00003222 DBuilder.createImportedDeclaration(
3223 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
3224 getLineNumber(USD.getLocation()));
3225}
3226
David Blaikiefc46ebc2013-05-20 22:50:41 +00003227llvm::DIImportedEntity
3228CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
3229 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3230 return llvm::DIImportedEntity(0);
3231 llvm::WeakVH &VH = NamespaceAliasCache[&NA];
3232 if (VH)
3233 return llvm::DIImportedEntity(cast<llvm::MDNode>(VH));
3234 llvm::DIImportedEntity R(0);
3235 if (const NamespaceAliasDecl *Underlying =
3236 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
3237 // This could cache & dedup here rather than relying on metadata deduping.
3238 R = DBuilder.createImportedModule(
3239 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3240 EmitNamespaceAlias(*Underlying), getLineNumber(NA.getLocation()),
3241 NA.getName());
3242 else
3243 R = DBuilder.createImportedModule(
3244 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3245 getOrCreateNameSpace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
3246 getLineNumber(NA.getLocation()), NA.getName());
3247 VH = R;
3248 return R;
3249}
3250
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003251/// getOrCreateNamesSpace - Return namespace descriptor for the given
3252/// namespace decl.
Eric Christopher6537f082013-05-16 00:45:12 +00003253llvm::DINameSpace
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003254CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
David Blaikie8863e6b2013-08-16 22:52:07 +00003255 NSDecl = NSDecl->getCanonicalDecl();
Eric Christopher6537f082013-05-16 00:45:12 +00003256 llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003257 NameSpaceCache.find(NSDecl);
3258 if (I != NameSpaceCache.end())
3259 return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
Eric Christopher6537f082013-05-16 00:45:12 +00003260
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003261 unsigned LineNo = getLineNumber(NSDecl->getLocation());
3262 llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
Eric Christopher6537f082013-05-16 00:45:12 +00003263 llvm::DIDescriptor Context =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003264 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
3265 llvm::DINameSpace NS =
3266 DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
3267 NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
3268 return NS;
3269}
3270
3271void CGDebugInfo::finalize() {
3272 for (std::vector<std::pair<void *, llvm::WeakVH> >::const_iterator VI
3273 = ReplaceMap.begin(), VE = ReplaceMap.end(); VI != VE; ++VI) {
3274 llvm::DIType Ty, RepTy;
3275 // Verify that the debug info still exists.
3276 if (llvm::Value *V = VI->second)
3277 Ty = llvm::DIType(cast<llvm::MDNode>(V));
Eric Christopher6537f082013-05-16 00:45:12 +00003278
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003279 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
3280 TypeCache.find(VI->first);
3281 if (it != TypeCache.end()) {
3282 // Verify that the debug info still exists.
3283 if (llvm::Value *V = it->second)
3284 RepTy = llvm::DIType(cast<llvm::MDNode>(V));
3285 }
Adrian Prantlebbd7e02013-03-11 18:33:46 +00003286
Eric Christopherb2d13922013-07-18 00:52:50 +00003287 if (Ty && Ty.isForwardDecl() && RepTy)
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003288 Ty.replaceAllUsesWith(RepTy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003289 }
Adrian Prantlebbd7e02013-03-11 18:33:46 +00003290
3291 // We keep our own list of retained types, because we need to look
3292 // up the final type in the type cache.
3293 for (std::vector<void *>::const_iterator RI = RetainedTypes.begin(),
3294 RE = RetainedTypes.end(); RI != RE; ++RI)
Manman Ren18760452013-08-29 20:48:48 +00003295 DBuilder.retainType(llvm::DIType(cast<llvm::MDNode>(TypeCache[*RI])));
Adrian Prantlebbd7e02013-03-11 18:33:46 +00003296
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003297 DBuilder.finalize();
3298}