blob: f81d2cf683e53ef80a59e3c03eb4693763d05721 [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
Benjamin Kramere5753592013-09-09 14:48:42 +0000161/// name is constructed on demand (e.g. C++ destructor) then the name
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000162/// 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 Kramer84953792013-09-09 16:39:06 +0000187 return internString(OS.str());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000188}
189
190StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
191 SmallString<256> MethodName;
192 llvm::raw_svector_ostream OS(MethodName);
193 OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
194 const DeclContext *DC = OMD->getDeclContext();
Eric Christopher6537f082013-05-16 00:45:12 +0000195 if (const ObjCImplementationDecl *OID =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000196 dyn_cast<const ObjCImplementationDecl>(DC)) {
197 OS << OID->getName();
Eric Christopher6537f082013-05-16 00:45:12 +0000198 } else if (const ObjCInterfaceDecl *OID =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000199 dyn_cast<const ObjCInterfaceDecl>(DC)) {
200 OS << OID->getName();
Eric Christopher6537f082013-05-16 00:45:12 +0000201 } else if (const ObjCCategoryImplDecl *OCD =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000202 dyn_cast<const ObjCCategoryImplDecl>(DC)){
203 OS << ((const NamedDecl *)OCD)->getIdentifier()->getNameStart() << '(' <<
204 OCD->getIdentifier()->getNameStart() << ')';
Adrian Prantlb5092242013-05-17 23:58:45 +0000205 } else if (isa<ObjCProtocolDecl>(DC)) {
Adrian Prantl687ecae2013-05-17 23:49:10 +0000206 // We can extract the type of the class from the self pointer.
207 if (ImplicitParamDecl* SelfDecl = OMD->getSelfDecl()) {
208 QualType ClassTy =
209 cast<ObjCObjectPointerType>(SelfDecl->getType())->getPointeeType();
210 ClassTy.print(OS, PrintingPolicy(LangOptions()));
211 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000212 }
213 OS << ' ' << OMD->getSelector().getAsString() << ']';
214
Benjamin Kramer84953792013-09-09 16:39:06 +0000215 return internString(OS.str());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000216}
217
218/// getSelectorName - Return selector name. This is used for debugging
219/// info.
220StringRef CGDebugInfo::getSelectorName(Selector S) {
Benjamin Kramer84953792013-09-09 16:39:06 +0000221 return internString(S.getAsString());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000222}
223
224/// getClassName - Get class name including template argument list.
Eric Christopher6537f082013-05-16 00:45:12 +0000225StringRef
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000226CGDebugInfo::getClassName(const RecordDecl *RD) {
227 const ClassTemplateSpecializationDecl *Spec
228 = dyn_cast<ClassTemplateSpecializationDecl>(RD);
229 if (!Spec)
230 return RD->getName();
231
232 const TemplateArgument *Args;
233 unsigned NumArgs;
234 if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) {
235 const TemplateSpecializationType *TST =
236 cast<TemplateSpecializationType>(TAW->getType());
237 Args = TST->getArgs();
238 NumArgs = TST->getNumArgs();
239 } else {
240 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
241 Args = TemplateArgs.data();
242 NumArgs = TemplateArgs.size();
243 }
244 StringRef Name = RD->getIdentifier()->getName();
245 PrintingPolicy Policy(CGM.getLangOpts());
Benjamin Kramer5eada842013-02-22 15:46:01 +0000246 SmallString<128> TemplateArgList;
247 {
248 llvm::raw_svector_ostream OS(TemplateArgList);
249 TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs,
250 Policy);
251 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000252
253 // Copy this name on the side and use its reference.
Benjamin Kramer84953792013-09-09 16:39:06 +0000254 return internString(Name, TemplateArgList);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000255}
256
257/// getOrCreateFile - Get the file debug info descriptor for the input location.
258llvm::DIFile CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
259 if (!Loc.isValid())
260 // If Location is not valid then use main input file.
261 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
262
263 SourceManager &SM = CGM.getContext().getSourceManager();
264 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
265
266 if (PLoc.isInvalid() || StringRef(PLoc.getFilename()).empty())
267 // If the location is not valid then use main input file.
268 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
269
270 // Cache the results.
271 const char *fname = PLoc.getFilename();
272 llvm::DenseMap<const char *, llvm::WeakVH>::iterator it =
273 DIFileCache.find(fname);
274
275 if (it != DIFileCache.end()) {
276 // Verify that the information still exists.
277 if (llvm::Value *V = it->second)
278 return llvm::DIFile(cast<llvm::MDNode>(V));
279 }
280
281 llvm::DIFile F = DBuilder.createFile(PLoc.getFilename(), getCurrentDirname());
282
283 DIFileCache[fname] = F;
284 return F;
285}
286
287/// getOrCreateMainFile - Get the file info for main compile unit.
288llvm::DIFile CGDebugInfo::getOrCreateMainFile() {
289 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
290}
291
292/// getLineNumber - Get line number for the location. If location is invalid
293/// then use current location.
294unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
295 if (Loc.isInvalid() && CurLoc.isInvalid())
296 return 0;
297 SourceManager &SM = CGM.getContext().getSourceManager();
298 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
299 return PLoc.isValid()? PLoc.getLine() : 0;
300}
301
302/// getColumnNumber - Get column number for the location.
Adrian Prantl00df5ea2013-03-12 20:43:25 +0000303unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000304 // We may not want column information at all.
Adrian Prantl00df5ea2013-03-12 20:43:25 +0000305 if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000306 return 0;
307
308 // If the location is invalid then use the current column.
309 if (Loc.isInvalid() && CurLoc.isInvalid())
310 return 0;
311 SourceManager &SM = CGM.getContext().getSourceManager();
312 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
313 return PLoc.isValid()? PLoc.getColumn() : 0;
314}
315
316StringRef CGDebugInfo::getCurrentDirname() {
317 if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
318 return CGM.getCodeGenOpts().DebugCompilationDir;
319
320 if (!CWDName.empty())
321 return CWDName;
322 SmallString<256> CWD;
323 llvm::sys::fs::current_path(CWD);
Benjamin Kramer84953792013-09-09 16:39:06 +0000324 return CWDName = internString(CWD);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000325}
326
327/// CreateCompileUnit - Create new compile unit.
328void CGDebugInfo::CreateCompileUnit() {
329
330 // Get absolute path name.
331 SourceManager &SM = CGM.getContext().getSourceManager();
332 std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
333 if (MainFileName.empty())
334 MainFileName = "<unknown>";
335
336 // The main file name provided via the "-main-file-name" option contains just
337 // the file name itself with no path information. This file name may have had
338 // a relative path, so we look into the actual file entry for the main
339 // file to determine the real absolute path for the file.
340 std::string MainFileDir;
341 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
342 MainFileDir = MainFile->getDir()->getName();
343 if (MainFileDir != ".")
344 MainFileName = MainFileDir + "/" + MainFileName;
345 }
346
347 // Save filename string.
Benjamin Kramer84953792013-09-09 16:39:06 +0000348 StringRef Filename = internString(MainFileName);
Eric Christopherff971d72013-02-22 23:50:16 +0000349
350 // Save split dwarf file string.
351 std::string SplitDwarfFile = CGM.getCodeGenOpts().SplitDwarfFile;
Benjamin Kramer84953792013-09-09 16:39:06 +0000352 StringRef SplitDwarfFilename = internString(SplitDwarfFile);
Eric Christopher6537f082013-05-16 00:45:12 +0000353
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000354 unsigned LangTag;
355 const LangOptions &LO = CGM.getLangOpts();
356 if (LO.CPlusPlus) {
357 if (LO.ObjC1)
358 LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
359 else
360 LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
361 } else if (LO.ObjC1) {
362 LangTag = llvm::dwarf::DW_LANG_ObjC;
363 } else if (LO.C99) {
364 LangTag = llvm::dwarf::DW_LANG_C99;
365 } else {
366 LangTag = llvm::dwarf::DW_LANG_C89;
367 }
368
369 std::string Producer = getClangFullVersion();
370
371 // Figure out which version of the ObjC runtime we have.
372 unsigned RuntimeVers = 0;
373 if (LO.ObjC1)
374 RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
375
376 // Create new compile unit.
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000377 // FIXME - Eliminate TheCU.
Eric Christopher8fed3f42013-07-19 00:51:58 +0000378 TheCU = DBuilder.createCompileUnit(LangTag, Filename, getCurrentDirname(),
379 Producer, LO.Optimize,
380 CGM.getCodeGenOpts().DwarfDebugFlags,
381 RuntimeVers, SplitDwarfFilename);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000382}
383
384/// CreateType - Get the Basic type from the cache or create a new
385/// one if necessary.
386llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT) {
387 unsigned Encoding = 0;
388 StringRef BTName;
389 switch (BT->getKind()) {
390#define BUILTIN_TYPE(Id, SingletonId)
391#define PLACEHOLDER_TYPE(Id, SingletonId) \
392 case BuiltinType::Id:
393#include "clang/AST/BuiltinTypes.def"
394 case BuiltinType::Dependent:
395 llvm_unreachable("Unexpected builtin type");
396 case BuiltinType::NullPtr:
Peter Collingbourne24118f52013-06-27 22:51:01 +0000397 return DBuilder.createNullPtrType();
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000398 case BuiltinType::Void:
399 return llvm::DIType();
400 case BuiltinType::ObjCClass:
Eric Christopherb2d13922013-07-18 00:52:50 +0000401 if (ClassTy)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000402 return ClassTy;
403 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
404 "objc_class", TheCU,
405 getOrCreateMainFile(), 0);
406 return ClassTy;
407 case BuiltinType::ObjCId: {
408 // typedef struct objc_class *Class;
409 // typedef struct objc_object {
410 // Class isa;
411 // } *id;
412
Eric Christopherb2d13922013-07-18 00:52:50 +0000413 if (ObjTy)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000414 return ObjTy;
415
Eric Christopherb2d13922013-07-18 00:52:50 +0000416 if (!ClassTy)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000417 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
418 "objc_class", TheCU,
419 getOrCreateMainFile(), 0);
420
421 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
Eric Christopher6537f082013-05-16 00:45:12 +0000422
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000423 llvm::DIType ISATy = DBuilder.createPointerType(ClassTy, Size);
424
Eric Christopherf068c922013-04-02 22:59:11 +0000425 ObjTy =
David Blaikiec1d0af12013-02-25 01:07:08 +0000426 DBuilder.createStructType(TheCU, "objc_object", getOrCreateMainFile(),
427 0, 0, 0, 0, llvm::DIType(), llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000428
Eric Christopherf068c922013-04-02 22:59:11 +0000429 ObjTy.setTypeArray(DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
430 ObjTy, "isa", getOrCreateMainFile(), 0, Size, 0, 0, 0, ISATy)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000431 return ObjTy;
432 }
433 case BuiltinType::ObjCSel: {
Eric Christopherb2d13922013-07-18 00:52:50 +0000434 if (SelTy)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000435 return SelTy;
436 SelTy =
437 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
438 "objc_selector", TheCU, getOrCreateMainFile(),
439 0);
440 return SelTy;
441 }
Guy Benyeib13621d2012-12-18 14:38:23 +0000442
443 case BuiltinType::OCLImage1d:
444 return getOrCreateStructPtrType("opencl_image1d_t",
445 OCLImage1dDITy);
446 case BuiltinType::OCLImage1dArray:
Eric Christopher6537f082013-05-16 00:45:12 +0000447 return getOrCreateStructPtrType("opencl_image1d_array_t",
Guy Benyeib13621d2012-12-18 14:38:23 +0000448 OCLImage1dArrayDITy);
449 case BuiltinType::OCLImage1dBuffer:
450 return getOrCreateStructPtrType("opencl_image1d_buffer_t",
451 OCLImage1dBufferDITy);
452 case BuiltinType::OCLImage2d:
453 return getOrCreateStructPtrType("opencl_image2d_t",
454 OCLImage2dDITy);
455 case BuiltinType::OCLImage2dArray:
456 return getOrCreateStructPtrType("opencl_image2d_array_t",
457 OCLImage2dArrayDITy);
458 case BuiltinType::OCLImage3d:
459 return getOrCreateStructPtrType("opencl_image3d_t",
460 OCLImage3dDITy);
Guy Benyei21f18c42013-02-07 10:55:47 +0000461 case BuiltinType::OCLSampler:
462 return DBuilder.createBasicType("opencl_sampler_t",
463 CGM.getContext().getTypeSize(BT),
464 CGM.getContext().getTypeAlign(BT),
465 llvm::dwarf::DW_ATE_unsigned);
Guy Benyeie6b9d802013-01-20 12:31:11 +0000466 case BuiltinType::OCLEvent:
467 return getOrCreateStructPtrType("opencl_event_t",
468 OCLEventDITy);
Guy Benyeib13621d2012-12-18 14:38:23 +0000469
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000470 case BuiltinType::UChar:
471 case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
472 case BuiltinType::Char_S:
473 case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
474 case BuiltinType::Char16:
475 case BuiltinType::Char32: Encoding = llvm::dwarf::DW_ATE_UTF; break;
476 case BuiltinType::UShort:
477 case BuiltinType::UInt:
478 case BuiltinType::UInt128:
479 case BuiltinType::ULong:
480 case BuiltinType::WChar_U:
481 case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
482 case BuiltinType::Short:
483 case BuiltinType::Int:
484 case BuiltinType::Int128:
485 case BuiltinType::Long:
486 case BuiltinType::WChar_S:
487 case BuiltinType::LongLong: Encoding = llvm::dwarf::DW_ATE_signed; break;
488 case BuiltinType::Bool: Encoding = llvm::dwarf::DW_ATE_boolean; break;
489 case BuiltinType::Half:
490 case BuiltinType::Float:
491 case BuiltinType::LongDouble:
492 case BuiltinType::Double: Encoding = llvm::dwarf::DW_ATE_float; break;
493 }
494
495 switch (BT->getKind()) {
496 case BuiltinType::Long: BTName = "long int"; break;
497 case BuiltinType::LongLong: BTName = "long long int"; break;
498 case BuiltinType::ULong: BTName = "long unsigned int"; break;
499 case BuiltinType::ULongLong: BTName = "long long unsigned int"; break;
500 default:
501 BTName = BT->getName(CGM.getLangOpts());
502 break;
503 }
504 // Bit size, align and offset of the type.
505 uint64_t Size = CGM.getContext().getTypeSize(BT);
506 uint64_t Align = CGM.getContext().getTypeAlign(BT);
Eric Christopher6537f082013-05-16 00:45:12 +0000507 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000508 DBuilder.createBasicType(BTName, Size, Align, Encoding);
509 return DbgTy;
510}
511
512llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty) {
513 // Bit size, align and offset of the type.
514 unsigned Encoding = llvm::dwarf::DW_ATE_complex_float;
515 if (Ty->isComplexIntegerType())
516 Encoding = llvm::dwarf::DW_ATE_lo_user;
517
518 uint64_t Size = CGM.getContext().getTypeSize(Ty);
519 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
Eric Christopher6537f082013-05-16 00:45:12 +0000520 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000521 DBuilder.createBasicType("complex", Size, Align, Encoding);
522
523 return DbgTy;
524}
525
526/// CreateCVRType - Get the qualified type from the cache or create
527/// a new one if necessary.
David Blaikie29b8b682013-09-04 22:03:57 +0000528llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000529 QualifierCollector Qc;
530 const Type *T = Qc.strip(Ty);
531
532 // Ignore these qualifiers for now.
533 Qc.removeObjCGCAttr();
534 Qc.removeAddressSpace();
535 Qc.removeObjCLifetime();
536
537 // We will create one Derived type for one qualifier and recurse to handle any
538 // additional ones.
539 unsigned Tag;
540 if (Qc.hasConst()) {
541 Tag = llvm::dwarf::DW_TAG_const_type;
542 Qc.removeConst();
543 } else if (Qc.hasVolatile()) {
544 Tag = llvm::dwarf::DW_TAG_volatile_type;
545 Qc.removeVolatile();
546 } else if (Qc.hasRestrict()) {
547 Tag = llvm::dwarf::DW_TAG_restrict_type;
548 Qc.removeRestrict();
549 } else {
550 assert(Qc.empty() && "Unknown type qualifier for debug info");
551 return getOrCreateType(QualType(T, 0), Unit);
552 }
553
David Blaikie29b8b682013-09-04 22:03:57 +0000554 llvm::DIType FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000555
556 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
557 // CVR derived types.
558 llvm::DIType DbgTy = DBuilder.createQualifiedType(Tag, FromTy);
Eric Christopher6537f082013-05-16 00:45:12 +0000559
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000560 return DbgTy;
561}
562
563llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
564 llvm::DIFile Unit) {
Fariborz Jahanian05f8ff12013-02-21 20:42:11 +0000565
566 // The frontend treats 'id' as a typedef to an ObjCObjectType,
567 // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
568 // debug info, we want to emit 'id' in both cases.
569 if (Ty->isObjCQualifiedIdType())
570 return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
571
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000572 llvm::DIType DbgTy =
Eric Christopher6537f082013-05-16 00:45:12 +0000573 CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000574 Ty->getPointeeType(), Unit);
575 return DbgTy;
576}
577
578llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
579 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +0000580 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000581 Ty->getPointeeType(), Unit);
582}
583
Manman Ren83369bf2013-08-29 23:19:58 +0000584/// In C++ mode, types have linkage, so we can rely on the ODR and
585/// on their mangled names, if they're external.
586static SmallString<256>
587getUniqueTagTypeName(const TagType *Ty, CodeGenModule &CGM,
588 llvm::DICompileUnit TheCU) {
589 SmallString<256> FullName;
590 // FIXME: ODR should apply to ObjC++ exactly the same wasy it does to C++.
591 // For now, only apply ODR with C++.
592 const TagDecl *TD = Ty->getDecl();
593 if (TheCU.getLanguage() != llvm::dwarf::DW_LANG_C_plus_plus ||
594 !TD->isExternallyVisible())
595 return FullName;
596 // Microsoft Mangler does not have support for mangleCXXRTTIName yet.
597 if (CGM.getTarget().getCXXABI().isMicrosoft())
598 return FullName;
599
600 // TODO: This is using the RTTI name. Is there a better way to get
601 // a unique string for a type?
602 llvm::raw_svector_ostream Out(FullName);
603 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(QualType(Ty, 0), Out);
604 Out.flush();
605 return FullName;
606}
607
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000608// Creates a forward declaration for a RecordDecl in the given context.
David Blaikieeaacc882013-08-20 21:03:29 +0000609llvm::DICompositeType
Manman Renf3327332013-08-28 21:20:28 +0000610CGDebugInfo::getOrCreateRecordFwdDecl(const RecordType *Ty,
David Blaikieeaacc882013-08-20 21:03:29 +0000611 llvm::DIDescriptor Ctx) {
Manman Renf3327332013-08-28 21:20:28 +0000612 const RecordDecl *RD = Ty->getDecl();
David Blaikiec5cd1a72013-08-15 20:17:25 +0000613 if (llvm::DIType T = getTypeOrNull(CGM.getContext().getRecordType(RD)))
David Blaikieeaacc882013-08-20 21:03:29 +0000614 return llvm::DICompositeType(T);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000615 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
616 unsigned Line = getLineNumber(RD->getLocation());
617 StringRef RDName = getClassName(RD);
618
619 unsigned Tag = 0;
620 if (RD->isStruct() || RD->isInterface())
621 Tag = llvm::dwarf::DW_TAG_structure_type;
622 else if (RD->isUnion())
623 Tag = llvm::dwarf::DW_TAG_union_type;
624 else {
625 assert(RD->isClass());
626 Tag = llvm::dwarf::DW_TAG_class_type;
627 }
628
629 // Create the type.
Manman Ren83369bf2013-08-29 23:19:58 +0000630 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
631 return DBuilder.createForwardDecl(Tag, RDName, Ctx, DefUnit, Line, 0, 0, 0,
632 FullName);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000633}
634
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000635llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag,
Eric Christopher6537f082013-05-16 00:45:12 +0000636 const Type *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000637 QualType PointeeTy,
638 llvm::DIFile Unit) {
639 if (Tag == llvm::dwarf::DW_TAG_reference_type ||
640 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
David Blaikie29b8b682013-09-04 22:03:57 +0000641 return DBuilder.createReferenceType(Tag, getOrCreateType(PointeeTy, Unit));
Fariborz Jahanian05f8ff12013-02-21 20:42:11 +0000642
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000643 // Bit size, align and offset of the type.
644 // Size is always the size of a pointer. We can't use getTypeSize here
645 // because that does not return the correct value for references.
646 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCall64aa4b32013-04-16 22:48:15 +0000647 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000648 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
649
David Blaikie29b8b682013-09-04 22:03:57 +0000650 return DBuilder.createPointerType(getOrCreateType(PointeeTy, Unit), Size,
651 Align);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000652}
653
Eric Christopherf0890c42013-05-16 00:52:20 +0000654llvm::DIType CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
655 llvm::DIType &Cache) {
Eric Christopherb2d13922013-07-18 00:52:50 +0000656 if (Cache)
Guy Benyeib13621d2012-12-18 14:38:23 +0000657 return Cache;
David Blaikie1e97c1e2013-05-21 17:58:54 +0000658 Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
659 TheCU, getOrCreateMainFile(), 0);
660 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
661 Cache = DBuilder.createPointerType(Cache, Size);
662 return Cache;
Guy Benyeib13621d2012-12-18 14:38:23 +0000663}
664
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000665llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
666 llvm::DIFile Unit) {
Eric Christopherb2d13922013-07-18 00:52:50 +0000667 if (BlockLiteralGeneric)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000668 return BlockLiteralGeneric;
669
670 SmallVector<llvm::Value *, 8> EltTys;
671 llvm::DIType FieldTy;
672 QualType FType;
673 uint64_t FieldSize, FieldOffset;
674 unsigned FieldAlign;
675 llvm::DIArray Elements;
676 llvm::DIType EltTy, DescTy;
677
678 FieldOffset = 0;
679 FType = CGM.getContext().UnsignedLongTy;
680 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
681 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
682
683 Elements = DBuilder.getOrCreateArray(EltTys);
684 EltTys.clear();
685
686 unsigned Flags = llvm::DIDescriptor::FlagAppleBlock;
687 unsigned LineNo = getLineNumber(CurLoc);
688
689 EltTy = DBuilder.createStructType(Unit, "__block_descriptor",
690 Unit, LineNo, FieldOffset, 0,
David Blaikiec1d0af12013-02-25 01:07:08 +0000691 Flags, llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000692
693 // Bit size, align and offset of the type.
694 uint64_t Size = CGM.getContext().getTypeSize(Ty);
695
696 DescTy = DBuilder.createPointerType(EltTy, Size);
697
698 FieldOffset = 0;
699 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
700 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
701 FType = CGM.getContext().IntTy;
702 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
703 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
704 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
705 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
706
707 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
708 FieldTy = DescTy;
709 FieldSize = CGM.getContext().getTypeSize(Ty);
710 FieldAlign = CGM.getContext().getTypeAlign(Ty);
711 FieldTy = DBuilder.createMemberType(Unit, "__descriptor", Unit,
712 LineNo, FieldSize, FieldAlign,
713 FieldOffset, 0, FieldTy);
714 EltTys.push_back(FieldTy);
715
716 FieldOffset += FieldSize;
717 Elements = DBuilder.getOrCreateArray(EltTys);
718
719 EltTy = DBuilder.createStructType(Unit, "__block_literal_generic",
720 Unit, LineNo, FieldOffset, 0,
David Blaikiec1d0af12013-02-25 01:07:08 +0000721 Flags, llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000722
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000723 BlockLiteralGeneric = DBuilder.createPointerType(EltTy, Size);
724 return BlockLiteralGeneric;
725}
726
David Blaikie29b8b682013-09-04 22:03:57 +0000727llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty, llvm::DIFile Unit) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000728 // Typedefs are derived from some other type. If we have a typedef of a
729 // typedef, make sure to emit the whole chain.
David Blaikie29b8b682013-09-04 22:03:57 +0000730 llvm::DIType Src = getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
Eric Christopherb2d13922013-07-18 00:52:50 +0000731 if (!Src)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000732 return llvm::DIType();
733 // We don't set size information, but do specify where the typedef was
734 // declared.
735 unsigned Line = getLineNumber(Ty->getDecl()->getLocation());
736 const TypedefNameDecl *TyDecl = Ty->getDecl();
Eric Christopher6537f082013-05-16 00:45:12 +0000737
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000738 llvm::DIDescriptor TypedefContext =
739 getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext()));
Eric Christopher6537f082013-05-16 00:45:12 +0000740
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000741 return
742 DBuilder.createTypedef(Src, TyDecl->getName(), Unit, Line, TypedefContext);
743}
744
745llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
746 llvm::DIFile Unit) {
747 SmallVector<llvm::Value *, 16> EltTys;
748
749 // Add the result type at least.
David Blaikie29b8b682013-09-04 22:03:57 +0000750 EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000751
752 // Set up remainder of arguments if there is a prototype.
753 // FIXME: IF NOT, HOW IS THIS REPRESENTED? llvm-gcc doesn't represent '...'!
754 if (isa<FunctionNoProtoType>(Ty))
755 EltTys.push_back(DBuilder.createUnspecifiedParameter());
756 else if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Ty)) {
757 for (unsigned i = 0, e = FPT->getNumArgs(); i != e; ++i)
David Blaikie29b8b682013-09-04 22:03:57 +0000758 EltTys.push_back(getOrCreateType(FPT->getArgType(i), Unit));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000759 }
760
761 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
762 return DBuilder.createSubroutineType(Unit, EltTypeArray);
763}
764
765
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000766llvm::DIType CGDebugInfo::createFieldType(StringRef name,
767 QualType type,
768 uint64_t sizeInBitsOverride,
769 SourceLocation loc,
770 AccessSpecifier AS,
771 uint64_t offsetInBits,
772 llvm::DIFile tunit,
Manman Renc23b1db2013-09-08 03:45:05 +0000773 llvm::DIScope scope) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000774 llvm::DIType debugType = getOrCreateType(type, tunit);
775
776 // Get the location for the field.
777 llvm::DIFile file = getOrCreateFile(loc);
778 unsigned line = getLineNumber(loc);
779
780 uint64_t sizeInBits = 0;
781 unsigned alignInBits = 0;
782 if (!type->isIncompleteArrayType()) {
783 llvm::tie(sizeInBits, alignInBits) = CGM.getContext().getTypeInfo(type);
784
785 if (sizeInBitsOverride)
786 sizeInBits = sizeInBitsOverride;
787 }
788
789 unsigned flags = 0;
790 if (AS == clang::AS_private)
791 flags |= llvm::DIDescriptor::FlagPrivate;
792 else if (AS == clang::AS_protected)
793 flags |= llvm::DIDescriptor::FlagProtected;
794
795 return DBuilder.createMemberType(scope, name, file, line, sizeInBits,
796 alignInBits, offsetInBits, flags, debugType);
797}
798
Eric Christopher0395de32013-01-16 01:22:32 +0000799/// CollectRecordLambdaFields - Helper for CollectRecordFields.
800void CGDebugInfo::
801CollectRecordLambdaFields(const CXXRecordDecl *CXXDecl,
802 SmallVectorImpl<llvm::Value *> &elements,
803 llvm::DIType RecordTy) {
804 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
805 // has the name and the location of the variable so we should iterate over
806 // both concurrently.
807 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
808 RecordDecl::field_iterator Field = CXXDecl->field_begin();
809 unsigned fieldno = 0;
810 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
811 E = CXXDecl->captures_end(); I != E; ++I, ++Field, ++fieldno) {
812 const LambdaExpr::Capture C = *I;
813 if (C.capturesVariable()) {
814 VarDecl *V = C.getCapturedVar();
815 llvm::DIFile VUnit = getOrCreateFile(C.getLocation());
816 StringRef VName = V->getName();
817 uint64_t SizeInBitsOverride = 0;
818 if (Field->isBitField()) {
819 SizeInBitsOverride = Field->getBitWidthValue(CGM.getContext());
820 assert(SizeInBitsOverride && "found named 0-width bitfield");
821 }
822 llvm::DIType fieldType
823 = createFieldType(VName, Field->getType(), SizeInBitsOverride,
824 C.getLocation(), Field->getAccess(),
825 layout.getFieldOffset(fieldno), VUnit, RecordTy);
826 elements.push_back(fieldType);
827 } else {
828 // TODO: Need to handle 'this' in some way by probably renaming the
829 // this of the lambda class and having a field member of 'this' or
830 // by using AT_object_pointer for the function and having that be
831 // used as 'this' for semantic references.
832 assert(C.capturesThis() && "Field that isn't captured and isn't this?");
833 FieldDecl *f = *Field;
834 llvm::DIFile VUnit = getOrCreateFile(f->getLocation());
835 QualType type = f->getType();
836 llvm::DIType fieldType
837 = createFieldType("this", type, 0, f->getLocation(), f->getAccess(),
838 layout.getFieldOffset(fieldno), VUnit, RecordTy);
839
840 elements.push_back(fieldType);
841 }
842 }
843}
844
David Blaikie5434fc22013-08-20 01:28:15 +0000845/// Helper for CollectRecordFields.
David Blaikiecbcb0302013-08-15 22:50:29 +0000846llvm::DIDerivedType
847CGDebugInfo::CreateRecordStaticField(const VarDecl *Var,
848 llvm::DIType RecordTy) {
Eric Christopher0395de32013-01-16 01:22:32 +0000849 // Create the descriptor for the static variable, with or without
850 // constant initializers.
851 llvm::DIFile VUnit = getOrCreateFile(Var->getLocation());
852 llvm::DIType VTy = getOrCreateType(Var->getType(), VUnit);
853
Eric Christopher0395de32013-01-16 01:22:32 +0000854 unsigned LineNumber = getLineNumber(Var->getLocation());
855 StringRef VName = Var->getName();
David Blaikiea89701b2013-01-20 01:19:17 +0000856 llvm::Constant *C = NULL;
Eric Christopher0395de32013-01-16 01:22:32 +0000857 if (Var->getInit()) {
858 const APValue *Value = Var->evaluateValue();
David Blaikiea89701b2013-01-20 01:19:17 +0000859 if (Value) {
860 if (Value->isInt())
861 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
862 if (Value->isFloat())
863 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
864 }
Eric Christopher0395de32013-01-16 01:22:32 +0000865 }
866
867 unsigned Flags = 0;
868 AccessSpecifier Access = Var->getAccess();
869 if (Access == clang::AS_private)
870 Flags |= llvm::DIDescriptor::FlagPrivate;
871 else if (Access == clang::AS_protected)
872 Flags |= llvm::DIDescriptor::FlagProtected;
873
David Blaikiecbcb0302013-08-15 22:50:29 +0000874 llvm::DIDerivedType GV = DBuilder.createStaticMemberType(
875 RecordTy, VName, VUnit, LineNumber, VTy, Flags, C);
Eric Christopher0395de32013-01-16 01:22:32 +0000876 StaticDataMemberCache[Var->getCanonicalDecl()] = llvm::WeakVH(GV);
David Blaikiecbcb0302013-08-15 22:50:29 +0000877 return GV;
Eric Christopher0395de32013-01-16 01:22:32 +0000878}
879
880/// CollectRecordNormalField - Helper for CollectRecordFields.
881void CGDebugInfo::
882CollectRecordNormalField(const FieldDecl *field, uint64_t OffsetInBits,
883 llvm::DIFile tunit,
884 SmallVectorImpl<llvm::Value *> &elements,
885 llvm::DIType RecordTy) {
886 StringRef name = field->getName();
887 QualType type = field->getType();
888
889 // Ignore unnamed fields unless they're anonymous structs/unions.
890 if (name.empty() && !type->isRecordType())
891 return;
892
893 uint64_t SizeInBitsOverride = 0;
894 if (field->isBitField()) {
895 SizeInBitsOverride = field->getBitWidthValue(CGM.getContext());
896 assert(SizeInBitsOverride && "found named 0-width bitfield");
897 }
898
899 llvm::DIType fieldType
900 = createFieldType(name, type, SizeInBitsOverride,
901 field->getLocation(), field->getAccess(),
902 OffsetInBits, tunit, RecordTy);
903
904 elements.push_back(fieldType);
905}
906
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000907/// CollectRecordFields - A helper function to collect debug info for
908/// record fields. This is used while creating debug info entry for a Record.
David Blaikie841fd112013-08-16 20:40:25 +0000909void CGDebugInfo::CollectRecordFields(const RecordDecl *record,
910 llvm::DIFile tunit,
911 SmallVectorImpl<llvm::Value *> &elements,
912 llvm::DICompositeType RecordTy) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000913 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(record);
914
Eric Christopher0395de32013-01-16 01:22:32 +0000915 if (CXXDecl && CXXDecl->isLambda())
916 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
917 else {
918 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000919
Eric Christopher0395de32013-01-16 01:22:32 +0000920 // Field number for non-static fields.
Eric Christopherfd5ac0d2013-01-04 17:59:07 +0000921 unsigned fieldNo = 0;
Eric Christopher0395de32013-01-16 01:22:32 +0000922
Eric Christopher0395de32013-01-16 01:22:32 +0000923 // Static and non-static members should appear in the same order as
924 // the corresponding declarations in the source program.
925 for (RecordDecl::decl_iterator I = record->decls_begin(),
926 E = record->decls_end(); I != E; ++I)
David Blaikie5e6937b2013-08-20 21:49:21 +0000927 if (const VarDecl *V = dyn_cast<VarDecl>(*I)) {
928 // Reuse the existing static member declaration if one exists
929 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator MI =
930 StaticDataMemberCache.find(V->getCanonicalDecl());
931 if (MI != StaticDataMemberCache.end()) {
932 assert(MI->second &&
933 "Static data member declaration should still exist");
934 elements.push_back(
935 llvm::DIDerivedType(cast<llvm::MDNode>(MI->second)));
936 } else
937 elements.push_back(CreateRecordStaticField(V, RecordTy));
938 } else if (FieldDecl *field = dyn_cast<FieldDecl>(*I)) {
Eric Christopher0395de32013-01-16 01:22:32 +0000939 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo),
940 tunit, elements, RecordTy);
941
942 // Bump field number for next field.
943 ++fieldNo;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000944 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000945 }
946}
947
948/// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
949/// function type is not updated to include implicit "this" pointer. Use this
950/// routine to get a method type which includes "this" pointer.
David Blaikie9a845292013-05-22 23:22:42 +0000951llvm::DICompositeType
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000952CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
953 llvm::DIFile Unit) {
David Blaikie9c78f9b2013-01-07 23:06:35 +0000954 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
David Blaikie67f8b5e2013-01-07 22:24:59 +0000955 if (Method->isStatic())
David Blaikie9a845292013-05-22 23:22:42 +0000956 return llvm::DICompositeType(getOrCreateType(QualType(Func, 0), Unit));
David Blaikie9c78f9b2013-01-07 23:06:35 +0000957 return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()),
958 Func, Unit);
959}
David Blaikie67f8b5e2013-01-07 22:24:59 +0000960
David Blaikie9a845292013-05-22 23:22:42 +0000961llvm::DICompositeType CGDebugInfo::getOrCreateInstanceMethodType(
David Blaikie9c78f9b2013-01-07 23:06:35 +0000962 QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile Unit) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000963 // Add "this" pointer.
David Blaikie9c78f9b2013-01-07 23:06:35 +0000964 llvm::DIArray Args = llvm::DICompositeType(
965 getOrCreateType(QualType(Func, 0), Unit)).getTypeArray();
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000966 assert (Args.getNumElements() && "Invalid number of arguments!");
967
968 SmallVector<llvm::Value *, 16> Elts;
969
970 // First element is always return type. For 'void' functions it is NULL.
971 Elts.push_back(Args.getElement(0));
972
David Blaikie67f8b5e2013-01-07 22:24:59 +0000973 // "this" pointer is always first argument.
David Blaikie9c78f9b2013-01-07 23:06:35 +0000974 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
David Blaikie67f8b5e2013-01-07 22:24:59 +0000975 if (isa<ClassTemplateSpecializationDecl>(RD)) {
976 // Create pointer type directly in this case.
977 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
978 QualType PointeeTy = ThisPtrTy->getPointeeType();
979 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCall64aa4b32013-04-16 22:48:15 +0000980 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
David Blaikie67f8b5e2013-01-07 22:24:59 +0000981 uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy);
982 llvm::DIType PointeeType = getOrCreateType(PointeeTy, Unit);
Eric Christopherf0890c42013-05-16 00:52:20 +0000983 llvm::DIType ThisPtrType =
984 DBuilder.createPointerType(PointeeType, Size, Align);
David Blaikie67f8b5e2013-01-07 22:24:59 +0000985 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
986 // TODO: This and the artificial type below are misleading, the
987 // types aren't artificial the argument is, but the current
988 // metadata doesn't represent that.
989 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
990 Elts.push_back(ThisPtrType);
991 } else {
992 llvm::DIType ThisPtrType = getOrCreateType(ThisPtr, Unit);
993 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
994 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
995 Elts.push_back(ThisPtrType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000996 }
997
998 // Copy rest of the arguments.
999 for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
1000 Elts.push_back(Args.getElement(i));
1001
1002 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
1003
1004 return DBuilder.createSubroutineType(Unit, EltTypeArray);
1005}
1006
Eric Christopher6537f082013-05-16 00:45:12 +00001007/// isFunctionLocalClass - Return true if CXXRecordDecl is defined
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001008/// inside a function.
1009static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
1010 if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
1011 return isFunctionLocalClass(NRD);
1012 if (isa<FunctionDecl>(RD->getDeclContext()))
1013 return true;
1014 return false;
1015}
1016
1017/// CreateCXXMemberFunction - A helper function to create a DISubprogram for
1018/// a single member function GlobalDecl.
1019llvm::DISubprogram
1020CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
1021 llvm::DIFile Unit,
1022 llvm::DIType RecordTy) {
Eric Christopher6537f082013-05-16 00:45:12 +00001023 bool IsCtorOrDtor =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001024 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
Eric Christopher6537f082013-05-16 00:45:12 +00001025
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001026 StringRef MethodName = getFunctionName(Method);
David Blaikie9a845292013-05-22 23:22:42 +00001027 llvm::DICompositeType MethodTy = getOrCreateMethodType(Method, Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001028
1029 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1030 // make sense to give a single ctor/dtor a linkage name.
1031 StringRef MethodLinkageName;
1032 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1033 MethodLinkageName = CGM.getMangledName(Method);
1034
1035 // Get the location for the method.
David Blaikiefc946272013-08-19 03:37:48 +00001036 llvm::DIFile MethodDefUnit;
1037 unsigned MethodLine = 0;
1038 if (!Method->isImplicit()) {
1039 MethodDefUnit = getOrCreateFile(Method->getLocation());
1040 MethodLine = getLineNumber(Method->getLocation());
1041 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001042
1043 // Collect virtual method info.
1044 llvm::DIType ContainingType;
Eric Christopher6537f082013-05-16 00:45:12 +00001045 unsigned Virtuality = 0;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001046 unsigned VIndex = 0;
Eric Christopher6537f082013-05-16 00:45:12 +00001047
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001048 if (Method->isVirtual()) {
1049 if (Method->isPure())
1050 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
1051 else
1052 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
Eric Christopher6537f082013-05-16 00:45:12 +00001053
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001054 // It doesn't make sense to give a virtual destructor a vtable index,
1055 // since a single destructor has two entries in the vtable.
1056 if (!isa<CXXDestructorDecl>(Method))
1057 VIndex = CGM.getVTableContext().getMethodVTableIndex(Method);
1058 ContainingType = RecordTy;
1059 }
1060
1061 unsigned Flags = 0;
1062 if (Method->isImplicit())
1063 Flags |= llvm::DIDescriptor::FlagArtificial;
1064 AccessSpecifier Access = Method->getAccess();
1065 if (Access == clang::AS_private)
1066 Flags |= llvm::DIDescriptor::FlagPrivate;
1067 else if (Access == clang::AS_protected)
1068 Flags |= llvm::DIDescriptor::FlagProtected;
1069 if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1070 if (CXXC->isExplicit())
1071 Flags |= llvm::DIDescriptor::FlagExplicit;
Eric Christopher6537f082013-05-16 00:45:12 +00001072 } else if (const CXXConversionDecl *CXXC =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001073 dyn_cast<CXXConversionDecl>(Method)) {
1074 if (CXXC->isExplicit())
1075 Flags |= llvm::DIDescriptor::FlagExplicit;
1076 }
1077 if (Method->hasPrototype())
1078 Flags |= llvm::DIDescriptor::FlagPrototyped;
1079
1080 llvm::DIArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1081 llvm::DISubprogram SP =
Eric Christopher6537f082013-05-16 00:45:12 +00001082 DBuilder.createMethod(RecordTy, MethodName, MethodLinkageName,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001083 MethodDefUnit, MethodLine,
Eric Christopher6537f082013-05-16 00:45:12 +00001084 MethodTy, /*isLocalToUnit=*/false,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001085 /* isDefinition=*/ false,
1086 Virtuality, VIndex, ContainingType,
1087 Flags, CGM.getLangOpts().Optimize, NULL,
1088 TParamsArray);
Eric Christopher6537f082013-05-16 00:45:12 +00001089
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001090 SPCache[Method->getCanonicalDecl()] = llvm::WeakVH(SP);
1091
1092 return SP;
1093}
1094
1095/// CollectCXXMemberFunctions - A helper function to collect debug info for
Eric Christopher6537f082013-05-16 00:45:12 +00001096/// C++ member functions. This is used while creating debug info entry for
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001097/// a Record.
1098void CGDebugInfo::
1099CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
1100 SmallVectorImpl<llvm::Value *> &EltTys,
1101 llvm::DIType RecordTy) {
1102
1103 // Since we want more than just the individual member decls if we
1104 // have templated functions iterate over every declaration to gather
1105 // the functions.
1106 for(DeclContext::decl_iterator I = RD->decls_begin(),
1107 E = RD->decls_end(); I != E; ++I) {
David Blaikiec5761272013-08-28 17:27:13 +00001108 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*I)) {
David Blaikiedd658022013-08-28 20:58:00 +00001109 // Reuse the existing member function declaration if it exists.
David Blaikie4a684912013-08-28 20:24:55 +00001110 // It may be associated with the declaration of the type & should be
1111 // reused as we're building the definition.
David Blaikiedd658022013-08-28 20:58:00 +00001112 //
1113 // This situation can arise in the vtable-based debug info reduction where
1114 // implicit members are emitted in a non-vtable TU.
David Blaikie5434fc22013-08-20 01:28:15 +00001115 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator MI =
1116 SPCache.find(Method->getCanonicalDecl());
David Blaikiec5761272013-08-28 17:27:13 +00001117 if (MI == SPCache.end()) {
David Blaikie4a684912013-08-28 20:24:55 +00001118 // If the member is implicit, lazily create it when we see the
1119 // definition, not before. (an ODR-used implicit default ctor that's
1120 // never actually code generated should not produce debug info)
David Blaikiec5761272013-08-28 17:27:13 +00001121 if (!Method->isImplicit())
1122 EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
1123 } else
David Blaikie5434fc22013-08-20 01:28:15 +00001124 EltTys.push_back(MI->second);
Eric Christopherac7c25f2013-08-28 23:12:10 +00001125 } else if (const FunctionTemplateDecl *FTD =
1126 dyn_cast<FunctionTemplateDecl>(*I)) {
David Blaikie11fa7512013-08-28 23:06:52 +00001127 // Add any template specializations that have already been seen. Like
1128 // implicit member functions, these may have been added to a declaration
1129 // in the case of vtable-based debug info reduction.
Eric Christopherac7c25f2013-08-28 23:12:10 +00001130 for (FunctionTemplateDecl::spec_iterator SI = FTD->spec_begin(),
1131 SE = FTD->spec_end();
1132 SI != SE; ++SI) {
David Blaikie11fa7512013-08-28 23:06:52 +00001133 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator MI =
1134 SPCache.find(cast<CXXMethodDecl>(*SI)->getCanonicalDecl());
1135 if (MI != SPCache.end())
1136 EltTys.push_back(MI->second);
1137 }
David Blaikie5434fc22013-08-20 01:28:15 +00001138 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001139 }
Eric Christopher6537f082013-05-16 00:45:12 +00001140}
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001141
1142/// CollectCXXFriends - A helper function to collect debug info for
1143/// C++ base classes. This is used while creating debug info entry for
1144/// a Record.
1145void CGDebugInfo::
1146CollectCXXFriends(const CXXRecordDecl *RD, llvm::DIFile Unit,
1147 SmallVectorImpl<llvm::Value *> &EltTys,
1148 llvm::DIType RecordTy) {
1149 for (CXXRecordDecl::friend_iterator BI = RD->friend_begin(),
1150 BE = RD->friend_end(); BI != BE; ++BI) {
1151 if ((*BI)->isUnsupportedFriend())
1152 continue;
1153 if (TypeSourceInfo *TInfo = (*BI)->getFriendType())
David Blaikie3de73f02013-08-18 04:50:23 +00001154 EltTys.push_back(DBuilder.createFriend(
David Blaikie29b8b682013-09-04 22:03:57 +00001155 RecordTy, getOrCreateType(TInfo->getType(), Unit)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001156 }
1157}
1158
1159/// CollectCXXBases - A helper function to collect debug info for
Eric Christopher6537f082013-05-16 00:45:12 +00001160/// C++ base classes. This is used while creating debug info entry for
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001161/// a Record.
1162void CGDebugInfo::
1163CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
1164 SmallVectorImpl<llvm::Value *> &EltTys,
1165 llvm::DIType RecordTy) {
1166
1167 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1168 for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
1169 BE = RD->bases_end(); BI != BE; ++BI) {
1170 unsigned BFlags = 0;
1171 uint64_t BaseOffset;
Eric Christopher6537f082013-05-16 00:45:12 +00001172
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001173 const CXXRecordDecl *Base =
1174 cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl());
Eric Christopher6537f082013-05-16 00:45:12 +00001175
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001176 if (BI->isVirtual()) {
1177 // virtual base offset offset is -ve. The code generator emits dwarf
1178 // expression where it expects +ve number.
Eric Christopher6537f082013-05-16 00:45:12 +00001179 BaseOffset =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001180 0 - CGM.getVTableContext()
1181 .getVirtualBaseOffsetOffset(RD, Base).getQuantity();
1182 BFlags = llvm::DIDescriptor::FlagVirtual;
1183 } else
1184 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1185 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1186 // BI->isVirtual() and bits when not.
Eric Christopher6537f082013-05-16 00:45:12 +00001187
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001188 AccessSpecifier Access = BI->getAccessSpecifier();
1189 if (Access == clang::AS_private)
1190 BFlags |= llvm::DIDescriptor::FlagPrivate;
1191 else if (Access == clang::AS_protected)
1192 BFlags |= llvm::DIDescriptor::FlagProtected;
Eric Christopher6537f082013-05-16 00:45:12 +00001193
1194 llvm::DIType DTy =
1195 DBuilder.createInheritance(RecordTy,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001196 getOrCreateType(BI->getType(), Unit),
1197 BaseOffset, BFlags);
1198 EltTys.push_back(DTy);
1199 }
1200}
1201
1202/// CollectTemplateParams - A helper function to collect template parameters.
1203llvm::DIArray CGDebugInfo::
1204CollectTemplateParams(const TemplateParameterList *TPList,
David Blaikie35178dc2013-06-22 18:59:18 +00001205 ArrayRef<TemplateArgument> TAList,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001206 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +00001207 SmallVector<llvm::Value *, 16> TemplateParams;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001208 for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1209 const TemplateArgument &TA = TAList[i];
David Blaikie35178dc2013-06-22 18:59:18 +00001210 StringRef Name;
1211 if (TPList)
1212 Name = TPList->getParam(i)->getName();
David Blaikie9dfd2432013-05-10 21:53:14 +00001213 switch (TA.getKind()) {
1214 case TemplateArgument::Type: {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001215 llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit);
1216 llvm::DITemplateTypeParameter TTP =
David Blaikie35178dc2013-06-22 18:59:18 +00001217 DBuilder.createTemplateTypeParameter(TheCU, Name, TTy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001218 TemplateParams.push_back(TTP);
David Blaikie9dfd2432013-05-10 21:53:14 +00001219 } break;
1220 case TemplateArgument::Integral: {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001221 llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit);
1222 llvm::DITemplateValueParameter TVP =
David Blaikie9dfd2432013-05-10 21:53:14 +00001223 DBuilder.createTemplateValueParameter(
David Blaikie35178dc2013-06-22 18:59:18 +00001224 TheCU, Name, TTy,
David Blaikie9dfd2432013-05-10 21:53:14 +00001225 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral()));
1226 TemplateParams.push_back(TVP);
1227 } break;
1228 case TemplateArgument::Declaration: {
1229 const ValueDecl *D = TA.getAsDecl();
1230 bool InstanceMember = D->isCXXInstanceMember();
1231 QualType T = InstanceMember
1232 ? CGM.getContext().getMemberPointerType(
1233 D->getType(), cast<RecordDecl>(D->getDeclContext())
1234 ->getTypeForDecl())
1235 : CGM.getContext().getPointerType(D->getType());
1236 llvm::DIType TTy = getOrCreateType(T, Unit);
1237 llvm::Value *V = 0;
1238 // Variable pointer template parameters have a value that is the address
1239 // of the variable.
1240 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1241 V = CGM.GetAddrOfGlobalVar(VD);
1242 // Member function pointers have special support for building them, though
1243 // this is currently unsupported in LLVM CodeGen.
David Blaikief8aa1552013-05-13 06:57:50 +00001244 if (InstanceMember) {
David Blaikie9dfd2432013-05-10 21:53:14 +00001245 if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(D))
1246 V = CGM.getCXXABI().EmitMemberPointer(method);
David Blaikief8aa1552013-05-13 06:57:50 +00001247 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1248 V = CGM.GetAddrOfFunction(FD);
David Blaikie9dfd2432013-05-10 21:53:14 +00001249 // Member data pointers have special handling too to compute the fixed
1250 // offset within the object.
1251 if (isa<FieldDecl>(D)) {
1252 // These five lines (& possibly the above member function pointer
1253 // handling) might be able to be refactored to use similar code in
1254 // CodeGenModule::getMemberPointerConstant
1255 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
1256 CharUnits chars =
1257 CGM.getContext().toCharUnitsFromBits((int64_t) fieldOffset);
1258 V = CGM.getCXXABI().EmitMemberDataPointer(
1259 cast<MemberPointerType>(T.getTypePtr()), chars);
1260 }
1261 llvm::DITemplateValueParameter TVP =
David Majnemer5db8b312013-08-25 22:13:27 +00001262 DBuilder.createTemplateValueParameter(TheCU, Name, TTy,
1263 V->stripPointerCasts());
David Blaikie9dfd2432013-05-10 21:53:14 +00001264 TemplateParams.push_back(TVP);
1265 } break;
1266 case TemplateArgument::NullPtr: {
1267 QualType T = TA.getNullPtrType();
1268 llvm::DIType TTy = getOrCreateType(T, Unit);
1269 llvm::Value *V = 0;
1270 // Special case member data pointer null values since they're actually -1
1271 // instead of zero.
1272 if (const MemberPointerType *MPT =
1273 dyn_cast<MemberPointerType>(T.getTypePtr()))
1274 // But treat member function pointers as simple zero integers because
1275 // it's easier than having a special case in LLVM's CodeGen. If LLVM
1276 // CodeGen grows handling for values of non-null member function
1277 // pointers then perhaps we could remove this special case and rely on
1278 // EmitNullMemberPointer for member function pointers.
1279 if (MPT->isMemberDataPointer())
1280 V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1281 if (!V)
1282 V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
1283 llvm::DITemplateValueParameter TVP =
David Blaikie35178dc2013-06-22 18:59:18 +00001284 DBuilder.createTemplateValueParameter(TheCU, Name, TTy, V);
David Blaikie9dfd2432013-05-10 21:53:14 +00001285 TemplateParams.push_back(TVP);
1286 } break;
David Blaikie35178dc2013-06-22 18:59:18 +00001287 case TemplateArgument::Template: {
1288 llvm::DITemplateValueParameter TVP =
1289 DBuilder.createTemplateTemplateParameter(
1290 TheCU, Name, llvm::DIType(),
1291 TA.getAsTemplate().getAsTemplateDecl()
1292 ->getQualifiedNameAsString());
1293 TemplateParams.push_back(TVP);
1294 } break;
1295 case TemplateArgument::Pack: {
1296 llvm::DITemplateValueParameter TVP =
1297 DBuilder.createTemplateParameterPack(
1298 TheCU, Name, llvm::DIType(),
1299 CollectTemplateParams(NULL, TA.getPackAsArray(), Unit));
1300 TemplateParams.push_back(TVP);
1301 } break;
David Majnemer87b1f6d2013-08-24 08:21:10 +00001302 case TemplateArgument::Expression: {
1303 const Expr *E = TA.getAsExpr();
1304 QualType T = E->getType();
1305 llvm::Value *V = CGM.EmitConstantExpr(E, T);
1306 assert(V && "Expression in template argument isn't constant");
1307 llvm::DIType TTy = getOrCreateType(T, Unit);
1308 llvm::DITemplateValueParameter TVP =
1309 DBuilder.createTemplateValueParameter(TheCU, Name, TTy,
1310 V->stripPointerCasts());
1311 TemplateParams.push_back(TVP);
1312 } break;
David Blaikiee8065122013-05-10 23:36:06 +00001313 // And the following should never occur:
David Blaikie9dfd2432013-05-10 21:53:14 +00001314 case TemplateArgument::TemplateExpansion:
David Blaikie9dfd2432013-05-10 21:53:14 +00001315 case TemplateArgument::Null:
1316 llvm_unreachable(
1317 "These argument types shouldn't exist in concrete types");
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001318 }
1319 }
1320 return DBuilder.getOrCreateArray(TemplateParams);
1321}
1322
1323/// CollectFunctionTemplateParams - A helper function to collect debug
1324/// info for function template parameters.
1325llvm::DIArray CGDebugInfo::
1326CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) {
1327 if (FD->getTemplatedKind() ==
1328 FunctionDecl::TK_FunctionTemplateSpecialization) {
1329 const TemplateParameterList *TList =
1330 FD->getTemplateSpecializationInfo()->getTemplate()
1331 ->getTemplateParameters();
David Blaikie35178dc2013-06-22 18:59:18 +00001332 return CollectTemplateParams(
1333 TList, FD->getTemplateSpecializationArgs()->asArray(), Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001334 }
1335 return llvm::DIArray();
1336}
1337
1338/// CollectCXXTemplateParams - A helper function to collect debug info for
1339/// template parameters.
1340llvm::DIArray CGDebugInfo::
1341CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial,
1342 llvm::DIFile Unit) {
1343 llvm::PointerUnion<ClassTemplateDecl *,
1344 ClassTemplatePartialSpecializationDecl *>
1345 PU = TSpecial->getSpecializedTemplateOrPartial();
Eric Christopher6537f082013-05-16 00:45:12 +00001346
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001347 TemplateParameterList *TPList = PU.is<ClassTemplateDecl *>() ?
1348 PU.get<ClassTemplateDecl *>()->getTemplateParameters() :
1349 PU.get<ClassTemplatePartialSpecializationDecl *>()->getTemplateParameters();
1350 const TemplateArgumentList &TAList = TSpecial->getTemplateInstantiationArgs();
David Blaikie35178dc2013-06-22 18:59:18 +00001351 return CollectTemplateParams(TPList, TAList.asArray(), Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001352}
1353
1354/// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
1355llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
1356 if (VTablePtrType.isValid())
1357 return VTablePtrType;
1358
1359 ASTContext &Context = CGM.getContext();
1360
1361 /* Function type */
1362 llvm::Value *STy = getOrCreateType(Context.IntTy, Unit);
1363 llvm::DIArray SElements = DBuilder.getOrCreateArray(STy);
1364 llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements);
1365 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1366 llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0,
1367 "__vtbl_ptr_type");
1368 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1369 return VTablePtrType;
1370}
1371
1372/// getVTableName - Get vtable name for the given Class.
1373StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
Benjamin Kramer84953792013-09-09 16:39:06 +00001374 // Copy the gdb compatible name on the side and use its reference.
1375 return internString("_vptr$", RD->getNameAsString());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001376}
1377
1378
1379/// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
1380/// debug info entry in EltTys vector.
1381void CGDebugInfo::
1382CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
1383 SmallVectorImpl<llvm::Value *> &EltTys) {
1384 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1385
1386 // If there is a primary base then it will hold vtable info.
1387 if (RL.getPrimaryBase())
1388 return;
1389
1390 // If this class is not dynamic then there is not any vtable info to collect.
1391 if (!RD->isDynamicClass())
1392 return;
1393
1394 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1395 llvm::DIType VPTR
1396 = DBuilder.createMemberType(Unit, getVTableName(RD), Unit,
Eric Christopherf0890c42013-05-16 00:52:20 +00001397 0, Size, 0, 0,
1398 llvm::DIDescriptor::FlagArtificial,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001399 getOrCreateVTablePtrType(Unit));
1400 EltTys.push_back(VPTR);
1401}
1402
Eric Christopher6537f082013-05-16 00:45:12 +00001403/// getOrCreateRecordType - Emit record type's standalone debug info.
1404llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001405 SourceLocation Loc) {
Eric Christopher13c97672013-05-16 00:45:23 +00001406 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001407 llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc));
1408 return T;
1409}
1410
1411/// getOrCreateInterfaceType - Emit an objective c interface type standalone
1412/// debug info.
1413llvm::DIType CGDebugInfo::getOrCreateInterfaceType(QualType D,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001414 SourceLocation Loc) {
Eric Christopher13c97672013-05-16 00:45:23 +00001415 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001416 llvm::DIType T = getOrCreateType(D, getOrCreateFile(Loc));
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001417 RetainedTypes.push_back(D.getAsOpaquePtr());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001418 return T;
1419}
1420
David Blaikie27804892013-08-15 20:49:17 +00001421void CGDebugInfo::completeType(const RecordDecl *RD) {
1422 if (DebugKind > CodeGenOptions::LimitedDebugInfo ||
1423 !CGM.getLangOpts().CPlusPlus)
1424 completeRequiredType(RD);
1425}
1426
1427void CGDebugInfo::completeRequiredType(const RecordDecl *RD) {
David Blaikie5434fc22013-08-20 01:28:15 +00001428 if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
1429 if (CXXDecl->isDynamicClass())
1430 return;
1431
David Blaikie27804892013-08-15 20:49:17 +00001432 QualType Ty = CGM.getContext().getRecordType(RD);
1433 llvm::DIType T = getTypeOrNull(Ty);
David Blaikie5434fc22013-08-20 01:28:15 +00001434 if (T && T.isForwardDecl())
1435 completeClassData(RD);
1436}
1437
1438void CGDebugInfo::completeClassData(const RecordDecl *RD) {
1439 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
Michael Gottesman90e55232013-08-19 18:46:16 +00001440 return;
David Blaikie5434fc22013-08-20 01:28:15 +00001441 QualType Ty = CGM.getContext().getRecordType(RD);
David Blaikie27804892013-08-15 20:49:17 +00001442 void* TyPtr = Ty.getAsOpaquePtr();
1443 if (CompletedTypeCache.count(TyPtr))
1444 return;
1445 llvm::DIType Res = CreateTypeDefinition(Ty->castAs<RecordType>());
1446 assert(!Res.isForwardDecl());
1447 CompletedTypeCache[TyPtr] = Res;
1448 TypeCache[TyPtr] = Res;
1449}
1450
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001451/// CreateType - get structure or union type.
David Blaikie29b8b682013-09-04 22:03:57 +00001452llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001453 RecordDecl *RD = Ty->getDecl();
David Blaikie5434fc22013-08-20 01:28:15 +00001454 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
David Blaikie29b8b682013-09-04 22:03:57 +00001455 // Always emit declarations for types that aren't required to be complete when
1456 // in limit-debug-info mode. If the type is later found to be required to be
1457 // complete this declaration will be upgraded to a definition by
1458 // `completeRequiredType`.
1459 // If the type is dynamic, only emit the definition in TUs that require class
1460 // data. This is handled by `completeClassData`.
David Blaikie74341d82013-09-06 06:45:04 +00001461 llvm::DICompositeType T(getTypeOrNull(QualType(Ty, 0)));
1462 // If we've already emitted the type, just use that, even if it's only a
1463 // declaration. The completeType, completeRequiredType, and completeClassData
1464 // callbacks will handle promoting the declaration to a definition.
1465 if (T ||
1466 (DebugKind <= CodeGenOptions::LimitedDebugInfo &&
1467 // Under -flimit-debug-info, emit only a declaration unless the type is
1468 // required to be complete.
David Blaikie5434fc22013-08-20 01:28:15 +00001469 !RD->isCompleteDefinitionRequired() && CGM.getLangOpts().CPlusPlus) ||
David Blaikie74341d82013-09-06 06:45:04 +00001470 // If the class is dynamic, only emit a declaration. A definition will be
1471 // emitted whenever the vtable is emitted.
1472 (CXXDecl && CXXDecl->hasDefinition() && CXXDecl->isDynamicClass()) || T) {
David Blaikie5f6e2f42013-06-05 05:32:23 +00001473 llvm::DIDescriptor FDContext =
1474 getContextDescriptor(cast<Decl>(RD->getDeclContext()));
David Blaikie74341d82013-09-06 06:45:04 +00001475 if (!T)
1476 T = getOrCreateRecordFwdDecl(Ty, FDContext);
1477 return T;
David Blaikie5f6e2f42013-06-05 05:32:23 +00001478 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001479
David Blaikie27804892013-08-15 20:49:17 +00001480 return CreateTypeDefinition(Ty);
1481}
1482
1483llvm::DIType CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {
1484 RecordDecl *RD = Ty->getDecl();
1485
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001486 // Get overall information about the record type for the debug info.
1487 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1488
1489 // Records and classes and unions can all be recursive. To handle them, we
1490 // first generate a debug descriptor for the struct as a forward declaration.
1491 // Then (if it is a definition) we go through and get debug info for all of
1492 // its members. Finally, we create a descriptor for the complete type (which
1493 // may refer to the forward decl if the struct is recursive) and replace all
1494 // uses of the forward declaration with the final definition.
1495
David Blaikie4a077162013-08-12 22:24:20 +00001496 llvm::DICompositeType FwdDecl(getOrCreateLimitedType(Ty, DefUnit));
Manman Renb6b0a712013-07-02 19:01:53 +00001497 assert(FwdDecl.isCompositeType() &&
David Blaikie9a845292013-05-22 23:22:42 +00001498 "The debug type of a RecordType should be a llvm::DICompositeType");
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001499
1500 if (FwdDecl.isForwardDecl())
1501 return FwdDecl;
1502
David Blaikie498298d2013-08-18 16:55:33 +00001503 if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
1504 CollectContainingType(CXXDecl, FwdDecl);
1505
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001506 // Push the struct on region stack.
Eric Christopherf068c922013-04-02 22:59:11 +00001507 LexicalBlockStack.push_back(&*FwdDecl);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001508 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1509
Adrian Prantl4919de62013-03-06 22:03:30 +00001510 // Add this to the completed-type cache while we're completing it recursively.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001511 CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1512
1513 // Convert all the elements.
1514 SmallVector<llvm::Value *, 16> EltTys;
David Blaikie5434fc22013-08-20 01:28:15 +00001515 // what about nested types?
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001516
1517 // Note: The split of CXXDecl information here is intentional, the
1518 // gdb tests will depend on a certain ordering at printout. The debug
1519 // information offsets are still correct if we merge them all together
1520 // though.
1521 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1522 if (CXXDecl) {
1523 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1524 CollectVTableInfo(CXXDecl, DefUnit, EltTys);
1525 }
1526
Eric Christopher0395de32013-01-16 01:22:32 +00001527 // Collect data fields (including static variables and any initializers).
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001528 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001529 if (CXXDecl) {
1530 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
1531 CollectCXXFriends(CXXDecl, DefUnit, EltTys, FwdDecl);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001532 }
1533
1534 LexicalBlockStack.pop_back();
1535 RegionMap.erase(Ty->getDecl());
1536
1537 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
David Blaikie80588332013-08-01 20:31:40 +00001538 FwdDecl.setTypeArray(Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001539
Eric Christopherf068c922013-04-02 22:59:11 +00001540 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1541 return FwdDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001542}
1543
1544/// CreateType - get objective-c object type.
1545llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1546 llvm::DIFile Unit) {
1547 // Ignore protocols.
1548 return getOrCreateType(Ty->getBaseType(), Unit);
1549}
1550
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001551
1552/// \return true if Getter has the default name for the property PD.
1553static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
1554 const ObjCMethodDecl *Getter) {
1555 assert(PD);
1556 if (!Getter)
1557 return true;
1558
1559 assert(Getter->getDeclName().isObjCZeroArgSelector());
1560 return PD->getName() ==
1561 Getter->getDeclName().getObjCSelector().getNameForSlot(0);
1562}
1563
1564/// \return true if Setter has the default name for the property PD.
1565static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
1566 const ObjCMethodDecl *Setter) {
1567 assert(PD);
1568 if (!Setter)
1569 return true;
1570
1571 assert(Setter->getDeclName().isObjCOneArgSelector());
Adrian Prantl80e8ea92013-06-07 22:29:12 +00001572 return SelectorTable::constructSetterName(PD->getName()) ==
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001573 Setter->getDeclName().getObjCSelector().getNameForSlot(0);
1574}
1575
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001576/// CreateType - get objective-c interface type.
1577llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1578 llvm::DIFile Unit) {
1579 ObjCInterfaceDecl *ID = Ty->getDecl();
1580 if (!ID)
1581 return llvm::DIType();
1582
1583 // Get overall information about the record type for the debug info.
1584 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1585 unsigned Line = getLineNumber(ID->getLocation());
1586 unsigned RuntimeLang = TheCU.getLanguage();
1587
1588 // If this is just a forward declaration return a special forward-declaration
1589 // debug type since we won't be able to lay out the entire type.
1590 ObjCInterfaceDecl *Def = ID->getDefinition();
1591 if (!Def) {
1592 llvm::DIType FwdDecl =
1593 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001594 ID->getName(), TheCU, DefUnit, Line,
1595 RuntimeLang);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001596 return FwdDecl;
1597 }
1598
1599 ID = Def;
1600
1601 // Bit size, align and offset of the type.
1602 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1603 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1604
1605 unsigned Flags = 0;
1606 if (ID->getImplementation())
1607 Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
1608
Eric Christopherf068c922013-04-02 22:59:11 +00001609 llvm::DICompositeType RealDecl =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001610 DBuilder.createStructType(Unit, ID->getName(), DefUnit,
1611 Line, Size, Align, Flags,
David Blaikiec1d0af12013-02-25 01:07:08 +00001612 llvm::DIType(), llvm::DIArray(), RuntimeLang);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001613
1614 // Otherwise, insert it into the CompletedTypeCache so that recursive uses
1615 // will find it and we're emitting the complete type.
Adrian Prantl4919de62013-03-06 22:03:30 +00001616 QualType QualTy = QualType(Ty, 0);
1617 CompletedTypeCache[QualTy.getAsOpaquePtr()] = RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001618
Eric Christopherd3003dc2013-07-14 21:00:07 +00001619 // Push the struct on region stack.
Eric Christopherf068c922013-04-02 22:59:11 +00001620 LexicalBlockStack.push_back(static_cast<llvm::MDNode*>(RealDecl));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001621 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1622
1623 // Convert all the elements.
1624 SmallVector<llvm::Value *, 16> EltTys;
1625
1626 ObjCInterfaceDecl *SClass = ID->getSuperClass();
1627 if (SClass) {
1628 llvm::DIType SClassTy =
1629 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1630 if (!SClassTy.isValid())
1631 return llvm::DIType();
Eric Christopher6537f082013-05-16 00:45:12 +00001632
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001633 llvm::DIType InhTag =
1634 DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
1635 EltTys.push_back(InhTag);
1636 }
1637
Eric Christopherd3003dc2013-07-14 21:00:07 +00001638 // Create entries for all of the properties.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001639 for (ObjCContainerDecl::prop_iterator I = ID->prop_begin(),
1640 E = ID->prop_end(); I != E; ++I) {
1641 const ObjCPropertyDecl *PD = *I;
1642 SourceLocation Loc = PD->getLocation();
1643 llvm::DIFile PUnit = getOrCreateFile(Loc);
1644 unsigned PLine = getLineNumber(Loc);
1645 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1646 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1647 llvm::MDNode *PropertyNode =
1648 DBuilder.createObjCProperty(PD->getName(),
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001649 PUnit, PLine,
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001650 hasDefaultGetterName(PD, Getter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001651 getSelectorName(PD->getGetterName()),
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001652 hasDefaultSetterName(PD, Setter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001653 getSelectorName(PD->getSetterName()),
1654 PD->getPropertyAttributes(),
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001655 getOrCreateType(PD->getType(), PUnit));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001656 EltTys.push_back(PropertyNode);
1657 }
1658
1659 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1660 unsigned FieldNo = 0;
1661 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1662 Field = Field->getNextIvar(), ++FieldNo) {
1663 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1664 if (!FieldTy.isValid())
1665 return llvm::DIType();
Eric Christopher6537f082013-05-16 00:45:12 +00001666
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001667 StringRef FieldName = Field->getName();
1668
1669 // Ignore unnamed fields.
1670 if (FieldName.empty())
1671 continue;
1672
1673 // Get the location for the field.
1674 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1675 unsigned FieldLine = getLineNumber(Field->getLocation());
1676 QualType FType = Field->getType();
1677 uint64_t FieldSize = 0;
1678 unsigned FieldAlign = 0;
1679
1680 if (!FType->isIncompleteArrayType()) {
1681
1682 // Bit size, align and offset of the type.
1683 FieldSize = Field->isBitField()
Eric Christopherd3003dc2013-07-14 21:00:07 +00001684 ? Field->getBitWidthValue(CGM.getContext())
1685 : CGM.getContext().getTypeSize(FType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001686 FieldAlign = CGM.getContext().getTypeAlign(FType);
1687 }
1688
1689 uint64_t FieldOffset;
1690 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1691 // We don't know the runtime offset of an ivar if we're using the
1692 // non-fragile ABI. For bitfields, use the bit offset into the first
1693 // byte of storage of the bitfield. For other fields, use zero.
1694 if (Field->isBitField()) {
1695 FieldOffset = CGM.getObjCRuntime().ComputeBitfieldBitOffset(
1696 CGM, ID, Field);
1697 FieldOffset %= CGM.getContext().getCharWidth();
1698 } else {
1699 FieldOffset = 0;
1700 }
1701 } else {
1702 FieldOffset = RL.getFieldOffset(FieldNo);
1703 }
1704
1705 unsigned Flags = 0;
1706 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1707 Flags = llvm::DIDescriptor::FlagProtected;
1708 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1709 Flags = llvm::DIDescriptor::FlagPrivate;
1710
1711 llvm::MDNode *PropertyNode = NULL;
1712 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
Eric Christopher6537f082013-05-16 00:45:12 +00001713 if (ObjCPropertyImplDecl *PImpD =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001714 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
1715 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001716 SourceLocation Loc = PD->getLocation();
1717 llvm::DIFile PUnit = getOrCreateFile(Loc);
1718 unsigned PLine = getLineNumber(Loc);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001719 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1720 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1721 PropertyNode =
1722 DBuilder.createObjCProperty(PD->getName(),
1723 PUnit, PLine,
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001724 hasDefaultGetterName(PD, Getter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001725 getSelectorName(PD->getGetterName()),
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001726 hasDefaultSetterName(PD, Setter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001727 getSelectorName(PD->getSetterName()),
1728 PD->getPropertyAttributes(),
1729 getOrCreateType(PD->getType(), PUnit));
1730 }
1731 }
1732 }
1733 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
1734 FieldLine, FieldSize, FieldAlign,
1735 FieldOffset, Flags, FieldTy,
1736 PropertyNode);
1737 EltTys.push_back(FieldTy);
1738 }
1739
1740 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopherf068c922013-04-02 22:59:11 +00001741 RealDecl.setTypeArray(Elements);
Adrian Prantl4919de62013-03-06 22:03:30 +00001742
1743 // If the implementation is not yet set, we do not want to mark it
1744 // as complete. An implementation may declare additional
1745 // private ivars that we would miss otherwise.
1746 if (ID->getImplementation() == 0)
1747 CompletedTypeCache.erase(QualTy.getAsOpaquePtr());
Eric Christopher6537f082013-05-16 00:45:12 +00001748
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001749 LexicalBlockStack.pop_back();
Eric Christopherf068c922013-04-02 22:59:11 +00001750 return RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001751}
1752
1753llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) {
1754 llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1755 int64_t Count = Ty->getNumElements();
1756 if (Count == 0)
1757 // If number of elements are not known then this is an unbounded array.
1758 // Use Count == -1 to express such arrays.
1759 Count = -1;
1760
1761 llvm::Value *Subscript = DBuilder.getOrCreateSubrange(0, Count);
1762 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1763
1764 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1765 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1766
1767 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1768}
1769
1770llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1771 llvm::DIFile Unit) {
1772 uint64_t Size;
1773 uint64_t Align;
1774
1775 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1776 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1777 Size = 0;
1778 Align =
1779 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1780 } else if (Ty->isIncompleteArrayType()) {
1781 Size = 0;
1782 if (Ty->getElementType()->isIncompleteType())
1783 Align = 0;
1784 else
1785 Align = CGM.getContext().getTypeAlign(Ty->getElementType());
David Blaikie089db2e2013-05-09 20:48:12 +00001786 } else if (Ty->isIncompleteType()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001787 Size = 0;
1788 Align = 0;
1789 } else {
1790 // Size and align of the whole array, not the element type.
1791 Size = CGM.getContext().getTypeSize(Ty);
1792 Align = CGM.getContext().getTypeAlign(Ty);
1793 }
1794
1795 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
1796 // interior arrays, do we care? Why aren't nested arrays represented the
1797 // obvious/recursive way?
1798 SmallVector<llvm::Value *, 8> Subscripts;
1799 QualType EltTy(Ty, 0);
1800 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1801 // If the number of elements is known, then count is that number. Otherwise,
1802 // it's -1. This allows us to represent a subrange with an array of 0
1803 // elements, like this:
1804 //
1805 // struct foo {
1806 // int x[0];
1807 // };
1808 int64_t Count = -1; // Count == -1 is an unbounded array.
1809 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1810 Count = CAT->getSize().getZExtValue();
Eric Christopher6537f082013-05-16 00:45:12 +00001811
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001812 // FIXME: Verify this is right for VLAs.
1813 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
1814 EltTy = Ty->getElementType();
1815 }
1816
1817 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1818
Eric Christopher6537f082013-05-16 00:45:12 +00001819 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001820 DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1821 SubscriptArray);
1822 return DbgTy;
1823}
1824
Eric Christopher6537f082013-05-16 00:45:12 +00001825llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001826 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +00001827 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001828 Ty, Ty->getPointeeType(), Unit);
1829}
1830
Eric Christopher6537f082013-05-16 00:45:12 +00001831llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001832 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +00001833 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001834 Ty, Ty->getPointeeType(), Unit);
1835}
1836
Eric Christopher6537f082013-05-16 00:45:12 +00001837llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001838 llvm::DIFile U) {
David Blaikiee8d75142013-01-19 19:20:56 +00001839 llvm::DIType ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
1840 if (!Ty->getPointeeType()->isFunctionType())
1841 return DBuilder.createMemberPointerType(
David Blaikie29b8b682013-09-04 22:03:57 +00001842 getOrCreateType(Ty->getPointeeType(), U), ClassType);
David Blaikiee8d75142013-01-19 19:20:56 +00001843 return DBuilder.createMemberPointerType(getOrCreateInstanceMethodType(
1844 CGM.getContext().getPointerType(
1845 QualType(Ty->getClass(), Ty->getPointeeType().getCVRQualifiers())),
1846 Ty->getPointeeType()->getAs<FunctionProtoType>(), U),
1847 ClassType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001848}
1849
Eric Christopher6537f082013-05-16 00:45:12 +00001850llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001851 llvm::DIFile U) {
1852 // Ignore the atomic wrapping
1853 // FIXME: What is the correct representation?
1854 return getOrCreateType(Ty->getValueType(), U);
1855}
1856
1857/// CreateEnumType - get enumeration type.
Manman Ren0a0be742013-08-28 21:46:36 +00001858llvm::DIType CGDebugInfo::CreateEnumType(const EnumType *Ty) {
Manman Renf3327332013-08-28 21:20:28 +00001859 const EnumDecl *ED = Ty->getDecl();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001860 uint64_t Size = 0;
1861 uint64_t Align = 0;
1862 if (!ED->getTypeForDecl()->isIncompleteType()) {
1863 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1864 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1865 }
1866
Manman Ren83369bf2013-08-29 23:19:58 +00001867 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
1868
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001869 // If this is just a forward declaration, construct an appropriately
1870 // marked node and just return it.
1871 if (!ED->getDefinition()) {
1872 llvm::DIDescriptor EDContext;
1873 EDContext = getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1874 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1875 unsigned Line = getLineNumber(ED->getLocation());
1876 StringRef EDName = ED->getName();
1877 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_enumeration_type,
1878 EDName, EDContext, DefUnit, Line, 0,
Manman Ren83369bf2013-08-29 23:19:58 +00001879 Size, Align, FullName);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001880 }
1881
1882 // Create DIEnumerator elements for each enumerator.
1883 SmallVector<llvm::Value *, 16> Enumerators;
1884 ED = ED->getDefinition();
1885 for (EnumDecl::enumerator_iterator
1886 Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
1887 Enum != EnumEnd; ++Enum) {
1888 Enumerators.push_back(
1889 DBuilder.createEnumerator(Enum->getName(),
David Blaikieac8f43c2013-06-24 07:13:13 +00001890 Enum->getInitVal().getSExtValue()));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001891 }
1892
1893 // Return a CompositeType for the enum itself.
1894 llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1895
1896 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1897 unsigned Line = getLineNumber(ED->getLocation());
Eric Christopher6537f082013-05-16 00:45:12 +00001898 llvm::DIDescriptor EnumContext =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001899 getContextDescriptor(cast<Decl>(ED->getDeclContext()));
Adrian Prantl59d6a712013-04-19 19:56:39 +00001900 llvm::DIType ClassTy = ED->isFixed() ?
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001901 getOrCreateType(ED->getIntegerType(), DefUnit) : llvm::DIType();
Eric Christopher6537f082013-05-16 00:45:12 +00001902 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001903 DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1904 Size, Align, EltArray,
Manman Ren83369bf2013-08-29 23:19:58 +00001905 ClassTy, FullName);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001906 return DbgTy;
1907}
1908
David Blaikie4b12be62013-01-21 04:37:12 +00001909static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
1910 Qualifiers Quals;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001911 do {
David Blaikie4b12be62013-01-21 04:37:12 +00001912 Quals += T.getLocalQualifiers();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001913 QualType LastT = T;
1914 switch (T->getTypeClass()) {
1915 default:
David Blaikie4b12be62013-01-21 04:37:12 +00001916 return C.getQualifiedType(T.getTypePtr(), Quals);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001917 case Type::TemplateSpecialization:
1918 T = cast<TemplateSpecializationType>(T)->desugar();
1919 break;
1920 case Type::TypeOfExpr:
1921 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1922 break;
1923 case Type::TypeOf:
1924 T = cast<TypeOfType>(T)->getUnderlyingType();
1925 break;
1926 case Type::Decltype:
1927 T = cast<DecltypeType>(T)->getUnderlyingType();
1928 break;
1929 case Type::UnaryTransform:
1930 T = cast<UnaryTransformType>(T)->getUnderlyingType();
1931 break;
1932 case Type::Attributed:
1933 T = cast<AttributedType>(T)->getEquivalentType();
1934 break;
1935 case Type::Elaborated:
1936 T = cast<ElaboratedType>(T)->getNamedType();
1937 break;
1938 case Type::Paren:
1939 T = cast<ParenType>(T)->getInnerType();
1940 break;
David Blaikie4b12be62013-01-21 04:37:12 +00001941 case Type::SubstTemplateTypeParm:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001942 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001943 break;
1944 case Type::Auto:
David Blaikie91296482013-05-24 21:24:35 +00001945 QualType DT = cast<AutoType>(T)->getDeducedType();
1946 if (DT.isNull())
1947 return T;
1948 T = DT;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001949 break;
1950 }
Eric Christopher6537f082013-05-16 00:45:12 +00001951
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001952 assert(T != LastT && "Type unwrapping failed to unwrap!");
NAKAMURA Takumid24c9ab2013-01-21 10:51:28 +00001953 (void)LastT;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001954 } while (true);
1955}
1956
Eric Christopherf0890c42013-05-16 00:52:20 +00001957/// getType - Get the type from the cache or return null type if it doesn't
1958/// exist.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001959llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) {
1960
1961 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00001962 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Eric Christopher6537f082013-05-16 00:45:12 +00001963
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001964 // Check for existing entry.
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001965 if (Ty->getTypeClass() == Type::ObjCInterface) {
1966 llvm::Value *V = getCachedInterfaceTypeOrNull(Ty);
1967 if (V)
1968 return llvm::DIType(cast<llvm::MDNode>(V));
1969 else return llvm::DIType();
1970 }
1971
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001972 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1973 TypeCache.find(Ty.getAsOpaquePtr());
1974 if (it != TypeCache.end()) {
1975 // Verify that the debug info still exists.
1976 if (llvm::Value *V = it->second)
1977 return llvm::DIType(cast<llvm::MDNode>(V));
1978 }
1979
1980 return llvm::DIType();
1981}
1982
1983/// getCompletedTypeOrNull - Get the type from the cache or return null if it
1984/// doesn't exist.
1985llvm::DIType CGDebugInfo::getCompletedTypeOrNull(QualType Ty) {
1986
1987 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00001988 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001989
1990 // Check for existing entry.
Adrian Prantl4919de62013-03-06 22:03:30 +00001991 llvm::Value *V = 0;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001992 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1993 CompletedTypeCache.find(Ty.getAsOpaquePtr());
Adrian Prantl4919de62013-03-06 22:03:30 +00001994 if (it != CompletedTypeCache.end())
1995 V = it->second;
1996 else {
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001997 V = getCachedInterfaceTypeOrNull(Ty);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001998 }
1999
Adrian Prantl4919de62013-03-06 22:03:30 +00002000 // Verify that any cached debug info still exists.
David Blaikie00383082013-08-13 04:21:38 +00002001 return llvm::DIType(cast_or_null<llvm::MDNode>(V));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002002}
2003
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002004/// getCachedInterfaceTypeOrNull - Get the type from the interface
2005/// cache, unless it needs to regenerated. Otherwise return null.
2006llvm::Value *CGDebugInfo::getCachedInterfaceTypeOrNull(QualType Ty) {
2007 // Is there a cached interface that hasn't changed?
2008 llvm::DenseMap<void *, std::pair<llvm::WeakVH, unsigned > >
2009 ::iterator it1 = ObjCInterfaceCache.find(Ty.getAsOpaquePtr());
2010
2011 if (it1 != ObjCInterfaceCache.end())
2012 if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty))
2013 if (Checksum(Decl) == it1->second.second)
2014 // Return cached forward declaration.
2015 return it1->second.first;
2016
2017 return 0;
2018}
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002019
2020/// getOrCreateType - Get the type from the cache or create a new
2021/// one if necessary.
David Blaikie29b8b682013-09-04 22:03:57 +00002022llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002023 if (Ty.isNull())
2024 return llvm::DIType();
2025
2026 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00002027 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002028
David Blaikie29b8b682013-09-04 22:03:57 +00002029 if (llvm::DIType T = getCompletedTypeOrNull(Ty))
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002030 return T;
2031
2032 // Otherwise create the type.
David Blaikie29b8b682013-09-04 22:03:57 +00002033 llvm::DIType Res = CreateTypeNode(Ty, Unit);
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002034 void* TyPtr = Ty.getAsOpaquePtr();
2035
2036 // And update the type cache.
2037 TypeCache[TyPtr] = Res;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002038
David Blaikie492b1022013-08-15 21:21:19 +00002039 // FIXME: this getTypeOrNull call seems silly when we just inserted the type
2040 // into the cache - but getTypeOrNull has a special case for cached interface
2041 // types. We should probably just pull that out as a special case for the
2042 // "else" block below & skip the otherwise needless lookup.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002043 llvm::DIType TC = getTypeOrNull(Ty);
Eric Christopherb2d13922013-07-18 00:52:50 +00002044 if (TC && TC.isForwardDecl())
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002045 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
2046 else if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty)) {
2047 // Interface types may have elements added to them by a
2048 // subsequent implementation or extension, so we keep them in
2049 // the ObjCInterfaceCache together with a checksum. Instead of
Adrian Prantlf06989b2013-05-08 23:37:22 +00002050 // the (possibly) incomplete interface type, we return a forward
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002051 // declaration that gets RAUW'd in CGDebugInfo::finalize().
David Blaikiee2eb89a2013-05-21 18:29:40 +00002052 std::pair<llvm::WeakVH, unsigned> &V = ObjCInterfaceCache[TyPtr];
2053 if (V.first)
2054 return llvm::DIType(cast<llvm::MDNode>(V.first));
2055 TC = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
2056 Decl->getName(), TheCU, Unit,
2057 getLineNumber(Decl->getLocation()),
2058 TheCU.getLanguage());
2059 // Store the forward declaration in the cache.
2060 V.first = TC;
2061 V.second = Checksum(Decl);
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002062
David Blaikiee2eb89a2013-05-21 18:29:40 +00002063 // Register the type for replacement in finalize().
2064 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
2065
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002066 return TC;
Adrian Prantl4919de62013-03-06 22:03:30 +00002067 }
2068
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002069 if (!Res.isForwardDecl())
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002070 CompletedTypeCache[TyPtr] = Res;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002071
2072 return Res;
2073}
2074
Adrian Prantlb5a50072013-06-07 01:10:41 +00002075/// Currently the checksum of an interface includes the number of
2076/// ivars and property accessors.
Eric Christopher56b108a2013-06-07 22:54:39 +00002077unsigned CGDebugInfo::Checksum(const ObjCInterfaceDecl *ID) {
Adrian Prantl4f97f852013-06-07 01:10:48 +00002078 // The assumption is that the number of ivars can only increase
2079 // monotonically, so it is safe to just use their current number as
2080 // a checksum.
Adrian Prantlb5a50072013-06-07 01:10:41 +00002081 unsigned Sum = 0;
2082 for (const ObjCIvarDecl *Ivar = ID->all_declared_ivar_begin();
2083 Ivar != 0; Ivar = Ivar->getNextIvar())
2084 ++Sum;
2085
2086 return Sum;
Adrian Prantl4919de62013-03-06 22:03:30 +00002087}
2088
2089ObjCInterfaceDecl *CGDebugInfo::getObjCInterfaceDecl(QualType Ty) {
2090 switch (Ty->getTypeClass()) {
2091 case Type::ObjCObjectPointer:
Eric Christopherf0890c42013-05-16 00:52:20 +00002092 return getObjCInterfaceDecl(cast<ObjCObjectPointerType>(Ty)
2093 ->getPointeeType());
Adrian Prantl4919de62013-03-06 22:03:30 +00002094 case Type::ObjCInterface:
2095 return cast<ObjCInterfaceType>(Ty)->getDecl();
2096 default:
2097 return 0;
2098 }
2099}
2100
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002101/// CreateTypeNode - Create a new debug type node.
David Blaikie29b8b682013-09-04 22:03:57 +00002102llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002103 // Handle qualifiers, which recursively handles what they refer to.
2104 if (Ty.hasLocalQualifiers())
David Blaikie29b8b682013-09-04 22:03:57 +00002105 return CreateQualifiedType(Ty, Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002106
2107 const char *Diag = 0;
Eric Christopher6537f082013-05-16 00:45:12 +00002108
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002109 // Work out details of type.
2110 switch (Ty->getTypeClass()) {
2111#define TYPE(Class, Base)
2112#define ABSTRACT_TYPE(Class, Base)
2113#define NON_CANONICAL_TYPE(Class, Base)
2114#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2115#include "clang/AST/TypeNodes.def"
2116 llvm_unreachable("Dependent types cannot show up in debug information");
2117
2118 case Type::ExtVector:
2119 case Type::Vector:
2120 return CreateType(cast<VectorType>(Ty), Unit);
2121 case Type::ObjCObjectPointer:
2122 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
2123 case Type::ObjCObject:
2124 return CreateType(cast<ObjCObjectType>(Ty), Unit);
2125 case Type::ObjCInterface:
2126 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
2127 case Type::Builtin:
2128 return CreateType(cast<BuiltinType>(Ty));
2129 case Type::Complex:
2130 return CreateType(cast<ComplexType>(Ty));
2131 case Type::Pointer:
2132 return CreateType(cast<PointerType>(Ty), Unit);
Reid Kleckner12df2462013-06-24 17:51:48 +00002133 case Type::Decayed:
2134 // Decayed types are just pointers in LLVM and DWARF.
2135 return CreateType(
2136 cast<PointerType>(cast<DecayedType>(Ty)->getDecayedType()), Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002137 case Type::BlockPointer:
2138 return CreateType(cast<BlockPointerType>(Ty), Unit);
2139 case Type::Typedef:
David Blaikie29b8b682013-09-04 22:03:57 +00002140 return CreateType(cast<TypedefType>(Ty), Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002141 case Type::Record:
David Blaikie29b8b682013-09-04 22:03:57 +00002142 return CreateType(cast<RecordType>(Ty));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002143 case Type::Enum:
Manman Renf3327332013-08-28 21:20:28 +00002144 return CreateEnumType(cast<EnumType>(Ty));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002145 case Type::FunctionProto:
2146 case Type::FunctionNoProto:
2147 return CreateType(cast<FunctionType>(Ty), Unit);
2148 case Type::ConstantArray:
2149 case Type::VariableArray:
2150 case Type::IncompleteArray:
2151 return CreateType(cast<ArrayType>(Ty), Unit);
2152
2153 case Type::LValueReference:
2154 return CreateType(cast<LValueReferenceType>(Ty), Unit);
2155 case Type::RValueReference:
2156 return CreateType(cast<RValueReferenceType>(Ty), Unit);
2157
2158 case Type::MemberPointer:
2159 return CreateType(cast<MemberPointerType>(Ty), Unit);
2160
2161 case Type::Atomic:
2162 return CreateType(cast<AtomicType>(Ty), Unit);
2163
2164 case Type::Attributed:
2165 case Type::TemplateSpecialization:
2166 case Type::Elaborated:
2167 case Type::Paren:
2168 case Type::SubstTemplateTypeParm:
2169 case Type::TypeOfExpr:
2170 case Type::TypeOf:
2171 case Type::Decltype:
2172 case Type::UnaryTransform:
David Blaikie226399c2013-07-13 21:08:08 +00002173 case Type::PackExpansion:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002174 llvm_unreachable("type should have been unwrapped!");
David Blaikie91296482013-05-24 21:24:35 +00002175 case Type::Auto:
2176 Diag = "auto";
2177 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002178 }
Eric Christopher6537f082013-05-16 00:45:12 +00002179
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002180 assert(Diag && "Fall through without a diagnostic?");
2181 unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error,
2182 "debug information for %0 is not yet supported");
2183 CGM.getDiags().Report(DiagID)
2184 << Diag;
2185 return llvm::DIType();
2186}
2187
2188/// getOrCreateLimitedType - Get the type from the cache or create a new
2189/// limited type if necessary.
David Blaikie4a077162013-08-12 22:24:20 +00002190llvm::DIType CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002191 llvm::DIFile Unit) {
David Blaikie4a077162013-08-12 22:24:20 +00002192 QualType QTy(Ty, 0);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002193
David Blaikieeaacc882013-08-20 21:03:29 +00002194 llvm::DICompositeType T(getTypeOrNull(QTy));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002195
2196 // We may have cached a forward decl when we could have created
2197 // a non-forward decl. Go ahead and create a non-forward decl
2198 // now.
Eric Christopherb2d13922013-07-18 00:52:50 +00002199 if (T && !T.isForwardDecl()) return T;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002200
2201 // Otherwise create the type.
David Blaikieeaacc882013-08-20 21:03:29 +00002202 llvm::DICompositeType Res = CreateLimitedType(Ty);
2203
2204 // Propagate members from the declaration to the definition
2205 // CreateType(const RecordType*) will overwrite this with the members in the
2206 // correct order if the full type is needed.
2207 Res.setTypeArray(T.getTypeArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002208
Eric Christopherb2d13922013-07-18 00:52:50 +00002209 if (T && T.isForwardDecl())
David Blaikie4a077162013-08-12 22:24:20 +00002210 ReplaceMap.push_back(
2211 std::make_pair(QTy.getAsOpaquePtr(), static_cast<llvm::Value *>(T)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002212
2213 // And update the type cache.
David Blaikie4a077162013-08-12 22:24:20 +00002214 TypeCache[QTy.getAsOpaquePtr()] = Res;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002215 return Res;
2216}
2217
2218// TODO: Currently used for context chains when limiting debug info.
David Blaikieeaacc882013-08-20 21:03:29 +00002219llvm::DICompositeType CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002220 RecordDecl *RD = Ty->getDecl();
Eric Christopher6537f082013-05-16 00:45:12 +00002221
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002222 // Get overall information about the record type for the debug info.
2223 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
2224 unsigned Line = getLineNumber(RD->getLocation());
2225 StringRef RDName = getClassName(RD);
2226
2227 llvm::DIDescriptor RDContext;
David Blaikie74341d82013-09-06 06:45:04 +00002228 RDContext = getContextDescriptor(cast<Decl>(RD->getDeclContext()));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002229
David Blaikiec138ff52013-08-18 17:36:19 +00002230 // If we ended up creating the type during the context chain construction,
2231 // just return that.
2232 // FIXME: this could be dealt with better if the type was recorded as
2233 // completed before we started this (see the CompletedTypeCache usage in
2234 // CGDebugInfo::CreateTypeDefinition(const RecordType*) - that would need to
2235 // be pushed to before context creation, but after it was known to be
2236 // destined for completion (might still have an issue if this caller only
2237 // required a declaration but the context construction ended up creating a
2238 // definition)
David Blaikieeaacc882013-08-20 21:03:29 +00002239 llvm::DICompositeType T(getTypeOrNull(CGM.getContext().getRecordType(RD)));
2240 if (T && (!T.isForwardDecl() || !RD->getDefinition()))
David Blaikiec138ff52013-08-18 17:36:19 +00002241 return T;
2242
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002243 // If this is just a forward declaration, construct an appropriately
2244 // marked node and just return it.
2245 if (!RD->getDefinition())
Manman Renf3327332013-08-28 21:20:28 +00002246 return getOrCreateRecordFwdDecl(Ty, RDContext);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002247
2248 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2249 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
David Blaikie2fcadbe2013-03-26 23:47:35 +00002250 llvm::DICompositeType RealDecl;
Eric Christopher6537f082013-05-16 00:45:12 +00002251
Manman Ren83369bf2013-08-29 23:19:58 +00002252 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
2253
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002254 if (RD->isUnion())
2255 RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
Manman Ren83369bf2013-08-29 23:19:58 +00002256 Size, Align, 0, llvm::DIArray(), 0,
2257 FullName);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002258 else if (RD->isClass()) {
2259 // FIXME: This could be a struct type giving a default visibility different
2260 // than C++ class type, but needs llvm metadata changes first.
2261 RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002262 Size, Align, 0, 0, llvm::DIType(),
2263 llvm::DIArray(), llvm::DIType(),
Manman Ren83369bf2013-08-29 23:19:58 +00002264 llvm::DIArray(), FullName);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002265 } else
2266 RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line,
Eric Christopherf0890c42013-05-16 00:52:20 +00002267 Size, Align, 0, llvm::DIType(),
Manman Ren83369bf2013-08-29 23:19:58 +00002268 llvm::DIArray(), 0, 0, FullName);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002269
2270 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
David Blaikie2fcadbe2013-03-26 23:47:35 +00002271 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002272
David Blaikie498298d2013-08-18 16:55:33 +00002273 if (const ClassTemplateSpecializationDecl *TSpecial =
2274 dyn_cast<ClassTemplateSpecializationDecl>(RD))
2275 RealDecl.setTypeArray(llvm::DIArray(),
2276 CollectCXXTemplateParams(TSpecial, DefUnit));
David Blaikiefab829d2013-08-15 22:42:12 +00002277 return RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002278}
2279
David Blaikie498298d2013-08-18 16:55:33 +00002280void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,
2281 llvm::DICompositeType RealDecl) {
2282 // A class's primary base or the class itself contains the vtable.
2283 llvm::DICompositeType ContainingType;
2284 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2285 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
2286 // Seek non virtual primary base root.
2287 while (1) {
2288 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
2289 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
2290 if (PBT && !BRL.isPrimaryBaseVirtual())
2291 PBase = PBT;
2292 else
2293 break;
2294 }
2295 ContainingType = llvm::DICompositeType(
2296 getOrCreateType(QualType(PBase->getTypeForDecl(), 0),
2297 getOrCreateFile(RD->getLocation())));
2298 } else if (RD->isDynamicClass())
2299 ContainingType = RealDecl;
2300
2301 RealDecl.setContainingType(ContainingType);
2302}
2303
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002304/// CreateMemberType - Create new member and increase Offset by FType's size.
2305llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
2306 StringRef Name,
2307 uint64_t *Offset) {
2308 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2309 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
2310 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
2311 llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0,
2312 FieldSize, FieldAlign,
2313 *Offset, 0, FieldTy);
2314 *Offset += FieldSize;
2315 return Ty;
2316}
2317
David Blaikie9faebd22013-05-20 04:58:53 +00002318llvm::DIDescriptor CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
2319 // We only need a declaration (not a definition) of the type - so use whatever
2320 // we would otherwise do to get a type for a pointee. (forward declarations in
2321 // limited debug info, full definitions (if the type definition is available)
2322 // in unlimited debug info)
David Blaikieb3c23772013-08-12 23:14:36 +00002323 if (const TypeDecl *TD = dyn_cast<TypeDecl>(D))
2324 return getOrCreateType(CGM.getContext().getTypeDeclType(TD),
David Blaikie29b8b682013-09-04 22:03:57 +00002325 getOrCreateFile(TD->getLocation()));
David Blaikie9faebd22013-05-20 04:58:53 +00002326 // Otherwise fall back to a fairly rudimentary cache of existing declarations.
2327 // This doesn't handle providing declarations (for functions or variables) for
2328 // entities without definitions in this TU, nor when the definition proceeds
2329 // the call to this function.
2330 // FIXME: This should be split out into more specific maps with support for
2331 // emitting forward declarations and merging definitions with declarations,
2332 // the same way as we do for types.
2333 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator I =
2334 DeclCache.find(D->getCanonicalDecl());
2335 if (I == DeclCache.end())
2336 return llvm::DIDescriptor();
2337 llvm::Value *V = I->second;
2338 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
2339}
2340
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002341/// getFunctionDeclaration - Return debug info descriptor to describe method
2342/// declaration for the given method definition.
2343llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
David Blaikie23e66db2013-06-22 00:09:36 +00002344 if (!D || DebugKind == CodeGenOptions::DebugLineTablesOnly)
2345 return llvm::DISubprogram();
2346
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002347 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
2348 if (!FD) return llvm::DISubprogram();
2349
2350 // Setup context.
David Blaikied6d5d692013-08-09 17:20:05 +00002351 llvm::DIScope S = getContextDescriptor(cast<Decl>(D->getDeclContext()));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002352
2353 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2354 MI = SPCache.find(FD->getCanonicalDecl());
David Blaikied6d5d692013-08-09 17:20:05 +00002355 if (MI == SPCache.end()) {
Eric Christopherac7c25f2013-08-28 23:12:10 +00002356 if (const CXXMethodDecl *MD =
2357 dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
David Blaikied6d5d692013-08-09 17:20:05 +00002358 llvm::DICompositeType T(S);
Eric Christopherac7c25f2013-08-28 23:12:10 +00002359 llvm::DISubprogram SP =
2360 CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()), T);
David Blaikied6d5d692013-08-09 17:20:05 +00002361 T.addMember(SP);
2362 return SP;
2363 }
2364 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002365 if (MI != SPCache.end()) {
2366 llvm::Value *V = MI->second;
2367 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
David Blaikie23e66db2013-06-22 00:09:36 +00002368 if (SP.isSubprogram() && !SP.isDefinition())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002369 return SP;
2370 }
2371
2372 for (FunctionDecl::redecl_iterator I = FD->redecls_begin(),
2373 E = FD->redecls_end(); I != E; ++I) {
2374 const FunctionDecl *NextFD = *I;
2375 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2376 MI = SPCache.find(NextFD->getCanonicalDecl());
2377 if (MI != SPCache.end()) {
2378 llvm::Value *V = MI->second;
2379 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
David Blaikie23e66db2013-06-22 00:09:36 +00002380 if (SP.isSubprogram() && !SP.isDefinition())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002381 return SP;
2382 }
2383 }
2384 return llvm::DISubprogram();
2385}
2386
2387// getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
2388// implicit parameter "this".
David Blaikie9a845292013-05-22 23:22:42 +00002389llvm::DICompositeType CGDebugInfo::getOrCreateFunctionType(const Decl *D,
2390 QualType FnType,
2391 llvm::DIFile F) {
David Blaikie23e66db2013-06-22 00:09:36 +00002392 if (!D || DebugKind == CodeGenOptions::DebugLineTablesOnly)
2393 // Create fake but valid subroutine type. Otherwise
2394 // llvm::DISubprogram::Verify() would return false, and
2395 // subprogram DIE will miss DW_AT_decl_file and
2396 // DW_AT_decl_line fields.
2397 return DBuilder.createSubroutineType(F, DBuilder.getOrCreateArray(None));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002398
2399 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
2400 return getOrCreateMethodType(Method, F);
2401 if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
2402 // Add "self" and "_cmd"
2403 SmallVector<llvm::Value *, 16> Elts;
2404
2405 // First element is always return type. For 'void' functions it is NULL.
Adrian Prantl0cb00022013-05-22 21:37:49 +00002406 QualType ResultTy = OMethod->getResultType();
2407
2408 // Replace the instancetype keyword with the actual type.
2409 if (ResultTy == CGM.getContext().getObjCInstanceType())
2410 ResultTy = CGM.getContext().getPointerType(
2411 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
2412
Adrian Prantl566a9c32013-05-10 21:08:31 +00002413 Elts.push_back(getOrCreateType(ResultTy, F));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002414 // "self" pointer is always first argument.
Adrian Prantle86fcc42013-03-29 19:20:29 +00002415 QualType SelfDeclTy = OMethod->getSelfDecl()->getType();
2416 llvm::DIType SelfTy = getOrCreateType(SelfDeclTy, F);
2417 Elts.push_back(CreateSelfType(SelfDeclTy, SelfTy));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002418 // "_cmd" pointer is always second argument.
2419 llvm::DIType CmdTy = getOrCreateType(OMethod->getCmdDecl()->getType(), F);
2420 Elts.push_back(DBuilder.createArtificialType(CmdTy));
2421 // Get rest of the arguments.
Eric Christopher6537f082013-05-16 00:45:12 +00002422 for (ObjCMethodDecl::param_const_iterator PI = OMethod->param_begin(),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002423 PE = OMethod->param_end(); PI != PE; ++PI)
2424 Elts.push_back(getOrCreateType((*PI)->getType(), F));
2425
2426 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2427 return DBuilder.createSubroutineType(F, EltTypeArray);
2428 }
David Blaikie9a845292013-05-22 23:22:42 +00002429 return llvm::DICompositeType(getOrCreateType(FnType, F));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002430}
2431
2432/// EmitFunctionStart - Constructs the debug code for entering a function.
2433void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
2434 llvm::Function *Fn,
2435 CGBuilderTy &Builder) {
2436
2437 StringRef Name;
2438 StringRef LinkageName;
2439
2440 FnBeginRegionCount.push_back(LexicalBlockStack.size());
2441
2442 const Decl *D = GD.getDecl();
2443 // Function may lack declaration in source code if it is created by Clang
2444 // CodeGen (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
2445 bool HasDecl = (D != 0);
2446 // Use the location of the declaration.
2447 SourceLocation Loc;
2448 if (HasDecl)
2449 Loc = D->getLocation();
2450
2451 unsigned Flags = 0;
2452 llvm::DIFile Unit = getOrCreateFile(Loc);
2453 llvm::DIDescriptor FDContext(Unit);
2454 llvm::DIArray TParamsArray;
2455 if (!HasDecl) {
2456 // Use llvm function name.
David Blaikiec7971a92013-08-27 23:57:18 +00002457 LinkageName = Fn->getName();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002458 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2459 // If there is a DISubprogram for this function available then use it.
2460 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2461 FI = SPCache.find(FD->getCanonicalDecl());
2462 if (FI != SPCache.end()) {
2463 llvm::Value *V = FI->second;
2464 llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(V));
2465 if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
2466 llvm::MDNode *SPN = SP;
2467 LexicalBlockStack.push_back(SPN);
2468 RegionMap[D] = llvm::WeakVH(SP);
2469 return;
2470 }
2471 }
2472 Name = getFunctionName(FD);
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002473 // Use mangled name as linkage name for C/C++ functions.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002474 if (FD->hasPrototype()) {
2475 LinkageName = CGM.getMangledName(GD);
2476 Flags |= llvm::DIDescriptor::FlagPrototyped;
2477 }
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002478 // No need to replicate the linkage name if it isn't different from the
2479 // subprogram name, no need to have it at all unless coverage is enabled or
2480 // debug is set to more than just line tables.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002481 if (LinkageName == Name ||
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002482 (!CGM.getCodeGenOpts().EmitGcovArcs &&
2483 !CGM.getCodeGenOpts().EmitGcovNotes &&
Eric Christopher13c97672013-05-16 00:45:23 +00002484 DebugKind <= CodeGenOptions::DebugLineTablesOnly))
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002485 LinkageName = StringRef();
2486
Eric Christopher13c97672013-05-16 00:45:23 +00002487 if (DebugKind >= CodeGenOptions::LimitedDebugInfo) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002488 if (const NamespaceDecl *NSDecl =
2489 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
2490 FDContext = getOrCreateNameSpace(NSDecl);
2491 else if (const RecordDecl *RDecl =
2492 dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
2493 FDContext = getContextDescriptor(cast<Decl>(RDecl->getDeclContext()));
2494
2495 // Collect template parameters.
2496 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
2497 }
2498 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
2499 Name = getObjCMethodName(OMD);
2500 Flags |= llvm::DIDescriptor::FlagPrototyped;
2501 } else {
2502 // Use llvm function name.
2503 Name = Fn->getName();
2504 Flags |= llvm::DIDescriptor::FlagPrototyped;
2505 }
2506 if (!Name.empty() && Name[0] == '\01')
2507 Name = Name.substr(1);
2508
2509 unsigned LineNo = getLineNumber(Loc);
2510 if (!HasDecl || D->isImplicit())
2511 Flags |= llvm::DIDescriptor::FlagArtificial;
2512
David Blaikie23e66db2013-06-22 00:09:36 +00002513 llvm::DISubprogram SP = DBuilder.createFunction(
2514 FDContext, Name, LinkageName, Unit, LineNo,
2515 getOrCreateFunctionType(D, FnType, Unit), Fn->hasInternalLinkage(),
2516 true /*definition*/, getLineNumber(CurLoc), Flags,
2517 CGM.getLangOpts().Optimize, Fn, TParamsArray, getFunctionDeclaration(D));
David Blaikie9faebd22013-05-20 04:58:53 +00002518 if (HasDecl)
2519 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(SP)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002520
2521 // Push function on region stack.
2522 llvm::MDNode *SPN = SP;
2523 LexicalBlockStack.push_back(SPN);
2524 if (HasDecl)
2525 RegionMap[D] = llvm::WeakVH(SP);
2526}
2527
2528/// EmitLocation - Emit metadata to indicate a change in line/column
Adrian Prantl18a0cd52013-07-18 00:27:59 +00002529/// information in the source file. If the location is invalid, the
2530/// previous location will be reused.
Adrian Prantl00df5ea2013-03-12 20:43:25 +00002531void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc,
2532 bool ForceColumnInfo) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002533 // Update our current location
2534 setLocation(Loc);
2535
2536 if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
2537
2538 // Don't bother if things are the same as last time.
2539 SourceManager &SM = CGM.getContext().getSourceManager();
2540 if (CurLoc == PrevLoc ||
2541 SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc))
2542 // New Builder may not be in sync with CGDebugInfo.
David Blaikie0a0f93c2013-02-01 19:09:49 +00002543 if (!Builder.getCurrentDebugLocation().isUnknown() &&
2544 Builder.getCurrentDebugLocation().getScope(CGM.getLLVMContext()) ==
2545 LexicalBlockStack.back())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002546 return;
Eric Christopher6537f082013-05-16 00:45:12 +00002547
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002548 // Update last state.
2549 PrevLoc = CurLoc;
2550
2551 llvm::MDNode *Scope = LexicalBlockStack.back();
Adrian Prantl00df5ea2013-03-12 20:43:25 +00002552 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get
2553 (getLineNumber(CurLoc),
2554 getColumnNumber(CurLoc, ForceColumnInfo),
2555 Scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002556}
2557
2558/// CreateLexicalBlock - Creates a new lexical block node and pushes it on
2559/// the stack.
2560void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
2561 llvm::DIDescriptor D =
2562 DBuilder.createLexicalBlock(LexicalBlockStack.empty() ?
2563 llvm::DIDescriptor() :
2564 llvm::DIDescriptor(LexicalBlockStack.back()),
2565 getOrCreateFile(CurLoc),
2566 getLineNumber(CurLoc),
2567 getColumnNumber(CurLoc));
2568 llvm::MDNode *DN = D;
2569 LexicalBlockStack.push_back(DN);
2570}
2571
2572/// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
2573/// region - beginning of a DW_TAG_lexical_block.
Eric Christopherf0890c42013-05-16 00:52:20 +00002574void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
2575 SourceLocation Loc) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002576 // Set our current location.
2577 setLocation(Loc);
2578
2579 // Create a new lexical block and push it on the stack.
2580 CreateLexicalBlock(Loc);
2581
2582 // Emit a line table change for the current location inside the new scope.
2583 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc),
2584 getColumnNumber(Loc),
2585 LexicalBlockStack.back()));
2586}
2587
2588/// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative
2589/// region - end of a DW_TAG_lexical_block.
Eric Christopherf0890c42013-05-16 00:52:20 +00002590void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
2591 SourceLocation Loc) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002592 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2593
2594 // Provide an entry in the line table for the end of the block.
2595 EmitLocation(Builder, Loc);
2596
2597 LexicalBlockStack.pop_back();
2598}
2599
2600/// EmitFunctionEnd - Constructs the debug code for exiting a function.
2601void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
2602 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2603 unsigned RCount = FnBeginRegionCount.back();
2604 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
2605
2606 // Pop all regions for this function.
2607 while (LexicalBlockStack.size() != RCount)
2608 EmitLexicalBlockEnd(Builder, CurLoc);
2609 FnBeginRegionCount.pop_back();
2610}
2611
Eric Christopher6537f082013-05-16 00:45:12 +00002612// EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002613// See BuildByRefType.
2614llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
2615 uint64_t *XOffset) {
2616
2617 SmallVector<llvm::Value *, 5> EltTys;
2618 QualType FType;
2619 uint64_t FieldSize, FieldOffset;
2620 unsigned FieldAlign;
Eric Christopher6537f082013-05-16 00:45:12 +00002621
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002622 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
Eric Christopher6537f082013-05-16 00:45:12 +00002623 QualType Type = VD->getType();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002624
2625 FieldOffset = 0;
2626 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2627 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
2628 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
2629 FType = CGM.getContext().IntTy;
2630 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
2631 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
2632
2633 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
2634 if (HasCopyAndDispose) {
2635 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2636 EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
2637 &FieldOffset));
2638 EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
2639 &FieldOffset));
2640 }
2641 bool HasByrefExtendedLayout;
2642 Qualifiers::ObjCLifetime Lifetime;
2643 if (CGM.getContext().getByrefLifetime(Type,
2644 Lifetime, HasByrefExtendedLayout)
Adrian Prantl1f437912013-07-23 00:12:14 +00002645 && HasByrefExtendedLayout) {
2646 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002647 EltTys.push_back(CreateMemberType(Unit, FType,
2648 "__byref_variable_layout",
2649 &FieldOffset));
Adrian Prantl1f437912013-07-23 00:12:14 +00002650 }
Eric Christopher6537f082013-05-16 00:45:12 +00002651
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002652 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2653 if (Align > CGM.getContext().toCharUnitsFromBits(
John McCall64aa4b32013-04-16 22:48:15 +00002654 CGM.getTarget().getPointerAlign(0))) {
Eric Christopher6537f082013-05-16 00:45:12 +00002655 CharUnits FieldOffsetInBytes
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002656 = CGM.getContext().toCharUnitsFromBits(FieldOffset);
2657 CharUnits AlignedOffsetInBytes
2658 = FieldOffsetInBytes.RoundUpToAlignment(Align);
2659 CharUnits NumPaddingBytes
2660 = AlignedOffsetInBytes - FieldOffsetInBytes;
Eric Christopher6537f082013-05-16 00:45:12 +00002661
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002662 if (NumPaddingBytes.isPositive()) {
2663 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
2664 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
2665 pad, ArrayType::Normal, 0);
2666 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
2667 }
2668 }
Eric Christopher6537f082013-05-16 00:45:12 +00002669
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002670 FType = Type;
2671 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2672 FieldSize = CGM.getContext().getTypeSize(FType);
2673 FieldAlign = CGM.getContext().toBits(Align);
2674
Eric Christopher6537f082013-05-16 00:45:12 +00002675 *XOffset = FieldOffset;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002676 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit,
2677 0, FieldSize, FieldAlign,
2678 FieldOffset, 0, FieldTy);
2679 EltTys.push_back(FieldTy);
2680 FieldOffset += FieldSize;
Eric Christopher6537f082013-05-16 00:45:12 +00002681
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002682 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopher6537f082013-05-16 00:45:12 +00002683
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002684 unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
Eric Christopher6537f082013-05-16 00:45:12 +00002685
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002686 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
David Blaikiec1d0af12013-02-25 01:07:08 +00002687 llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002688}
2689
2690/// EmitDeclare - Emit local variable declaration debug info.
2691void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
Eric Christopher6537f082013-05-16 00:45:12 +00002692 llvm::Value *Storage,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002693 unsigned ArgNo, CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002694 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002695 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2696
David Blaikiefc946272013-08-19 03:37:48 +00002697 bool Unwritten =
2698 VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) &&
2699 cast<Decl>(VD->getDeclContext())->isImplicit());
2700 llvm::DIFile Unit;
2701 if (!Unwritten)
2702 Unit = getOrCreateFile(VD->getLocation());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002703 llvm::DIType Ty;
2704 uint64_t XOffset = 0;
2705 if (VD->hasAttr<BlocksAttr>())
2706 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopher6537f082013-05-16 00:45:12 +00002707 else
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002708 Ty = getOrCreateType(VD->getType(), Unit);
2709
2710 // If there is no debug info for this type then do not emit debug info
2711 // for this variable.
2712 if (!Ty)
2713 return;
2714
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002715 // Get location information.
David Blaikiefc946272013-08-19 03:37:48 +00002716 unsigned Line = 0;
2717 unsigned Column = 0;
2718 if (!Unwritten) {
2719 Line = getLineNumber(VD->getLocation());
2720 Column = getColumnNumber(VD->getLocation());
2721 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002722 unsigned Flags = 0;
2723 if (VD->isImplicit())
2724 Flags |= llvm::DIDescriptor::FlagArtificial;
2725 // If this is the first argument and it is implicit then
2726 // give it an object pointer flag.
2727 // FIXME: There has to be a better way to do this, but for static
2728 // functions there won't be an implicit param at arg1 and
2729 // otherwise it is 'self' or 'this'.
2730 if (isa<ImplicitParamDecl>(VD) && ArgNo == 1)
2731 Flags |= llvm::DIDescriptor::FlagObjectPointer;
David Blaikie41c9bae2013-06-19 21:53:53 +00002732 if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage))
Eric Christopher7dab97b2013-07-17 22:52:53 +00002733 if (Arg->getType()->isPointerTy() && !Arg->hasByValAttr() &&
2734 !VD->getType()->isPointerType())
David Blaikie41c9bae2013-06-19 21:53:53 +00002735 Flags |= llvm::DIDescriptor::FlagIndirectVariable;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002736
2737 llvm::MDNode *Scope = LexicalBlockStack.back();
2738
2739 StringRef Name = VD->getName();
2740 if (!Name.empty()) {
2741 if (VD->hasAttr<BlocksAttr>()) {
2742 CharUnits offset = CharUnits::fromQuantity(32);
2743 SmallVector<llvm::Value *, 9> addr;
2744 llvm::Type *Int64Ty = CGM.Int64Ty;
2745 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2746 // offset of __forwarding field
2747 offset = CGM.getContext().toCharUnitsFromBits(
John McCall64aa4b32013-04-16 22:48:15 +00002748 CGM.getTarget().getPointerWidth(0));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002749 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2750 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2751 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2752 // offset of x field
2753 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2754 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2755
2756 // Create the descriptor for the variable.
2757 llvm::DIVariable D =
Eric Christopher6537f082013-05-16 00:45:12 +00002758 DBuilder.createComplexVariable(Tag,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002759 llvm::DIDescriptor(Scope),
2760 VD->getName(), Unit, Line, Ty,
2761 addr, ArgNo);
Eric Christopher6537f082013-05-16 00:45:12 +00002762
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002763 // Insert an llvm.dbg.declare into the current block.
2764 llvm::Instruction *Call =
2765 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2766 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2767 return;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002768 }
David Blaikie436653b2013-01-05 05:58:35 +00002769 } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2770 // If VD is an anonymous union then Storage represents value for
2771 // all union fields.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002772 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
David Blaikied8180cf2013-01-05 20:03:07 +00002773 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002774 for (RecordDecl::field_iterator I = RD->field_begin(),
2775 E = RD->field_end();
2776 I != E; ++I) {
2777 FieldDecl *Field = *I;
2778 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2779 StringRef FieldName = Field->getName();
Eric Christopher6537f082013-05-16 00:45:12 +00002780
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002781 // Ignore unnamed fields. Do not ignore unnamed records.
2782 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2783 continue;
Eric Christopher6537f082013-05-16 00:45:12 +00002784
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002785 // Use VarDecl's Tag, Scope and Line number.
2786 llvm::DIVariable D =
2787 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
Eric Christopher6537f082013-05-16 00:45:12 +00002788 FieldName, Unit, Line, FieldTy,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002789 CGM.getLangOpts().Optimize, Flags,
2790 ArgNo);
Eric Christopher6537f082013-05-16 00:45:12 +00002791
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002792 // Insert an llvm.dbg.declare into the current block.
2793 llvm::Instruction *Call =
2794 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2795 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2796 }
David Blaikied8180cf2013-01-05 20:03:07 +00002797 return;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002798 }
2799 }
David Blaikie436653b2013-01-05 05:58:35 +00002800
2801 // Create the descriptor for the variable.
2802 llvm::DIVariable D =
2803 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2804 Name, Unit, Line, Ty,
2805 CGM.getLangOpts().Optimize, Flags, ArgNo);
2806
2807 // Insert an llvm.dbg.declare into the current block.
2808 llvm::Instruction *Call =
2809 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2810 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002811}
2812
2813void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2814 llvm::Value *Storage,
2815 CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002816 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002817 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2818}
2819
Adrian Prantle86fcc42013-03-29 19:20:29 +00002820/// Look up the completed type for a self pointer in the TypeCache and
2821/// create a copy of it with the ObjectPointer and Artificial flags
2822/// set. If the type is not cached, a new one is created. This should
2823/// never happen though, since creating a type for the implicit self
2824/// argument implies that we already parsed the interface definition
2825/// and the ivar declarations in the implementation.
Eric Christopherf0890c42013-05-16 00:52:20 +00002826llvm::DIType CGDebugInfo::CreateSelfType(const QualType &QualTy,
2827 llvm::DIType Ty) {
Adrian Prantle86fcc42013-03-29 19:20:29 +00002828 llvm::DIType CachedTy = getTypeOrNull(QualTy);
Eric Christopherb2d13922013-07-18 00:52:50 +00002829 if (CachedTy) Ty = CachedTy;
Adrian Prantle86fcc42013-03-29 19:20:29 +00002830 else DEBUG(llvm::dbgs() << "No cached type for self.");
2831 return DBuilder.createObjectPointerType(Ty);
2832}
2833
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002834void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(const VarDecl *VD,
2835 llvm::Value *Storage,
2836 CGBuilderTy &Builder,
2837 const CGBlockInfo &blockInfo) {
Eric Christopher13c97672013-05-16 00:45:23 +00002838 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002839 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
Eric Christopher6537f082013-05-16 00:45:12 +00002840
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002841 if (Builder.GetInsertBlock() == 0)
2842 return;
Eric Christopher6537f082013-05-16 00:45:12 +00002843
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002844 bool isByRef = VD->hasAttr<BlocksAttr>();
Eric Christopher6537f082013-05-16 00:45:12 +00002845
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002846 uint64_t XOffset = 0;
2847 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2848 llvm::DIType Ty;
2849 if (isByRef)
2850 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopher6537f082013-05-16 00:45:12 +00002851 else
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002852 Ty = getOrCreateType(VD->getType(), Unit);
2853
2854 // Self is passed along as an implicit non-arg variable in a
2855 // block. Mark it as the object pointer.
2856 if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self")
Adrian Prantle86fcc42013-03-29 19:20:29 +00002857 Ty = CreateSelfType(VD->getType(), Ty);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002858
2859 // Get location information.
2860 unsigned Line = getLineNumber(VD->getLocation());
2861 unsigned Column = getColumnNumber(VD->getLocation());
2862
2863 const llvm::DataLayout &target = CGM.getDataLayout();
2864
2865 CharUnits offset = CharUnits::fromQuantity(
2866 target.getStructLayout(blockInfo.StructureType)
2867 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2868
2869 SmallVector<llvm::Value *, 9> addr;
2870 llvm::Type *Int64Ty = CGM.Int64Ty;
Adrian Prantl9b97adf2013-03-29 19:20:35 +00002871 if (isa<llvm::AllocaInst>(Storage))
2872 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002873 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2874 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2875 if (isByRef) {
2876 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2877 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2878 // offset of __forwarding field
2879 offset = CGM.getContext()
2880 .toCharUnitsFromBits(target.getPointerSizeInBits(0));
2881 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2882 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2883 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2884 // offset of x field
2885 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2886 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2887 }
2888
2889 // Create the descriptor for the variable.
2890 llvm::DIVariable D =
Eric Christopher6537f082013-05-16 00:45:12 +00002891 DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002892 llvm::DIDescriptor(LexicalBlockStack.back()),
2893 VD->getName(), Unit, Line, Ty, addr);
Adrian Prantl9b97adf2013-03-29 19:20:35 +00002894
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002895 // Insert an llvm.dbg.declare into the current block.
2896 llvm::Instruction *Call =
2897 DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
2898 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column,
2899 LexicalBlockStack.back()));
2900}
2901
2902/// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2903/// variable declaration.
2904void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2905 unsigned ArgNo,
2906 CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002907 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002908 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2909}
2910
2911namespace {
2912 struct BlockLayoutChunk {
2913 uint64_t OffsetInBits;
2914 const BlockDecl::Capture *Capture;
2915 };
2916 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2917 return l.OffsetInBits < r.OffsetInBits;
2918 }
2919}
2920
2921void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
Adrian Prantl836e7c92013-03-14 17:53:33 +00002922 llvm::Value *Arg,
2923 llvm::Value *LocalAddr,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002924 CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002925 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002926 ASTContext &C = CGM.getContext();
2927 const BlockDecl *blockDecl = block.getBlockDecl();
2928
2929 // Collect some general information about the block's location.
2930 SourceLocation loc = blockDecl->getCaretLocation();
2931 llvm::DIFile tunit = getOrCreateFile(loc);
2932 unsigned line = getLineNumber(loc);
2933 unsigned column = getColumnNumber(loc);
Eric Christopher6537f082013-05-16 00:45:12 +00002934
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002935 // Build the debug-info type for the block literal.
2936 getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
2937
2938 const llvm::StructLayout *blockLayout =
2939 CGM.getDataLayout().getStructLayout(block.StructureType);
2940
2941 SmallVector<llvm::Value*, 16> fields;
2942 fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
2943 blockLayout->getElementOffsetInBits(0),
2944 tunit, tunit));
2945 fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
2946 blockLayout->getElementOffsetInBits(1),
2947 tunit, tunit));
2948 fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
2949 blockLayout->getElementOffsetInBits(2),
2950 tunit, tunit));
2951 fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
2952 blockLayout->getElementOffsetInBits(3),
2953 tunit, tunit));
2954 fields.push_back(createFieldType("__descriptor",
2955 C.getPointerType(block.NeedsCopyDispose ?
2956 C.getBlockDescriptorExtendedType() :
2957 C.getBlockDescriptorType()),
2958 0, loc, AS_public,
2959 blockLayout->getElementOffsetInBits(4),
2960 tunit, tunit));
2961
2962 // We want to sort the captures by offset, not because DWARF
2963 // requires this, but because we're paranoid about debuggers.
2964 SmallVector<BlockLayoutChunk, 8> chunks;
2965
2966 // 'this' capture.
2967 if (blockDecl->capturesCXXThis()) {
2968 BlockLayoutChunk chunk;
2969 chunk.OffsetInBits =
2970 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
2971 chunk.Capture = 0;
2972 chunks.push_back(chunk);
2973 }
2974
2975 // Variable captures.
2976 for (BlockDecl::capture_const_iterator
2977 i = blockDecl->capture_begin(), e = blockDecl->capture_end();
2978 i != e; ++i) {
2979 const BlockDecl::Capture &capture = *i;
2980 const VarDecl *variable = capture.getVariable();
2981 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
2982
2983 // Ignore constant captures.
2984 if (captureInfo.isConstant())
2985 continue;
2986
2987 BlockLayoutChunk chunk;
2988 chunk.OffsetInBits =
2989 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
2990 chunk.Capture = &capture;
2991 chunks.push_back(chunk);
2992 }
2993
2994 // Sort by offset.
2995 llvm::array_pod_sort(chunks.begin(), chunks.end());
2996
2997 for (SmallVectorImpl<BlockLayoutChunk>::iterator
2998 i = chunks.begin(), e = chunks.end(); i != e; ++i) {
2999 uint64_t offsetInBits = i->OffsetInBits;
3000 const BlockDecl::Capture *capture = i->Capture;
3001
3002 // If we have a null capture, this must be the C++ 'this' capture.
3003 if (!capture) {
3004 const CXXMethodDecl *method =
3005 cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
3006 QualType type = method->getThisType(C);
3007
3008 fields.push_back(createFieldType("this", type, 0, loc, AS_public,
3009 offsetInBits, tunit, tunit));
3010 continue;
3011 }
3012
3013 const VarDecl *variable = capture->getVariable();
3014 StringRef name = variable->getName();
3015
3016 llvm::DIType fieldType;
3017 if (capture->isByRef()) {
3018 std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
3019
3020 // FIXME: this creates a second copy of this type!
3021 uint64_t xoffset;
3022 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
3023 fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
3024 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
3025 ptrInfo.first, ptrInfo.second,
3026 offsetInBits, 0, fieldType);
3027 } else {
3028 fieldType = createFieldType(name, variable->getType(), 0,
3029 loc, AS_public, offsetInBits, tunit, tunit);
3030 }
3031 fields.push_back(fieldType);
3032 }
3033
3034 SmallString<36> typeName;
3035 llvm::raw_svector_ostream(typeName)
3036 << "__block_literal_" << CGM.getUniqueBlockCount();
3037
3038 llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
3039
3040 llvm::DIType type =
3041 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
3042 CGM.getContext().toBits(block.BlockSize),
3043 CGM.getContext().toBits(block.BlockAlign),
David Blaikiec1d0af12013-02-25 01:07:08 +00003044 0, llvm::DIType(), fieldsArray);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003045 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
3046
3047 // Get overall information about the block.
3048 unsigned flags = llvm::DIDescriptor::FlagArtificial;
3049 llvm::MDNode *scope = LexicalBlockStack.back();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003050
3051 // Create the descriptor for the parameter.
3052 llvm::DIVariable debugVar =
3053 DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
Eric Christopher6537f082013-05-16 00:45:12 +00003054 llvm::DIDescriptor(scope),
Adrian Prantl836e7c92013-03-14 17:53:33 +00003055 Arg->getName(), tunit, line, type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003056 CGM.getLangOpts().Optimize, flags,
Adrian Prantl836e7c92013-03-14 17:53:33 +00003057 cast<llvm::Argument>(Arg)->getArgNo() + 1);
3058
Adrian Prantlbea407c2013-03-14 21:52:59 +00003059 if (LocalAddr) {
Adrian Prantl836e7c92013-03-14 17:53:33 +00003060 // Insert an llvm.dbg.value into the current block.
Adrian Prantlbea407c2013-03-14 21:52:59 +00003061 llvm::Instruction *DbgVal =
3062 DBuilder.insertDbgValueIntrinsic(LocalAddr, 0, debugVar,
Eric Christopherf068c922013-04-02 22:59:11 +00003063 Builder.GetInsertBlock());
Adrian Prantlbea407c2013-03-14 21:52:59 +00003064 DbgVal->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
3065 }
Adrian Prantl836e7c92013-03-14 17:53:33 +00003066
Adrian Prantlbea407c2013-03-14 21:52:59 +00003067 // Insert an llvm.dbg.declare into the current block.
3068 llvm::Instruction *DbgDecl =
3069 DBuilder.insertDeclare(Arg, debugVar, Builder.GetInsertBlock());
3070 DbgDecl->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003071}
3072
David Blaikie5434fc22013-08-20 01:28:15 +00003073/// If D is an out-of-class definition of a static data member of a class, find
3074/// its corresponding in-class declaration.
3075llvm::DIDerivedType
3076CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {
3077 if (!D->isStaticDataMember())
3078 return llvm::DIDerivedType();
3079 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator MI =
3080 StaticDataMemberCache.find(D->getCanonicalDecl());
3081 if (MI != StaticDataMemberCache.end()) {
3082 assert(MI->second && "Static data member declaration should still exist");
3083 return llvm::DIDerivedType(cast<llvm::MDNode>(MI->second));
Evgeniy Stepanov045a9f62013-08-16 10:35:31 +00003084 }
David Blaikie5e6937b2013-08-20 21:49:21 +00003085
3086 // If the member wasn't found in the cache, lazily construct and add it to the
3087 // type (used when a limited form of the type is emitted).
David Blaikie5434fc22013-08-20 01:28:15 +00003088 llvm::DICompositeType Ctxt(
3089 getContextDescriptor(cast<Decl>(D->getDeclContext())));
3090 llvm::DIDerivedType T = CreateRecordStaticField(D, Ctxt);
3091 Ctxt.addMember(T);
3092 return T;
3093}
3094
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003095/// EmitGlobalVariable - Emit information about a global variable.
Yunzhong Gao3b8e0b72013-08-30 08:53:09 +00003096void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003097 const VarDecl *D) {
Eric Christopher13c97672013-05-16 00:45:23 +00003098 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003099 // Create global variable debug descriptor.
3100 llvm::DIFile Unit = getOrCreateFile(D->getLocation());
3101 unsigned LineNo = getLineNumber(D->getLocation());
3102
Yunzhong Gao3b8e0b72013-08-30 08:53:09 +00003103 setLocation(D->getLocation());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003104
3105 QualType T = D->getType();
3106 if (T->isIncompleteArrayType()) {
3107
3108 // CodeGen turns int[] into int[1] so we'll do the same here.
3109 llvm::APInt ConstVal(32, 1);
3110 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3111
3112 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3113 ArrayType::Normal, 0);
3114 }
Yunzhong Gao3b8e0b72013-08-30 08:53:09 +00003115 StringRef DeclName = D->getName();
3116 StringRef LinkageName;
3117 if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext())
3118 && !isa<ObjCMethodDecl>(D->getDeclContext()))
3119 LinkageName = Var->getName();
3120 if (LinkageName == DeclName)
3121 LinkageName = StringRef();
Eric Christopher6537f082013-05-16 00:45:12 +00003122 llvm::DIDescriptor DContext =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003123 getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
David Blaikie5434fc22013-08-20 01:28:15 +00003124 llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(
3125 DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
Yunzhong Gao3b8e0b72013-08-30 08:53:09 +00003126 Var->hasInternalLinkage(), Var,
David Blaikie5434fc22013-08-20 01:28:15 +00003127 getOrCreateStaticDataMemberDeclarationOrNull(D));
David Blaikie9faebd22013-05-20 04:58:53 +00003128 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(GV)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003129}
3130
3131/// EmitGlobalVariable - Emit information about an objective-c interface.
3132void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
3133 ObjCInterfaceDecl *ID) {
Eric Christopher13c97672013-05-16 00:45:23 +00003134 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003135 // Create global variable debug descriptor.
3136 llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
3137 unsigned LineNo = getLineNumber(ID->getLocation());
3138
3139 StringRef Name = ID->getName();
3140
3141 QualType T = CGM.getContext().getObjCInterfaceType(ID);
3142 if (T->isIncompleteArrayType()) {
3143
3144 // CodeGen turns int[] into int[1] so we'll do the same here.
3145 llvm::APInt ConstVal(32, 1);
3146 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3147
3148 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3149 ArrayType::Normal, 0);
3150 }
3151
3152 DBuilder.createGlobalVariable(Name, Unit, LineNo,
3153 getOrCreateType(T, Unit),
3154 Var->hasInternalLinkage(), Var);
3155}
3156
Yunzhong Gao3b8e0b72013-08-30 08:53:09 +00003157/// EmitGlobalVariable - Emit global variable's debug info.
3158void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
3159 llvm::Constant *Init) {
Eric Christopher13c97672013-05-16 00:45:23 +00003160 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Yunzhong Gao3b8e0b72013-08-30 08:53:09 +00003161 // Create the descriptor for the variable.
3162 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
3163 StringRef Name = VD->getName();
3164 llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
3165 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
3166 const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext());
3167 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
3168 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
3169 }
3170 // Do not use DIGlobalVariable for enums.
3171 if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
3172 return;
3173 llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(
3174 Unit, Name, Name, Unit, getLineNumber(VD->getLocation()), Ty, true, Init,
3175 getOrCreateStaticDataMemberDeclarationOrNull(cast<VarDecl>(VD)));
3176 DeclCache.insert(std::make_pair(VD->getCanonicalDecl(), llvm::WeakVH(GV)));
David Blaikie9faebd22013-05-20 04:58:53 +00003177}
3178
3179llvm::DIScope CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
3180 if (!LexicalBlockStack.empty())
3181 return llvm::DIScope(LexicalBlockStack.back());
3182 return getContextDescriptor(D);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003183}
3184
David Blaikie957dac52013-04-22 06:13:21 +00003185void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
David Blaikie9faebd22013-05-20 04:58:53 +00003186 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3187 return;
David Blaikie957dac52013-04-22 06:13:21 +00003188 DBuilder.createImportedModule(
David Blaikie9faebd22013-05-20 04:58:53 +00003189 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
3190 getOrCreateNameSpace(UD.getNominatedNamespace()),
David Blaikie957dac52013-04-22 06:13:21 +00003191 getLineNumber(UD.getLocation()));
3192}
3193
David Blaikie9faebd22013-05-20 04:58:53 +00003194void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
3195 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3196 return;
3197 assert(UD.shadow_size() &&
3198 "We shouldn't be codegening an invalid UsingDecl containing no decls");
3199 // Emitting one decl is sufficient - debuggers can detect that this is an
3200 // overloaded name & provide lookup for all the overloads.
3201 const UsingShadowDecl &USD = **UD.shadow_begin();
Eric Christopher56b108a2013-06-07 22:54:39 +00003202 if (llvm::DIDescriptor Target =
3203 getDeclarationOrDefinition(USD.getUnderlyingDecl()))
David Blaikie9faebd22013-05-20 04:58:53 +00003204 DBuilder.createImportedDeclaration(
3205 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
3206 getLineNumber(USD.getLocation()));
3207}
3208
David Blaikiefc46ebc2013-05-20 22:50:41 +00003209llvm::DIImportedEntity
3210CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
3211 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3212 return llvm::DIImportedEntity(0);
3213 llvm::WeakVH &VH = NamespaceAliasCache[&NA];
3214 if (VH)
3215 return llvm::DIImportedEntity(cast<llvm::MDNode>(VH));
3216 llvm::DIImportedEntity R(0);
3217 if (const NamespaceAliasDecl *Underlying =
3218 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
3219 // This could cache & dedup here rather than relying on metadata deduping.
3220 R = DBuilder.createImportedModule(
3221 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3222 EmitNamespaceAlias(*Underlying), getLineNumber(NA.getLocation()),
3223 NA.getName());
3224 else
3225 R = DBuilder.createImportedModule(
3226 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3227 getOrCreateNameSpace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
3228 getLineNumber(NA.getLocation()), NA.getName());
3229 VH = R;
3230 return R;
3231}
3232
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003233/// getOrCreateNamesSpace - Return namespace descriptor for the given
3234/// namespace decl.
Eric Christopher6537f082013-05-16 00:45:12 +00003235llvm::DINameSpace
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003236CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
David Blaikie8863e6b2013-08-16 22:52:07 +00003237 NSDecl = NSDecl->getCanonicalDecl();
Eric Christopher6537f082013-05-16 00:45:12 +00003238 llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003239 NameSpaceCache.find(NSDecl);
3240 if (I != NameSpaceCache.end())
3241 return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
Eric Christopher6537f082013-05-16 00:45:12 +00003242
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003243 unsigned LineNo = getLineNumber(NSDecl->getLocation());
3244 llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
Eric Christopher6537f082013-05-16 00:45:12 +00003245 llvm::DIDescriptor Context =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003246 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
3247 llvm::DINameSpace NS =
3248 DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
3249 NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
3250 return NS;
3251}
3252
3253void CGDebugInfo::finalize() {
3254 for (std::vector<std::pair<void *, llvm::WeakVH> >::const_iterator VI
3255 = ReplaceMap.begin(), VE = ReplaceMap.end(); VI != VE; ++VI) {
3256 llvm::DIType Ty, RepTy;
3257 // Verify that the debug info still exists.
3258 if (llvm::Value *V = VI->second)
3259 Ty = llvm::DIType(cast<llvm::MDNode>(V));
Eric Christopher6537f082013-05-16 00:45:12 +00003260
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003261 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
3262 TypeCache.find(VI->first);
3263 if (it != TypeCache.end()) {
3264 // Verify that the debug info still exists.
3265 if (llvm::Value *V = it->second)
3266 RepTy = llvm::DIType(cast<llvm::MDNode>(V));
3267 }
Adrian Prantlebbd7e02013-03-11 18:33:46 +00003268
Eric Christopherb2d13922013-07-18 00:52:50 +00003269 if (Ty && Ty.isForwardDecl() && RepTy)
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003270 Ty.replaceAllUsesWith(RepTy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003271 }
Adrian Prantlebbd7e02013-03-11 18:33:46 +00003272
3273 // We keep our own list of retained types, because we need to look
3274 // up the final type in the type cache.
3275 for (std::vector<void *>::const_iterator RI = RetainedTypes.begin(),
3276 RE = RetainedTypes.end(); RI != RE; ++RI)
Manman Ren18760452013-08-29 20:48:48 +00003277 DBuilder.retainType(llvm::DIType(cast<llvm::MDNode>(TypeCache[*RI])));
Adrian Prantlebbd7e02013-03-11 18:33:46 +00003278
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003279 DBuilder.finalize();
3280}