blob: 35bd57a053158cb7e4d111793b2cc5f6aaba0cde [file] [log] [blame]
Guy Benyei11169dd2012-12-18 14:30:41 +00001//===--- CGDebugInfo.cpp - Emit Debug Information for a Module ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the debug information generation while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGDebugInfo.h"
15#include "CGBlocks.h"
David Blaikie38079fd2013-05-10 21:53:14 +000016#include "CGCXXABI.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000017#include "CGObjCRuntime.h"
18#include "CodeGenFunction.h"
19#include "CodeGenModule.h"
20#include "clang/AST/ASTContext.h"
21#include "clang/AST/DeclFriend.h"
22#include "clang/AST/DeclObjC.h"
23#include "clang/AST/DeclTemplate.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/RecordLayout.h"
26#include "clang/Basic/FileManager.h"
27#include "clang/Basic/SourceManager.h"
28#include "clang/Basic/Version.h"
29#include "clang/Frontend/CodeGenOptions.h"
30#include "llvm/ADT/SmallVector.h"
31#include "llvm/ADT/StringExtras.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000032#include "llvm/IR/Constants.h"
33#include "llvm/IR/DataLayout.h"
34#include "llvm/IR/DerivedTypes.h"
35#include "llvm/IR/Instructions.h"
36#include "llvm/IR/Intrinsics.h"
37#include "llvm/IR/Module.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000038#include "llvm/Support/Dwarf.h"
39#include "llvm/Support/FileSystem.h"
Adrian Prantl0630eb72013-12-18 21:48:18 +000040#include "llvm/Support/Path.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000041using namespace clang;
42using namespace clang::CodeGen;
43
44CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
Eric Christopher324bbbd2013-07-14 21:12:44 +000045 : CGM(CGM), DebugKind(CGM.getCodeGenOpts().getDebugInfo()),
46 DBuilder(CGM.getModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +000047 CreateCompileUnit();
48}
49
50CGDebugInfo::~CGDebugInfo() {
51 assert(LexicalBlockStack.empty() &&
52 "Region stack mismatch, stack not empty!");
53}
54
Eric Christopher0a1301f2014-02-26 02:49:36 +000055SaveAndRestoreLocation::SaveAndRestoreLocation(CodeGenFunction &CGF,
56 CGBuilderTy &B)
57 : DI(CGF.getDebugInfo()), Builder(B) {
Adrian Prantl2e0637f2013-07-18 00:28:02 +000058 if (DI) {
59 SavedLoc = DI->getLocation();
60 DI->CurLoc = SourceLocation();
Adrian Prantl2e0637f2013-07-18 00:28:02 +000061 }
62}
63
Adrian Prantld1b151e2014-01-17 00:15:10 +000064SaveAndRestoreLocation::~SaveAndRestoreLocation() {
65 if (DI)
66 DI->EmitLocation(Builder, SavedLoc);
67}
68
69NoLocation::NoLocation(CodeGenFunction &CGF, CGBuilderTy &B)
70 : SaveAndRestoreLocation(CGF, B) {
71 if (DI)
72 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
73}
74
Adrian Prantl2e0637f2013-07-18 00:28:02 +000075NoLocation::~NoLocation() {
Adrian Prantld1b151e2014-01-17 00:15:10 +000076 if (DI)
Adrian Prantl2e0637f2013-07-18 00:28:02 +000077 assert(Builder.getCurrentDebugLocation().isUnknown());
Adrian Prantl2e0637f2013-07-18 00:28:02 +000078}
79
Adrian Prantlb75016d2013-07-18 01:36:04 +000080ArtificialLocation::ArtificialLocation(CodeGenFunction &CGF, CGBuilderTy &B)
Adrian Prantld1b151e2014-01-17 00:15:10 +000081 : SaveAndRestoreLocation(CGF, B) {
82 if (DI)
Adrian Prantl49a78562013-07-24 20:34:39 +000083 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
Adrian Prantl49a78562013-07-24 20:34:39 +000084}
85
86void ArtificialLocation::Emit() {
87 if (DI) {
Adrian Prantl2e0637f2013-07-18 00:28:02 +000088 // Sync the Builder.
89 DI->EmitLocation(Builder, SavedLoc);
90 DI->CurLoc = SourceLocation();
91 // Construct a location that has a valid scope, but no line info.
Adrian Prantl49a78562013-07-24 20:34:39 +000092 assert(!DI->LexicalBlockStack.empty());
93 llvm::DIDescriptor Scope(DI->LexicalBlockStack.back());
Adrian Prantl2e0637f2013-07-18 00:28:02 +000094 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(0, 0, Scope));
95 }
96}
97
Adrian Prantlb75016d2013-07-18 01:36:04 +000098ArtificialLocation::~ArtificialLocation() {
Adrian Prantld1b151e2014-01-17 00:15:10 +000099 if (DI)
Adrian Prantl2e0637f2013-07-18 00:28:02 +0000100 assert(Builder.getCurrentDebugLocation().getLine() == 0);
Adrian Prantl2e0637f2013-07-18 00:28:02 +0000101}
102
Guy Benyei11169dd2012-12-18 14:30:41 +0000103void CGDebugInfo::setLocation(SourceLocation Loc) {
104 // If the new location isn't valid return.
Adrian Prantlb1b3bfc2013-07-18 00:27:56 +0000105 if (Loc.isInvalid()) return;
Guy Benyei11169dd2012-12-18 14:30:41 +0000106
107 CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc);
108
109 // If we've changed files in the middle of a lexical scope go ahead
110 // and create a new lexical scope with file node if it's different
111 // from the one in the scope.
112 if (LexicalBlockStack.empty()) return;
113
114 SourceManager &SM = CGM.getContext().getSourceManager();
115 PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
116 PresumedLoc PPLoc = SM.getPresumedLoc(PrevLoc);
117
118 if (PCLoc.isInvalid() || PPLoc.isInvalid() ||
119 !strcmp(PPLoc.getFilename(), PCLoc.getFilename()))
120 return;
121
122 llvm::MDNode *LB = LexicalBlockStack.back();
123 llvm::DIScope Scope = llvm::DIScope(LB);
124 if (Scope.isLexicalBlockFile()) {
125 llvm::DILexicalBlockFile LBF = llvm::DILexicalBlockFile(LB);
126 llvm::DIDescriptor D
127 = DBuilder.createLexicalBlockFile(LBF.getScope(),
128 getOrCreateFile(CurLoc));
129 llvm::MDNode *N = D;
130 LexicalBlockStack.pop_back();
131 LexicalBlockStack.push_back(N);
David Blaikie0a21d0d2013-01-26 22:16:26 +0000132 } else if (Scope.isLexicalBlock() || Scope.isSubprogram()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000133 llvm::DIDescriptor D
134 = DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc));
135 llvm::MDNode *N = D;
136 LexicalBlockStack.pop_back();
137 LexicalBlockStack.push_back(N);
138 }
139}
140
141/// getContextDescriptor - Get context info for the decl.
David Blaikiebfa52742013-04-19 06:56:38 +0000142llvm::DIScope CGDebugInfo::getContextDescriptor(const Decl *Context) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000143 if (!Context)
144 return TheCU;
145
146 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
147 I = RegionMap.find(Context);
148 if (I != RegionMap.end()) {
149 llvm::Value *V = I->second;
David Blaikiebfa52742013-04-19 06:56:38 +0000150 return llvm::DIScope(dyn_cast_or_null<llvm::MDNode>(V));
Guy Benyei11169dd2012-12-18 14:30:41 +0000151 }
152
153 // Check namespace.
154 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
David Blaikiebfa52742013-04-19 06:56:38 +0000155 return getOrCreateNameSpace(NSDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +0000156
David Blaikiebfa52742013-04-19 06:56:38 +0000157 if (const RecordDecl *RDecl = dyn_cast<RecordDecl>(Context))
158 if (!RDecl->isDependentType())
159 return getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
Guy Benyei11169dd2012-12-18 14:30:41 +0000160 getOrCreateMainFile());
Guy Benyei11169dd2012-12-18 14:30:41 +0000161 return TheCU;
162}
163
164/// getFunctionName - Get function name for the given FunctionDecl. If the
Benjamin Kramer60509af2013-09-09 14:48:42 +0000165/// name is constructed on demand (e.g. C++ destructor) then the name
Guy Benyei11169dd2012-12-18 14:30:41 +0000166/// is stored on the side.
167StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
168 assert (FD && "Invalid FunctionDecl!");
169 IdentifierInfo *FII = FD->getIdentifier();
170 FunctionTemplateSpecializationInfo *Info
171 = FD->getTemplateSpecializationInfo();
172 if (!Info && FII)
173 return FII->getName();
174
175 // Otherwise construct human readable name for debug info.
Benjamin Kramer9170e912013-02-22 15:46:01 +0000176 SmallString<128> NS;
177 llvm::raw_svector_ostream OS(NS);
178 FD->printName(OS);
Guy Benyei11169dd2012-12-18 14:30:41 +0000179
180 // Add any template specialization args.
181 if (Info) {
182 const TemplateArgumentList *TArgs = Info->TemplateArguments;
183 const TemplateArgument *Args = TArgs->data();
184 unsigned NumArgs = TArgs->size();
185 PrintingPolicy Policy(CGM.getLangOpts());
Benjamin Kramer9170e912013-02-22 15:46:01 +0000186 TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs,
187 Policy);
Guy Benyei11169dd2012-12-18 14:30:41 +0000188 }
189
190 // Copy this name on the side and use its reference.
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +0000191 return internString(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +0000192}
193
194StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
195 SmallString<256> MethodName;
196 llvm::raw_svector_ostream OS(MethodName);
197 OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
198 const DeclContext *DC = OMD->getDeclContext();
Eric Christopherb2a008c2013-05-16 00:45:12 +0000199 if (const ObjCImplementationDecl *OID =
Guy Benyei11169dd2012-12-18 14:30:41 +0000200 dyn_cast<const ObjCImplementationDecl>(DC)) {
201 OS << OID->getName();
Eric Christopherb2a008c2013-05-16 00:45:12 +0000202 } else if (const ObjCInterfaceDecl *OID =
Guy Benyei11169dd2012-12-18 14:30:41 +0000203 dyn_cast<const ObjCInterfaceDecl>(DC)) {
204 OS << OID->getName();
Eric Christopherb2a008c2013-05-16 00:45:12 +0000205 } else if (const ObjCCategoryImplDecl *OCD =
Guy Benyei11169dd2012-12-18 14:30:41 +0000206 dyn_cast<const ObjCCategoryImplDecl>(DC)){
207 OS << ((const NamedDecl *)OCD)->getIdentifier()->getNameStart() << '(' <<
208 OCD->getIdentifier()->getNameStart() << ')';
Adrian Prantlb39fc142013-05-17 23:58:45 +0000209 } else if (isa<ObjCProtocolDecl>(DC)) {
Adrian Prantl6e785ec2013-05-17 23:49:10 +0000210 // We can extract the type of the class from the self pointer.
211 if (ImplicitParamDecl* SelfDecl = OMD->getSelfDecl()) {
212 QualType ClassTy =
213 cast<ObjCObjectPointerType>(SelfDecl->getType())->getPointeeType();
214 ClassTy.print(OS, PrintingPolicy(LangOptions()));
215 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000216 }
217 OS << ' ' << OMD->getSelector().getAsString() << ']';
218
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +0000219 return internString(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +0000220}
221
222/// getSelectorName - Return selector name. This is used for debugging
223/// info.
224StringRef CGDebugInfo::getSelectorName(Selector S) {
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +0000225 return internString(S.getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +0000226}
227
228/// getClassName - Get class name including template argument list.
Eric Christopherb2a008c2013-05-16 00:45:12 +0000229StringRef
Guy Benyei11169dd2012-12-18 14:30:41 +0000230CGDebugInfo::getClassName(const RecordDecl *RD) {
231 const ClassTemplateSpecializationDecl *Spec
232 = dyn_cast<ClassTemplateSpecializationDecl>(RD);
233 if (!Spec)
234 return RD->getName();
235
236 const TemplateArgument *Args;
237 unsigned NumArgs;
238 if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) {
239 const TemplateSpecializationType *TST =
240 cast<TemplateSpecializationType>(TAW->getType());
241 Args = TST->getArgs();
242 NumArgs = TST->getNumArgs();
243 } else {
244 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
245 Args = TemplateArgs.data();
246 NumArgs = TemplateArgs.size();
247 }
248 StringRef Name = RD->getIdentifier()->getName();
249 PrintingPolicy Policy(CGM.getLangOpts());
Benjamin Kramer9170e912013-02-22 15:46:01 +0000250 SmallString<128> TemplateArgList;
251 {
252 llvm::raw_svector_ostream OS(TemplateArgList);
253 TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs,
254 Policy);
255 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000256
257 // Copy this name on the side and use its reference.
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +0000258 return internString(Name, TemplateArgList);
Guy Benyei11169dd2012-12-18 14:30:41 +0000259}
260
261/// getOrCreateFile - Get the file debug info descriptor for the input location.
262llvm::DIFile CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
263 if (!Loc.isValid())
264 // If Location is not valid then use main input file.
265 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
266
267 SourceManager &SM = CGM.getContext().getSourceManager();
268 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
269
270 if (PLoc.isInvalid() || StringRef(PLoc.getFilename()).empty())
271 // If the location is not valid then use main input file.
272 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
273
274 // Cache the results.
275 const char *fname = PLoc.getFilename();
276 llvm::DenseMap<const char *, llvm::WeakVH>::iterator it =
277 DIFileCache.find(fname);
278
279 if (it != DIFileCache.end()) {
280 // Verify that the information still exists.
281 if (llvm::Value *V = it->second)
282 return llvm::DIFile(cast<llvm::MDNode>(V));
283 }
284
285 llvm::DIFile F = DBuilder.createFile(PLoc.getFilename(), getCurrentDirname());
286
287 DIFileCache[fname] = F;
288 return F;
289}
290
291/// getOrCreateMainFile - Get the file info for main compile unit.
292llvm::DIFile CGDebugInfo::getOrCreateMainFile() {
293 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
294}
295
296/// getLineNumber - Get line number for the location. If location is invalid
297/// then use current location.
298unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
299 if (Loc.isInvalid() && CurLoc.isInvalid())
300 return 0;
301 SourceManager &SM = CGM.getContext().getSourceManager();
302 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
303 return PLoc.isValid()? PLoc.getLine() : 0;
304}
305
306/// getColumnNumber - Get column number for the location.
Adrian Prantlc7822422013-03-12 20:43:25 +0000307unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000308 // We may not want column information at all.
Adrian Prantlc7822422013-03-12 20:43:25 +0000309 if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo)
Guy Benyei11169dd2012-12-18 14:30:41 +0000310 return 0;
311
312 // If the location is invalid then use the current column.
313 if (Loc.isInvalid() && CurLoc.isInvalid())
314 return 0;
315 SourceManager &SM = CGM.getContext().getSourceManager();
316 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
317 return PLoc.isValid()? PLoc.getColumn() : 0;
318}
319
320StringRef CGDebugInfo::getCurrentDirname() {
321 if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
322 return CGM.getCodeGenOpts().DebugCompilationDir;
323
324 if (!CWDName.empty())
325 return CWDName;
326 SmallString<256> CWD;
327 llvm::sys::fs::current_path(CWD);
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +0000328 return CWDName = internString(CWD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000329}
330
331/// CreateCompileUnit - Create new compile unit.
332void CGDebugInfo::CreateCompileUnit() {
333
334 // Get absolute path name.
335 SourceManager &SM = CGM.getContext().getSourceManager();
336 std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
337 if (MainFileName.empty())
338 MainFileName = "<unknown>";
339
340 // The main file name provided via the "-main-file-name" option contains just
341 // the file name itself with no path information. This file name may have had
342 // a relative path, so we look into the actual file entry for the main
343 // file to determine the real absolute path for the file.
344 std::string MainFileDir;
345 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
346 MainFileDir = MainFile->getDir()->getName();
Yaron Keren9fb7e902013-10-21 20:07:37 +0000347 if (MainFileDir != ".") {
Eric Christopher0a1301f2014-02-26 02:49:36 +0000348 llvm::SmallString<1024> MainFileDirSS(MainFileDir);
349 llvm::sys::path::append(MainFileDirSS, MainFileName);
350 MainFileName = MainFileDirSS.str();
Yaron Keren9fb7e902013-10-21 20:07:37 +0000351 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000352 }
353
354 // Save filename string.
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +0000355 StringRef Filename = internString(MainFileName);
Eric Christopherf1545832013-02-22 23:50:16 +0000356
357 // Save split dwarf file string.
358 std::string SplitDwarfFile = CGM.getCodeGenOpts().SplitDwarfFile;
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +0000359 StringRef SplitDwarfFilename = internString(SplitDwarfFile);
Eric Christopherb2a008c2013-05-16 00:45:12 +0000360
Guy Benyei11169dd2012-12-18 14:30:41 +0000361 unsigned LangTag;
362 const LangOptions &LO = CGM.getLangOpts();
363 if (LO.CPlusPlus) {
364 if (LO.ObjC1)
365 LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
366 else
367 LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
368 } else if (LO.ObjC1) {
369 LangTag = llvm::dwarf::DW_LANG_ObjC;
370 } else if (LO.C99) {
371 LangTag = llvm::dwarf::DW_LANG_C99;
372 } else {
373 LangTag = llvm::dwarf::DW_LANG_C89;
374 }
375
376 std::string Producer = getClangFullVersion();
377
378 // Figure out which version of the ObjC runtime we have.
379 unsigned RuntimeVers = 0;
380 if (LO.ObjC1)
381 RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
382
383 // Create new compile unit.
Guy Benyei11169dd2012-12-18 14:30:41 +0000384 // FIXME - Eliminate TheCU.
Eric Christophere4200a22014-02-27 01:25:08 +0000385 TheCU = DBuilder.createCompileUnit(
386 LangTag, Filename, getCurrentDirname(), Producer, LO.Optimize,
387 CGM.getCodeGenOpts().DwarfDebugFlags, RuntimeVers, SplitDwarfFilename,
388 DebugKind == CodeGenOptions::DebugLineTablesOnly
389 ? llvm::DIBuilder::LineTablesOnly
390 : llvm::DIBuilder::FullDebug);
Guy Benyei11169dd2012-12-18 14:30:41 +0000391}
392
393/// CreateType - Get the Basic type from the cache or create a new
394/// one if necessary.
395llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT) {
396 unsigned Encoding = 0;
397 StringRef BTName;
398 switch (BT->getKind()) {
399#define BUILTIN_TYPE(Id, SingletonId)
400#define PLACEHOLDER_TYPE(Id, SingletonId) \
401 case BuiltinType::Id:
402#include "clang/AST/BuiltinTypes.def"
403 case BuiltinType::Dependent:
404 llvm_unreachable("Unexpected builtin type");
405 case BuiltinType::NullPtr:
Peter Collingbourne5c5e6172013-06-27 22:51:01 +0000406 return DBuilder.createNullPtrType();
Guy Benyei11169dd2012-12-18 14:30:41 +0000407 case BuiltinType::Void:
408 return llvm::DIType();
409 case BuiltinType::ObjCClass:
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000410 if (ClassTy)
Guy Benyei11169dd2012-12-18 14:30:41 +0000411 return ClassTy;
412 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
413 "objc_class", TheCU,
414 getOrCreateMainFile(), 0);
415 return ClassTy;
416 case BuiltinType::ObjCId: {
417 // typedef struct objc_class *Class;
418 // typedef struct objc_object {
419 // Class isa;
420 // } *id;
421
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000422 if (ObjTy)
Guy Benyei11169dd2012-12-18 14:30:41 +0000423 return ObjTy;
424
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000425 if (!ClassTy)
Guy Benyei11169dd2012-12-18 14:30:41 +0000426 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
427 "objc_class", TheCU,
428 getOrCreateMainFile(), 0);
429
430 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
Eric Christopherb2a008c2013-05-16 00:45:12 +0000431
Guy Benyei11169dd2012-12-18 14:30:41 +0000432 llvm::DIType ISATy = DBuilder.createPointerType(ClassTy, Size);
433
Eric Christopher5c7ee8b2013-04-02 22:59:11 +0000434 ObjTy =
David Blaikie6d4fe152013-02-25 01:07:08 +0000435 DBuilder.createStructType(TheCU, "objc_object", getOrCreateMainFile(),
436 0, 0, 0, 0, llvm::DIType(), llvm::DIArray());
Guy Benyei11169dd2012-12-18 14:30:41 +0000437
Eric Christopher5c7ee8b2013-04-02 22:59:11 +0000438 ObjTy.setTypeArray(DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
439 ObjTy, "isa", getOrCreateMainFile(), 0, Size, 0, 0, 0, ISATy)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000440 return ObjTy;
441 }
442 case BuiltinType::ObjCSel: {
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000443 if (SelTy)
Guy Benyei11169dd2012-12-18 14:30:41 +0000444 return SelTy;
445 SelTy =
446 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
447 "objc_selector", TheCU, getOrCreateMainFile(),
448 0);
449 return SelTy;
450 }
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000451
452 case BuiltinType::OCLImage1d:
453 return getOrCreateStructPtrType("opencl_image1d_t",
454 OCLImage1dDITy);
455 case BuiltinType::OCLImage1dArray:
Eric Christopherb2a008c2013-05-16 00:45:12 +0000456 return getOrCreateStructPtrType("opencl_image1d_array_t",
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000457 OCLImage1dArrayDITy);
458 case BuiltinType::OCLImage1dBuffer:
459 return getOrCreateStructPtrType("opencl_image1d_buffer_t",
460 OCLImage1dBufferDITy);
461 case BuiltinType::OCLImage2d:
462 return getOrCreateStructPtrType("opencl_image2d_t",
463 OCLImage2dDITy);
464 case BuiltinType::OCLImage2dArray:
465 return getOrCreateStructPtrType("opencl_image2d_array_t",
466 OCLImage2dArrayDITy);
467 case BuiltinType::OCLImage3d:
468 return getOrCreateStructPtrType("opencl_image3d_t",
469 OCLImage3dDITy);
Guy Benyei61054192013-02-07 10:55:47 +0000470 case BuiltinType::OCLSampler:
471 return DBuilder.createBasicType("opencl_sampler_t",
472 CGM.getContext().getTypeSize(BT),
473 CGM.getContext().getTypeAlign(BT),
474 llvm::dwarf::DW_ATE_unsigned);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +0000475 case BuiltinType::OCLEvent:
476 return getOrCreateStructPtrType("opencl_event_t",
477 OCLEventDITy);
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000478
Guy Benyei11169dd2012-12-18 14:30:41 +0000479 case BuiltinType::UChar:
480 case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
481 case BuiltinType::Char_S:
482 case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
483 case BuiltinType::Char16:
484 case BuiltinType::Char32: Encoding = llvm::dwarf::DW_ATE_UTF; break;
485 case BuiltinType::UShort:
486 case BuiltinType::UInt:
487 case BuiltinType::UInt128:
488 case BuiltinType::ULong:
489 case BuiltinType::WChar_U:
490 case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
491 case BuiltinType::Short:
492 case BuiltinType::Int:
493 case BuiltinType::Int128:
494 case BuiltinType::Long:
495 case BuiltinType::WChar_S:
496 case BuiltinType::LongLong: Encoding = llvm::dwarf::DW_ATE_signed; break;
497 case BuiltinType::Bool: Encoding = llvm::dwarf::DW_ATE_boolean; break;
498 case BuiltinType::Half:
499 case BuiltinType::Float:
500 case BuiltinType::LongDouble:
501 case BuiltinType::Double: Encoding = llvm::dwarf::DW_ATE_float; break;
502 }
503
504 switch (BT->getKind()) {
505 case BuiltinType::Long: BTName = "long int"; break;
506 case BuiltinType::LongLong: BTName = "long long int"; break;
507 case BuiltinType::ULong: BTName = "long unsigned int"; break;
508 case BuiltinType::ULongLong: BTName = "long long unsigned int"; break;
509 default:
510 BTName = BT->getName(CGM.getLangOpts());
511 break;
512 }
513 // Bit size, align and offset of the type.
514 uint64_t Size = CGM.getContext().getTypeSize(BT);
515 uint64_t Align = CGM.getContext().getTypeAlign(BT);
Eric Christopherb2a008c2013-05-16 00:45:12 +0000516 llvm::DIType DbgTy =
Guy Benyei11169dd2012-12-18 14:30:41 +0000517 DBuilder.createBasicType(BTName, Size, Align, Encoding);
518 return DbgTy;
519}
520
521llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty) {
522 // Bit size, align and offset of the type.
523 unsigned Encoding = llvm::dwarf::DW_ATE_complex_float;
524 if (Ty->isComplexIntegerType())
525 Encoding = llvm::dwarf::DW_ATE_lo_user;
526
527 uint64_t Size = CGM.getContext().getTypeSize(Ty);
528 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
Eric Christopherb2a008c2013-05-16 00:45:12 +0000529 llvm::DIType DbgTy =
Guy Benyei11169dd2012-12-18 14:30:41 +0000530 DBuilder.createBasicType("complex", Size, Align, Encoding);
531
532 return DbgTy;
533}
534
535/// CreateCVRType - Get the qualified type from the cache or create
536/// a new one if necessary.
David Blaikie99dab3b2013-09-04 22:03:57 +0000537llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000538 QualifierCollector Qc;
539 const Type *T = Qc.strip(Ty);
540
541 // Ignore these qualifiers for now.
542 Qc.removeObjCGCAttr();
543 Qc.removeAddressSpace();
544 Qc.removeObjCLifetime();
545
546 // We will create one Derived type for one qualifier and recurse to handle any
547 // additional ones.
548 unsigned Tag;
549 if (Qc.hasConst()) {
550 Tag = llvm::dwarf::DW_TAG_const_type;
551 Qc.removeConst();
552 } else if (Qc.hasVolatile()) {
553 Tag = llvm::dwarf::DW_TAG_volatile_type;
554 Qc.removeVolatile();
555 } else if (Qc.hasRestrict()) {
556 Tag = llvm::dwarf::DW_TAG_restrict_type;
557 Qc.removeRestrict();
558 } else {
559 assert(Qc.empty() && "Unknown type qualifier for debug info");
560 return getOrCreateType(QualType(T, 0), Unit);
561 }
562
David Blaikie99dab3b2013-09-04 22:03:57 +0000563 llvm::DIType FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +0000564
565 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
566 // CVR derived types.
567 llvm::DIType DbgTy = DBuilder.createQualifiedType(Tag, FromTy);
Eric Christopherb2a008c2013-05-16 00:45:12 +0000568
Guy Benyei11169dd2012-12-18 14:30:41 +0000569 return DbgTy;
570}
571
572llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
573 llvm::DIFile Unit) {
Fariborz Jahanian65f1fa12013-02-21 20:42:11 +0000574
575 // The frontend treats 'id' as a typedef to an ObjCObjectType,
576 // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
577 // debug info, we want to emit 'id' in both cases.
578 if (Ty->isObjCQualifiedIdType())
579 return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
580
Guy Benyei11169dd2012-12-18 14:30:41 +0000581 llvm::DIType DbgTy =
Eric Christopherb2a008c2013-05-16 00:45:12 +0000582 CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +0000583 Ty->getPointeeType(), Unit);
584 return DbgTy;
585}
586
587llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
588 llvm::DIFile Unit) {
Eric Christopherb2a008c2013-05-16 00:45:12 +0000589 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +0000590 Ty->getPointeeType(), Unit);
591}
592
Manman Rene0064d82013-08-29 23:19:58 +0000593/// In C++ mode, types have linkage, so we can rely on the ODR and
594/// on their mangled names, if they're external.
595static SmallString<256>
596getUniqueTagTypeName(const TagType *Ty, CodeGenModule &CGM,
597 llvm::DICompileUnit TheCU) {
598 SmallString<256> FullName;
599 // FIXME: ODR should apply to ObjC++ exactly the same wasy it does to C++.
600 // For now, only apply ODR with C++.
601 const TagDecl *TD = Ty->getDecl();
602 if (TheCU.getLanguage() != llvm::dwarf::DW_LANG_C_plus_plus ||
603 !TD->isExternallyVisible())
604 return FullName;
605 // Microsoft Mangler does not have support for mangleCXXRTTIName yet.
606 if (CGM.getTarget().getCXXABI().isMicrosoft())
607 return FullName;
608
609 // TODO: This is using the RTTI name. Is there a better way to get
610 // a unique string for a type?
611 llvm::raw_svector_ostream Out(FullName);
612 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(QualType(Ty, 0), Out);
613 Out.flush();
614 return FullName;
615}
616
Guy Benyei11169dd2012-12-18 14:30:41 +0000617// Creates a forward declaration for a RecordDecl in the given context.
David Blaikie8d5e1282013-08-20 21:03:29 +0000618llvm::DICompositeType
Manman Ren1b457022013-08-28 21:20:28 +0000619CGDebugInfo::getOrCreateRecordFwdDecl(const RecordType *Ty,
David Blaikie8d5e1282013-08-20 21:03:29 +0000620 llvm::DIDescriptor Ctx) {
Manman Ren1b457022013-08-28 21:20:28 +0000621 const RecordDecl *RD = Ty->getDecl();
David Blaikie4e7ef802013-08-15 20:17:25 +0000622 if (llvm::DIType T = getTypeOrNull(CGM.getContext().getRecordType(RD)))
David Blaikie8d5e1282013-08-20 21:03:29 +0000623 return llvm::DICompositeType(T);
Guy Benyei11169dd2012-12-18 14:30:41 +0000624 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
625 unsigned Line = getLineNumber(RD->getLocation());
626 StringRef RDName = getClassName(RD);
627
628 unsigned Tag = 0;
629 if (RD->isStruct() || RD->isInterface())
630 Tag = llvm::dwarf::DW_TAG_structure_type;
631 else if (RD->isUnion())
632 Tag = llvm::dwarf::DW_TAG_union_type;
633 else {
634 assert(RD->isClass());
635 Tag = llvm::dwarf::DW_TAG_class_type;
636 }
637
638 // Create the type.
Manman Rene0064d82013-08-29 23:19:58 +0000639 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
640 return DBuilder.createForwardDecl(Tag, RDName, Ctx, DefUnit, Line, 0, 0, 0,
641 FullName);
Guy Benyei11169dd2012-12-18 14:30:41 +0000642}
643
Guy Benyei11169dd2012-12-18 14:30:41 +0000644llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag,
Eric Christopherb2a008c2013-05-16 00:45:12 +0000645 const Type *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +0000646 QualType PointeeTy,
647 llvm::DIFile Unit) {
648 if (Tag == llvm::dwarf::DW_TAG_reference_type ||
649 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
David Blaikie99dab3b2013-09-04 22:03:57 +0000650 return DBuilder.createReferenceType(Tag, getOrCreateType(PointeeTy, Unit));
Fariborz Jahanian65f1fa12013-02-21 20:42:11 +0000651
Guy Benyei11169dd2012-12-18 14:30:41 +0000652 // Bit size, align and offset of the type.
653 // Size is always the size of a pointer. We can't use getTypeSize here
654 // because that does not return the correct value for references.
655 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCallc8e01702013-04-16 22:48:15 +0000656 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
Guy Benyei11169dd2012-12-18 14:30:41 +0000657 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
658
David Blaikie99dab3b2013-09-04 22:03:57 +0000659 return DBuilder.createPointerType(getOrCreateType(PointeeTy, Unit), Size,
660 Align);
Guy Benyei11169dd2012-12-18 14:30:41 +0000661}
662
Eric Christopher0fdcb312013-05-16 00:52:20 +0000663llvm::DIType CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
664 llvm::DIType &Cache) {
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000665 if (Cache)
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000666 return Cache;
David Blaikiefefc7f72013-05-21 17:58:54 +0000667 Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
668 TheCU, getOrCreateMainFile(), 0);
669 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
670 Cache = DBuilder.createPointerType(Cache, Size);
671 return Cache;
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000672}
673
Guy Benyei11169dd2012-12-18 14:30:41 +0000674llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
675 llvm::DIFile Unit) {
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000676 if (BlockLiteralGeneric)
Guy Benyei11169dd2012-12-18 14:30:41 +0000677 return BlockLiteralGeneric;
678
679 SmallVector<llvm::Value *, 8> EltTys;
680 llvm::DIType FieldTy;
681 QualType FType;
682 uint64_t FieldSize, FieldOffset;
683 unsigned FieldAlign;
684 llvm::DIArray Elements;
685 llvm::DIType EltTy, DescTy;
686
687 FieldOffset = 0;
688 FType = CGM.getContext().UnsignedLongTy;
689 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
690 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
691
692 Elements = DBuilder.getOrCreateArray(EltTys);
693 EltTys.clear();
694
695 unsigned Flags = llvm::DIDescriptor::FlagAppleBlock;
696 unsigned LineNo = getLineNumber(CurLoc);
697
698 EltTy = DBuilder.createStructType(Unit, "__block_descriptor",
699 Unit, LineNo, FieldOffset, 0,
David Blaikie6d4fe152013-02-25 01:07:08 +0000700 Flags, llvm::DIType(), Elements);
Guy Benyei11169dd2012-12-18 14:30:41 +0000701
702 // Bit size, align and offset of the type.
703 uint64_t Size = CGM.getContext().getTypeSize(Ty);
704
705 DescTy = DBuilder.createPointerType(EltTy, Size);
706
707 FieldOffset = 0;
708 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
709 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
710 FType = CGM.getContext().IntTy;
711 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
712 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
713 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
714 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
715
716 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
717 FieldTy = DescTy;
718 FieldSize = CGM.getContext().getTypeSize(Ty);
719 FieldAlign = CGM.getContext().getTypeAlign(Ty);
720 FieldTy = DBuilder.createMemberType(Unit, "__descriptor", Unit,
721 LineNo, FieldSize, FieldAlign,
722 FieldOffset, 0, FieldTy);
723 EltTys.push_back(FieldTy);
724
725 FieldOffset += FieldSize;
726 Elements = DBuilder.getOrCreateArray(EltTys);
727
728 EltTy = DBuilder.createStructType(Unit, "__block_literal_generic",
729 Unit, LineNo, FieldOffset, 0,
David Blaikie6d4fe152013-02-25 01:07:08 +0000730 Flags, llvm::DIType(), Elements);
Guy Benyei11169dd2012-12-18 14:30:41 +0000731
Guy Benyei11169dd2012-12-18 14:30:41 +0000732 BlockLiteralGeneric = DBuilder.createPointerType(EltTy, Size);
733 return BlockLiteralGeneric;
734}
735
David Blaikie99dab3b2013-09-04 22:03:57 +0000736llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty, llvm::DIFile Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000737 // Typedefs are derived from some other type. If we have a typedef of a
738 // typedef, make sure to emit the whole chain.
David Blaikie99dab3b2013-09-04 22:03:57 +0000739 llvm::DIType Src = getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000740 if (!Src)
Guy Benyei11169dd2012-12-18 14:30:41 +0000741 return llvm::DIType();
742 // We don't set size information, but do specify where the typedef was
743 // declared.
Adrian Prantl3eff2252014-01-21 18:42:27 +0000744 SourceLocation Loc = Ty->getDecl()->getLocation();
745 llvm::DIFile File = getOrCreateFile(Loc);
746 unsigned Line = getLineNumber(Loc);
Guy Benyei11169dd2012-12-18 14:30:41 +0000747 const TypedefNameDecl *TyDecl = Ty->getDecl();
Eric Christopherb2a008c2013-05-16 00:45:12 +0000748
Guy Benyei11169dd2012-12-18 14:30:41 +0000749 llvm::DIDescriptor TypedefContext =
750 getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext()));
Eric Christopherb2a008c2013-05-16 00:45:12 +0000751
Guy Benyei11169dd2012-12-18 14:30:41 +0000752 return
Adrian Prantl3eff2252014-01-21 18:42:27 +0000753 DBuilder.createTypedef(Src, TyDecl->getName(), File, Line, TypedefContext);
Guy Benyei11169dd2012-12-18 14:30:41 +0000754}
755
756llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
757 llvm::DIFile Unit) {
758 SmallVector<llvm::Value *, 16> EltTys;
759
760 // Add the result type at least.
Alp Toker314cc812014-01-25 16:55:45 +0000761 EltTys.push_back(getOrCreateType(Ty->getReturnType(), Unit));
Guy Benyei11169dd2012-12-18 14:30:41 +0000762
763 // Set up remainder of arguments if there is a prototype.
Adrian Prantl800faef2014-02-25 23:42:18 +0000764 // otherwise emit it as a variadic function.
Guy Benyei11169dd2012-12-18 14:30:41 +0000765 if (isa<FunctionNoProtoType>(Ty))
766 EltTys.push_back(DBuilder.createUnspecifiedParameter());
767 else if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Ty)) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000768 for (unsigned i = 0, e = FPT->getNumParams(); i != e; ++i)
769 EltTys.push_back(getOrCreateType(FPT->getParamType(i), Unit));
Adrian Prantld45ba252014-02-25 19:38:11 +0000770 if (FPT->isVariadic())
771 EltTys.push_back(DBuilder.createUnspecifiedParameter());
Guy Benyei11169dd2012-12-18 14:30:41 +0000772 }
773
774 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
775 return DBuilder.createSubroutineType(Unit, EltTypeArray);
776}
777
778
Guy Benyei11169dd2012-12-18 14:30:41 +0000779llvm::DIType CGDebugInfo::createFieldType(StringRef name,
780 QualType type,
781 uint64_t sizeInBitsOverride,
782 SourceLocation loc,
783 AccessSpecifier AS,
784 uint64_t offsetInBits,
785 llvm::DIFile tunit,
Manman Ren2c826dc2013-09-08 03:45:05 +0000786 llvm::DIScope scope) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000787 llvm::DIType debugType = getOrCreateType(type, tunit);
788
789 // Get the location for the field.
790 llvm::DIFile file = getOrCreateFile(loc);
791 unsigned line = getLineNumber(loc);
792
793 uint64_t sizeInBits = 0;
794 unsigned alignInBits = 0;
795 if (!type->isIncompleteArrayType()) {
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000796 std::tie(sizeInBits, alignInBits) = CGM.getContext().getTypeInfo(type);
Guy Benyei11169dd2012-12-18 14:30:41 +0000797
798 if (sizeInBitsOverride)
799 sizeInBits = sizeInBitsOverride;
800 }
801
802 unsigned flags = 0;
803 if (AS == clang::AS_private)
804 flags |= llvm::DIDescriptor::FlagPrivate;
805 else if (AS == clang::AS_protected)
806 flags |= llvm::DIDescriptor::FlagProtected;
807
808 return DBuilder.createMemberType(scope, name, file, line, sizeInBits,
809 alignInBits, offsetInBits, flags, debugType);
810}
811
Eric Christopher91a31902013-01-16 01:22:32 +0000812/// CollectRecordLambdaFields - Helper for CollectRecordFields.
813void CGDebugInfo::
814CollectRecordLambdaFields(const CXXRecordDecl *CXXDecl,
815 SmallVectorImpl<llvm::Value *> &elements,
816 llvm::DIType RecordTy) {
817 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
818 // has the name and the location of the variable so we should iterate over
819 // both concurrently.
820 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
821 RecordDecl::field_iterator Field = CXXDecl->field_begin();
822 unsigned fieldno = 0;
823 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
824 E = CXXDecl->captures_end(); I != E; ++I, ++Field, ++fieldno) {
825 const LambdaExpr::Capture C = *I;
826 if (C.capturesVariable()) {
827 VarDecl *V = C.getCapturedVar();
828 llvm::DIFile VUnit = getOrCreateFile(C.getLocation());
829 StringRef VName = V->getName();
830 uint64_t SizeInBitsOverride = 0;
831 if (Field->isBitField()) {
832 SizeInBitsOverride = Field->getBitWidthValue(CGM.getContext());
833 assert(SizeInBitsOverride && "found named 0-width bitfield");
834 }
835 llvm::DIType fieldType
836 = createFieldType(VName, Field->getType(), SizeInBitsOverride,
837 C.getLocation(), Field->getAccess(),
838 layout.getFieldOffset(fieldno), VUnit, RecordTy);
839 elements.push_back(fieldType);
840 } else {
841 // TODO: Need to handle 'this' in some way by probably renaming the
842 // this of the lambda class and having a field member of 'this' or
843 // by using AT_object_pointer for the function and having that be
844 // used as 'this' for semantic references.
845 assert(C.capturesThis() && "Field that isn't captured and isn't this?");
846 FieldDecl *f = *Field;
847 llvm::DIFile VUnit = getOrCreateFile(f->getLocation());
848 QualType type = f->getType();
849 llvm::DIType fieldType
850 = createFieldType("this", type, 0, f->getLocation(), f->getAccess(),
851 layout.getFieldOffset(fieldno), VUnit, RecordTy);
852
853 elements.push_back(fieldType);
854 }
855 }
856}
857
David Blaikie6943dea2013-08-20 01:28:15 +0000858/// Helper for CollectRecordFields.
David Blaikieae019462013-08-15 22:50:29 +0000859llvm::DIDerivedType
860CGDebugInfo::CreateRecordStaticField(const VarDecl *Var,
861 llvm::DIType RecordTy) {
Eric Christopher91a31902013-01-16 01:22:32 +0000862 // Create the descriptor for the static variable, with or without
863 // constant initializers.
864 llvm::DIFile VUnit = getOrCreateFile(Var->getLocation());
865 llvm::DIType VTy = getOrCreateType(Var->getType(), VUnit);
866
Eric Christopher91a31902013-01-16 01:22:32 +0000867 unsigned LineNumber = getLineNumber(Var->getLocation());
868 StringRef VName = Var->getName();
David Blaikied42917f2013-01-20 01:19:17 +0000869 llvm::Constant *C = NULL;
Eric Christopher91a31902013-01-16 01:22:32 +0000870 if (Var->getInit()) {
871 const APValue *Value = Var->evaluateValue();
David Blaikied42917f2013-01-20 01:19:17 +0000872 if (Value) {
873 if (Value->isInt())
874 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
875 if (Value->isFloat())
876 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
877 }
Eric Christopher91a31902013-01-16 01:22:32 +0000878 }
879
880 unsigned Flags = 0;
881 AccessSpecifier Access = Var->getAccess();
882 if (Access == clang::AS_private)
883 Flags |= llvm::DIDescriptor::FlagPrivate;
884 else if (Access == clang::AS_protected)
885 Flags |= llvm::DIDescriptor::FlagProtected;
886
David Blaikieae019462013-08-15 22:50:29 +0000887 llvm::DIDerivedType GV = DBuilder.createStaticMemberType(
888 RecordTy, VName, VUnit, LineNumber, VTy, Flags, C);
Eric Christopher91a31902013-01-16 01:22:32 +0000889 StaticDataMemberCache[Var->getCanonicalDecl()] = llvm::WeakVH(GV);
David Blaikieae019462013-08-15 22:50:29 +0000890 return GV;
Eric Christopher91a31902013-01-16 01:22:32 +0000891}
892
893/// CollectRecordNormalField - Helper for CollectRecordFields.
894void CGDebugInfo::
895CollectRecordNormalField(const FieldDecl *field, uint64_t OffsetInBits,
896 llvm::DIFile tunit,
897 SmallVectorImpl<llvm::Value *> &elements,
898 llvm::DIType RecordTy) {
899 StringRef name = field->getName();
900 QualType type = field->getType();
901
902 // Ignore unnamed fields unless they're anonymous structs/unions.
903 if (name.empty() && !type->isRecordType())
904 return;
905
906 uint64_t SizeInBitsOverride = 0;
907 if (field->isBitField()) {
908 SizeInBitsOverride = field->getBitWidthValue(CGM.getContext());
909 assert(SizeInBitsOverride && "found named 0-width bitfield");
910 }
911
912 llvm::DIType fieldType
913 = createFieldType(name, type, SizeInBitsOverride,
914 field->getLocation(), field->getAccess(),
915 OffsetInBits, tunit, RecordTy);
916
917 elements.push_back(fieldType);
918}
919
Guy Benyei11169dd2012-12-18 14:30:41 +0000920/// CollectRecordFields - A helper function to collect debug info for
921/// record fields. This is used while creating debug info entry for a Record.
David Blaikieab255bb2013-08-16 20:40:25 +0000922void CGDebugInfo::CollectRecordFields(const RecordDecl *record,
923 llvm::DIFile tunit,
924 SmallVectorImpl<llvm::Value *> &elements,
925 llvm::DICompositeType RecordTy) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000926 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(record);
927
Eric Christopher91a31902013-01-16 01:22:32 +0000928 if (CXXDecl && CXXDecl->isLambda())
929 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
930 else {
931 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
Guy Benyei11169dd2012-12-18 14:30:41 +0000932
Eric Christopher91a31902013-01-16 01:22:32 +0000933 // Field number for non-static fields.
Eric Christopher0f7594372013-01-04 17:59:07 +0000934 unsigned fieldNo = 0;
Eric Christopher91a31902013-01-16 01:22:32 +0000935
Eric Christopher91a31902013-01-16 01:22:32 +0000936 // Static and non-static members should appear in the same order as
937 // the corresponding declarations in the source program.
938 for (RecordDecl::decl_iterator I = record->decls_begin(),
939 E = record->decls_end(); I != E; ++I)
David Blaikiece763042013-08-20 21:49:21 +0000940 if (const VarDecl *V = dyn_cast<VarDecl>(*I)) {
941 // Reuse the existing static member declaration if one exists
942 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator MI =
943 StaticDataMemberCache.find(V->getCanonicalDecl());
944 if (MI != StaticDataMemberCache.end()) {
945 assert(MI->second &&
946 "Static data member declaration should still exist");
947 elements.push_back(
948 llvm::DIDerivedType(cast<llvm::MDNode>(MI->second)));
949 } else
950 elements.push_back(CreateRecordStaticField(V, RecordTy));
951 } else if (FieldDecl *field = dyn_cast<FieldDecl>(*I)) {
Eric Christopher91a31902013-01-16 01:22:32 +0000952 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo),
953 tunit, elements, RecordTy);
954
955 // Bump field number for next field.
956 ++fieldNo;
Guy Benyei11169dd2012-12-18 14:30:41 +0000957 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000958 }
959}
960
961/// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
962/// function type is not updated to include implicit "this" pointer. Use this
963/// routine to get a method type which includes "this" pointer.
David Blaikie469f0792013-05-22 23:22:42 +0000964llvm::DICompositeType
Guy Benyei11169dd2012-12-18 14:30:41 +0000965CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
966 llvm::DIFile Unit) {
David Blaikie7eb06852013-01-07 23:06:35 +0000967 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
David Blaikie2aaf0652013-01-07 22:24:59 +0000968 if (Method->isStatic())
David Blaikie469f0792013-05-22 23:22:42 +0000969 return llvm::DICompositeType(getOrCreateType(QualType(Func, 0), Unit));
David Blaikie7eb06852013-01-07 23:06:35 +0000970 return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()),
971 Func, Unit);
972}
David Blaikie2aaf0652013-01-07 22:24:59 +0000973
David Blaikie469f0792013-05-22 23:22:42 +0000974llvm::DICompositeType CGDebugInfo::getOrCreateInstanceMethodType(
David Blaikie7eb06852013-01-07 23:06:35 +0000975 QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000976 // Add "this" pointer.
David Blaikie7eb06852013-01-07 23:06:35 +0000977 llvm::DIArray Args = llvm::DICompositeType(
978 getOrCreateType(QualType(Func, 0), Unit)).getTypeArray();
Guy Benyei11169dd2012-12-18 14:30:41 +0000979 assert (Args.getNumElements() && "Invalid number of arguments!");
980
981 SmallVector<llvm::Value *, 16> Elts;
982
983 // First element is always return type. For 'void' functions it is NULL.
984 Elts.push_back(Args.getElement(0));
985
David Blaikie2aaf0652013-01-07 22:24:59 +0000986 // "this" pointer is always first argument.
David Blaikie7eb06852013-01-07 23:06:35 +0000987 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
David Blaikie2aaf0652013-01-07 22:24:59 +0000988 if (isa<ClassTemplateSpecializationDecl>(RD)) {
989 // Create pointer type directly in this case.
990 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
991 QualType PointeeTy = ThisPtrTy->getPointeeType();
992 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCallc8e01702013-04-16 22:48:15 +0000993 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
David Blaikie2aaf0652013-01-07 22:24:59 +0000994 uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy);
995 llvm::DIType PointeeType = getOrCreateType(PointeeTy, Unit);
Eric Christopher0fdcb312013-05-16 00:52:20 +0000996 llvm::DIType ThisPtrType =
997 DBuilder.createPointerType(PointeeType, Size, Align);
David Blaikie2aaf0652013-01-07 22:24:59 +0000998 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
999 // TODO: This and the artificial type below are misleading, the
1000 // types aren't artificial the argument is, but the current
1001 // metadata doesn't represent that.
1002 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1003 Elts.push_back(ThisPtrType);
1004 } else {
1005 llvm::DIType ThisPtrType = getOrCreateType(ThisPtr, Unit);
1006 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
1007 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1008 Elts.push_back(ThisPtrType);
Guy Benyei11169dd2012-12-18 14:30:41 +00001009 }
1010
1011 // Copy rest of the arguments.
1012 for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
1013 Elts.push_back(Args.getElement(i));
1014
1015 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
1016
Adrian Prantl0630eb72013-12-18 21:48:18 +00001017 unsigned Flags = 0;
1018 if (Func->getExtProtoInfo().RefQualifier == RQ_LValue)
1019 Flags |= llvm::DIDescriptor::FlagLValueReference;
1020 if (Func->getExtProtoInfo().RefQualifier == RQ_RValue)
1021 Flags |= llvm::DIDescriptor::FlagRValueReference;
1022
1023 return DBuilder.createSubroutineType(Unit, EltTypeArray, Flags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001024}
1025
Eric Christopherb2a008c2013-05-16 00:45:12 +00001026/// isFunctionLocalClass - Return true if CXXRecordDecl is defined
Guy Benyei11169dd2012-12-18 14:30:41 +00001027/// inside a function.
1028static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
1029 if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
1030 return isFunctionLocalClass(NRD);
1031 if (isa<FunctionDecl>(RD->getDeclContext()))
1032 return true;
1033 return false;
1034}
1035
1036/// CreateCXXMemberFunction - A helper function to create a DISubprogram for
1037/// a single member function GlobalDecl.
1038llvm::DISubprogram
1039CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
1040 llvm::DIFile Unit,
1041 llvm::DIType RecordTy) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001042 bool IsCtorOrDtor =
Guy Benyei11169dd2012-12-18 14:30:41 +00001043 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
Eric Christopherb2a008c2013-05-16 00:45:12 +00001044
Guy Benyei11169dd2012-12-18 14:30:41 +00001045 StringRef MethodName = getFunctionName(Method);
David Blaikie469f0792013-05-22 23:22:42 +00001046 llvm::DICompositeType MethodTy = getOrCreateMethodType(Method, Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00001047
1048 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1049 // make sense to give a single ctor/dtor a linkage name.
1050 StringRef MethodLinkageName;
1051 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1052 MethodLinkageName = CGM.getMangledName(Method);
1053
1054 // Get the location for the method.
David Blaikie7fceebf2013-08-19 03:37:48 +00001055 llvm::DIFile MethodDefUnit;
1056 unsigned MethodLine = 0;
1057 if (!Method->isImplicit()) {
1058 MethodDefUnit = getOrCreateFile(Method->getLocation());
1059 MethodLine = getLineNumber(Method->getLocation());
1060 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001061
1062 // Collect virtual method info.
1063 llvm::DIType ContainingType;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001064 unsigned Virtuality = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00001065 unsigned VIndex = 0;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001066
Guy Benyei11169dd2012-12-18 14:30:41 +00001067 if (Method->isVirtual()) {
1068 if (Method->isPure())
1069 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
1070 else
1071 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001072
Guy Benyei11169dd2012-12-18 14:30:41 +00001073 // It doesn't make sense to give a virtual destructor a vtable index,
1074 // since a single destructor has two entries in the vtable.
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001075 // FIXME: Add proper support for debug info for virtual calls in
1076 // the Microsoft ABI, where we may use multiple vptrs to make a vftable
1077 // lookup if we have multiple or virtual inheritance.
1078 if (!isa<CXXDestructorDecl>(Method) &&
1079 !CGM.getTarget().getCXXABI().isMicrosoft())
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001080 VIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(Method);
Guy Benyei11169dd2012-12-18 14:30:41 +00001081 ContainingType = RecordTy;
1082 }
1083
1084 unsigned Flags = 0;
1085 if (Method->isImplicit())
1086 Flags |= llvm::DIDescriptor::FlagArtificial;
1087 AccessSpecifier Access = Method->getAccess();
1088 if (Access == clang::AS_private)
1089 Flags |= llvm::DIDescriptor::FlagPrivate;
1090 else if (Access == clang::AS_protected)
1091 Flags |= llvm::DIDescriptor::FlagProtected;
1092 if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1093 if (CXXC->isExplicit())
1094 Flags |= llvm::DIDescriptor::FlagExplicit;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001095 } else if (const CXXConversionDecl *CXXC =
Guy Benyei11169dd2012-12-18 14:30:41 +00001096 dyn_cast<CXXConversionDecl>(Method)) {
1097 if (CXXC->isExplicit())
1098 Flags |= llvm::DIDescriptor::FlagExplicit;
1099 }
1100 if (Method->hasPrototype())
1101 Flags |= llvm::DIDescriptor::FlagPrototyped;
Adrian Prantl0630eb72013-12-18 21:48:18 +00001102 if (Method->getRefQualifier() == RQ_LValue)
1103 Flags |= llvm::DIDescriptor::FlagLValueReference;
1104 if (Method->getRefQualifier() == RQ_RValue)
1105 Flags |= llvm::DIDescriptor::FlagRValueReference;
Guy Benyei11169dd2012-12-18 14:30:41 +00001106
1107 llvm::DIArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1108 llvm::DISubprogram SP =
Eric Christopherb2a008c2013-05-16 00:45:12 +00001109 DBuilder.createMethod(RecordTy, MethodName, MethodLinkageName,
Guy Benyei11169dd2012-12-18 14:30:41 +00001110 MethodDefUnit, MethodLine,
Eric Christopherb2a008c2013-05-16 00:45:12 +00001111 MethodTy, /*isLocalToUnit=*/false,
Guy Benyei11169dd2012-12-18 14:30:41 +00001112 /* isDefinition=*/ false,
1113 Virtuality, VIndex, ContainingType,
1114 Flags, CGM.getLangOpts().Optimize, NULL,
1115 TParamsArray);
Eric Christopherb2a008c2013-05-16 00:45:12 +00001116
Guy Benyei11169dd2012-12-18 14:30:41 +00001117 SPCache[Method->getCanonicalDecl()] = llvm::WeakVH(SP);
1118
1119 return SP;
1120}
1121
1122/// CollectCXXMemberFunctions - A helper function to collect debug info for
Eric Christopherb2a008c2013-05-16 00:45:12 +00001123/// C++ member functions. This is used while creating debug info entry for
Guy Benyei11169dd2012-12-18 14:30:41 +00001124/// a Record.
1125void CGDebugInfo::
1126CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
1127 SmallVectorImpl<llvm::Value *> &EltTys,
1128 llvm::DIType RecordTy) {
1129
1130 // Since we want more than just the individual member decls if we
1131 // have templated functions iterate over every declaration to gather
1132 // the functions.
1133 for(DeclContext::decl_iterator I = RD->decls_begin(),
1134 E = RD->decls_end(); I != E; ++I) {
David Blaikiefae219a2013-08-28 17:27:13 +00001135 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*I)) {
David Blaikiea6cc8212013-08-28 20:58:00 +00001136 // Reuse the existing member function declaration if it exists.
David Blaikie8c8e8e22013-08-28 20:24:55 +00001137 // It may be associated with the declaration of the type & should be
1138 // reused as we're building the definition.
David Blaikiea6cc8212013-08-28 20:58:00 +00001139 //
1140 // This situation can arise in the vtable-based debug info reduction where
1141 // implicit members are emitted in a non-vtable TU.
David Blaikie6943dea2013-08-20 01:28:15 +00001142 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator MI =
1143 SPCache.find(Method->getCanonicalDecl());
David Blaikiefae219a2013-08-28 17:27:13 +00001144 if (MI == SPCache.end()) {
David Blaikie8c8e8e22013-08-28 20:24:55 +00001145 // If the member is implicit, lazily create it when we see the
1146 // definition, not before. (an ODR-used implicit default ctor that's
1147 // never actually code generated should not produce debug info)
David Blaikiefae219a2013-08-28 17:27:13 +00001148 if (!Method->isImplicit())
1149 EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
1150 } else
David Blaikie6943dea2013-08-20 01:28:15 +00001151 EltTys.push_back(MI->second);
Eric Christopherf86c4052013-08-28 23:12:10 +00001152 } else if (const FunctionTemplateDecl *FTD =
1153 dyn_cast<FunctionTemplateDecl>(*I)) {
David Blaikief2053af2013-08-28 23:06:52 +00001154 // Add any template specializations that have already been seen. Like
1155 // implicit member functions, these may have been added to a declaration
1156 // in the case of vtable-based debug info reduction.
Eric Christopherf86c4052013-08-28 23:12:10 +00001157 for (FunctionTemplateDecl::spec_iterator SI = FTD->spec_begin(),
1158 SE = FTD->spec_end();
1159 SI != SE; ++SI) {
David Blaikief2053af2013-08-28 23:06:52 +00001160 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator MI =
1161 SPCache.find(cast<CXXMethodDecl>(*SI)->getCanonicalDecl());
1162 if (MI != SPCache.end())
1163 EltTys.push_back(MI->second);
1164 }
David Blaikie6943dea2013-08-20 01:28:15 +00001165 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001166 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00001167}
Guy Benyei11169dd2012-12-18 14:30:41 +00001168
Guy Benyei11169dd2012-12-18 14:30:41 +00001169/// CollectCXXBases - A helper function to collect debug info for
Eric Christopherb2a008c2013-05-16 00:45:12 +00001170/// C++ base classes. This is used while creating debug info entry for
Guy Benyei11169dd2012-12-18 14:30:41 +00001171/// a Record.
1172void CGDebugInfo::
1173CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
1174 SmallVectorImpl<llvm::Value *> &EltTys,
1175 llvm::DIType RecordTy) {
1176
1177 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1178 for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
1179 BE = RD->bases_end(); BI != BE; ++BI) {
1180 unsigned BFlags = 0;
1181 uint64_t BaseOffset;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001182
Guy Benyei11169dd2012-12-18 14:30:41 +00001183 const CXXRecordDecl *Base =
1184 cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl());
Eric Christopherb2a008c2013-05-16 00:45:12 +00001185
Guy Benyei11169dd2012-12-18 14:30:41 +00001186 if (BI->isVirtual()) {
1187 // virtual base offset offset is -ve. The code generator emits dwarf
1188 // expression where it expects +ve number.
Eric Christopherb2a008c2013-05-16 00:45:12 +00001189 BaseOffset =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001190 0 - CGM.getItaniumVTableContext()
Guy Benyei11169dd2012-12-18 14:30:41 +00001191 .getVirtualBaseOffsetOffset(RD, Base).getQuantity();
1192 BFlags = llvm::DIDescriptor::FlagVirtual;
1193 } else
1194 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1195 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1196 // BI->isVirtual() and bits when not.
Eric Christopherb2a008c2013-05-16 00:45:12 +00001197
Guy Benyei11169dd2012-12-18 14:30:41 +00001198 AccessSpecifier Access = BI->getAccessSpecifier();
1199 if (Access == clang::AS_private)
1200 BFlags |= llvm::DIDescriptor::FlagPrivate;
1201 else if (Access == clang::AS_protected)
1202 BFlags |= llvm::DIDescriptor::FlagProtected;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001203
1204 llvm::DIType DTy =
1205 DBuilder.createInheritance(RecordTy,
Guy Benyei11169dd2012-12-18 14:30:41 +00001206 getOrCreateType(BI->getType(), Unit),
1207 BaseOffset, BFlags);
1208 EltTys.push_back(DTy);
1209 }
1210}
1211
1212/// CollectTemplateParams - A helper function to collect template parameters.
1213llvm::DIArray CGDebugInfo::
1214CollectTemplateParams(const TemplateParameterList *TPList,
David Blaikie47c11502013-06-22 18:59:18 +00001215 ArrayRef<TemplateArgument> TAList,
Guy Benyei11169dd2012-12-18 14:30:41 +00001216 llvm::DIFile Unit) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001217 SmallVector<llvm::Value *, 16> TemplateParams;
Guy Benyei11169dd2012-12-18 14:30:41 +00001218 for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1219 const TemplateArgument &TA = TAList[i];
David Blaikie47c11502013-06-22 18:59:18 +00001220 StringRef Name;
1221 if (TPList)
1222 Name = TPList->getParam(i)->getName();
David Blaikie38079fd2013-05-10 21:53:14 +00001223 switch (TA.getKind()) {
1224 case TemplateArgument::Type: {
Guy Benyei11169dd2012-12-18 14:30:41 +00001225 llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit);
1226 llvm::DITemplateTypeParameter TTP =
David Blaikie47c11502013-06-22 18:59:18 +00001227 DBuilder.createTemplateTypeParameter(TheCU, Name, TTy);
Guy Benyei11169dd2012-12-18 14:30:41 +00001228 TemplateParams.push_back(TTP);
David Blaikie38079fd2013-05-10 21:53:14 +00001229 } break;
1230 case TemplateArgument::Integral: {
Guy Benyei11169dd2012-12-18 14:30:41 +00001231 llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit);
1232 llvm::DITemplateValueParameter TVP =
David Blaikie38079fd2013-05-10 21:53:14 +00001233 DBuilder.createTemplateValueParameter(
David Blaikie47c11502013-06-22 18:59:18 +00001234 TheCU, Name, TTy,
David Blaikie38079fd2013-05-10 21:53:14 +00001235 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral()));
1236 TemplateParams.push_back(TVP);
1237 } break;
1238 case TemplateArgument::Declaration: {
1239 const ValueDecl *D = TA.getAsDecl();
1240 bool InstanceMember = D->isCXXInstanceMember();
1241 QualType T = InstanceMember
1242 ? CGM.getContext().getMemberPointerType(
1243 D->getType(), cast<RecordDecl>(D->getDeclContext())
1244 ->getTypeForDecl())
1245 : CGM.getContext().getPointerType(D->getType());
1246 llvm::DIType TTy = getOrCreateType(T, Unit);
1247 llvm::Value *V = 0;
1248 // Variable pointer template parameters have a value that is the address
1249 // of the variable.
1250 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1251 V = CGM.GetAddrOfGlobalVar(VD);
1252 // Member function pointers have special support for building them, though
1253 // this is currently unsupported in LLVM CodeGen.
David Blaikied900f982013-05-13 06:57:50 +00001254 if (InstanceMember) {
David Blaikie38079fd2013-05-10 21:53:14 +00001255 if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(D))
1256 V = CGM.getCXXABI().EmitMemberPointer(method);
David Blaikied900f982013-05-13 06:57:50 +00001257 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1258 V = CGM.GetAddrOfFunction(FD);
David Blaikie38079fd2013-05-10 21:53:14 +00001259 // Member data pointers have special handling too to compute the fixed
1260 // offset within the object.
1261 if (isa<FieldDecl>(D)) {
1262 // These five lines (& possibly the above member function pointer
1263 // handling) might be able to be refactored to use similar code in
1264 // CodeGenModule::getMemberPointerConstant
1265 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
1266 CharUnits chars =
1267 CGM.getContext().toCharUnitsFromBits((int64_t) fieldOffset);
1268 V = CGM.getCXXABI().EmitMemberDataPointer(
1269 cast<MemberPointerType>(T.getTypePtr()), chars);
1270 }
1271 llvm::DITemplateValueParameter TVP =
David Majnemera3644d62013-08-25 22:13:27 +00001272 DBuilder.createTemplateValueParameter(TheCU, Name, TTy,
1273 V->stripPointerCasts());
David Blaikie38079fd2013-05-10 21:53:14 +00001274 TemplateParams.push_back(TVP);
1275 } break;
1276 case TemplateArgument::NullPtr: {
1277 QualType T = TA.getNullPtrType();
1278 llvm::DIType TTy = getOrCreateType(T, Unit);
1279 llvm::Value *V = 0;
1280 // Special case member data pointer null values since they're actually -1
1281 // instead of zero.
1282 if (const MemberPointerType *MPT =
1283 dyn_cast<MemberPointerType>(T.getTypePtr()))
1284 // But treat member function pointers as simple zero integers because
1285 // it's easier than having a special case in LLVM's CodeGen. If LLVM
1286 // CodeGen grows handling for values of non-null member function
1287 // pointers then perhaps we could remove this special case and rely on
1288 // EmitNullMemberPointer for member function pointers.
1289 if (MPT->isMemberDataPointer())
1290 V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1291 if (!V)
1292 V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
1293 llvm::DITemplateValueParameter TVP =
David Blaikie47c11502013-06-22 18:59:18 +00001294 DBuilder.createTemplateValueParameter(TheCU, Name, TTy, V);
David Blaikie38079fd2013-05-10 21:53:14 +00001295 TemplateParams.push_back(TVP);
1296 } break;
David Blaikie47c11502013-06-22 18:59:18 +00001297 case TemplateArgument::Template: {
1298 llvm::DITemplateValueParameter TVP =
1299 DBuilder.createTemplateTemplateParameter(
1300 TheCU, Name, llvm::DIType(),
1301 TA.getAsTemplate().getAsTemplateDecl()
1302 ->getQualifiedNameAsString());
1303 TemplateParams.push_back(TVP);
1304 } break;
1305 case TemplateArgument::Pack: {
1306 llvm::DITemplateValueParameter TVP =
1307 DBuilder.createTemplateParameterPack(
1308 TheCU, Name, llvm::DIType(),
1309 CollectTemplateParams(NULL, TA.getPackAsArray(), Unit));
1310 TemplateParams.push_back(TVP);
1311 } break;
David Majnemer5559d472013-08-24 08:21:10 +00001312 case TemplateArgument::Expression: {
1313 const Expr *E = TA.getAsExpr();
1314 QualType T = E->getType();
1315 llvm::Value *V = CGM.EmitConstantExpr(E, T);
1316 assert(V && "Expression in template argument isn't constant");
1317 llvm::DIType TTy = getOrCreateType(T, Unit);
1318 llvm::DITemplateValueParameter TVP =
1319 DBuilder.createTemplateValueParameter(TheCU, Name, TTy,
1320 V->stripPointerCasts());
1321 TemplateParams.push_back(TVP);
1322 } break;
David Blaikie2b93c542013-05-10 23:36:06 +00001323 // And the following should never occur:
David Blaikie38079fd2013-05-10 21:53:14 +00001324 case TemplateArgument::TemplateExpansion:
David Blaikie38079fd2013-05-10 21:53:14 +00001325 case TemplateArgument::Null:
1326 llvm_unreachable(
1327 "These argument types shouldn't exist in concrete types");
Guy Benyei11169dd2012-12-18 14:30:41 +00001328 }
1329 }
1330 return DBuilder.getOrCreateArray(TemplateParams);
1331}
1332
1333/// CollectFunctionTemplateParams - A helper function to collect debug
1334/// info for function template parameters.
1335llvm::DIArray CGDebugInfo::
1336CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) {
1337 if (FD->getTemplatedKind() ==
1338 FunctionDecl::TK_FunctionTemplateSpecialization) {
1339 const TemplateParameterList *TList =
1340 FD->getTemplateSpecializationInfo()->getTemplate()
1341 ->getTemplateParameters();
David Blaikie47c11502013-06-22 18:59:18 +00001342 return CollectTemplateParams(
1343 TList, FD->getTemplateSpecializationArgs()->asArray(), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00001344 }
1345 return llvm::DIArray();
1346}
1347
1348/// CollectCXXTemplateParams - A helper function to collect debug info for
1349/// template parameters.
1350llvm::DIArray CGDebugInfo::
1351CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial,
1352 llvm::DIFile Unit) {
1353 llvm::PointerUnion<ClassTemplateDecl *,
1354 ClassTemplatePartialSpecializationDecl *>
1355 PU = TSpecial->getSpecializedTemplateOrPartial();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001356
Guy Benyei11169dd2012-12-18 14:30:41 +00001357 TemplateParameterList *TPList = PU.is<ClassTemplateDecl *>() ?
1358 PU.get<ClassTemplateDecl *>()->getTemplateParameters() :
1359 PU.get<ClassTemplatePartialSpecializationDecl *>()->getTemplateParameters();
1360 const TemplateArgumentList &TAList = TSpecial->getTemplateInstantiationArgs();
David Blaikie47c11502013-06-22 18:59:18 +00001361 return CollectTemplateParams(TPList, TAList.asArray(), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00001362}
1363
1364/// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
1365llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
1366 if (VTablePtrType.isValid())
1367 return VTablePtrType;
1368
1369 ASTContext &Context = CGM.getContext();
1370
1371 /* Function type */
1372 llvm::Value *STy = getOrCreateType(Context.IntTy, Unit);
1373 llvm::DIArray SElements = DBuilder.getOrCreateArray(STy);
1374 llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements);
1375 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1376 llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0,
1377 "__vtbl_ptr_type");
1378 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1379 return VTablePtrType;
1380}
1381
1382/// getVTableName - Get vtable name for the given Class.
1383StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +00001384 // Copy the gdb compatible name on the side and use its reference.
1385 return internString("_vptr$", RD->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00001386}
1387
1388
1389/// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
1390/// debug info entry in EltTys vector.
1391void CGDebugInfo::
1392CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
1393 SmallVectorImpl<llvm::Value *> &EltTys) {
1394 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1395
1396 // If there is a primary base then it will hold vtable info.
1397 if (RL.getPrimaryBase())
1398 return;
1399
1400 // If this class is not dynamic then there is not any vtable info to collect.
1401 if (!RD->isDynamicClass())
1402 return;
1403
1404 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1405 llvm::DIType VPTR
1406 = DBuilder.createMemberType(Unit, getVTableName(RD), Unit,
Eric Christopher0fdcb312013-05-16 00:52:20 +00001407 0, Size, 0, 0,
1408 llvm::DIDescriptor::FlagArtificial,
Guy Benyei11169dd2012-12-18 14:30:41 +00001409 getOrCreateVTablePtrType(Unit));
1410 EltTys.push_back(VPTR);
1411}
1412
Eric Christopherb2a008c2013-05-16 00:45:12 +00001413/// getOrCreateRecordType - Emit record type's standalone debug info.
1414llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy,
Guy Benyei11169dd2012-12-18 14:30:41 +00001415 SourceLocation Loc) {
Eric Christopher75e17682013-05-16 00:45:23 +00001416 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00001417 llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc));
1418 return T;
1419}
1420
1421/// getOrCreateInterfaceType - Emit an objective c interface type standalone
1422/// debug info.
1423llvm::DIType CGDebugInfo::getOrCreateInterfaceType(QualType D,
Eric Christopherc0c5d462013-02-21 22:35:08 +00001424 SourceLocation Loc) {
Eric Christopher75e17682013-05-16 00:45:23 +00001425 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00001426 llvm::DIType T = getOrCreateType(D, getOrCreateFile(Loc));
Adrian Prantl73409ce2013-03-11 18:33:46 +00001427 RetainedTypes.push_back(D.getAsOpaquePtr());
Guy Benyei11169dd2012-12-18 14:30:41 +00001428 return T;
1429}
1430
David Blaikieb2e86eb2013-08-15 20:49:17 +00001431void CGDebugInfo::completeType(const RecordDecl *RD) {
1432 if (DebugKind > CodeGenOptions::LimitedDebugInfo ||
1433 !CGM.getLangOpts().CPlusPlus)
1434 completeRequiredType(RD);
1435}
1436
1437void CGDebugInfo::completeRequiredType(const RecordDecl *RD) {
David Blaikie6943dea2013-08-20 01:28:15 +00001438 if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
1439 if (CXXDecl->isDynamicClass())
1440 return;
1441
David Blaikieb2e86eb2013-08-15 20:49:17 +00001442 QualType Ty = CGM.getContext().getRecordType(RD);
1443 llvm::DIType T = getTypeOrNull(Ty);
David Blaikie6943dea2013-08-20 01:28:15 +00001444 if (T && T.isForwardDecl())
1445 completeClassData(RD);
1446}
1447
1448void CGDebugInfo::completeClassData(const RecordDecl *RD) {
1449 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
Michael Gottesman349542b2013-08-19 18:46:16 +00001450 return;
David Blaikie6943dea2013-08-20 01:28:15 +00001451 QualType Ty = CGM.getContext().getRecordType(RD);
David Blaikieb2e86eb2013-08-15 20:49:17 +00001452 void* TyPtr = Ty.getAsOpaquePtr();
1453 if (CompletedTypeCache.count(TyPtr))
1454 return;
1455 llvm::DIType Res = CreateTypeDefinition(Ty->castAs<RecordType>());
1456 assert(!Res.isForwardDecl());
1457 CompletedTypeCache[TyPtr] = Res;
1458 TypeCache[TyPtr] = Res;
1459}
1460
David Blaikie0e716b42014-03-03 23:48:23 +00001461static bool hasExplicitMemberDefinition(CXXRecordDecl::method_iterator I,
1462 CXXRecordDecl::method_iterator End) {
1463 for (; I != End; ++I)
1464 if (FunctionDecl *Tmpl = I->getInstantiatedFromMemberFunction())
David Blaikief7f21852014-03-04 03:08:14 +00001465 if (!Tmpl->isImplicit() && Tmpl->isThisDeclarationADefinition() &&
1466 !I->getMemberSpecializationInfo()->isExplicitSpecialization())
David Blaikie0e716b42014-03-03 23:48:23 +00001467 return true;
1468 return false;
1469}
1470
1471static bool shouldOmitDefinition(CodeGenOptions::DebugInfoKind DebugKind,
1472 const RecordDecl *RD,
1473 const LangOptions &LangOpts) {
1474 if (DebugKind > CodeGenOptions::LimitedDebugInfo)
1475 return false;
1476
1477 if (!LangOpts.CPlusPlus)
1478 return false;
1479
1480 if (!RD->isCompleteDefinitionRequired())
1481 return true;
1482
1483 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1484
1485 if (!CXXDecl)
1486 return false;
1487
1488 if (CXXDecl->hasDefinition() && CXXDecl->isDynamicClass())
1489 return true;
1490
1491 TemplateSpecializationKind Spec = TSK_Undeclared;
1492 if (const ClassTemplateSpecializationDecl *SD =
1493 dyn_cast<ClassTemplateSpecializationDecl>(RD))
1494 Spec = SD->getSpecializationKind();
1495
1496 if (Spec == TSK_ExplicitInstantiationDeclaration &&
1497 hasExplicitMemberDefinition(CXXDecl->method_begin(),
1498 CXXDecl->method_end()))
1499 return true;
1500
1501 return false;
1502}
1503
Guy Benyei11169dd2012-12-18 14:30:41 +00001504/// CreateType - get structure or union type.
David Blaikie99dab3b2013-09-04 22:03:57 +00001505llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001506 RecordDecl *RD = Ty->getDecl();
David Blaikie3b1cc9b2013-09-06 06:45:04 +00001507 llvm::DICompositeType T(getTypeOrNull(QualType(Ty, 0)));
David Blaikie0e716b42014-03-03 23:48:23 +00001508 if (T || shouldOmitDefinition(DebugKind, RD, CGM.getLangOpts())) {
David Blaikie3b1cc9b2013-09-06 06:45:04 +00001509 if (!T)
David Blaikie65ec94e2014-02-18 20:52:05 +00001510 T = getOrCreateRecordFwdDecl(
1511 Ty, getContextDescriptor(cast<Decl>(RD->getDeclContext())));
David Blaikie3b1cc9b2013-09-06 06:45:04 +00001512 return T;
David Blaikiee36464c2013-06-05 05:32:23 +00001513 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001514
David Blaikieb2e86eb2013-08-15 20:49:17 +00001515 return CreateTypeDefinition(Ty);
1516}
1517
1518llvm::DIType CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {
1519 RecordDecl *RD = Ty->getDecl();
1520
Guy Benyei11169dd2012-12-18 14:30:41 +00001521 // Get overall information about the record type for the debug info.
1522 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1523
1524 // Records and classes and unions can all be recursive. To handle them, we
1525 // first generate a debug descriptor for the struct as a forward declaration.
1526 // Then (if it is a definition) we go through and get debug info for all of
1527 // its members. Finally, we create a descriptor for the complete type (which
1528 // may refer to the forward decl if the struct is recursive) and replace all
1529 // uses of the forward declaration with the final definition.
1530
David Blaikie4a2b5ef2013-08-12 22:24:20 +00001531 llvm::DICompositeType FwdDecl(getOrCreateLimitedType(Ty, DefUnit));
Manman Ren0d441f12013-07-02 19:01:53 +00001532 assert(FwdDecl.isCompositeType() &&
David Blaikie469f0792013-05-22 23:22:42 +00001533 "The debug type of a RecordType should be a llvm::DICompositeType");
Guy Benyei11169dd2012-12-18 14:30:41 +00001534
1535 if (FwdDecl.isForwardDecl())
1536 return FwdDecl;
1537
David Blaikieadfbf992013-08-18 16:55:33 +00001538 if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
1539 CollectContainingType(CXXDecl, FwdDecl);
1540
Guy Benyei11169dd2012-12-18 14:30:41 +00001541 // Push the struct on region stack.
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001542 LexicalBlockStack.push_back(&*FwdDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00001543 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1544
Adrian Prantla03a85a2013-03-06 22:03:30 +00001545 // Add this to the completed-type cache while we're completing it recursively.
Guy Benyei11169dd2012-12-18 14:30:41 +00001546 CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1547
1548 // Convert all the elements.
1549 SmallVector<llvm::Value *, 16> EltTys;
David Blaikie6943dea2013-08-20 01:28:15 +00001550 // what about nested types?
Guy Benyei11169dd2012-12-18 14:30:41 +00001551
1552 // Note: The split of CXXDecl information here is intentional, the
1553 // gdb tests will depend on a certain ordering at printout. The debug
1554 // information offsets are still correct if we merge them all together
1555 // though.
1556 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1557 if (CXXDecl) {
1558 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1559 CollectVTableInfo(CXXDecl, DefUnit, EltTys);
1560 }
1561
Eric Christopher91a31902013-01-16 01:22:32 +00001562 // Collect data fields (including static variables and any initializers).
Guy Benyei11169dd2012-12-18 14:30:41 +00001563 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
Eric Christopher2df080e2013-10-11 18:16:51 +00001564 if (CXXDecl)
Guy Benyei11169dd2012-12-18 14:30:41 +00001565 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00001566
1567 LexicalBlockStack.pop_back();
1568 RegionMap.erase(Ty->getDecl());
1569
1570 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
David Blaikie4a5b8952013-08-01 20:31:40 +00001571 FwdDecl.setTypeArray(Elements);
Guy Benyei11169dd2012-12-18 14:30:41 +00001572
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001573 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1574 return FwdDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00001575}
1576
1577/// CreateType - get objective-c object type.
1578llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1579 llvm::DIFile Unit) {
1580 // Ignore protocols.
1581 return getOrCreateType(Ty->getBaseType(), Unit);
1582}
1583
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001584
1585/// \return true if Getter has the default name for the property PD.
1586static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
1587 const ObjCMethodDecl *Getter) {
1588 assert(PD);
1589 if (!Getter)
1590 return true;
1591
1592 assert(Getter->getDeclName().isObjCZeroArgSelector());
1593 return PD->getName() ==
1594 Getter->getDeclName().getObjCSelector().getNameForSlot(0);
1595}
1596
1597/// \return true if Setter has the default name for the property PD.
1598static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
1599 const ObjCMethodDecl *Setter) {
1600 assert(PD);
1601 if (!Setter)
1602 return true;
1603
1604 assert(Setter->getDeclName().isObjCOneArgSelector());
Adrian Prantla4ce9062013-06-07 22:29:12 +00001605 return SelectorTable::constructSetterName(PD->getName()) ==
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001606 Setter->getDeclName().getObjCSelector().getNameForSlot(0);
1607}
1608
Guy Benyei11169dd2012-12-18 14:30:41 +00001609/// CreateType - get objective-c interface type.
1610llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1611 llvm::DIFile Unit) {
1612 ObjCInterfaceDecl *ID = Ty->getDecl();
1613 if (!ID)
1614 return llvm::DIType();
1615
1616 // Get overall information about the record type for the debug info.
1617 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1618 unsigned Line = getLineNumber(ID->getLocation());
1619 unsigned RuntimeLang = TheCU.getLanguage();
1620
1621 // If this is just a forward declaration return a special forward-declaration
1622 // debug type since we won't be able to lay out the entire type.
1623 ObjCInterfaceDecl *Def = ID->getDefinition();
1624 if (!Def) {
1625 llvm::DIType FwdDecl =
1626 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
Eric Christopherc0c5d462013-02-21 22:35:08 +00001627 ID->getName(), TheCU, DefUnit, Line,
1628 RuntimeLang);
Guy Benyei11169dd2012-12-18 14:30:41 +00001629 return FwdDecl;
1630 }
1631
1632 ID = Def;
1633
1634 // Bit size, align and offset of the type.
1635 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1636 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1637
1638 unsigned Flags = 0;
1639 if (ID->getImplementation())
1640 Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
1641
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001642 llvm::DICompositeType RealDecl =
Guy Benyei11169dd2012-12-18 14:30:41 +00001643 DBuilder.createStructType(Unit, ID->getName(), DefUnit,
1644 Line, Size, Align, Flags,
David Blaikie6d4fe152013-02-25 01:07:08 +00001645 llvm::DIType(), llvm::DIArray(), RuntimeLang);
Guy Benyei11169dd2012-12-18 14:30:41 +00001646
1647 // Otherwise, insert it into the CompletedTypeCache so that recursive uses
1648 // will find it and we're emitting the complete type.
Adrian Prantla03a85a2013-03-06 22:03:30 +00001649 QualType QualTy = QualType(Ty, 0);
1650 CompletedTypeCache[QualTy.getAsOpaquePtr()] = RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00001651
Eric Christopher35f1f9f2013-07-14 21:00:07 +00001652 // Push the struct on region stack.
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001653 LexicalBlockStack.push_back(static_cast<llvm::MDNode*>(RealDecl));
Guy Benyei11169dd2012-12-18 14:30:41 +00001654 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1655
1656 // Convert all the elements.
1657 SmallVector<llvm::Value *, 16> EltTys;
1658
1659 ObjCInterfaceDecl *SClass = ID->getSuperClass();
1660 if (SClass) {
1661 llvm::DIType SClassTy =
1662 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1663 if (!SClassTy.isValid())
1664 return llvm::DIType();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001665
Guy Benyei11169dd2012-12-18 14:30:41 +00001666 llvm::DIType InhTag =
1667 DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
1668 EltTys.push_back(InhTag);
1669 }
1670
Eric Christopher35f1f9f2013-07-14 21:00:07 +00001671 // Create entries for all of the properties.
Guy Benyei11169dd2012-12-18 14:30:41 +00001672 for (ObjCContainerDecl::prop_iterator I = ID->prop_begin(),
1673 E = ID->prop_end(); I != E; ++I) {
1674 const ObjCPropertyDecl *PD = *I;
1675 SourceLocation Loc = PD->getLocation();
1676 llvm::DIFile PUnit = getOrCreateFile(Loc);
1677 unsigned PLine = getLineNumber(Loc);
1678 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1679 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1680 llvm::MDNode *PropertyNode =
1681 DBuilder.createObjCProperty(PD->getName(),
Eric Christopherc0c5d462013-02-21 22:35:08 +00001682 PUnit, PLine,
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001683 hasDefaultGetterName(PD, Getter) ? "" :
Guy Benyei11169dd2012-12-18 14:30:41 +00001684 getSelectorName(PD->getGetterName()),
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001685 hasDefaultSetterName(PD, Setter) ? "" :
Guy Benyei11169dd2012-12-18 14:30:41 +00001686 getSelectorName(PD->getSetterName()),
1687 PD->getPropertyAttributes(),
Eric Christopherc0c5d462013-02-21 22:35:08 +00001688 getOrCreateType(PD->getType(), PUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00001689 EltTys.push_back(PropertyNode);
1690 }
1691
1692 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1693 unsigned FieldNo = 0;
1694 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1695 Field = Field->getNextIvar(), ++FieldNo) {
1696 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1697 if (!FieldTy.isValid())
1698 return llvm::DIType();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001699
Guy Benyei11169dd2012-12-18 14:30:41 +00001700 StringRef FieldName = Field->getName();
1701
1702 // Ignore unnamed fields.
1703 if (FieldName.empty())
1704 continue;
1705
1706 // Get the location for the field.
1707 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1708 unsigned FieldLine = getLineNumber(Field->getLocation());
1709 QualType FType = Field->getType();
1710 uint64_t FieldSize = 0;
1711 unsigned FieldAlign = 0;
1712
1713 if (!FType->isIncompleteArrayType()) {
1714
1715 // Bit size, align and offset of the type.
1716 FieldSize = Field->isBitField()
Eric Christopher35f1f9f2013-07-14 21:00:07 +00001717 ? Field->getBitWidthValue(CGM.getContext())
1718 : CGM.getContext().getTypeSize(FType);
Guy Benyei11169dd2012-12-18 14:30:41 +00001719 FieldAlign = CGM.getContext().getTypeAlign(FType);
1720 }
1721
1722 uint64_t FieldOffset;
1723 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1724 // We don't know the runtime offset of an ivar if we're using the
1725 // non-fragile ABI. For bitfields, use the bit offset into the first
1726 // byte of storage of the bitfield. For other fields, use zero.
1727 if (Field->isBitField()) {
1728 FieldOffset = CGM.getObjCRuntime().ComputeBitfieldBitOffset(
1729 CGM, ID, Field);
1730 FieldOffset %= CGM.getContext().getCharWidth();
1731 } else {
1732 FieldOffset = 0;
1733 }
1734 } else {
1735 FieldOffset = RL.getFieldOffset(FieldNo);
1736 }
1737
1738 unsigned Flags = 0;
1739 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1740 Flags = llvm::DIDescriptor::FlagProtected;
1741 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1742 Flags = llvm::DIDescriptor::FlagPrivate;
1743
1744 llvm::MDNode *PropertyNode = NULL;
1745 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001746 if (ObjCPropertyImplDecl *PImpD =
Guy Benyei11169dd2012-12-18 14:30:41 +00001747 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
1748 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
Eric Christopherc0c5d462013-02-21 22:35:08 +00001749 SourceLocation Loc = PD->getLocation();
1750 llvm::DIFile PUnit = getOrCreateFile(Loc);
1751 unsigned PLine = getLineNumber(Loc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001752 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1753 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1754 PropertyNode =
1755 DBuilder.createObjCProperty(PD->getName(),
1756 PUnit, PLine,
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001757 hasDefaultGetterName(PD, Getter) ? "" :
Guy Benyei11169dd2012-12-18 14:30:41 +00001758 getSelectorName(PD->getGetterName()),
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001759 hasDefaultSetterName(PD, Setter) ? "" :
Guy Benyei11169dd2012-12-18 14:30:41 +00001760 getSelectorName(PD->getSetterName()),
1761 PD->getPropertyAttributes(),
1762 getOrCreateType(PD->getType(), PUnit));
1763 }
1764 }
1765 }
1766 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
1767 FieldLine, FieldSize, FieldAlign,
1768 FieldOffset, Flags, FieldTy,
1769 PropertyNode);
1770 EltTys.push_back(FieldTy);
1771 }
1772
1773 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001774 RealDecl.setTypeArray(Elements);
Adrian Prantla03a85a2013-03-06 22:03:30 +00001775
1776 // If the implementation is not yet set, we do not want to mark it
1777 // as complete. An implementation may declare additional
1778 // private ivars that we would miss otherwise.
1779 if (ID->getImplementation() == 0)
1780 CompletedTypeCache.erase(QualTy.getAsOpaquePtr());
Eric Christopherb2a008c2013-05-16 00:45:12 +00001781
Guy Benyei11169dd2012-12-18 14:30:41 +00001782 LexicalBlockStack.pop_back();
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001783 return RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00001784}
1785
1786llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) {
1787 llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1788 int64_t Count = Ty->getNumElements();
1789 if (Count == 0)
1790 // If number of elements are not known then this is an unbounded array.
1791 // Use Count == -1 to express such arrays.
1792 Count = -1;
1793
1794 llvm::Value *Subscript = DBuilder.getOrCreateSubrange(0, Count);
1795 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1796
1797 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1798 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1799
1800 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1801}
1802
1803llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1804 llvm::DIFile Unit) {
1805 uint64_t Size;
1806 uint64_t Align;
1807
1808 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1809 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1810 Size = 0;
1811 Align =
1812 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1813 } else if (Ty->isIncompleteArrayType()) {
1814 Size = 0;
1815 if (Ty->getElementType()->isIncompleteType())
1816 Align = 0;
1817 else
1818 Align = CGM.getContext().getTypeAlign(Ty->getElementType());
David Blaikief03b2e82013-05-09 20:48:12 +00001819 } else if (Ty->isIncompleteType()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001820 Size = 0;
1821 Align = 0;
1822 } else {
1823 // Size and align of the whole array, not the element type.
1824 Size = CGM.getContext().getTypeSize(Ty);
1825 Align = CGM.getContext().getTypeAlign(Ty);
1826 }
1827
1828 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
1829 // interior arrays, do we care? Why aren't nested arrays represented the
1830 // obvious/recursive way?
1831 SmallVector<llvm::Value *, 8> Subscripts;
1832 QualType EltTy(Ty, 0);
1833 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1834 // If the number of elements is known, then count is that number. Otherwise,
1835 // it's -1. This allows us to represent a subrange with an array of 0
1836 // elements, like this:
1837 //
1838 // struct foo {
1839 // int x[0];
1840 // };
1841 int64_t Count = -1; // Count == -1 is an unbounded array.
1842 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1843 Count = CAT->getSize().getZExtValue();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001844
Guy Benyei11169dd2012-12-18 14:30:41 +00001845 // FIXME: Verify this is right for VLAs.
1846 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
1847 EltTy = Ty->getElementType();
1848 }
1849
1850 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1851
Eric Christopherb2a008c2013-05-16 00:45:12 +00001852 llvm::DIType DbgTy =
Guy Benyei11169dd2012-12-18 14:30:41 +00001853 DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1854 SubscriptArray);
1855 return DbgTy;
1856}
1857
Eric Christopherb2a008c2013-05-16 00:45:12 +00001858llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +00001859 llvm::DIFile Unit) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001860 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
Guy Benyei11169dd2012-12-18 14:30:41 +00001861 Ty, Ty->getPointeeType(), Unit);
1862}
1863
Eric Christopherb2a008c2013-05-16 00:45:12 +00001864llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +00001865 llvm::DIFile Unit) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001866 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
Guy Benyei11169dd2012-12-18 14:30:41 +00001867 Ty, Ty->getPointeeType(), Unit);
1868}
1869
Eric Christopherb2a008c2013-05-16 00:45:12 +00001870llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +00001871 llvm::DIFile U) {
David Blaikie2c705ca2013-01-19 19:20:56 +00001872 llvm::DIType ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
1873 if (!Ty->getPointeeType()->isFunctionType())
1874 return DBuilder.createMemberPointerType(
David Blaikie99dab3b2013-09-04 22:03:57 +00001875 getOrCreateType(Ty->getPointeeType(), U), ClassType);
Adrian Prantl0866acd2013-12-19 01:38:47 +00001876
1877 const FunctionProtoType *FPT =
1878 Ty->getPointeeType()->getAs<FunctionProtoType>();
David Blaikie2c705ca2013-01-19 19:20:56 +00001879 return DBuilder.createMemberPointerType(getOrCreateInstanceMethodType(
Adrian Prantl0866acd2013-12-19 01:38:47 +00001880 CGM.getContext().getPointerType(QualType(Ty->getClass(),
1881 FPT->getTypeQuals())),
1882 FPT, U), ClassType);
Guy Benyei11169dd2012-12-18 14:30:41 +00001883}
1884
Eric Christopherb2a008c2013-05-16 00:45:12 +00001885llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +00001886 llvm::DIFile U) {
1887 // Ignore the atomic wrapping
1888 // FIXME: What is the correct representation?
1889 return getOrCreateType(Ty->getValueType(), U);
1890}
1891
1892/// CreateEnumType - get enumeration type.
Manman Ren501ecf92013-08-28 21:46:36 +00001893llvm::DIType CGDebugInfo::CreateEnumType(const EnumType *Ty) {
Manman Ren1b457022013-08-28 21:20:28 +00001894 const EnumDecl *ED = Ty->getDecl();
Guy Benyei11169dd2012-12-18 14:30:41 +00001895 uint64_t Size = 0;
1896 uint64_t Align = 0;
1897 if (!ED->getTypeForDecl()->isIncompleteType()) {
1898 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1899 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1900 }
1901
Manman Rene0064d82013-08-29 23:19:58 +00001902 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
1903
Guy Benyei11169dd2012-12-18 14:30:41 +00001904 // If this is just a forward declaration, construct an appropriately
1905 // marked node and just return it.
1906 if (!ED->getDefinition()) {
1907 llvm::DIDescriptor EDContext;
1908 EDContext = getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1909 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1910 unsigned Line = getLineNumber(ED->getLocation());
1911 StringRef EDName = ED->getName();
1912 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_enumeration_type,
1913 EDName, EDContext, DefUnit, Line, 0,
Manman Rene0064d82013-08-29 23:19:58 +00001914 Size, Align, FullName);
Guy Benyei11169dd2012-12-18 14:30:41 +00001915 }
1916
1917 // Create DIEnumerator elements for each enumerator.
1918 SmallVector<llvm::Value *, 16> Enumerators;
1919 ED = ED->getDefinition();
1920 for (EnumDecl::enumerator_iterator
1921 Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
1922 Enum != EnumEnd; ++Enum) {
1923 Enumerators.push_back(
1924 DBuilder.createEnumerator(Enum->getName(),
David Blaikiece1ae382013-06-24 07:13:13 +00001925 Enum->getInitVal().getSExtValue()));
Guy Benyei11169dd2012-12-18 14:30:41 +00001926 }
1927
1928 // Return a CompositeType for the enum itself.
1929 llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1930
1931 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1932 unsigned Line = getLineNumber(ED->getLocation());
Eric Christopherb2a008c2013-05-16 00:45:12 +00001933 llvm::DIDescriptor EnumContext =
Guy Benyei11169dd2012-12-18 14:30:41 +00001934 getContextDescriptor(cast<Decl>(ED->getDeclContext()));
Adrian Prantlc60dc712013-04-19 19:56:39 +00001935 llvm::DIType ClassTy = ED->isFixed() ?
Guy Benyei11169dd2012-12-18 14:30:41 +00001936 getOrCreateType(ED->getIntegerType(), DefUnit) : llvm::DIType();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001937 llvm::DIType DbgTy =
Guy Benyei11169dd2012-12-18 14:30:41 +00001938 DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1939 Size, Align, EltArray,
Manman Rene0064d82013-08-29 23:19:58 +00001940 ClassTy, FullName);
Guy Benyei11169dd2012-12-18 14:30:41 +00001941 return DbgTy;
1942}
1943
David Blaikie05491062013-01-21 04:37:12 +00001944static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
1945 Qualifiers Quals;
Guy Benyei11169dd2012-12-18 14:30:41 +00001946 do {
Adrian Prantl179af902013-09-26 21:35:50 +00001947 Qualifiers InnerQuals = T.getLocalQualifiers();
1948 // Qualifiers::operator+() doesn't like it if you add a Qualifier
1949 // that is already there.
1950 Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals);
1951 Quals += InnerQuals;
Guy Benyei11169dd2012-12-18 14:30:41 +00001952 QualType LastT = T;
1953 switch (T->getTypeClass()) {
1954 default:
David Blaikie05491062013-01-21 04:37:12 +00001955 return C.getQualifiedType(T.getTypePtr(), Quals);
Guy Benyei11169dd2012-12-18 14:30:41 +00001956 case Type::TemplateSpecialization:
1957 T = cast<TemplateSpecializationType>(T)->desugar();
1958 break;
1959 case Type::TypeOfExpr:
1960 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1961 break;
1962 case Type::TypeOf:
1963 T = cast<TypeOfType>(T)->getUnderlyingType();
1964 break;
1965 case Type::Decltype:
1966 T = cast<DecltypeType>(T)->getUnderlyingType();
1967 break;
1968 case Type::UnaryTransform:
1969 T = cast<UnaryTransformType>(T)->getUnderlyingType();
1970 break;
1971 case Type::Attributed:
1972 T = cast<AttributedType>(T)->getEquivalentType();
1973 break;
1974 case Type::Elaborated:
1975 T = cast<ElaboratedType>(T)->getNamedType();
1976 break;
1977 case Type::Paren:
1978 T = cast<ParenType>(T)->getInnerType();
1979 break;
David Blaikie05491062013-01-21 04:37:12 +00001980 case Type::SubstTemplateTypeParm:
Guy Benyei11169dd2012-12-18 14:30:41 +00001981 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
Guy Benyei11169dd2012-12-18 14:30:41 +00001982 break;
1983 case Type::Auto:
David Blaikie22c460a02013-05-24 21:24:35 +00001984 QualType DT = cast<AutoType>(T)->getDeducedType();
1985 if (DT.isNull())
1986 return T;
1987 T = DT;
Guy Benyei11169dd2012-12-18 14:30:41 +00001988 break;
1989 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00001990
Guy Benyei11169dd2012-12-18 14:30:41 +00001991 assert(T != LastT && "Type unwrapping failed to unwrap!");
NAKAMURA Takumi3e0a3632013-01-21 10:51:28 +00001992 (void)LastT;
Guy Benyei11169dd2012-12-18 14:30:41 +00001993 } while (true);
1994}
1995
Eric Christopher0fdcb312013-05-16 00:52:20 +00001996/// getType - Get the type from the cache or return null type if it doesn't
1997/// exist.
Guy Benyei11169dd2012-12-18 14:30:41 +00001998llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) {
1999
2000 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00002001 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Eric Christopherb2a008c2013-05-16 00:45:12 +00002002
Guy Benyei11169dd2012-12-18 14:30:41 +00002003 // Check for existing entry.
Adrian Prantl73409ce2013-03-11 18:33:46 +00002004 if (Ty->getTypeClass() == Type::ObjCInterface) {
2005 llvm::Value *V = getCachedInterfaceTypeOrNull(Ty);
2006 if (V)
2007 return llvm::DIType(cast<llvm::MDNode>(V));
2008 else return llvm::DIType();
2009 }
2010
Guy Benyei11169dd2012-12-18 14:30:41 +00002011 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
2012 TypeCache.find(Ty.getAsOpaquePtr());
2013 if (it != TypeCache.end()) {
2014 // Verify that the debug info still exists.
2015 if (llvm::Value *V = it->second)
2016 return llvm::DIType(cast<llvm::MDNode>(V));
2017 }
2018
2019 return llvm::DIType();
2020}
2021
2022/// getCompletedTypeOrNull - Get the type from the cache or return null if it
2023/// doesn't exist.
2024llvm::DIType CGDebugInfo::getCompletedTypeOrNull(QualType Ty) {
2025
2026 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00002027 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00002028
2029 // Check for existing entry.
Adrian Prantla03a85a2013-03-06 22:03:30 +00002030 llvm::Value *V = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00002031 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
2032 CompletedTypeCache.find(Ty.getAsOpaquePtr());
Adrian Prantla03a85a2013-03-06 22:03:30 +00002033 if (it != CompletedTypeCache.end())
2034 V = it->second;
2035 else {
Adrian Prantl73409ce2013-03-11 18:33:46 +00002036 V = getCachedInterfaceTypeOrNull(Ty);
Guy Benyei11169dd2012-12-18 14:30:41 +00002037 }
2038
Adrian Prantla03a85a2013-03-06 22:03:30 +00002039 // Verify that any cached debug info still exists.
David Blaikie80d28de2013-08-13 04:21:38 +00002040 return llvm::DIType(cast_or_null<llvm::MDNode>(V));
Guy Benyei11169dd2012-12-18 14:30:41 +00002041}
2042
David Blaikie0e716b42014-03-03 23:48:23 +00002043void CGDebugInfo::completeTemplateDefinition(
2044 const ClassTemplateSpecializationDecl &SD) {
2045 completeClassData(&SD);
2046 // In case this type has no member function definitions being emitted, ensure
2047 // it is retained
2048 RetainedTypes.push_back(CGM.getContext().getRecordType(&SD).getAsOpaquePtr());
2049}
2050
Adrian Prantl73409ce2013-03-11 18:33:46 +00002051/// getCachedInterfaceTypeOrNull - Get the type from the interface
2052/// cache, unless it needs to regenerated. Otherwise return null.
2053llvm::Value *CGDebugInfo::getCachedInterfaceTypeOrNull(QualType Ty) {
2054 // Is there a cached interface that hasn't changed?
2055 llvm::DenseMap<void *, std::pair<llvm::WeakVH, unsigned > >
2056 ::iterator it1 = ObjCInterfaceCache.find(Ty.getAsOpaquePtr());
2057
2058 if (it1 != ObjCInterfaceCache.end())
2059 if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty))
2060 if (Checksum(Decl) == it1->second.second)
2061 // Return cached forward declaration.
2062 return it1->second.first;
2063
2064 return 0;
2065}
Guy Benyei11169dd2012-12-18 14:30:41 +00002066
2067/// getOrCreateType - Get the type from the cache or create a new
2068/// one if necessary.
David Blaikie99dab3b2013-09-04 22:03:57 +00002069llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002070 if (Ty.isNull())
2071 return llvm::DIType();
2072
2073 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00002074 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00002075
David Blaikie99dab3b2013-09-04 22:03:57 +00002076 if (llvm::DIType T = getCompletedTypeOrNull(Ty))
Guy Benyei11169dd2012-12-18 14:30:41 +00002077 return T;
2078
2079 // Otherwise create the type.
David Blaikie99dab3b2013-09-04 22:03:57 +00002080 llvm::DIType Res = CreateTypeNode(Ty, Unit);
Adrian Prantl73409ce2013-03-11 18:33:46 +00002081 void* TyPtr = Ty.getAsOpaquePtr();
2082
2083 // And update the type cache.
2084 TypeCache[TyPtr] = Res;
Guy Benyei11169dd2012-12-18 14:30:41 +00002085
David Blaikie6a723442013-08-15 21:21:19 +00002086 // FIXME: this getTypeOrNull call seems silly when we just inserted the type
2087 // into the cache - but getTypeOrNull has a special case for cached interface
2088 // types. We should probably just pull that out as a special case for the
2089 // "else" block below & skip the otherwise needless lookup.
Guy Benyei11169dd2012-12-18 14:30:41 +00002090 llvm::DIType TC = getTypeOrNull(Ty);
Eric Christopherf8bc4d82013-07-18 00:52:50 +00002091 if (TC && TC.isForwardDecl())
Adrian Prantl73409ce2013-03-11 18:33:46 +00002092 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
2093 else if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty)) {
2094 // Interface types may have elements added to them by a
2095 // subsequent implementation or extension, so we keep them in
2096 // the ObjCInterfaceCache together with a checksum. Instead of
Adrian Prantlc20237d2013-05-08 23:37:22 +00002097 // the (possibly) incomplete interface type, we return a forward
Adrian Prantl73409ce2013-03-11 18:33:46 +00002098 // declaration that gets RAUW'd in CGDebugInfo::finalize().
David Blaikie8e5939b2013-05-21 18:29:40 +00002099 std::pair<llvm::WeakVH, unsigned> &V = ObjCInterfaceCache[TyPtr];
2100 if (V.first)
2101 return llvm::DIType(cast<llvm::MDNode>(V.first));
2102 TC = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
2103 Decl->getName(), TheCU, Unit,
2104 getLineNumber(Decl->getLocation()),
2105 TheCU.getLanguage());
2106 // Store the forward declaration in the cache.
2107 V.first = TC;
2108 V.second = Checksum(Decl);
Adrian Prantl73409ce2013-03-11 18:33:46 +00002109
David Blaikie8e5939b2013-05-21 18:29:40 +00002110 // Register the type for replacement in finalize().
2111 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
2112
Adrian Prantl73409ce2013-03-11 18:33:46 +00002113 return TC;
Adrian Prantla03a85a2013-03-06 22:03:30 +00002114 }
2115
Guy Benyei11169dd2012-12-18 14:30:41 +00002116 if (!Res.isForwardDecl())
Adrian Prantl73409ce2013-03-11 18:33:46 +00002117 CompletedTypeCache[TyPtr] = Res;
Guy Benyei11169dd2012-12-18 14:30:41 +00002118
2119 return Res;
2120}
2121
Adrian Prantlc4de1ef2013-06-07 01:10:41 +00002122/// Currently the checksum of an interface includes the number of
2123/// ivars and property accessors.
Eric Christopher1ecc5632013-06-07 22:54:39 +00002124unsigned CGDebugInfo::Checksum(const ObjCInterfaceDecl *ID) {
Adrian Prantl817bbb32013-06-07 01:10:48 +00002125 // The assumption is that the number of ivars can only increase
2126 // monotonically, so it is safe to just use their current number as
2127 // a checksum.
Adrian Prantlc4de1ef2013-06-07 01:10:41 +00002128 unsigned Sum = 0;
2129 for (const ObjCIvarDecl *Ivar = ID->all_declared_ivar_begin();
2130 Ivar != 0; Ivar = Ivar->getNextIvar())
2131 ++Sum;
2132
2133 return Sum;
Adrian Prantla03a85a2013-03-06 22:03:30 +00002134}
2135
2136ObjCInterfaceDecl *CGDebugInfo::getObjCInterfaceDecl(QualType Ty) {
2137 switch (Ty->getTypeClass()) {
2138 case Type::ObjCObjectPointer:
Eric Christopher0fdcb312013-05-16 00:52:20 +00002139 return getObjCInterfaceDecl(cast<ObjCObjectPointerType>(Ty)
2140 ->getPointeeType());
Adrian Prantla03a85a2013-03-06 22:03:30 +00002141 case Type::ObjCInterface:
2142 return cast<ObjCInterfaceType>(Ty)->getDecl();
2143 default:
2144 return 0;
2145 }
2146}
2147
Guy Benyei11169dd2012-12-18 14:30:41 +00002148/// CreateTypeNode - Create a new debug type node.
David Blaikie99dab3b2013-09-04 22:03:57 +00002149llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002150 // Handle qualifiers, which recursively handles what they refer to.
2151 if (Ty.hasLocalQualifiers())
David Blaikie99dab3b2013-09-04 22:03:57 +00002152 return CreateQualifiedType(Ty, Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00002153
2154 const char *Diag = 0;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002155
Guy Benyei11169dd2012-12-18 14:30:41 +00002156 // Work out details of type.
2157 switch (Ty->getTypeClass()) {
2158#define TYPE(Class, Base)
2159#define ABSTRACT_TYPE(Class, Base)
2160#define NON_CANONICAL_TYPE(Class, Base)
2161#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2162#include "clang/AST/TypeNodes.def"
2163 llvm_unreachable("Dependent types cannot show up in debug information");
2164
2165 case Type::ExtVector:
2166 case Type::Vector:
2167 return CreateType(cast<VectorType>(Ty), Unit);
2168 case Type::ObjCObjectPointer:
2169 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
2170 case Type::ObjCObject:
2171 return CreateType(cast<ObjCObjectType>(Ty), Unit);
2172 case Type::ObjCInterface:
2173 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
2174 case Type::Builtin:
2175 return CreateType(cast<BuiltinType>(Ty));
2176 case Type::Complex:
2177 return CreateType(cast<ComplexType>(Ty));
2178 case Type::Pointer:
2179 return CreateType(cast<PointerType>(Ty), Unit);
Reid Kleckner0503a872013-12-05 01:23:43 +00002180 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00002181 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00002182 // Decayed and adjusted types use the adjusted type in LLVM and DWARF.
Reid Kleckner8a365022013-06-24 17:51:48 +00002183 return CreateType(
Reid Kleckner0503a872013-12-05 01:23:43 +00002184 cast<PointerType>(cast<AdjustedType>(Ty)->getAdjustedType()), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00002185 case Type::BlockPointer:
2186 return CreateType(cast<BlockPointerType>(Ty), Unit);
2187 case Type::Typedef:
David Blaikie99dab3b2013-09-04 22:03:57 +00002188 return CreateType(cast<TypedefType>(Ty), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00002189 case Type::Record:
David Blaikie99dab3b2013-09-04 22:03:57 +00002190 return CreateType(cast<RecordType>(Ty));
Guy Benyei11169dd2012-12-18 14:30:41 +00002191 case Type::Enum:
Manman Ren1b457022013-08-28 21:20:28 +00002192 return CreateEnumType(cast<EnumType>(Ty));
Guy Benyei11169dd2012-12-18 14:30:41 +00002193 case Type::FunctionProto:
2194 case Type::FunctionNoProto:
2195 return CreateType(cast<FunctionType>(Ty), Unit);
2196 case Type::ConstantArray:
2197 case Type::VariableArray:
2198 case Type::IncompleteArray:
2199 return CreateType(cast<ArrayType>(Ty), Unit);
2200
2201 case Type::LValueReference:
2202 return CreateType(cast<LValueReferenceType>(Ty), Unit);
2203 case Type::RValueReference:
2204 return CreateType(cast<RValueReferenceType>(Ty), Unit);
2205
2206 case Type::MemberPointer:
2207 return CreateType(cast<MemberPointerType>(Ty), Unit);
2208
2209 case Type::Atomic:
2210 return CreateType(cast<AtomicType>(Ty), Unit);
2211
2212 case Type::Attributed:
2213 case Type::TemplateSpecialization:
2214 case Type::Elaborated:
2215 case Type::Paren:
2216 case Type::SubstTemplateTypeParm:
2217 case Type::TypeOfExpr:
2218 case Type::TypeOf:
2219 case Type::Decltype:
2220 case Type::UnaryTransform:
David Blaikie66ed89d2013-07-13 21:08:08 +00002221 case Type::PackExpansion:
Guy Benyei11169dd2012-12-18 14:30:41 +00002222 llvm_unreachable("type should have been unwrapped!");
David Blaikie22c460a02013-05-24 21:24:35 +00002223 case Type::Auto:
2224 Diag = "auto";
2225 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002226 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00002227
Guy Benyei11169dd2012-12-18 14:30:41 +00002228 assert(Diag && "Fall through without a diagnostic?");
2229 unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error,
2230 "debug information for %0 is not yet supported");
2231 CGM.getDiags().Report(DiagID)
2232 << Diag;
2233 return llvm::DIType();
2234}
2235
2236/// getOrCreateLimitedType - Get the type from the cache or create a new
2237/// limited type if necessary.
David Blaikie4a2b5ef2013-08-12 22:24:20 +00002238llvm::DIType CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty,
Eric Christopherc0c5d462013-02-21 22:35:08 +00002239 llvm::DIFile Unit) {
David Blaikie4a2b5ef2013-08-12 22:24:20 +00002240 QualType QTy(Ty, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00002241
David Blaikie8d5e1282013-08-20 21:03:29 +00002242 llvm::DICompositeType T(getTypeOrNull(QTy));
Guy Benyei11169dd2012-12-18 14:30:41 +00002243
2244 // We may have cached a forward decl when we could have created
2245 // a non-forward decl. Go ahead and create a non-forward decl
2246 // now.
Eric Christopherf8bc4d82013-07-18 00:52:50 +00002247 if (T && !T.isForwardDecl()) return T;
Guy Benyei11169dd2012-12-18 14:30:41 +00002248
2249 // Otherwise create the type.
David Blaikie8d5e1282013-08-20 21:03:29 +00002250 llvm::DICompositeType Res = CreateLimitedType(Ty);
2251
2252 // Propagate members from the declaration to the definition
2253 // CreateType(const RecordType*) will overwrite this with the members in the
2254 // correct order if the full type is needed.
2255 Res.setTypeArray(T.getTypeArray());
Guy Benyei11169dd2012-12-18 14:30:41 +00002256
Eric Christopherf8bc4d82013-07-18 00:52:50 +00002257 if (T && T.isForwardDecl())
David Blaikie4a2b5ef2013-08-12 22:24:20 +00002258 ReplaceMap.push_back(
2259 std::make_pair(QTy.getAsOpaquePtr(), static_cast<llvm::Value *>(T)));
Guy Benyei11169dd2012-12-18 14:30:41 +00002260
2261 // And update the type cache.
David Blaikie4a2b5ef2013-08-12 22:24:20 +00002262 TypeCache[QTy.getAsOpaquePtr()] = Res;
Guy Benyei11169dd2012-12-18 14:30:41 +00002263 return Res;
2264}
2265
2266// TODO: Currently used for context chains when limiting debug info.
David Blaikie8d5e1282013-08-20 21:03:29 +00002267llvm::DICompositeType CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002268 RecordDecl *RD = Ty->getDecl();
Eric Christopherb2a008c2013-05-16 00:45:12 +00002269
Guy Benyei11169dd2012-12-18 14:30:41 +00002270 // Get overall information about the record type for the debug info.
2271 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
2272 unsigned Line = getLineNumber(RD->getLocation());
2273 StringRef RDName = getClassName(RD);
2274
Eric Christopher07429ff2013-10-15 21:22:34 +00002275 llvm::DIDescriptor RDContext =
2276 getContextDescriptor(cast<Decl>(RD->getDeclContext()));
Guy Benyei11169dd2012-12-18 14:30:41 +00002277
David Blaikied2785892013-08-18 17:36:19 +00002278 // If we ended up creating the type during the context chain construction,
2279 // just return that.
2280 // FIXME: this could be dealt with better if the type was recorded as
2281 // completed before we started this (see the CompletedTypeCache usage in
2282 // CGDebugInfo::CreateTypeDefinition(const RecordType*) - that would need to
2283 // be pushed to before context creation, but after it was known to be
2284 // destined for completion (might still have an issue if this caller only
2285 // required a declaration but the context construction ended up creating a
2286 // definition)
David Blaikie8d5e1282013-08-20 21:03:29 +00002287 llvm::DICompositeType T(getTypeOrNull(CGM.getContext().getRecordType(RD)));
2288 if (T && (!T.isForwardDecl() || !RD->getDefinition()))
David Blaikied2785892013-08-18 17:36:19 +00002289 return T;
2290
Adrian Prantl381e7552014-02-04 21:29:50 +00002291 // If this is just a forward or incomplete declaration, construct an
2292 // appropriately marked node and just return it.
2293 const RecordDecl *D = RD->getDefinition();
2294 if (!D || !D->isCompleteDefinition())
Manman Ren1b457022013-08-28 21:20:28 +00002295 return getOrCreateRecordFwdDecl(Ty, RDContext);
Guy Benyei11169dd2012-12-18 14:30:41 +00002296
2297 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2298 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
David Blaikie49ae6a72013-03-26 23:47:35 +00002299 llvm::DICompositeType RealDecl;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002300
Manman Rene0064d82013-08-29 23:19:58 +00002301 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
2302
Guy Benyei11169dd2012-12-18 14:30:41 +00002303 if (RD->isUnion())
2304 RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
Manman Rene0064d82013-08-29 23:19:58 +00002305 Size, Align, 0, llvm::DIArray(), 0,
2306 FullName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002307 else if (RD->isClass()) {
2308 // FIXME: This could be a struct type giving a default visibility different
2309 // than C++ class type, but needs llvm metadata changes first.
2310 RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
Eric Christopherc0c5d462013-02-21 22:35:08 +00002311 Size, Align, 0, 0, llvm::DIType(),
2312 llvm::DIArray(), llvm::DIType(),
Manman Rene0064d82013-08-29 23:19:58 +00002313 llvm::DIArray(), FullName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002314 } else
2315 RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line,
Eric Christopher0fdcb312013-05-16 00:52:20 +00002316 Size, Align, 0, llvm::DIType(),
David Blaikieba477362013-11-18 23:38:26 +00002317 llvm::DIArray(), 0, llvm::DIType(),
2318 FullName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002319
2320 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
David Blaikie49ae6a72013-03-26 23:47:35 +00002321 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00002322
David Blaikieadfbf992013-08-18 16:55:33 +00002323 if (const ClassTemplateSpecializationDecl *TSpecial =
2324 dyn_cast<ClassTemplateSpecializationDecl>(RD))
2325 RealDecl.setTypeArray(llvm::DIArray(),
2326 CollectCXXTemplateParams(TSpecial, DefUnit));
David Blaikie952dac32013-08-15 22:42:12 +00002327 return RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00002328}
2329
David Blaikieadfbf992013-08-18 16:55:33 +00002330void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,
2331 llvm::DICompositeType RealDecl) {
2332 // A class's primary base or the class itself contains the vtable.
2333 llvm::DICompositeType ContainingType;
2334 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2335 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
Alp Tokerd4733632013-12-05 04:47:09 +00002336 // Seek non-virtual primary base root.
David Blaikieadfbf992013-08-18 16:55:33 +00002337 while (1) {
2338 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
2339 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
2340 if (PBT && !BRL.isPrimaryBaseVirtual())
2341 PBase = PBT;
2342 else
2343 break;
2344 }
2345 ContainingType = llvm::DICompositeType(
2346 getOrCreateType(QualType(PBase->getTypeForDecl(), 0),
2347 getOrCreateFile(RD->getLocation())));
2348 } else if (RD->isDynamicClass())
2349 ContainingType = RealDecl;
2350
2351 RealDecl.setContainingType(ContainingType);
2352}
2353
Guy Benyei11169dd2012-12-18 14:30:41 +00002354/// CreateMemberType - Create new member and increase Offset by FType's size.
2355llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
2356 StringRef Name,
2357 uint64_t *Offset) {
2358 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2359 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
2360 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
2361 llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0,
2362 FieldSize, FieldAlign,
2363 *Offset, 0, FieldTy);
2364 *Offset += FieldSize;
2365 return Ty;
2366}
2367
David Blaikiebd483762013-05-20 04:58:53 +00002368llvm::DIDescriptor CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
2369 // We only need a declaration (not a definition) of the type - so use whatever
2370 // we would otherwise do to get a type for a pointee. (forward declarations in
2371 // limited debug info, full definitions (if the type definition is available)
2372 // in unlimited debug info)
David Blaikie6b7d060c2013-08-12 23:14:36 +00002373 if (const TypeDecl *TD = dyn_cast<TypeDecl>(D))
2374 return getOrCreateType(CGM.getContext().getTypeDeclType(TD),
David Blaikie99dab3b2013-09-04 22:03:57 +00002375 getOrCreateFile(TD->getLocation()));
David Blaikiebd483762013-05-20 04:58:53 +00002376 // Otherwise fall back to a fairly rudimentary cache of existing declarations.
2377 // This doesn't handle providing declarations (for functions or variables) for
2378 // entities without definitions in this TU, nor when the definition proceeds
2379 // the call to this function.
2380 // FIXME: This should be split out into more specific maps with support for
2381 // emitting forward declarations and merging definitions with declarations,
2382 // the same way as we do for types.
2383 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator I =
2384 DeclCache.find(D->getCanonicalDecl());
2385 if (I == DeclCache.end())
2386 return llvm::DIDescriptor();
2387 llvm::Value *V = I->second;
2388 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
2389}
2390
Guy Benyei11169dd2012-12-18 14:30:41 +00002391/// getFunctionDeclaration - Return debug info descriptor to describe method
2392/// declaration for the given method definition.
2393llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
David Blaikie18cfbc52013-06-22 00:09:36 +00002394 if (!D || DebugKind == CodeGenOptions::DebugLineTablesOnly)
2395 return llvm::DISubprogram();
2396
Guy Benyei11169dd2012-12-18 14:30:41 +00002397 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
2398 if (!FD) return llvm::DISubprogram();
2399
2400 // Setup context.
David Blaikiefd07c602013-08-09 17:20:05 +00002401 llvm::DIScope S = getContextDescriptor(cast<Decl>(D->getDeclContext()));
Guy Benyei11169dd2012-12-18 14:30:41 +00002402
2403 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2404 MI = SPCache.find(FD->getCanonicalDecl());
David Blaikiefd07c602013-08-09 17:20:05 +00002405 if (MI == SPCache.end()) {
Eric Christopherf86c4052013-08-28 23:12:10 +00002406 if (const CXXMethodDecl *MD =
2407 dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
David Blaikiefd07c602013-08-09 17:20:05 +00002408 llvm::DICompositeType T(S);
Eric Christopherf86c4052013-08-28 23:12:10 +00002409 llvm::DISubprogram SP =
2410 CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()), T);
David Blaikiefd07c602013-08-09 17:20:05 +00002411 return SP;
2412 }
2413 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002414 if (MI != SPCache.end()) {
2415 llvm::Value *V = MI->second;
2416 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
David Blaikie18cfbc52013-06-22 00:09:36 +00002417 if (SP.isSubprogram() && !SP.isDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00002418 return SP;
2419 }
2420
2421 for (FunctionDecl::redecl_iterator I = FD->redecls_begin(),
2422 E = FD->redecls_end(); I != E; ++I) {
2423 const FunctionDecl *NextFD = *I;
2424 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2425 MI = SPCache.find(NextFD->getCanonicalDecl());
2426 if (MI != SPCache.end()) {
2427 llvm::Value *V = MI->second;
2428 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
David Blaikie18cfbc52013-06-22 00:09:36 +00002429 if (SP.isSubprogram() && !SP.isDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00002430 return SP;
2431 }
2432 }
2433 return llvm::DISubprogram();
2434}
2435
2436// getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
2437// implicit parameter "this".
David Blaikie469f0792013-05-22 23:22:42 +00002438llvm::DICompositeType CGDebugInfo::getOrCreateFunctionType(const Decl *D,
2439 QualType FnType,
2440 llvm::DIFile F) {
David Blaikie18cfbc52013-06-22 00:09:36 +00002441 if (!D || DebugKind == CodeGenOptions::DebugLineTablesOnly)
2442 // Create fake but valid subroutine type. Otherwise
2443 // llvm::DISubprogram::Verify() would return false, and
2444 // subprogram DIE will miss DW_AT_decl_file and
2445 // DW_AT_decl_line fields.
2446 return DBuilder.createSubroutineType(F, DBuilder.getOrCreateArray(None));
Guy Benyei11169dd2012-12-18 14:30:41 +00002447
2448 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
2449 return getOrCreateMethodType(Method, F);
2450 if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
2451 // Add "self" and "_cmd"
2452 SmallVector<llvm::Value *, 16> Elts;
2453
2454 // First element is always return type. For 'void' functions it is NULL.
Alp Toker314cc812014-01-25 16:55:45 +00002455 QualType ResultTy = OMethod->getReturnType();
Adrian Prantl5f360102013-05-22 21:37:49 +00002456
2457 // Replace the instancetype keyword with the actual type.
2458 if (ResultTy == CGM.getContext().getObjCInstanceType())
2459 ResultTy = CGM.getContext().getPointerType(
2460 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
2461
Adrian Prantl7bec9032013-05-10 21:08:31 +00002462 Elts.push_back(getOrCreateType(ResultTy, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002463 // "self" pointer is always first argument.
Adrian Prantlde17db32013-03-29 19:20:29 +00002464 QualType SelfDeclTy = OMethod->getSelfDecl()->getType();
2465 llvm::DIType SelfTy = getOrCreateType(SelfDeclTy, F);
2466 Elts.push_back(CreateSelfType(SelfDeclTy, SelfTy));
Guy Benyei11169dd2012-12-18 14:30:41 +00002467 // "_cmd" pointer is always second argument.
2468 llvm::DIType CmdTy = getOrCreateType(OMethod->getCmdDecl()->getType(), F);
2469 Elts.push_back(DBuilder.createArtificialType(CmdTy));
2470 // Get rest of the arguments.
Eric Christopherb2a008c2013-05-16 00:45:12 +00002471 for (ObjCMethodDecl::param_const_iterator PI = OMethod->param_begin(),
Guy Benyei11169dd2012-12-18 14:30:41 +00002472 PE = OMethod->param_end(); PI != PE; ++PI)
2473 Elts.push_back(getOrCreateType((*PI)->getType(), F));
2474
2475 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2476 return DBuilder.createSubroutineType(F, EltTypeArray);
2477 }
Adrian Prantld45ba252014-02-25 19:38:11 +00002478
Adrian Prantl800faef2014-02-25 23:42:18 +00002479 // Handle variadic function types; they need an additional
2480 // unspecified parameter.
Adrian Prantld45ba252014-02-25 19:38:11 +00002481 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2482 if (FD->isVariadic()) {
2483 SmallVector<llvm::Value *, 16> EltTys;
2484 EltTys.push_back(getOrCreateType(FD->getReturnType(), F));
2485 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FnType))
2486 for (unsigned i = 0, e = FPT->getNumParams(); i != e; ++i)
2487 EltTys.push_back(getOrCreateType(FPT->getParamType(i), F));
2488 EltTys.push_back(DBuilder.createUnspecifiedParameter());
2489 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
2490 return DBuilder.createSubroutineType(F, EltTypeArray);
2491 }
2492
David Blaikie469f0792013-05-22 23:22:42 +00002493 return llvm::DICompositeType(getOrCreateType(FnType, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002494}
2495
2496/// EmitFunctionStart - Constructs the debug code for entering a function.
2497void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
2498 llvm::Function *Fn,
2499 CGBuilderTy &Builder) {
2500
2501 StringRef Name;
2502 StringRef LinkageName;
2503
2504 FnBeginRegionCount.push_back(LexicalBlockStack.size());
2505
2506 const Decl *D = GD.getDecl();
2507 // Function may lack declaration in source code if it is created by Clang
2508 // CodeGen (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
2509 bool HasDecl = (D != 0);
2510 // Use the location of the declaration.
2511 SourceLocation Loc;
2512 if (HasDecl)
2513 Loc = D->getLocation();
2514
2515 unsigned Flags = 0;
2516 llvm::DIFile Unit = getOrCreateFile(Loc);
2517 llvm::DIDescriptor FDContext(Unit);
2518 llvm::DIArray TParamsArray;
2519 if (!HasDecl) {
2520 // Use llvm function name.
David Blaikieebe87e12013-08-27 23:57:18 +00002521 LinkageName = Fn->getName();
Guy Benyei11169dd2012-12-18 14:30:41 +00002522 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2523 // If there is a DISubprogram for this function available then use it.
2524 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2525 FI = SPCache.find(FD->getCanonicalDecl());
2526 if (FI != SPCache.end()) {
2527 llvm::Value *V = FI->second;
2528 llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(V));
2529 if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
2530 llvm::MDNode *SPN = SP;
2531 LexicalBlockStack.push_back(SPN);
2532 RegionMap[D] = llvm::WeakVH(SP);
2533 return;
2534 }
2535 }
2536 Name = getFunctionName(FD);
Nick Lewyckyc02bbb62013-03-20 01:38:16 +00002537 // Use mangled name as linkage name for C/C++ functions.
Guy Benyei11169dd2012-12-18 14:30:41 +00002538 if (FD->hasPrototype()) {
2539 LinkageName = CGM.getMangledName(GD);
2540 Flags |= llvm::DIDescriptor::FlagPrototyped;
2541 }
Nick Lewyckyc02bbb62013-03-20 01:38:16 +00002542 // No need to replicate the linkage name if it isn't different from the
2543 // subprogram name, no need to have it at all unless coverage is enabled or
2544 // debug is set to more than just line tables.
Guy Benyei11169dd2012-12-18 14:30:41 +00002545 if (LinkageName == Name ||
Nick Lewyckyc02bbb62013-03-20 01:38:16 +00002546 (!CGM.getCodeGenOpts().EmitGcovArcs &&
2547 !CGM.getCodeGenOpts().EmitGcovNotes &&
Eric Christopher75e17682013-05-16 00:45:23 +00002548 DebugKind <= CodeGenOptions::DebugLineTablesOnly))
Guy Benyei11169dd2012-12-18 14:30:41 +00002549 LinkageName = StringRef();
2550
Eric Christopher75e17682013-05-16 00:45:23 +00002551 if (DebugKind >= CodeGenOptions::LimitedDebugInfo) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002552 if (const NamespaceDecl *NSDecl =
Eric Christopher9e6f5f92013-10-17 01:31:21 +00002553 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
Guy Benyei11169dd2012-12-18 14:30:41 +00002554 FDContext = getOrCreateNameSpace(NSDecl);
2555 else if (const RecordDecl *RDecl =
Eric Christopher9e6f5f92013-10-17 01:31:21 +00002556 dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
2557 FDContext = getContextDescriptor(cast<Decl>(RDecl));
Guy Benyei11169dd2012-12-18 14:30:41 +00002558
2559 // Collect template parameters.
2560 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
2561 }
2562 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
2563 Name = getObjCMethodName(OMD);
2564 Flags |= llvm::DIDescriptor::FlagPrototyped;
2565 } else {
2566 // Use llvm function name.
2567 Name = Fn->getName();
2568 Flags |= llvm::DIDescriptor::FlagPrototyped;
2569 }
2570 if (!Name.empty() && Name[0] == '\01')
2571 Name = Name.substr(1);
2572
2573 unsigned LineNo = getLineNumber(Loc);
2574 if (!HasDecl || D->isImplicit())
2575 Flags |= llvm::DIDescriptor::FlagArtificial;
2576
Eric Christopher9e6f5f92013-10-17 01:31:21 +00002577 llvm::DISubprogram SP =
2578 DBuilder.createFunction(FDContext, Name, LinkageName, Unit, LineNo,
2579 getOrCreateFunctionType(D, FnType, Unit),
2580 Fn->hasInternalLinkage(), true /*definition*/,
2581 getLineNumber(CurLoc), Flags,
2582 CGM.getLangOpts().Optimize, Fn, TParamsArray,
2583 getFunctionDeclaration(D));
David Blaikiebd483762013-05-20 04:58:53 +00002584 if (HasDecl)
2585 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(SP)));
Guy Benyei11169dd2012-12-18 14:30:41 +00002586
2587 // Push function on region stack.
2588 llvm::MDNode *SPN = SP;
2589 LexicalBlockStack.push_back(SPN);
2590 if (HasDecl)
2591 RegionMap[D] = llvm::WeakVH(SP);
2592}
2593
2594/// EmitLocation - Emit metadata to indicate a change in line/column
Adrian Prantl02c0caa2013-07-18 00:27:59 +00002595/// information in the source file. If the location is invalid, the
2596/// previous location will be reused.
Adrian Prantlc7822422013-03-12 20:43:25 +00002597void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc,
Adrian Prantle83b1302014-01-07 22:05:52 +00002598 bool ForceColumnInfo) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002599 // Update our current location
2600 setLocation(Loc);
2601
2602 if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
2603
2604 // Don't bother if things are the same as last time.
2605 SourceManager &SM = CGM.getContext().getSourceManager();
2606 if (CurLoc == PrevLoc ||
2607 SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc))
2608 // New Builder may not be in sync with CGDebugInfo.
David Blaikie357aafb2013-02-01 19:09:49 +00002609 if (!Builder.getCurrentDebugLocation().isUnknown() &&
2610 Builder.getCurrentDebugLocation().getScope(CGM.getLLVMContext()) ==
2611 LexicalBlockStack.back())
Guy Benyei11169dd2012-12-18 14:30:41 +00002612 return;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002613
Guy Benyei11169dd2012-12-18 14:30:41 +00002614 // Update last state.
2615 PrevLoc = CurLoc;
2616
Adrian Prantle83b1302014-01-07 22:05:52 +00002617 llvm::MDNode *Scope = LexicalBlockStack.back();
Adrian Prantlc7822422013-03-12 20:43:25 +00002618 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get
2619 (getLineNumber(CurLoc),
2620 getColumnNumber(CurLoc, ForceColumnInfo),
2621 Scope));
Guy Benyei11169dd2012-12-18 14:30:41 +00002622}
2623
2624/// CreateLexicalBlock - Creates a new lexical block node and pushes it on
2625/// the stack.
2626void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
2627 llvm::DIDescriptor D =
2628 DBuilder.createLexicalBlock(LexicalBlockStack.empty() ?
2629 llvm::DIDescriptor() :
2630 llvm::DIDescriptor(LexicalBlockStack.back()),
2631 getOrCreateFile(CurLoc),
2632 getLineNumber(CurLoc),
Diego Novilloe6d398182014-03-03 18:53:32 +00002633 getColumnNumber(CurLoc),
2634 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00002635 llvm::MDNode *DN = D;
2636 LexicalBlockStack.push_back(DN);
2637}
2638
2639/// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
2640/// region - beginning of a DW_TAG_lexical_block.
Eric Christopher0fdcb312013-05-16 00:52:20 +00002641void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
2642 SourceLocation Loc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002643 // Set our current location.
2644 setLocation(Loc);
2645
2646 // Create a new lexical block and push it on the stack.
2647 CreateLexicalBlock(Loc);
2648
2649 // Emit a line table change for the current location inside the new scope.
2650 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc),
2651 getColumnNumber(Loc),
2652 LexicalBlockStack.back()));
2653}
2654
2655/// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative
2656/// region - end of a DW_TAG_lexical_block.
Eric Christopher0fdcb312013-05-16 00:52:20 +00002657void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
2658 SourceLocation Loc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002659 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2660
2661 // Provide an entry in the line table for the end of the block.
2662 EmitLocation(Builder, Loc);
2663
2664 LexicalBlockStack.pop_back();
2665}
2666
2667/// EmitFunctionEnd - Constructs the debug code for exiting a function.
2668void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
2669 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2670 unsigned RCount = FnBeginRegionCount.back();
2671 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
2672
2673 // Pop all regions for this function.
2674 while (LexicalBlockStack.size() != RCount)
2675 EmitLexicalBlockEnd(Builder, CurLoc);
2676 FnBeginRegionCount.pop_back();
2677}
2678
Eric Christopherb2a008c2013-05-16 00:45:12 +00002679// EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
Guy Benyei11169dd2012-12-18 14:30:41 +00002680// See BuildByRefType.
2681llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
2682 uint64_t *XOffset) {
2683
2684 SmallVector<llvm::Value *, 5> EltTys;
2685 QualType FType;
2686 uint64_t FieldSize, FieldOffset;
2687 unsigned FieldAlign;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002688
Guy Benyei11169dd2012-12-18 14:30:41 +00002689 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
Eric Christopherb2a008c2013-05-16 00:45:12 +00002690 QualType Type = VD->getType();
Guy Benyei11169dd2012-12-18 14:30:41 +00002691
2692 FieldOffset = 0;
2693 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2694 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
2695 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
2696 FType = CGM.getContext().IntTy;
2697 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
2698 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
2699
2700 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
2701 if (HasCopyAndDispose) {
2702 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2703 EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
2704 &FieldOffset));
2705 EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
2706 &FieldOffset));
2707 }
2708 bool HasByrefExtendedLayout;
2709 Qualifiers::ObjCLifetime Lifetime;
2710 if (CGM.getContext().getByrefLifetime(Type,
2711 Lifetime, HasByrefExtendedLayout)
Adrian Prantlead2ba42013-07-23 00:12:14 +00002712 && HasByrefExtendedLayout) {
2713 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
Guy Benyei11169dd2012-12-18 14:30:41 +00002714 EltTys.push_back(CreateMemberType(Unit, FType,
2715 "__byref_variable_layout",
2716 &FieldOffset));
Adrian Prantlead2ba42013-07-23 00:12:14 +00002717 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00002718
Guy Benyei11169dd2012-12-18 14:30:41 +00002719 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2720 if (Align > CGM.getContext().toCharUnitsFromBits(
John McCallc8e01702013-04-16 22:48:15 +00002721 CGM.getTarget().getPointerAlign(0))) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00002722 CharUnits FieldOffsetInBytes
Guy Benyei11169dd2012-12-18 14:30:41 +00002723 = CGM.getContext().toCharUnitsFromBits(FieldOffset);
2724 CharUnits AlignedOffsetInBytes
2725 = FieldOffsetInBytes.RoundUpToAlignment(Align);
2726 CharUnits NumPaddingBytes
2727 = AlignedOffsetInBytes - FieldOffsetInBytes;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002728
Guy Benyei11169dd2012-12-18 14:30:41 +00002729 if (NumPaddingBytes.isPositive()) {
2730 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
2731 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
2732 pad, ArrayType::Normal, 0);
2733 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
2734 }
2735 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00002736
Guy Benyei11169dd2012-12-18 14:30:41 +00002737 FType = Type;
2738 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2739 FieldSize = CGM.getContext().getTypeSize(FType);
2740 FieldAlign = CGM.getContext().toBits(Align);
2741
Eric Christopherb2a008c2013-05-16 00:45:12 +00002742 *XOffset = FieldOffset;
Guy Benyei11169dd2012-12-18 14:30:41 +00002743 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit,
2744 0, FieldSize, FieldAlign,
2745 FieldOffset, 0, FieldTy);
2746 EltTys.push_back(FieldTy);
2747 FieldOffset += FieldSize;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002748
Guy Benyei11169dd2012-12-18 14:30:41 +00002749 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002750
Guy Benyei11169dd2012-12-18 14:30:41 +00002751 unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002752
Guy Benyei11169dd2012-12-18 14:30:41 +00002753 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
David Blaikie6d4fe152013-02-25 01:07:08 +00002754 llvm::DIType(), Elements);
Guy Benyei11169dd2012-12-18 14:30:41 +00002755}
2756
2757/// EmitDeclare - Emit local variable declaration debug info.
2758void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
Eric Christopherb2a008c2013-05-16 00:45:12 +00002759 llvm::Value *Storage,
Guy Benyei11169dd2012-12-18 14:30:41 +00002760 unsigned ArgNo, CGBuilderTy &Builder) {
Eric Christopher75e17682013-05-16 00:45:23 +00002761 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002762 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2763
David Blaikie7fceebf2013-08-19 03:37:48 +00002764 bool Unwritten =
2765 VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) &&
2766 cast<Decl>(VD->getDeclContext())->isImplicit());
2767 llvm::DIFile Unit;
2768 if (!Unwritten)
2769 Unit = getOrCreateFile(VD->getLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00002770 llvm::DIType Ty;
2771 uint64_t XOffset = 0;
2772 if (VD->hasAttr<BlocksAttr>())
2773 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002774 else
Guy Benyei11169dd2012-12-18 14:30:41 +00002775 Ty = getOrCreateType(VD->getType(), Unit);
2776
2777 // If there is no debug info for this type then do not emit debug info
2778 // for this variable.
2779 if (!Ty)
2780 return;
2781
Guy Benyei11169dd2012-12-18 14:30:41 +00002782 // Get location information.
David Blaikie7fceebf2013-08-19 03:37:48 +00002783 unsigned Line = 0;
2784 unsigned Column = 0;
2785 if (!Unwritten) {
2786 Line = getLineNumber(VD->getLocation());
2787 Column = getColumnNumber(VD->getLocation());
2788 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002789 unsigned Flags = 0;
2790 if (VD->isImplicit())
2791 Flags |= llvm::DIDescriptor::FlagArtificial;
2792 // If this is the first argument and it is implicit then
2793 // give it an object pointer flag.
2794 // FIXME: There has to be a better way to do this, but for static
2795 // functions there won't be an implicit param at arg1 and
2796 // otherwise it is 'self' or 'this'.
2797 if (isa<ImplicitParamDecl>(VD) && ArgNo == 1)
2798 Flags |= llvm::DIDescriptor::FlagObjectPointer;
David Blaikieb9c667d2013-06-19 21:53:53 +00002799 if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage))
Eric Christopherffdeb1e2013-07-17 22:52:53 +00002800 if (Arg->getType()->isPointerTy() && !Arg->hasByValAttr() &&
2801 !VD->getType()->isPointerType())
David Blaikieb9c667d2013-06-19 21:53:53 +00002802 Flags |= llvm::DIDescriptor::FlagIndirectVariable;
Guy Benyei11169dd2012-12-18 14:30:41 +00002803
2804 llvm::MDNode *Scope = LexicalBlockStack.back();
2805
2806 StringRef Name = VD->getName();
2807 if (!Name.empty()) {
2808 if (VD->hasAttr<BlocksAttr>()) {
2809 CharUnits offset = CharUnits::fromQuantity(32);
2810 SmallVector<llvm::Value *, 9> addr;
2811 llvm::Type *Int64Ty = CGM.Int64Ty;
2812 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2813 // offset of __forwarding field
2814 offset = CGM.getContext().toCharUnitsFromBits(
John McCallc8e01702013-04-16 22:48:15 +00002815 CGM.getTarget().getPointerWidth(0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002816 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2817 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2818 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2819 // offset of x field
2820 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2821 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2822
2823 // Create the descriptor for the variable.
2824 llvm::DIVariable D =
Eric Christopherb2a008c2013-05-16 00:45:12 +00002825 DBuilder.createComplexVariable(Tag,
Guy Benyei11169dd2012-12-18 14:30:41 +00002826 llvm::DIDescriptor(Scope),
2827 VD->getName(), Unit, Line, Ty,
2828 addr, ArgNo);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002829
Guy Benyei11169dd2012-12-18 14:30:41 +00002830 // Insert an llvm.dbg.declare into the current block.
2831 llvm::Instruction *Call =
2832 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2833 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2834 return;
Adrian Prantl7f2ef222013-09-18 22:18:17 +00002835 } else if (isa<VariableArrayType>(VD->getType()))
Adrian Prantl0315f382013-09-18 22:08:57 +00002836 Flags |= llvm::DIDescriptor::FlagIndirectVariable;
David Blaikiea76a7c92013-01-05 05:58:35 +00002837 } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2838 // If VD is an anonymous union then Storage represents value for
2839 // all union fields.
Guy Benyei11169dd2012-12-18 14:30:41 +00002840 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
David Blaikie219c7d92013-01-05 20:03:07 +00002841 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002842 for (RecordDecl::field_iterator I = RD->field_begin(),
2843 E = RD->field_end();
2844 I != E; ++I) {
2845 FieldDecl *Field = *I;
2846 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2847 StringRef FieldName = Field->getName();
Eric Christopherb2a008c2013-05-16 00:45:12 +00002848
Guy Benyei11169dd2012-12-18 14:30:41 +00002849 // Ignore unnamed fields. Do not ignore unnamed records.
2850 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2851 continue;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002852
Guy Benyei11169dd2012-12-18 14:30:41 +00002853 // Use VarDecl's Tag, Scope and Line number.
2854 llvm::DIVariable D =
2855 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
Eric Christopherb2a008c2013-05-16 00:45:12 +00002856 FieldName, Unit, Line, FieldTy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002857 CGM.getLangOpts().Optimize, Flags,
2858 ArgNo);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002859
Guy Benyei11169dd2012-12-18 14:30:41 +00002860 // Insert an llvm.dbg.declare into the current block.
2861 llvm::Instruction *Call =
2862 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2863 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2864 }
David Blaikie219c7d92013-01-05 20:03:07 +00002865 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00002866 }
2867 }
David Blaikiea76a7c92013-01-05 05:58:35 +00002868
2869 // Create the descriptor for the variable.
2870 llvm::DIVariable D =
2871 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2872 Name, Unit, Line, Ty,
2873 CGM.getLangOpts().Optimize, Flags, ArgNo);
2874
2875 // Insert an llvm.dbg.declare into the current block.
2876 llvm::Instruction *Call =
2877 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2878 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
Guy Benyei11169dd2012-12-18 14:30:41 +00002879}
2880
2881void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2882 llvm::Value *Storage,
2883 CGBuilderTy &Builder) {
Eric Christopher75e17682013-05-16 00:45:23 +00002884 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002885 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2886}
2887
Adrian Prantlde17db32013-03-29 19:20:29 +00002888/// Look up the completed type for a self pointer in the TypeCache and
2889/// create a copy of it with the ObjectPointer and Artificial flags
2890/// set. If the type is not cached, a new one is created. This should
2891/// never happen though, since creating a type for the implicit self
2892/// argument implies that we already parsed the interface definition
2893/// and the ivar declarations in the implementation.
Eric Christopher0fdcb312013-05-16 00:52:20 +00002894llvm::DIType CGDebugInfo::CreateSelfType(const QualType &QualTy,
2895 llvm::DIType Ty) {
Adrian Prantlde17db32013-03-29 19:20:29 +00002896 llvm::DIType CachedTy = getTypeOrNull(QualTy);
Eric Christopherf8bc4d82013-07-18 00:52:50 +00002897 if (CachedTy) Ty = CachedTy;
Adrian Prantlde17db32013-03-29 19:20:29 +00002898 else DEBUG(llvm::dbgs() << "No cached type for self.");
2899 return DBuilder.createObjectPointerType(Ty);
2900}
2901
Guy Benyei11169dd2012-12-18 14:30:41 +00002902void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(const VarDecl *VD,
2903 llvm::Value *Storage,
2904 CGBuilderTy &Builder,
2905 const CGBlockInfo &blockInfo) {
Eric Christopher75e17682013-05-16 00:45:23 +00002906 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002907 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
Eric Christopherb2a008c2013-05-16 00:45:12 +00002908
Guy Benyei11169dd2012-12-18 14:30:41 +00002909 if (Builder.GetInsertBlock() == 0)
2910 return;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002911
Guy Benyei11169dd2012-12-18 14:30:41 +00002912 bool isByRef = VD->hasAttr<BlocksAttr>();
Eric Christopherb2a008c2013-05-16 00:45:12 +00002913
Guy Benyei11169dd2012-12-18 14:30:41 +00002914 uint64_t XOffset = 0;
2915 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2916 llvm::DIType Ty;
2917 if (isByRef)
2918 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002919 else
Guy Benyei11169dd2012-12-18 14:30:41 +00002920 Ty = getOrCreateType(VD->getType(), Unit);
2921
2922 // Self is passed along as an implicit non-arg variable in a
2923 // block. Mark it as the object pointer.
2924 if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self")
Adrian Prantlde17db32013-03-29 19:20:29 +00002925 Ty = CreateSelfType(VD->getType(), Ty);
Guy Benyei11169dd2012-12-18 14:30:41 +00002926
2927 // Get location information.
2928 unsigned Line = getLineNumber(VD->getLocation());
2929 unsigned Column = getColumnNumber(VD->getLocation());
2930
2931 const llvm::DataLayout &target = CGM.getDataLayout();
2932
2933 CharUnits offset = CharUnits::fromQuantity(
2934 target.getStructLayout(blockInfo.StructureType)
2935 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2936
2937 SmallVector<llvm::Value *, 9> addr;
2938 llvm::Type *Int64Ty = CGM.Int64Ty;
Adrian Prantl0f6df002013-03-29 19:20:35 +00002939 if (isa<llvm::AllocaInst>(Storage))
2940 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
Guy Benyei11169dd2012-12-18 14:30:41 +00002941 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2942 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2943 if (isByRef) {
2944 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2945 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2946 // offset of __forwarding field
2947 offset = CGM.getContext()
2948 .toCharUnitsFromBits(target.getPointerSizeInBits(0));
2949 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2950 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2951 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2952 // offset of x field
2953 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2954 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2955 }
2956
2957 // Create the descriptor for the variable.
2958 llvm::DIVariable D =
Eric Christopherb2a008c2013-05-16 00:45:12 +00002959 DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable,
Guy Benyei11169dd2012-12-18 14:30:41 +00002960 llvm::DIDescriptor(LexicalBlockStack.back()),
2961 VD->getName(), Unit, Line, Ty, addr);
Adrian Prantl0f6df002013-03-29 19:20:35 +00002962
Guy Benyei11169dd2012-12-18 14:30:41 +00002963 // Insert an llvm.dbg.declare into the current block.
2964 llvm::Instruction *Call =
2965 DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
2966 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column,
2967 LexicalBlockStack.back()));
2968}
2969
2970/// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2971/// variable declaration.
2972void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2973 unsigned ArgNo,
2974 CGBuilderTy &Builder) {
Eric Christopher75e17682013-05-16 00:45:23 +00002975 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002976 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2977}
2978
2979namespace {
2980 struct BlockLayoutChunk {
2981 uint64_t OffsetInBits;
2982 const BlockDecl::Capture *Capture;
2983 };
2984 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2985 return l.OffsetInBits < r.OffsetInBits;
2986 }
2987}
2988
2989void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
Adrian Prantl51936dd2013-03-14 17:53:33 +00002990 llvm::Value *Arg,
2991 llvm::Value *LocalAddr,
Guy Benyei11169dd2012-12-18 14:30:41 +00002992 CGBuilderTy &Builder) {
Eric Christopher75e17682013-05-16 00:45:23 +00002993 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002994 ASTContext &C = CGM.getContext();
2995 const BlockDecl *blockDecl = block.getBlockDecl();
2996
2997 // Collect some general information about the block's location.
2998 SourceLocation loc = blockDecl->getCaretLocation();
2999 llvm::DIFile tunit = getOrCreateFile(loc);
3000 unsigned line = getLineNumber(loc);
3001 unsigned column = getColumnNumber(loc);
Eric Christopherb2a008c2013-05-16 00:45:12 +00003002
Guy Benyei11169dd2012-12-18 14:30:41 +00003003 // Build the debug-info type for the block literal.
3004 getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
3005
3006 const llvm::StructLayout *blockLayout =
3007 CGM.getDataLayout().getStructLayout(block.StructureType);
3008
3009 SmallVector<llvm::Value*, 16> fields;
3010 fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
3011 blockLayout->getElementOffsetInBits(0),
3012 tunit, tunit));
3013 fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
3014 blockLayout->getElementOffsetInBits(1),
3015 tunit, tunit));
3016 fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
3017 blockLayout->getElementOffsetInBits(2),
3018 tunit, tunit));
3019 fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
3020 blockLayout->getElementOffsetInBits(3),
3021 tunit, tunit));
3022 fields.push_back(createFieldType("__descriptor",
3023 C.getPointerType(block.NeedsCopyDispose ?
3024 C.getBlockDescriptorExtendedType() :
3025 C.getBlockDescriptorType()),
3026 0, loc, AS_public,
3027 blockLayout->getElementOffsetInBits(4),
3028 tunit, tunit));
3029
3030 // We want to sort the captures by offset, not because DWARF
3031 // requires this, but because we're paranoid about debuggers.
3032 SmallVector<BlockLayoutChunk, 8> chunks;
3033
3034 // 'this' capture.
3035 if (blockDecl->capturesCXXThis()) {
3036 BlockLayoutChunk chunk;
3037 chunk.OffsetInBits =
3038 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
3039 chunk.Capture = 0;
3040 chunks.push_back(chunk);
3041 }
3042
3043 // Variable captures.
3044 for (BlockDecl::capture_const_iterator
3045 i = blockDecl->capture_begin(), e = blockDecl->capture_end();
3046 i != e; ++i) {
3047 const BlockDecl::Capture &capture = *i;
3048 const VarDecl *variable = capture.getVariable();
3049 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
3050
3051 // Ignore constant captures.
3052 if (captureInfo.isConstant())
3053 continue;
3054
3055 BlockLayoutChunk chunk;
3056 chunk.OffsetInBits =
3057 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
3058 chunk.Capture = &capture;
3059 chunks.push_back(chunk);
3060 }
3061
3062 // Sort by offset.
3063 llvm::array_pod_sort(chunks.begin(), chunks.end());
3064
3065 for (SmallVectorImpl<BlockLayoutChunk>::iterator
3066 i = chunks.begin(), e = chunks.end(); i != e; ++i) {
3067 uint64_t offsetInBits = i->OffsetInBits;
3068 const BlockDecl::Capture *capture = i->Capture;
3069
3070 // If we have a null capture, this must be the C++ 'this' capture.
3071 if (!capture) {
3072 const CXXMethodDecl *method =
3073 cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
3074 QualType type = method->getThisType(C);
3075
3076 fields.push_back(createFieldType("this", type, 0, loc, AS_public,
3077 offsetInBits, tunit, tunit));
3078 continue;
3079 }
3080
3081 const VarDecl *variable = capture->getVariable();
3082 StringRef name = variable->getName();
3083
3084 llvm::DIType fieldType;
3085 if (capture->isByRef()) {
3086 std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
3087
3088 // FIXME: this creates a second copy of this type!
3089 uint64_t xoffset;
3090 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
3091 fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
3092 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
3093 ptrInfo.first, ptrInfo.second,
3094 offsetInBits, 0, fieldType);
3095 } else {
3096 fieldType = createFieldType(name, variable->getType(), 0,
3097 loc, AS_public, offsetInBits, tunit, tunit);
3098 }
3099 fields.push_back(fieldType);
3100 }
3101
3102 SmallString<36> typeName;
3103 llvm::raw_svector_ostream(typeName)
3104 << "__block_literal_" << CGM.getUniqueBlockCount();
3105
3106 llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
3107
3108 llvm::DIType type =
3109 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
3110 CGM.getContext().toBits(block.BlockSize),
3111 CGM.getContext().toBits(block.BlockAlign),
David Blaikie6d4fe152013-02-25 01:07:08 +00003112 0, llvm::DIType(), fieldsArray);
Guy Benyei11169dd2012-12-18 14:30:41 +00003113 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
3114
3115 // Get overall information about the block.
3116 unsigned flags = llvm::DIDescriptor::FlagArtificial;
3117 llvm::MDNode *scope = LexicalBlockStack.back();
Guy Benyei11169dd2012-12-18 14:30:41 +00003118
3119 // Create the descriptor for the parameter.
3120 llvm::DIVariable debugVar =
3121 DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
Eric Christopherb2a008c2013-05-16 00:45:12 +00003122 llvm::DIDescriptor(scope),
Adrian Prantl51936dd2013-03-14 17:53:33 +00003123 Arg->getName(), tunit, line, type,
Guy Benyei11169dd2012-12-18 14:30:41 +00003124 CGM.getLangOpts().Optimize, flags,
Adrian Prantl51936dd2013-03-14 17:53:33 +00003125 cast<llvm::Argument>(Arg)->getArgNo() + 1);
3126
Adrian Prantl616bef42013-03-14 21:52:59 +00003127 if (LocalAddr) {
Adrian Prantl51936dd2013-03-14 17:53:33 +00003128 // Insert an llvm.dbg.value into the current block.
Adrian Prantl616bef42013-03-14 21:52:59 +00003129 llvm::Instruction *DbgVal =
3130 DBuilder.insertDbgValueIntrinsic(LocalAddr, 0, debugVar,
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00003131 Builder.GetInsertBlock());
Adrian Prantl616bef42013-03-14 21:52:59 +00003132 DbgVal->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
3133 }
Adrian Prantl51936dd2013-03-14 17:53:33 +00003134
Adrian Prantl616bef42013-03-14 21:52:59 +00003135 // Insert an llvm.dbg.declare into the current block.
3136 llvm::Instruction *DbgDecl =
3137 DBuilder.insertDeclare(Arg, debugVar, Builder.GetInsertBlock());
3138 DbgDecl->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
Guy Benyei11169dd2012-12-18 14:30:41 +00003139}
3140
David Blaikie6943dea2013-08-20 01:28:15 +00003141/// If D is an out-of-class definition of a static data member of a class, find
3142/// its corresponding in-class declaration.
3143llvm::DIDerivedType
3144CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {
3145 if (!D->isStaticDataMember())
3146 return llvm::DIDerivedType();
3147 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator MI =
3148 StaticDataMemberCache.find(D->getCanonicalDecl());
3149 if (MI != StaticDataMemberCache.end()) {
3150 assert(MI->second && "Static data member declaration should still exist");
3151 return llvm::DIDerivedType(cast<llvm::MDNode>(MI->second));
Evgeniy Stepanov37b3f732013-08-16 10:35:31 +00003152 }
David Blaikiece763042013-08-20 21:49:21 +00003153
3154 // If the member wasn't found in the cache, lazily construct and add it to the
3155 // type (used when a limited form of the type is emitted).
David Blaikie6943dea2013-08-20 01:28:15 +00003156 llvm::DICompositeType Ctxt(
3157 getContextDescriptor(cast<Decl>(D->getDeclContext())));
3158 llvm::DIDerivedType T = CreateRecordStaticField(D, Ctxt);
David Blaikie6943dea2013-08-20 01:28:15 +00003159 return T;
3160}
3161
Guy Benyei11169dd2012-12-18 14:30:41 +00003162/// EmitGlobalVariable - Emit information about a global variable.
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003163void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
Guy Benyei11169dd2012-12-18 14:30:41 +00003164 const VarDecl *D) {
Eric Christopher75e17682013-05-16 00:45:23 +00003165 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00003166 // Create global variable debug descriptor.
3167 llvm::DIFile Unit = getOrCreateFile(D->getLocation());
3168 unsigned LineNo = getLineNumber(D->getLocation());
3169
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003170 setLocation(D->getLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00003171
3172 QualType T = D->getType();
3173 if (T->isIncompleteArrayType()) {
3174
3175 // CodeGen turns int[] into int[1] so we'll do the same here.
3176 llvm::APInt ConstVal(32, 1);
3177 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3178
3179 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3180 ArrayType::Normal, 0);
3181 }
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003182 StringRef DeclName = D->getName();
3183 StringRef LinkageName;
3184 if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext())
3185 && !isa<ObjCMethodDecl>(D->getDeclContext()))
3186 LinkageName = Var->getName();
3187 if (LinkageName == DeclName)
3188 LinkageName = StringRef();
Eric Christopherb2a008c2013-05-16 00:45:12 +00003189 llvm::DIDescriptor DContext =
Guy Benyei11169dd2012-12-18 14:30:41 +00003190 getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
David Blaikie6943dea2013-08-20 01:28:15 +00003191 llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(
3192 DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003193 Var->hasInternalLinkage(), Var,
David Blaikie6943dea2013-08-20 01:28:15 +00003194 getOrCreateStaticDataMemberDeclarationOrNull(D));
David Blaikiebd483762013-05-20 04:58:53 +00003195 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(GV)));
Guy Benyei11169dd2012-12-18 14:30:41 +00003196}
3197
3198/// EmitGlobalVariable - Emit information about an objective-c interface.
3199void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
3200 ObjCInterfaceDecl *ID) {
Eric Christopher75e17682013-05-16 00:45:23 +00003201 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00003202 // Create global variable debug descriptor.
3203 llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
3204 unsigned LineNo = getLineNumber(ID->getLocation());
3205
3206 StringRef Name = ID->getName();
3207
3208 QualType T = CGM.getContext().getObjCInterfaceType(ID);
3209 if (T->isIncompleteArrayType()) {
3210
3211 // CodeGen turns int[] into int[1] so we'll do the same here.
3212 llvm::APInt ConstVal(32, 1);
3213 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3214
3215 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3216 ArrayType::Normal, 0);
3217 }
3218
3219 DBuilder.createGlobalVariable(Name, Unit, LineNo,
3220 getOrCreateType(T, Unit),
3221 Var->hasInternalLinkage(), Var);
3222}
3223
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003224/// EmitGlobalVariable - Emit global variable's debug info.
3225void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
3226 llvm::Constant *Init) {
Eric Christopher75e17682013-05-16 00:45:23 +00003227 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003228 // Create the descriptor for the variable.
3229 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
3230 StringRef Name = VD->getName();
3231 llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
3232 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
3233 const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext());
3234 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
3235 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
3236 }
3237 // Do not use DIGlobalVariable for enums.
3238 if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
3239 return;
3240 llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(
3241 Unit, Name, Name, Unit, getLineNumber(VD->getLocation()), Ty, true, Init,
3242 getOrCreateStaticDataMemberDeclarationOrNull(cast<VarDecl>(VD)));
3243 DeclCache.insert(std::make_pair(VD->getCanonicalDecl(), llvm::WeakVH(GV)));
David Blaikiebd483762013-05-20 04:58:53 +00003244}
3245
3246llvm::DIScope CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
3247 if (!LexicalBlockStack.empty())
3248 return llvm::DIScope(LexicalBlockStack.back());
3249 return getContextDescriptor(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00003250}
3251
David Blaikie9f88fe82013-04-22 06:13:21 +00003252void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
David Blaikiebd483762013-05-20 04:58:53 +00003253 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3254 return;
David Blaikie9f88fe82013-04-22 06:13:21 +00003255 DBuilder.createImportedModule(
David Blaikiebd483762013-05-20 04:58:53 +00003256 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
3257 getOrCreateNameSpace(UD.getNominatedNamespace()),
David Blaikie9f88fe82013-04-22 06:13:21 +00003258 getLineNumber(UD.getLocation()));
3259}
3260
David Blaikiebd483762013-05-20 04:58:53 +00003261void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
3262 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3263 return;
3264 assert(UD.shadow_size() &&
3265 "We shouldn't be codegening an invalid UsingDecl containing no decls");
3266 // Emitting one decl is sufficient - debuggers can detect that this is an
3267 // overloaded name & provide lookup for all the overloads.
3268 const UsingShadowDecl &USD = **UD.shadow_begin();
Eric Christopher1ecc5632013-06-07 22:54:39 +00003269 if (llvm::DIDescriptor Target =
3270 getDeclarationOrDefinition(USD.getUnderlyingDecl()))
David Blaikiebd483762013-05-20 04:58:53 +00003271 DBuilder.createImportedDeclaration(
3272 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
3273 getLineNumber(USD.getLocation()));
3274}
3275
David Blaikief121b932013-05-20 22:50:41 +00003276llvm::DIImportedEntity
3277CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
3278 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3279 return llvm::DIImportedEntity(0);
3280 llvm::WeakVH &VH = NamespaceAliasCache[&NA];
3281 if (VH)
3282 return llvm::DIImportedEntity(cast<llvm::MDNode>(VH));
3283 llvm::DIImportedEntity R(0);
3284 if (const NamespaceAliasDecl *Underlying =
3285 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
3286 // This could cache & dedup here rather than relying on metadata deduping.
3287 R = DBuilder.createImportedModule(
3288 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3289 EmitNamespaceAlias(*Underlying), getLineNumber(NA.getLocation()),
3290 NA.getName());
3291 else
3292 R = DBuilder.createImportedModule(
3293 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3294 getOrCreateNameSpace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
3295 getLineNumber(NA.getLocation()), NA.getName());
3296 VH = R;
3297 return R;
3298}
3299
Guy Benyei11169dd2012-12-18 14:30:41 +00003300/// getOrCreateNamesSpace - Return namespace descriptor for the given
3301/// namespace decl.
Eric Christopherb2a008c2013-05-16 00:45:12 +00003302llvm::DINameSpace
Guy Benyei11169dd2012-12-18 14:30:41 +00003303CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
David Blaikie9fdedec2013-08-16 22:52:07 +00003304 NSDecl = NSDecl->getCanonicalDecl();
Eric Christopherb2a008c2013-05-16 00:45:12 +00003305 llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
Guy Benyei11169dd2012-12-18 14:30:41 +00003306 NameSpaceCache.find(NSDecl);
3307 if (I != NameSpaceCache.end())
3308 return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
Eric Christopherb2a008c2013-05-16 00:45:12 +00003309
Guy Benyei11169dd2012-12-18 14:30:41 +00003310 unsigned LineNo = getLineNumber(NSDecl->getLocation());
3311 llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
Eric Christopherb2a008c2013-05-16 00:45:12 +00003312 llvm::DIDescriptor Context =
Guy Benyei11169dd2012-12-18 14:30:41 +00003313 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
3314 llvm::DINameSpace NS =
3315 DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
3316 NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
3317 return NS;
3318}
3319
3320void CGDebugInfo::finalize() {
3321 for (std::vector<std::pair<void *, llvm::WeakVH> >::const_iterator VI
3322 = ReplaceMap.begin(), VE = ReplaceMap.end(); VI != VE; ++VI) {
3323 llvm::DIType Ty, RepTy;
3324 // Verify that the debug info still exists.
3325 if (llvm::Value *V = VI->second)
3326 Ty = llvm::DIType(cast<llvm::MDNode>(V));
Eric Christopherb2a008c2013-05-16 00:45:12 +00003327
Guy Benyei11169dd2012-12-18 14:30:41 +00003328 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
3329 TypeCache.find(VI->first);
3330 if (it != TypeCache.end()) {
3331 // Verify that the debug info still exists.
3332 if (llvm::Value *V = it->second)
3333 RepTy = llvm::DIType(cast<llvm::MDNode>(V));
3334 }
Adrian Prantl73409ce2013-03-11 18:33:46 +00003335
Eric Christopherf8bc4d82013-07-18 00:52:50 +00003336 if (Ty && Ty.isForwardDecl() && RepTy)
Guy Benyei11169dd2012-12-18 14:30:41 +00003337 Ty.replaceAllUsesWith(RepTy);
Guy Benyei11169dd2012-12-18 14:30:41 +00003338 }
Adrian Prantl73409ce2013-03-11 18:33:46 +00003339
3340 // We keep our own list of retained types, because we need to look
3341 // up the final type in the type cache.
3342 for (std::vector<void *>::const_iterator RI = RetainedTypes.begin(),
3343 RE = RetainedTypes.end(); RI != RE; ++RI)
Manman Renf801f802013-08-29 20:48:48 +00003344 DBuilder.retainType(llvm::DIType(cast<llvm::MDNode>(TypeCache[*RI])));
Adrian Prantl73409ce2013-03-11 18:33:46 +00003345
Guy Benyei11169dd2012-12-18 14:30:41 +00003346 DBuilder.finalize();
3347}