blob: 2de4dde12797671796afceac4ba5150e56356961 [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
Adrian Prantl2e0637f2013-07-18 00:28:02 +000055
Adrian Prantld1b151e2014-01-17 00:15:10 +000056SaveAndRestoreLocation::SaveAndRestoreLocation(CodeGenFunction &CGF, CGBuilderTy &B)
Adrian Prantl2e0637f2013-07-18 00:28:02 +000057 : DI(CGF.getDebugInfo()), Builder(B) {
58 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 != ".") {
348 llvm::SmallString<1024> MainFileDirSS(MainFileDir);
349 llvm::sys::path::append(MainFileDirSS, MainFileName);
350 MainFileName = MainFileDirSS.str();
351 }
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 Christopher978c8392013-07-19 00:51:58 +0000385 TheCU = DBuilder.createCompileUnit(LangTag, Filename, getCurrentDirname(),
386 Producer, LO.Optimize,
387 CGM.getCodeGenOpts().DwarfDebugFlags,
388 RuntimeVers, SplitDwarfFilename);
Guy Benyei11169dd2012-12-18 14:30:41 +0000389}
390
391/// CreateType - Get the Basic type from the cache or create a new
392/// one if necessary.
393llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT) {
394 unsigned Encoding = 0;
395 StringRef BTName;
396 switch (BT->getKind()) {
397#define BUILTIN_TYPE(Id, SingletonId)
398#define PLACEHOLDER_TYPE(Id, SingletonId) \
399 case BuiltinType::Id:
400#include "clang/AST/BuiltinTypes.def"
401 case BuiltinType::Dependent:
402 llvm_unreachable("Unexpected builtin type");
403 case BuiltinType::NullPtr:
Peter Collingbourne5c5e6172013-06-27 22:51:01 +0000404 return DBuilder.createNullPtrType();
Guy Benyei11169dd2012-12-18 14:30:41 +0000405 case BuiltinType::Void:
406 return llvm::DIType();
407 case BuiltinType::ObjCClass:
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000408 if (ClassTy)
Guy Benyei11169dd2012-12-18 14:30:41 +0000409 return ClassTy;
410 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
411 "objc_class", TheCU,
412 getOrCreateMainFile(), 0);
413 return ClassTy;
414 case BuiltinType::ObjCId: {
415 // typedef struct objc_class *Class;
416 // typedef struct objc_object {
417 // Class isa;
418 // } *id;
419
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000420 if (ObjTy)
Guy Benyei11169dd2012-12-18 14:30:41 +0000421 return ObjTy;
422
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000423 if (!ClassTy)
Guy Benyei11169dd2012-12-18 14:30:41 +0000424 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
425 "objc_class", TheCU,
426 getOrCreateMainFile(), 0);
427
428 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
Eric Christopherb2a008c2013-05-16 00:45:12 +0000429
Guy Benyei11169dd2012-12-18 14:30:41 +0000430 llvm::DIType ISATy = DBuilder.createPointerType(ClassTy, Size);
431
Eric Christopher5c7ee8b2013-04-02 22:59:11 +0000432 ObjTy =
David Blaikie6d4fe152013-02-25 01:07:08 +0000433 DBuilder.createStructType(TheCU, "objc_object", getOrCreateMainFile(),
434 0, 0, 0, 0, llvm::DIType(), llvm::DIArray());
Guy Benyei11169dd2012-12-18 14:30:41 +0000435
Eric Christopher5c7ee8b2013-04-02 22:59:11 +0000436 ObjTy.setTypeArray(DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
437 ObjTy, "isa", getOrCreateMainFile(), 0, Size, 0, 0, 0, ISATy)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000438 return ObjTy;
439 }
440 case BuiltinType::ObjCSel: {
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000441 if (SelTy)
Guy Benyei11169dd2012-12-18 14:30:41 +0000442 return SelTy;
443 SelTy =
444 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
445 "objc_selector", TheCU, getOrCreateMainFile(),
446 0);
447 return SelTy;
448 }
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000449
450 case BuiltinType::OCLImage1d:
451 return getOrCreateStructPtrType("opencl_image1d_t",
452 OCLImage1dDITy);
453 case BuiltinType::OCLImage1dArray:
Eric Christopherb2a008c2013-05-16 00:45:12 +0000454 return getOrCreateStructPtrType("opencl_image1d_array_t",
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000455 OCLImage1dArrayDITy);
456 case BuiltinType::OCLImage1dBuffer:
457 return getOrCreateStructPtrType("opencl_image1d_buffer_t",
458 OCLImage1dBufferDITy);
459 case BuiltinType::OCLImage2d:
460 return getOrCreateStructPtrType("opencl_image2d_t",
461 OCLImage2dDITy);
462 case BuiltinType::OCLImage2dArray:
463 return getOrCreateStructPtrType("opencl_image2d_array_t",
464 OCLImage2dArrayDITy);
465 case BuiltinType::OCLImage3d:
466 return getOrCreateStructPtrType("opencl_image3d_t",
467 OCLImage3dDITy);
Guy Benyei61054192013-02-07 10:55:47 +0000468 case BuiltinType::OCLSampler:
469 return DBuilder.createBasicType("opencl_sampler_t",
470 CGM.getContext().getTypeSize(BT),
471 CGM.getContext().getTypeAlign(BT),
472 llvm::dwarf::DW_ATE_unsigned);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +0000473 case BuiltinType::OCLEvent:
474 return getOrCreateStructPtrType("opencl_event_t",
475 OCLEventDITy);
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000476
Guy Benyei11169dd2012-12-18 14:30:41 +0000477 case BuiltinType::UChar:
478 case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
479 case BuiltinType::Char_S:
480 case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
481 case BuiltinType::Char16:
482 case BuiltinType::Char32: Encoding = llvm::dwarf::DW_ATE_UTF; break;
483 case BuiltinType::UShort:
484 case BuiltinType::UInt:
485 case BuiltinType::UInt128:
486 case BuiltinType::ULong:
487 case BuiltinType::WChar_U:
488 case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
489 case BuiltinType::Short:
490 case BuiltinType::Int:
491 case BuiltinType::Int128:
492 case BuiltinType::Long:
493 case BuiltinType::WChar_S:
494 case BuiltinType::LongLong: Encoding = llvm::dwarf::DW_ATE_signed; break;
495 case BuiltinType::Bool: Encoding = llvm::dwarf::DW_ATE_boolean; break;
496 case BuiltinType::Half:
497 case BuiltinType::Float:
498 case BuiltinType::LongDouble:
499 case BuiltinType::Double: Encoding = llvm::dwarf::DW_ATE_float; break;
500 }
501
502 switch (BT->getKind()) {
503 case BuiltinType::Long: BTName = "long int"; break;
504 case BuiltinType::LongLong: BTName = "long long int"; break;
505 case BuiltinType::ULong: BTName = "long unsigned int"; break;
506 case BuiltinType::ULongLong: BTName = "long long unsigned int"; break;
507 default:
508 BTName = BT->getName(CGM.getLangOpts());
509 break;
510 }
511 // Bit size, align and offset of the type.
512 uint64_t Size = CGM.getContext().getTypeSize(BT);
513 uint64_t Align = CGM.getContext().getTypeAlign(BT);
Eric Christopherb2a008c2013-05-16 00:45:12 +0000514 llvm::DIType DbgTy =
Guy Benyei11169dd2012-12-18 14:30:41 +0000515 DBuilder.createBasicType(BTName, Size, Align, Encoding);
516 return DbgTy;
517}
518
519llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty) {
520 // Bit size, align and offset of the type.
521 unsigned Encoding = llvm::dwarf::DW_ATE_complex_float;
522 if (Ty->isComplexIntegerType())
523 Encoding = llvm::dwarf::DW_ATE_lo_user;
524
525 uint64_t Size = CGM.getContext().getTypeSize(Ty);
526 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
Eric Christopherb2a008c2013-05-16 00:45:12 +0000527 llvm::DIType DbgTy =
Guy Benyei11169dd2012-12-18 14:30:41 +0000528 DBuilder.createBasicType("complex", Size, Align, Encoding);
529
530 return DbgTy;
531}
532
533/// CreateCVRType - Get the qualified type from the cache or create
534/// a new one if necessary.
David Blaikie99dab3b2013-09-04 22:03:57 +0000535llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000536 QualifierCollector Qc;
537 const Type *T = Qc.strip(Ty);
538
539 // Ignore these qualifiers for now.
540 Qc.removeObjCGCAttr();
541 Qc.removeAddressSpace();
542 Qc.removeObjCLifetime();
543
544 // We will create one Derived type for one qualifier and recurse to handle any
545 // additional ones.
546 unsigned Tag;
547 if (Qc.hasConst()) {
548 Tag = llvm::dwarf::DW_TAG_const_type;
549 Qc.removeConst();
550 } else if (Qc.hasVolatile()) {
551 Tag = llvm::dwarf::DW_TAG_volatile_type;
552 Qc.removeVolatile();
553 } else if (Qc.hasRestrict()) {
554 Tag = llvm::dwarf::DW_TAG_restrict_type;
555 Qc.removeRestrict();
556 } else {
557 assert(Qc.empty() && "Unknown type qualifier for debug info");
558 return getOrCreateType(QualType(T, 0), Unit);
559 }
560
David Blaikie99dab3b2013-09-04 22:03:57 +0000561 llvm::DIType FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +0000562
563 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
564 // CVR derived types.
565 llvm::DIType DbgTy = DBuilder.createQualifiedType(Tag, FromTy);
Eric Christopherb2a008c2013-05-16 00:45:12 +0000566
Guy Benyei11169dd2012-12-18 14:30:41 +0000567 return DbgTy;
568}
569
570llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
571 llvm::DIFile Unit) {
Fariborz Jahanian65f1fa12013-02-21 20:42:11 +0000572
573 // The frontend treats 'id' as a typedef to an ObjCObjectType,
574 // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
575 // debug info, we want to emit 'id' in both cases.
576 if (Ty->isObjCQualifiedIdType())
577 return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
578
Guy Benyei11169dd2012-12-18 14:30:41 +0000579 llvm::DIType DbgTy =
Eric Christopherb2a008c2013-05-16 00:45:12 +0000580 CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +0000581 Ty->getPointeeType(), Unit);
582 return DbgTy;
583}
584
585llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
586 llvm::DIFile Unit) {
Eric Christopherb2a008c2013-05-16 00:45:12 +0000587 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +0000588 Ty->getPointeeType(), Unit);
589}
590
Manman Rene0064d82013-08-29 23:19:58 +0000591/// In C++ mode, types have linkage, so we can rely on the ODR and
592/// on their mangled names, if they're external.
593static SmallString<256>
594getUniqueTagTypeName(const TagType *Ty, CodeGenModule &CGM,
595 llvm::DICompileUnit TheCU) {
596 SmallString<256> FullName;
597 // FIXME: ODR should apply to ObjC++ exactly the same wasy it does to C++.
598 // For now, only apply ODR with C++.
599 const TagDecl *TD = Ty->getDecl();
600 if (TheCU.getLanguage() != llvm::dwarf::DW_LANG_C_plus_plus ||
601 !TD->isExternallyVisible())
602 return FullName;
603 // Microsoft Mangler does not have support for mangleCXXRTTIName yet.
604 if (CGM.getTarget().getCXXABI().isMicrosoft())
605 return FullName;
606
607 // TODO: This is using the RTTI name. Is there a better way to get
608 // a unique string for a type?
609 llvm::raw_svector_ostream Out(FullName);
610 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(QualType(Ty, 0), Out);
611 Out.flush();
612 return FullName;
613}
614
Guy Benyei11169dd2012-12-18 14:30:41 +0000615// Creates a forward declaration for a RecordDecl in the given context.
David Blaikie8d5e1282013-08-20 21:03:29 +0000616llvm::DICompositeType
Manman Ren1b457022013-08-28 21:20:28 +0000617CGDebugInfo::getOrCreateRecordFwdDecl(const RecordType *Ty,
David Blaikie8d5e1282013-08-20 21:03:29 +0000618 llvm::DIDescriptor Ctx) {
Manman Ren1b457022013-08-28 21:20:28 +0000619 const RecordDecl *RD = Ty->getDecl();
David Blaikie4e7ef802013-08-15 20:17:25 +0000620 if (llvm::DIType T = getTypeOrNull(CGM.getContext().getRecordType(RD)))
David Blaikie8d5e1282013-08-20 21:03:29 +0000621 return llvm::DICompositeType(T);
Guy Benyei11169dd2012-12-18 14:30:41 +0000622 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
623 unsigned Line = getLineNumber(RD->getLocation());
624 StringRef RDName = getClassName(RD);
625
626 unsigned Tag = 0;
627 if (RD->isStruct() || RD->isInterface())
628 Tag = llvm::dwarf::DW_TAG_structure_type;
629 else if (RD->isUnion())
630 Tag = llvm::dwarf::DW_TAG_union_type;
631 else {
632 assert(RD->isClass());
633 Tag = llvm::dwarf::DW_TAG_class_type;
634 }
635
636 // Create the type.
Manman Rene0064d82013-08-29 23:19:58 +0000637 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
638 return DBuilder.createForwardDecl(Tag, RDName, Ctx, DefUnit, Line, 0, 0, 0,
639 FullName);
Guy Benyei11169dd2012-12-18 14:30:41 +0000640}
641
Guy Benyei11169dd2012-12-18 14:30:41 +0000642llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag,
Eric Christopherb2a008c2013-05-16 00:45:12 +0000643 const Type *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +0000644 QualType PointeeTy,
645 llvm::DIFile Unit) {
646 if (Tag == llvm::dwarf::DW_TAG_reference_type ||
647 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
David Blaikie99dab3b2013-09-04 22:03:57 +0000648 return DBuilder.createReferenceType(Tag, getOrCreateType(PointeeTy, Unit));
Fariborz Jahanian65f1fa12013-02-21 20:42:11 +0000649
Guy Benyei11169dd2012-12-18 14:30:41 +0000650 // Bit size, align and offset of the type.
651 // Size is always the size of a pointer. We can't use getTypeSize here
652 // because that does not return the correct value for references.
653 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCallc8e01702013-04-16 22:48:15 +0000654 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
Guy Benyei11169dd2012-12-18 14:30:41 +0000655 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
656
David Blaikie99dab3b2013-09-04 22:03:57 +0000657 return DBuilder.createPointerType(getOrCreateType(PointeeTy, Unit), Size,
658 Align);
Guy Benyei11169dd2012-12-18 14:30:41 +0000659}
660
Eric Christopher0fdcb312013-05-16 00:52:20 +0000661llvm::DIType CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
662 llvm::DIType &Cache) {
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000663 if (Cache)
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000664 return Cache;
David Blaikiefefc7f72013-05-21 17:58:54 +0000665 Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
666 TheCU, getOrCreateMainFile(), 0);
667 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
668 Cache = DBuilder.createPointerType(Cache, Size);
669 return Cache;
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000670}
671
Guy Benyei11169dd2012-12-18 14:30:41 +0000672llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
673 llvm::DIFile Unit) {
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000674 if (BlockLiteralGeneric)
Guy Benyei11169dd2012-12-18 14:30:41 +0000675 return BlockLiteralGeneric;
676
677 SmallVector<llvm::Value *, 8> EltTys;
678 llvm::DIType FieldTy;
679 QualType FType;
680 uint64_t FieldSize, FieldOffset;
681 unsigned FieldAlign;
682 llvm::DIArray Elements;
683 llvm::DIType EltTy, DescTy;
684
685 FieldOffset = 0;
686 FType = CGM.getContext().UnsignedLongTy;
687 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
688 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
689
690 Elements = DBuilder.getOrCreateArray(EltTys);
691 EltTys.clear();
692
693 unsigned Flags = llvm::DIDescriptor::FlagAppleBlock;
694 unsigned LineNo = getLineNumber(CurLoc);
695
696 EltTy = DBuilder.createStructType(Unit, "__block_descriptor",
697 Unit, LineNo, FieldOffset, 0,
David Blaikie6d4fe152013-02-25 01:07:08 +0000698 Flags, llvm::DIType(), Elements);
Guy Benyei11169dd2012-12-18 14:30:41 +0000699
700 // Bit size, align and offset of the type.
701 uint64_t Size = CGM.getContext().getTypeSize(Ty);
702
703 DescTy = DBuilder.createPointerType(EltTy, Size);
704
705 FieldOffset = 0;
706 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
707 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
708 FType = CGM.getContext().IntTy;
709 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
710 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
711 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
712 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
713
714 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
715 FieldTy = DescTy;
716 FieldSize = CGM.getContext().getTypeSize(Ty);
717 FieldAlign = CGM.getContext().getTypeAlign(Ty);
718 FieldTy = DBuilder.createMemberType(Unit, "__descriptor", Unit,
719 LineNo, FieldSize, FieldAlign,
720 FieldOffset, 0, FieldTy);
721 EltTys.push_back(FieldTy);
722
723 FieldOffset += FieldSize;
724 Elements = DBuilder.getOrCreateArray(EltTys);
725
726 EltTy = DBuilder.createStructType(Unit, "__block_literal_generic",
727 Unit, LineNo, FieldOffset, 0,
David Blaikie6d4fe152013-02-25 01:07:08 +0000728 Flags, llvm::DIType(), Elements);
Guy Benyei11169dd2012-12-18 14:30:41 +0000729
Guy Benyei11169dd2012-12-18 14:30:41 +0000730 BlockLiteralGeneric = DBuilder.createPointerType(EltTy, Size);
731 return BlockLiteralGeneric;
732}
733
David Blaikie99dab3b2013-09-04 22:03:57 +0000734llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty, llvm::DIFile Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000735 // Typedefs are derived from some other type. If we have a typedef of a
736 // typedef, make sure to emit the whole chain.
David Blaikie99dab3b2013-09-04 22:03:57 +0000737 llvm::DIType Src = getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000738 if (!Src)
Guy Benyei11169dd2012-12-18 14:30:41 +0000739 return llvm::DIType();
740 // We don't set size information, but do specify where the typedef was
741 // declared.
Adrian Prantl3eff2252014-01-21 18:42:27 +0000742 SourceLocation Loc = Ty->getDecl()->getLocation();
743 llvm::DIFile File = getOrCreateFile(Loc);
744 unsigned Line = getLineNumber(Loc);
Guy Benyei11169dd2012-12-18 14:30:41 +0000745 const TypedefNameDecl *TyDecl = Ty->getDecl();
Eric Christopherb2a008c2013-05-16 00:45:12 +0000746
Guy Benyei11169dd2012-12-18 14:30:41 +0000747 llvm::DIDescriptor TypedefContext =
748 getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext()));
Eric Christopherb2a008c2013-05-16 00:45:12 +0000749
Guy Benyei11169dd2012-12-18 14:30:41 +0000750 return
Adrian Prantl3eff2252014-01-21 18:42:27 +0000751 DBuilder.createTypedef(Src, TyDecl->getName(), File, Line, TypedefContext);
Guy Benyei11169dd2012-12-18 14:30:41 +0000752}
753
754llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
755 llvm::DIFile Unit) {
756 SmallVector<llvm::Value *, 16> EltTys;
757
758 // Add the result type at least.
Alp Toker314cc812014-01-25 16:55:45 +0000759 EltTys.push_back(getOrCreateType(Ty->getReturnType(), Unit));
Guy Benyei11169dd2012-12-18 14:30:41 +0000760
761 // Set up remainder of arguments if there is a prototype.
762 // FIXME: IF NOT, HOW IS THIS REPRESENTED? llvm-gcc doesn't represent '...'!
763 if (isa<FunctionNoProtoType>(Ty))
764 EltTys.push_back(DBuilder.createUnspecifiedParameter());
765 else if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Ty)) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000766 for (unsigned i = 0, e = FPT->getNumParams(); i != e; ++i)
767 EltTys.push_back(getOrCreateType(FPT->getParamType(i), Unit));
Adrian Prantld45ba252014-02-25 19:38:11 +0000768 if (FPT->isVariadic())
769 EltTys.push_back(DBuilder.createUnspecifiedParameter());
Guy Benyei11169dd2012-12-18 14:30:41 +0000770 }
771
772 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
773 return DBuilder.createSubroutineType(Unit, EltTypeArray);
774}
775
776
Guy Benyei11169dd2012-12-18 14:30:41 +0000777llvm::DIType CGDebugInfo::createFieldType(StringRef name,
778 QualType type,
779 uint64_t sizeInBitsOverride,
780 SourceLocation loc,
781 AccessSpecifier AS,
782 uint64_t offsetInBits,
783 llvm::DIFile tunit,
Manman Ren2c826dc2013-09-08 03:45:05 +0000784 llvm::DIScope scope) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000785 llvm::DIType debugType = getOrCreateType(type, tunit);
786
787 // Get the location for the field.
788 llvm::DIFile file = getOrCreateFile(loc);
789 unsigned line = getLineNumber(loc);
790
791 uint64_t sizeInBits = 0;
792 unsigned alignInBits = 0;
793 if (!type->isIncompleteArrayType()) {
794 llvm::tie(sizeInBits, alignInBits) = CGM.getContext().getTypeInfo(type);
795
796 if (sizeInBitsOverride)
797 sizeInBits = sizeInBitsOverride;
798 }
799
800 unsigned flags = 0;
801 if (AS == clang::AS_private)
802 flags |= llvm::DIDescriptor::FlagPrivate;
803 else if (AS == clang::AS_protected)
804 flags |= llvm::DIDescriptor::FlagProtected;
805
806 return DBuilder.createMemberType(scope, name, file, line, sizeInBits,
807 alignInBits, offsetInBits, flags, debugType);
808}
809
Eric Christopher91a31902013-01-16 01:22:32 +0000810/// CollectRecordLambdaFields - Helper for CollectRecordFields.
811void CGDebugInfo::
812CollectRecordLambdaFields(const CXXRecordDecl *CXXDecl,
813 SmallVectorImpl<llvm::Value *> &elements,
814 llvm::DIType RecordTy) {
815 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
816 // has the name and the location of the variable so we should iterate over
817 // both concurrently.
818 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
819 RecordDecl::field_iterator Field = CXXDecl->field_begin();
820 unsigned fieldno = 0;
821 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
822 E = CXXDecl->captures_end(); I != E; ++I, ++Field, ++fieldno) {
823 const LambdaExpr::Capture C = *I;
824 if (C.capturesVariable()) {
825 VarDecl *V = C.getCapturedVar();
826 llvm::DIFile VUnit = getOrCreateFile(C.getLocation());
827 StringRef VName = V->getName();
828 uint64_t SizeInBitsOverride = 0;
829 if (Field->isBitField()) {
830 SizeInBitsOverride = Field->getBitWidthValue(CGM.getContext());
831 assert(SizeInBitsOverride && "found named 0-width bitfield");
832 }
833 llvm::DIType fieldType
834 = createFieldType(VName, Field->getType(), SizeInBitsOverride,
835 C.getLocation(), Field->getAccess(),
836 layout.getFieldOffset(fieldno), VUnit, RecordTy);
837 elements.push_back(fieldType);
838 } else {
839 // TODO: Need to handle 'this' in some way by probably renaming the
840 // this of the lambda class and having a field member of 'this' or
841 // by using AT_object_pointer for the function and having that be
842 // used as 'this' for semantic references.
843 assert(C.capturesThis() && "Field that isn't captured and isn't this?");
844 FieldDecl *f = *Field;
845 llvm::DIFile VUnit = getOrCreateFile(f->getLocation());
846 QualType type = f->getType();
847 llvm::DIType fieldType
848 = createFieldType("this", type, 0, f->getLocation(), f->getAccess(),
849 layout.getFieldOffset(fieldno), VUnit, RecordTy);
850
851 elements.push_back(fieldType);
852 }
853 }
854}
855
David Blaikie6943dea2013-08-20 01:28:15 +0000856/// Helper for CollectRecordFields.
David Blaikieae019462013-08-15 22:50:29 +0000857llvm::DIDerivedType
858CGDebugInfo::CreateRecordStaticField(const VarDecl *Var,
859 llvm::DIType RecordTy) {
Eric Christopher91a31902013-01-16 01:22:32 +0000860 // Create the descriptor for the static variable, with or without
861 // constant initializers.
862 llvm::DIFile VUnit = getOrCreateFile(Var->getLocation());
863 llvm::DIType VTy = getOrCreateType(Var->getType(), VUnit);
864
Eric Christopher91a31902013-01-16 01:22:32 +0000865 unsigned LineNumber = getLineNumber(Var->getLocation());
866 StringRef VName = Var->getName();
David Blaikied42917f2013-01-20 01:19:17 +0000867 llvm::Constant *C = NULL;
Eric Christopher91a31902013-01-16 01:22:32 +0000868 if (Var->getInit()) {
869 const APValue *Value = Var->evaluateValue();
David Blaikied42917f2013-01-20 01:19:17 +0000870 if (Value) {
871 if (Value->isInt())
872 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
873 if (Value->isFloat())
874 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
875 }
Eric Christopher91a31902013-01-16 01:22:32 +0000876 }
877
878 unsigned Flags = 0;
879 AccessSpecifier Access = Var->getAccess();
880 if (Access == clang::AS_private)
881 Flags |= llvm::DIDescriptor::FlagPrivate;
882 else if (Access == clang::AS_protected)
883 Flags |= llvm::DIDescriptor::FlagProtected;
884
David Blaikieae019462013-08-15 22:50:29 +0000885 llvm::DIDerivedType GV = DBuilder.createStaticMemberType(
886 RecordTy, VName, VUnit, LineNumber, VTy, Flags, C);
Eric Christopher91a31902013-01-16 01:22:32 +0000887 StaticDataMemberCache[Var->getCanonicalDecl()] = llvm::WeakVH(GV);
David Blaikieae019462013-08-15 22:50:29 +0000888 return GV;
Eric Christopher91a31902013-01-16 01:22:32 +0000889}
890
891/// CollectRecordNormalField - Helper for CollectRecordFields.
892void CGDebugInfo::
893CollectRecordNormalField(const FieldDecl *field, uint64_t OffsetInBits,
894 llvm::DIFile tunit,
895 SmallVectorImpl<llvm::Value *> &elements,
896 llvm::DIType RecordTy) {
897 StringRef name = field->getName();
898 QualType type = field->getType();
899
900 // Ignore unnamed fields unless they're anonymous structs/unions.
901 if (name.empty() && !type->isRecordType())
902 return;
903
904 uint64_t SizeInBitsOverride = 0;
905 if (field->isBitField()) {
906 SizeInBitsOverride = field->getBitWidthValue(CGM.getContext());
907 assert(SizeInBitsOverride && "found named 0-width bitfield");
908 }
909
910 llvm::DIType fieldType
911 = createFieldType(name, type, SizeInBitsOverride,
912 field->getLocation(), field->getAccess(),
913 OffsetInBits, tunit, RecordTy);
914
915 elements.push_back(fieldType);
916}
917
Guy Benyei11169dd2012-12-18 14:30:41 +0000918/// CollectRecordFields - A helper function to collect debug info for
919/// record fields. This is used while creating debug info entry for a Record.
David Blaikieab255bb2013-08-16 20:40:25 +0000920void CGDebugInfo::CollectRecordFields(const RecordDecl *record,
921 llvm::DIFile tunit,
922 SmallVectorImpl<llvm::Value *> &elements,
923 llvm::DICompositeType RecordTy) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000924 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(record);
925
Eric Christopher91a31902013-01-16 01:22:32 +0000926 if (CXXDecl && CXXDecl->isLambda())
927 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
928 else {
929 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
Guy Benyei11169dd2012-12-18 14:30:41 +0000930
Eric Christopher91a31902013-01-16 01:22:32 +0000931 // Field number for non-static fields.
Eric Christopher0f7594372013-01-04 17:59:07 +0000932 unsigned fieldNo = 0;
Eric Christopher91a31902013-01-16 01:22:32 +0000933
Eric Christopher91a31902013-01-16 01:22:32 +0000934 // Static and non-static members should appear in the same order as
935 // the corresponding declarations in the source program.
936 for (RecordDecl::decl_iterator I = record->decls_begin(),
937 E = record->decls_end(); I != E; ++I)
David Blaikiece763042013-08-20 21:49:21 +0000938 if (const VarDecl *V = dyn_cast<VarDecl>(*I)) {
939 // Reuse the existing static member declaration if one exists
940 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator MI =
941 StaticDataMemberCache.find(V->getCanonicalDecl());
942 if (MI != StaticDataMemberCache.end()) {
943 assert(MI->second &&
944 "Static data member declaration should still exist");
945 elements.push_back(
946 llvm::DIDerivedType(cast<llvm::MDNode>(MI->second)));
947 } else
948 elements.push_back(CreateRecordStaticField(V, RecordTy));
949 } else if (FieldDecl *field = dyn_cast<FieldDecl>(*I)) {
Eric Christopher91a31902013-01-16 01:22:32 +0000950 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo),
951 tunit, elements, RecordTy);
952
953 // Bump field number for next field.
954 ++fieldNo;
Guy Benyei11169dd2012-12-18 14:30:41 +0000955 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000956 }
957}
958
959/// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
960/// function type is not updated to include implicit "this" pointer. Use this
961/// routine to get a method type which includes "this" pointer.
David Blaikie469f0792013-05-22 23:22:42 +0000962llvm::DICompositeType
Guy Benyei11169dd2012-12-18 14:30:41 +0000963CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
964 llvm::DIFile Unit) {
David Blaikie7eb06852013-01-07 23:06:35 +0000965 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
David Blaikie2aaf0652013-01-07 22:24:59 +0000966 if (Method->isStatic())
David Blaikie469f0792013-05-22 23:22:42 +0000967 return llvm::DICompositeType(getOrCreateType(QualType(Func, 0), Unit));
David Blaikie7eb06852013-01-07 23:06:35 +0000968 return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()),
969 Func, Unit);
970}
David Blaikie2aaf0652013-01-07 22:24:59 +0000971
David Blaikie469f0792013-05-22 23:22:42 +0000972llvm::DICompositeType CGDebugInfo::getOrCreateInstanceMethodType(
David Blaikie7eb06852013-01-07 23:06:35 +0000973 QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000974 // Add "this" pointer.
David Blaikie7eb06852013-01-07 23:06:35 +0000975 llvm::DIArray Args = llvm::DICompositeType(
976 getOrCreateType(QualType(Func, 0), Unit)).getTypeArray();
Guy Benyei11169dd2012-12-18 14:30:41 +0000977 assert (Args.getNumElements() && "Invalid number of arguments!");
978
979 SmallVector<llvm::Value *, 16> Elts;
980
981 // First element is always return type. For 'void' functions it is NULL.
982 Elts.push_back(Args.getElement(0));
983
David Blaikie2aaf0652013-01-07 22:24:59 +0000984 // "this" pointer is always first argument.
David Blaikie7eb06852013-01-07 23:06:35 +0000985 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
David Blaikie2aaf0652013-01-07 22:24:59 +0000986 if (isa<ClassTemplateSpecializationDecl>(RD)) {
987 // Create pointer type directly in this case.
988 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
989 QualType PointeeTy = ThisPtrTy->getPointeeType();
990 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCallc8e01702013-04-16 22:48:15 +0000991 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
David Blaikie2aaf0652013-01-07 22:24:59 +0000992 uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy);
993 llvm::DIType PointeeType = getOrCreateType(PointeeTy, Unit);
Eric Christopher0fdcb312013-05-16 00:52:20 +0000994 llvm::DIType ThisPtrType =
995 DBuilder.createPointerType(PointeeType, Size, Align);
David Blaikie2aaf0652013-01-07 22:24:59 +0000996 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
997 // TODO: This and the artificial type below are misleading, the
998 // types aren't artificial the argument is, but the current
999 // metadata doesn't represent that.
1000 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1001 Elts.push_back(ThisPtrType);
1002 } else {
1003 llvm::DIType ThisPtrType = getOrCreateType(ThisPtr, Unit);
1004 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
1005 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1006 Elts.push_back(ThisPtrType);
Guy Benyei11169dd2012-12-18 14:30:41 +00001007 }
1008
1009 // Copy rest of the arguments.
1010 for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
1011 Elts.push_back(Args.getElement(i));
1012
1013 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
1014
Adrian Prantl0630eb72013-12-18 21:48:18 +00001015 unsigned Flags = 0;
1016 if (Func->getExtProtoInfo().RefQualifier == RQ_LValue)
1017 Flags |= llvm::DIDescriptor::FlagLValueReference;
1018 if (Func->getExtProtoInfo().RefQualifier == RQ_RValue)
1019 Flags |= llvm::DIDescriptor::FlagRValueReference;
1020
1021 return DBuilder.createSubroutineType(Unit, EltTypeArray, Flags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001022}
1023
Eric Christopherb2a008c2013-05-16 00:45:12 +00001024/// isFunctionLocalClass - Return true if CXXRecordDecl is defined
Guy Benyei11169dd2012-12-18 14:30:41 +00001025/// inside a function.
1026static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
1027 if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
1028 return isFunctionLocalClass(NRD);
1029 if (isa<FunctionDecl>(RD->getDeclContext()))
1030 return true;
1031 return false;
1032}
1033
1034/// CreateCXXMemberFunction - A helper function to create a DISubprogram for
1035/// a single member function GlobalDecl.
1036llvm::DISubprogram
1037CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
1038 llvm::DIFile Unit,
1039 llvm::DIType RecordTy) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001040 bool IsCtorOrDtor =
Guy Benyei11169dd2012-12-18 14:30:41 +00001041 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
Eric Christopherb2a008c2013-05-16 00:45:12 +00001042
Guy Benyei11169dd2012-12-18 14:30:41 +00001043 StringRef MethodName = getFunctionName(Method);
David Blaikie469f0792013-05-22 23:22:42 +00001044 llvm::DICompositeType MethodTy = getOrCreateMethodType(Method, Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00001045
1046 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1047 // make sense to give a single ctor/dtor a linkage name.
1048 StringRef MethodLinkageName;
1049 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1050 MethodLinkageName = CGM.getMangledName(Method);
1051
1052 // Get the location for the method.
David Blaikie7fceebf2013-08-19 03:37:48 +00001053 llvm::DIFile MethodDefUnit;
1054 unsigned MethodLine = 0;
1055 if (!Method->isImplicit()) {
1056 MethodDefUnit = getOrCreateFile(Method->getLocation());
1057 MethodLine = getLineNumber(Method->getLocation());
1058 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001059
1060 // Collect virtual method info.
1061 llvm::DIType ContainingType;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001062 unsigned Virtuality = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00001063 unsigned VIndex = 0;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001064
Guy Benyei11169dd2012-12-18 14:30:41 +00001065 if (Method->isVirtual()) {
1066 if (Method->isPure())
1067 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
1068 else
1069 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001070
Guy Benyei11169dd2012-12-18 14:30:41 +00001071 // It doesn't make sense to give a virtual destructor a vtable index,
1072 // since a single destructor has two entries in the vtable.
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001073 // FIXME: Add proper support for debug info for virtual calls in
1074 // the Microsoft ABI, where we may use multiple vptrs to make a vftable
1075 // lookup if we have multiple or virtual inheritance.
1076 if (!isa<CXXDestructorDecl>(Method) &&
1077 !CGM.getTarget().getCXXABI().isMicrosoft())
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001078 VIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(Method);
Guy Benyei11169dd2012-12-18 14:30:41 +00001079 ContainingType = RecordTy;
1080 }
1081
1082 unsigned Flags = 0;
1083 if (Method->isImplicit())
1084 Flags |= llvm::DIDescriptor::FlagArtificial;
1085 AccessSpecifier Access = Method->getAccess();
1086 if (Access == clang::AS_private)
1087 Flags |= llvm::DIDescriptor::FlagPrivate;
1088 else if (Access == clang::AS_protected)
1089 Flags |= llvm::DIDescriptor::FlagProtected;
1090 if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1091 if (CXXC->isExplicit())
1092 Flags |= llvm::DIDescriptor::FlagExplicit;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001093 } else if (const CXXConversionDecl *CXXC =
Guy Benyei11169dd2012-12-18 14:30:41 +00001094 dyn_cast<CXXConversionDecl>(Method)) {
1095 if (CXXC->isExplicit())
1096 Flags |= llvm::DIDescriptor::FlagExplicit;
1097 }
1098 if (Method->hasPrototype())
1099 Flags |= llvm::DIDescriptor::FlagPrototyped;
Adrian Prantl0630eb72013-12-18 21:48:18 +00001100 if (Method->getRefQualifier() == RQ_LValue)
1101 Flags |= llvm::DIDescriptor::FlagLValueReference;
1102 if (Method->getRefQualifier() == RQ_RValue)
1103 Flags |= llvm::DIDescriptor::FlagRValueReference;
Guy Benyei11169dd2012-12-18 14:30:41 +00001104
1105 llvm::DIArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1106 llvm::DISubprogram SP =
Eric Christopherb2a008c2013-05-16 00:45:12 +00001107 DBuilder.createMethod(RecordTy, MethodName, MethodLinkageName,
Guy Benyei11169dd2012-12-18 14:30:41 +00001108 MethodDefUnit, MethodLine,
Eric Christopherb2a008c2013-05-16 00:45:12 +00001109 MethodTy, /*isLocalToUnit=*/false,
Guy Benyei11169dd2012-12-18 14:30:41 +00001110 /* isDefinition=*/ false,
1111 Virtuality, VIndex, ContainingType,
1112 Flags, CGM.getLangOpts().Optimize, NULL,
1113 TParamsArray);
Eric Christopherb2a008c2013-05-16 00:45:12 +00001114
Guy Benyei11169dd2012-12-18 14:30:41 +00001115 SPCache[Method->getCanonicalDecl()] = llvm::WeakVH(SP);
1116
1117 return SP;
1118}
1119
1120/// CollectCXXMemberFunctions - A helper function to collect debug info for
Eric Christopherb2a008c2013-05-16 00:45:12 +00001121/// C++ member functions. This is used while creating debug info entry for
Guy Benyei11169dd2012-12-18 14:30:41 +00001122/// a Record.
1123void CGDebugInfo::
1124CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
1125 SmallVectorImpl<llvm::Value *> &EltTys,
1126 llvm::DIType RecordTy) {
1127
1128 // Since we want more than just the individual member decls if we
1129 // have templated functions iterate over every declaration to gather
1130 // the functions.
1131 for(DeclContext::decl_iterator I = RD->decls_begin(),
1132 E = RD->decls_end(); I != E; ++I) {
David Blaikiefae219a2013-08-28 17:27:13 +00001133 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*I)) {
David Blaikiea6cc8212013-08-28 20:58:00 +00001134 // Reuse the existing member function declaration if it exists.
David Blaikie8c8e8e22013-08-28 20:24:55 +00001135 // It may be associated with the declaration of the type & should be
1136 // reused as we're building the definition.
David Blaikiea6cc8212013-08-28 20:58:00 +00001137 //
1138 // This situation can arise in the vtable-based debug info reduction where
1139 // implicit members are emitted in a non-vtable TU.
David Blaikie6943dea2013-08-20 01:28:15 +00001140 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator MI =
1141 SPCache.find(Method->getCanonicalDecl());
David Blaikiefae219a2013-08-28 17:27:13 +00001142 if (MI == SPCache.end()) {
David Blaikie8c8e8e22013-08-28 20:24:55 +00001143 // If the member is implicit, lazily create it when we see the
1144 // definition, not before. (an ODR-used implicit default ctor that's
1145 // never actually code generated should not produce debug info)
David Blaikiefae219a2013-08-28 17:27:13 +00001146 if (!Method->isImplicit())
1147 EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
1148 } else
David Blaikie6943dea2013-08-20 01:28:15 +00001149 EltTys.push_back(MI->second);
Eric Christopherf86c4052013-08-28 23:12:10 +00001150 } else if (const FunctionTemplateDecl *FTD =
1151 dyn_cast<FunctionTemplateDecl>(*I)) {
David Blaikief2053af2013-08-28 23:06:52 +00001152 // Add any template specializations that have already been seen. Like
1153 // implicit member functions, these may have been added to a declaration
1154 // in the case of vtable-based debug info reduction.
Eric Christopherf86c4052013-08-28 23:12:10 +00001155 for (FunctionTemplateDecl::spec_iterator SI = FTD->spec_begin(),
1156 SE = FTD->spec_end();
1157 SI != SE; ++SI) {
David Blaikief2053af2013-08-28 23:06:52 +00001158 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator MI =
1159 SPCache.find(cast<CXXMethodDecl>(*SI)->getCanonicalDecl());
1160 if (MI != SPCache.end())
1161 EltTys.push_back(MI->second);
1162 }
David Blaikie6943dea2013-08-20 01:28:15 +00001163 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001164 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00001165}
Guy Benyei11169dd2012-12-18 14:30:41 +00001166
Guy Benyei11169dd2012-12-18 14:30:41 +00001167/// CollectCXXBases - A helper function to collect debug info for
Eric Christopherb2a008c2013-05-16 00:45:12 +00001168/// C++ base classes. This is used while creating debug info entry for
Guy Benyei11169dd2012-12-18 14:30:41 +00001169/// a Record.
1170void CGDebugInfo::
1171CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
1172 SmallVectorImpl<llvm::Value *> &EltTys,
1173 llvm::DIType RecordTy) {
1174
1175 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1176 for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
1177 BE = RD->bases_end(); BI != BE; ++BI) {
1178 unsigned BFlags = 0;
1179 uint64_t BaseOffset;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001180
Guy Benyei11169dd2012-12-18 14:30:41 +00001181 const CXXRecordDecl *Base =
1182 cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl());
Eric Christopherb2a008c2013-05-16 00:45:12 +00001183
Guy Benyei11169dd2012-12-18 14:30:41 +00001184 if (BI->isVirtual()) {
1185 // virtual base offset offset is -ve. The code generator emits dwarf
1186 // expression where it expects +ve number.
Eric Christopherb2a008c2013-05-16 00:45:12 +00001187 BaseOffset =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001188 0 - CGM.getItaniumVTableContext()
Guy Benyei11169dd2012-12-18 14:30:41 +00001189 .getVirtualBaseOffsetOffset(RD, Base).getQuantity();
1190 BFlags = llvm::DIDescriptor::FlagVirtual;
1191 } else
1192 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1193 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1194 // BI->isVirtual() and bits when not.
Eric Christopherb2a008c2013-05-16 00:45:12 +00001195
Guy Benyei11169dd2012-12-18 14:30:41 +00001196 AccessSpecifier Access = BI->getAccessSpecifier();
1197 if (Access == clang::AS_private)
1198 BFlags |= llvm::DIDescriptor::FlagPrivate;
1199 else if (Access == clang::AS_protected)
1200 BFlags |= llvm::DIDescriptor::FlagProtected;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001201
1202 llvm::DIType DTy =
1203 DBuilder.createInheritance(RecordTy,
Guy Benyei11169dd2012-12-18 14:30:41 +00001204 getOrCreateType(BI->getType(), Unit),
1205 BaseOffset, BFlags);
1206 EltTys.push_back(DTy);
1207 }
1208}
1209
1210/// CollectTemplateParams - A helper function to collect template parameters.
1211llvm::DIArray CGDebugInfo::
1212CollectTemplateParams(const TemplateParameterList *TPList,
David Blaikie47c11502013-06-22 18:59:18 +00001213 ArrayRef<TemplateArgument> TAList,
Guy Benyei11169dd2012-12-18 14:30:41 +00001214 llvm::DIFile Unit) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001215 SmallVector<llvm::Value *, 16> TemplateParams;
Guy Benyei11169dd2012-12-18 14:30:41 +00001216 for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1217 const TemplateArgument &TA = TAList[i];
David Blaikie47c11502013-06-22 18:59:18 +00001218 StringRef Name;
1219 if (TPList)
1220 Name = TPList->getParam(i)->getName();
David Blaikie38079fd2013-05-10 21:53:14 +00001221 switch (TA.getKind()) {
1222 case TemplateArgument::Type: {
Guy Benyei11169dd2012-12-18 14:30:41 +00001223 llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit);
1224 llvm::DITemplateTypeParameter TTP =
David Blaikie47c11502013-06-22 18:59:18 +00001225 DBuilder.createTemplateTypeParameter(TheCU, Name, TTy);
Guy Benyei11169dd2012-12-18 14:30:41 +00001226 TemplateParams.push_back(TTP);
David Blaikie38079fd2013-05-10 21:53:14 +00001227 } break;
1228 case TemplateArgument::Integral: {
Guy Benyei11169dd2012-12-18 14:30:41 +00001229 llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit);
1230 llvm::DITemplateValueParameter TVP =
David Blaikie38079fd2013-05-10 21:53:14 +00001231 DBuilder.createTemplateValueParameter(
David Blaikie47c11502013-06-22 18:59:18 +00001232 TheCU, Name, TTy,
David Blaikie38079fd2013-05-10 21:53:14 +00001233 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral()));
1234 TemplateParams.push_back(TVP);
1235 } break;
1236 case TemplateArgument::Declaration: {
1237 const ValueDecl *D = TA.getAsDecl();
1238 bool InstanceMember = D->isCXXInstanceMember();
1239 QualType T = InstanceMember
1240 ? CGM.getContext().getMemberPointerType(
1241 D->getType(), cast<RecordDecl>(D->getDeclContext())
1242 ->getTypeForDecl())
1243 : CGM.getContext().getPointerType(D->getType());
1244 llvm::DIType TTy = getOrCreateType(T, Unit);
1245 llvm::Value *V = 0;
1246 // Variable pointer template parameters have a value that is the address
1247 // of the variable.
1248 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1249 V = CGM.GetAddrOfGlobalVar(VD);
1250 // Member function pointers have special support for building them, though
1251 // this is currently unsupported in LLVM CodeGen.
David Blaikied900f982013-05-13 06:57:50 +00001252 if (InstanceMember) {
David Blaikie38079fd2013-05-10 21:53:14 +00001253 if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(D))
1254 V = CGM.getCXXABI().EmitMemberPointer(method);
David Blaikied900f982013-05-13 06:57:50 +00001255 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1256 V = CGM.GetAddrOfFunction(FD);
David Blaikie38079fd2013-05-10 21:53:14 +00001257 // Member data pointers have special handling too to compute the fixed
1258 // offset within the object.
1259 if (isa<FieldDecl>(D)) {
1260 // These five lines (& possibly the above member function pointer
1261 // handling) might be able to be refactored to use similar code in
1262 // CodeGenModule::getMemberPointerConstant
1263 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
1264 CharUnits chars =
1265 CGM.getContext().toCharUnitsFromBits((int64_t) fieldOffset);
1266 V = CGM.getCXXABI().EmitMemberDataPointer(
1267 cast<MemberPointerType>(T.getTypePtr()), chars);
1268 }
1269 llvm::DITemplateValueParameter TVP =
David Majnemera3644d62013-08-25 22:13:27 +00001270 DBuilder.createTemplateValueParameter(TheCU, Name, TTy,
1271 V->stripPointerCasts());
David Blaikie38079fd2013-05-10 21:53:14 +00001272 TemplateParams.push_back(TVP);
1273 } break;
1274 case TemplateArgument::NullPtr: {
1275 QualType T = TA.getNullPtrType();
1276 llvm::DIType TTy = getOrCreateType(T, Unit);
1277 llvm::Value *V = 0;
1278 // Special case member data pointer null values since they're actually -1
1279 // instead of zero.
1280 if (const MemberPointerType *MPT =
1281 dyn_cast<MemberPointerType>(T.getTypePtr()))
1282 // But treat member function pointers as simple zero integers because
1283 // it's easier than having a special case in LLVM's CodeGen. If LLVM
1284 // CodeGen grows handling for values of non-null member function
1285 // pointers then perhaps we could remove this special case and rely on
1286 // EmitNullMemberPointer for member function pointers.
1287 if (MPT->isMemberDataPointer())
1288 V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1289 if (!V)
1290 V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
1291 llvm::DITemplateValueParameter TVP =
David Blaikie47c11502013-06-22 18:59:18 +00001292 DBuilder.createTemplateValueParameter(TheCU, Name, TTy, V);
David Blaikie38079fd2013-05-10 21:53:14 +00001293 TemplateParams.push_back(TVP);
1294 } break;
David Blaikie47c11502013-06-22 18:59:18 +00001295 case TemplateArgument::Template: {
1296 llvm::DITemplateValueParameter TVP =
1297 DBuilder.createTemplateTemplateParameter(
1298 TheCU, Name, llvm::DIType(),
1299 TA.getAsTemplate().getAsTemplateDecl()
1300 ->getQualifiedNameAsString());
1301 TemplateParams.push_back(TVP);
1302 } break;
1303 case TemplateArgument::Pack: {
1304 llvm::DITemplateValueParameter TVP =
1305 DBuilder.createTemplateParameterPack(
1306 TheCU, Name, llvm::DIType(),
1307 CollectTemplateParams(NULL, TA.getPackAsArray(), Unit));
1308 TemplateParams.push_back(TVP);
1309 } break;
David Majnemer5559d472013-08-24 08:21:10 +00001310 case TemplateArgument::Expression: {
1311 const Expr *E = TA.getAsExpr();
1312 QualType T = E->getType();
1313 llvm::Value *V = CGM.EmitConstantExpr(E, T);
1314 assert(V && "Expression in template argument isn't constant");
1315 llvm::DIType TTy = getOrCreateType(T, Unit);
1316 llvm::DITemplateValueParameter TVP =
1317 DBuilder.createTemplateValueParameter(TheCU, Name, TTy,
1318 V->stripPointerCasts());
1319 TemplateParams.push_back(TVP);
1320 } break;
David Blaikie2b93c542013-05-10 23:36:06 +00001321 // And the following should never occur:
David Blaikie38079fd2013-05-10 21:53:14 +00001322 case TemplateArgument::TemplateExpansion:
David Blaikie38079fd2013-05-10 21:53:14 +00001323 case TemplateArgument::Null:
1324 llvm_unreachable(
1325 "These argument types shouldn't exist in concrete types");
Guy Benyei11169dd2012-12-18 14:30:41 +00001326 }
1327 }
1328 return DBuilder.getOrCreateArray(TemplateParams);
1329}
1330
1331/// CollectFunctionTemplateParams - A helper function to collect debug
1332/// info for function template parameters.
1333llvm::DIArray CGDebugInfo::
1334CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) {
1335 if (FD->getTemplatedKind() ==
1336 FunctionDecl::TK_FunctionTemplateSpecialization) {
1337 const TemplateParameterList *TList =
1338 FD->getTemplateSpecializationInfo()->getTemplate()
1339 ->getTemplateParameters();
David Blaikie47c11502013-06-22 18:59:18 +00001340 return CollectTemplateParams(
1341 TList, FD->getTemplateSpecializationArgs()->asArray(), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00001342 }
1343 return llvm::DIArray();
1344}
1345
1346/// CollectCXXTemplateParams - A helper function to collect debug info for
1347/// template parameters.
1348llvm::DIArray CGDebugInfo::
1349CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial,
1350 llvm::DIFile Unit) {
1351 llvm::PointerUnion<ClassTemplateDecl *,
1352 ClassTemplatePartialSpecializationDecl *>
1353 PU = TSpecial->getSpecializedTemplateOrPartial();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001354
Guy Benyei11169dd2012-12-18 14:30:41 +00001355 TemplateParameterList *TPList = PU.is<ClassTemplateDecl *>() ?
1356 PU.get<ClassTemplateDecl *>()->getTemplateParameters() :
1357 PU.get<ClassTemplatePartialSpecializationDecl *>()->getTemplateParameters();
1358 const TemplateArgumentList &TAList = TSpecial->getTemplateInstantiationArgs();
David Blaikie47c11502013-06-22 18:59:18 +00001359 return CollectTemplateParams(TPList, TAList.asArray(), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00001360}
1361
1362/// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
1363llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
1364 if (VTablePtrType.isValid())
1365 return VTablePtrType;
1366
1367 ASTContext &Context = CGM.getContext();
1368
1369 /* Function type */
1370 llvm::Value *STy = getOrCreateType(Context.IntTy, Unit);
1371 llvm::DIArray SElements = DBuilder.getOrCreateArray(STy);
1372 llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements);
1373 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1374 llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0,
1375 "__vtbl_ptr_type");
1376 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1377 return VTablePtrType;
1378}
1379
1380/// getVTableName - Get vtable name for the given Class.
1381StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +00001382 // Copy the gdb compatible name on the side and use its reference.
1383 return internString("_vptr$", RD->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00001384}
1385
1386
1387/// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
1388/// debug info entry in EltTys vector.
1389void CGDebugInfo::
1390CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
1391 SmallVectorImpl<llvm::Value *> &EltTys) {
1392 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1393
1394 // If there is a primary base then it will hold vtable info.
1395 if (RL.getPrimaryBase())
1396 return;
1397
1398 // If this class is not dynamic then there is not any vtable info to collect.
1399 if (!RD->isDynamicClass())
1400 return;
1401
1402 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1403 llvm::DIType VPTR
1404 = DBuilder.createMemberType(Unit, getVTableName(RD), Unit,
Eric Christopher0fdcb312013-05-16 00:52:20 +00001405 0, Size, 0, 0,
1406 llvm::DIDescriptor::FlagArtificial,
Guy Benyei11169dd2012-12-18 14:30:41 +00001407 getOrCreateVTablePtrType(Unit));
1408 EltTys.push_back(VPTR);
1409}
1410
Eric Christopherb2a008c2013-05-16 00:45:12 +00001411/// getOrCreateRecordType - Emit record type's standalone debug info.
1412llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy,
Guy Benyei11169dd2012-12-18 14:30:41 +00001413 SourceLocation Loc) {
Eric Christopher75e17682013-05-16 00:45:23 +00001414 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00001415 llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc));
1416 return T;
1417}
1418
1419/// getOrCreateInterfaceType - Emit an objective c interface type standalone
1420/// debug info.
1421llvm::DIType CGDebugInfo::getOrCreateInterfaceType(QualType D,
Eric Christopherc0c5d462013-02-21 22:35:08 +00001422 SourceLocation Loc) {
Eric Christopher75e17682013-05-16 00:45:23 +00001423 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00001424 llvm::DIType T = getOrCreateType(D, getOrCreateFile(Loc));
Adrian Prantl73409ce2013-03-11 18:33:46 +00001425 RetainedTypes.push_back(D.getAsOpaquePtr());
Guy Benyei11169dd2012-12-18 14:30:41 +00001426 return T;
1427}
1428
David Blaikieb2e86eb2013-08-15 20:49:17 +00001429void CGDebugInfo::completeType(const RecordDecl *RD) {
1430 if (DebugKind > CodeGenOptions::LimitedDebugInfo ||
1431 !CGM.getLangOpts().CPlusPlus)
1432 completeRequiredType(RD);
1433}
1434
1435void CGDebugInfo::completeRequiredType(const RecordDecl *RD) {
David Blaikie6943dea2013-08-20 01:28:15 +00001436 if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
1437 if (CXXDecl->isDynamicClass())
1438 return;
1439
David Blaikieb2e86eb2013-08-15 20:49:17 +00001440 QualType Ty = CGM.getContext().getRecordType(RD);
1441 llvm::DIType T = getTypeOrNull(Ty);
David Blaikie6943dea2013-08-20 01:28:15 +00001442 if (T && T.isForwardDecl())
1443 completeClassData(RD);
1444}
1445
1446void CGDebugInfo::completeClassData(const RecordDecl *RD) {
1447 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
Michael Gottesman349542b2013-08-19 18:46:16 +00001448 return;
David Blaikie6943dea2013-08-20 01:28:15 +00001449 QualType Ty = CGM.getContext().getRecordType(RD);
David Blaikieb2e86eb2013-08-15 20:49:17 +00001450 void* TyPtr = Ty.getAsOpaquePtr();
1451 if (CompletedTypeCache.count(TyPtr))
1452 return;
1453 llvm::DIType Res = CreateTypeDefinition(Ty->castAs<RecordType>());
1454 assert(!Res.isForwardDecl());
1455 CompletedTypeCache[TyPtr] = Res;
1456 TypeCache[TyPtr] = Res;
1457}
1458
Guy Benyei11169dd2012-12-18 14:30:41 +00001459/// CreateType - get structure or union type.
David Blaikie99dab3b2013-09-04 22:03:57 +00001460llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001461 RecordDecl *RD = Ty->getDecl();
David Blaikie6943dea2013-08-20 01:28:15 +00001462 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
David Blaikie99dab3b2013-09-04 22:03:57 +00001463 // Always emit declarations for types that aren't required to be complete when
1464 // in limit-debug-info mode. If the type is later found to be required to be
1465 // complete this declaration will be upgraded to a definition by
1466 // `completeRequiredType`.
1467 // If the type is dynamic, only emit the definition in TUs that require class
1468 // data. This is handled by `completeClassData`.
David Blaikie3b1cc9b2013-09-06 06:45:04 +00001469 llvm::DICompositeType T(getTypeOrNull(QualType(Ty, 0)));
1470 // If we've already emitted the type, just use that, even if it's only a
1471 // declaration. The completeType, completeRequiredType, and completeClassData
1472 // callbacks will handle promoting the declaration to a definition.
1473 if (T ||
Adrian Prantld09906f2014-01-07 02:40:59 +00001474 // Under -fno-standalone-debug:
David Blaikie3b1cc9b2013-09-06 06:45:04 +00001475 (DebugKind <= CodeGenOptions::LimitedDebugInfo &&
Adrian Prantla7634472014-01-07 01:19:08 +00001476 // Emit only a forward declaration unless the type is required.
1477 ((!RD->isCompleteDefinitionRequired() && CGM.getLangOpts().CPlusPlus) ||
1478 // If the class is dynamic, only emit a declaration. A definition will be
1479 // emitted whenever the vtable is emitted.
1480 (CXXDecl && CXXDecl->hasDefinition() && CXXDecl->isDynamicClass())))) {
David Blaikie3b1cc9b2013-09-06 06:45:04 +00001481 if (!T)
David Blaikie65ec94e2014-02-18 20:52:05 +00001482 T = getOrCreateRecordFwdDecl(
1483 Ty, getContextDescriptor(cast<Decl>(RD->getDeclContext())));
David Blaikie3b1cc9b2013-09-06 06:45:04 +00001484 return T;
David Blaikiee36464c2013-06-05 05:32:23 +00001485 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001486
David Blaikieb2e86eb2013-08-15 20:49:17 +00001487 return CreateTypeDefinition(Ty);
1488}
1489
1490llvm::DIType CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {
1491 RecordDecl *RD = Ty->getDecl();
1492
Guy Benyei11169dd2012-12-18 14:30:41 +00001493 // Get overall information about the record type for the debug info.
1494 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1495
1496 // Records and classes and unions can all be recursive. To handle them, we
1497 // first generate a debug descriptor for the struct as a forward declaration.
1498 // Then (if it is a definition) we go through and get debug info for all of
1499 // its members. Finally, we create a descriptor for the complete type (which
1500 // may refer to the forward decl if the struct is recursive) and replace all
1501 // uses of the forward declaration with the final definition.
1502
David Blaikie4a2b5ef2013-08-12 22:24:20 +00001503 llvm::DICompositeType FwdDecl(getOrCreateLimitedType(Ty, DefUnit));
Manman Ren0d441f12013-07-02 19:01:53 +00001504 assert(FwdDecl.isCompositeType() &&
David Blaikie469f0792013-05-22 23:22:42 +00001505 "The debug type of a RecordType should be a llvm::DICompositeType");
Guy Benyei11169dd2012-12-18 14:30:41 +00001506
1507 if (FwdDecl.isForwardDecl())
1508 return FwdDecl;
1509
David Blaikieadfbf992013-08-18 16:55:33 +00001510 if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
1511 CollectContainingType(CXXDecl, FwdDecl);
1512
Guy Benyei11169dd2012-12-18 14:30:41 +00001513 // Push the struct on region stack.
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001514 LexicalBlockStack.push_back(&*FwdDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00001515 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1516
Adrian Prantla03a85a2013-03-06 22:03:30 +00001517 // Add this to the completed-type cache while we're completing it recursively.
Guy Benyei11169dd2012-12-18 14:30:41 +00001518 CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1519
1520 // Convert all the elements.
1521 SmallVector<llvm::Value *, 16> EltTys;
David Blaikie6943dea2013-08-20 01:28:15 +00001522 // what about nested types?
Guy Benyei11169dd2012-12-18 14:30:41 +00001523
1524 // Note: The split of CXXDecl information here is intentional, the
1525 // gdb tests will depend on a certain ordering at printout. The debug
1526 // information offsets are still correct if we merge them all together
1527 // though.
1528 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1529 if (CXXDecl) {
1530 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1531 CollectVTableInfo(CXXDecl, DefUnit, EltTys);
1532 }
1533
Eric Christopher91a31902013-01-16 01:22:32 +00001534 // Collect data fields (including static variables and any initializers).
Guy Benyei11169dd2012-12-18 14:30:41 +00001535 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
Eric Christopher2df080e2013-10-11 18:16:51 +00001536 if (CXXDecl)
Guy Benyei11169dd2012-12-18 14:30:41 +00001537 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00001538
1539 LexicalBlockStack.pop_back();
1540 RegionMap.erase(Ty->getDecl());
1541
1542 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
David Blaikie4a5b8952013-08-01 20:31:40 +00001543 FwdDecl.setTypeArray(Elements);
Guy Benyei11169dd2012-12-18 14:30:41 +00001544
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001545 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1546 return FwdDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00001547}
1548
1549/// CreateType - get objective-c object type.
1550llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1551 llvm::DIFile Unit) {
1552 // Ignore protocols.
1553 return getOrCreateType(Ty->getBaseType(), Unit);
1554}
1555
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001556
1557/// \return true if Getter has the default name for the property PD.
1558static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
1559 const ObjCMethodDecl *Getter) {
1560 assert(PD);
1561 if (!Getter)
1562 return true;
1563
1564 assert(Getter->getDeclName().isObjCZeroArgSelector());
1565 return PD->getName() ==
1566 Getter->getDeclName().getObjCSelector().getNameForSlot(0);
1567}
1568
1569/// \return true if Setter has the default name for the property PD.
1570static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
1571 const ObjCMethodDecl *Setter) {
1572 assert(PD);
1573 if (!Setter)
1574 return true;
1575
1576 assert(Setter->getDeclName().isObjCOneArgSelector());
Adrian Prantla4ce9062013-06-07 22:29:12 +00001577 return SelectorTable::constructSetterName(PD->getName()) ==
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001578 Setter->getDeclName().getObjCSelector().getNameForSlot(0);
1579}
1580
Guy Benyei11169dd2012-12-18 14:30:41 +00001581/// CreateType - get objective-c interface type.
1582llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1583 llvm::DIFile Unit) {
1584 ObjCInterfaceDecl *ID = Ty->getDecl();
1585 if (!ID)
1586 return llvm::DIType();
1587
1588 // Get overall information about the record type for the debug info.
1589 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1590 unsigned Line = getLineNumber(ID->getLocation());
1591 unsigned RuntimeLang = TheCU.getLanguage();
1592
1593 // If this is just a forward declaration return a special forward-declaration
1594 // debug type since we won't be able to lay out the entire type.
1595 ObjCInterfaceDecl *Def = ID->getDefinition();
1596 if (!Def) {
1597 llvm::DIType FwdDecl =
1598 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
Eric Christopherc0c5d462013-02-21 22:35:08 +00001599 ID->getName(), TheCU, DefUnit, Line,
1600 RuntimeLang);
Guy Benyei11169dd2012-12-18 14:30:41 +00001601 return FwdDecl;
1602 }
1603
1604 ID = Def;
1605
1606 // Bit size, align and offset of the type.
1607 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1608 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1609
1610 unsigned Flags = 0;
1611 if (ID->getImplementation())
1612 Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
1613
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001614 llvm::DICompositeType RealDecl =
Guy Benyei11169dd2012-12-18 14:30:41 +00001615 DBuilder.createStructType(Unit, ID->getName(), DefUnit,
1616 Line, Size, Align, Flags,
David Blaikie6d4fe152013-02-25 01:07:08 +00001617 llvm::DIType(), llvm::DIArray(), RuntimeLang);
Guy Benyei11169dd2012-12-18 14:30:41 +00001618
1619 // Otherwise, insert it into the CompletedTypeCache so that recursive uses
1620 // will find it and we're emitting the complete type.
Adrian Prantla03a85a2013-03-06 22:03:30 +00001621 QualType QualTy = QualType(Ty, 0);
1622 CompletedTypeCache[QualTy.getAsOpaquePtr()] = RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00001623
Eric Christopher35f1f9f2013-07-14 21:00:07 +00001624 // Push the struct on region stack.
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001625 LexicalBlockStack.push_back(static_cast<llvm::MDNode*>(RealDecl));
Guy Benyei11169dd2012-12-18 14:30:41 +00001626 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1627
1628 // Convert all the elements.
1629 SmallVector<llvm::Value *, 16> EltTys;
1630
1631 ObjCInterfaceDecl *SClass = ID->getSuperClass();
1632 if (SClass) {
1633 llvm::DIType SClassTy =
1634 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1635 if (!SClassTy.isValid())
1636 return llvm::DIType();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001637
Guy Benyei11169dd2012-12-18 14:30:41 +00001638 llvm::DIType InhTag =
1639 DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
1640 EltTys.push_back(InhTag);
1641 }
1642
Eric Christopher35f1f9f2013-07-14 21:00:07 +00001643 // Create entries for all of the properties.
Guy Benyei11169dd2012-12-18 14:30:41 +00001644 for (ObjCContainerDecl::prop_iterator I = ID->prop_begin(),
1645 E = ID->prop_end(); I != E; ++I) {
1646 const ObjCPropertyDecl *PD = *I;
1647 SourceLocation Loc = PD->getLocation();
1648 llvm::DIFile PUnit = getOrCreateFile(Loc);
1649 unsigned PLine = getLineNumber(Loc);
1650 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1651 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1652 llvm::MDNode *PropertyNode =
1653 DBuilder.createObjCProperty(PD->getName(),
Eric Christopherc0c5d462013-02-21 22:35:08 +00001654 PUnit, PLine,
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001655 hasDefaultGetterName(PD, Getter) ? "" :
Guy Benyei11169dd2012-12-18 14:30:41 +00001656 getSelectorName(PD->getGetterName()),
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001657 hasDefaultSetterName(PD, Setter) ? "" :
Guy Benyei11169dd2012-12-18 14:30:41 +00001658 getSelectorName(PD->getSetterName()),
1659 PD->getPropertyAttributes(),
Eric Christopherc0c5d462013-02-21 22:35:08 +00001660 getOrCreateType(PD->getType(), PUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00001661 EltTys.push_back(PropertyNode);
1662 }
1663
1664 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1665 unsigned FieldNo = 0;
1666 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1667 Field = Field->getNextIvar(), ++FieldNo) {
1668 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1669 if (!FieldTy.isValid())
1670 return llvm::DIType();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001671
Guy Benyei11169dd2012-12-18 14:30:41 +00001672 StringRef FieldName = Field->getName();
1673
1674 // Ignore unnamed fields.
1675 if (FieldName.empty())
1676 continue;
1677
1678 // Get the location for the field.
1679 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1680 unsigned FieldLine = getLineNumber(Field->getLocation());
1681 QualType FType = Field->getType();
1682 uint64_t FieldSize = 0;
1683 unsigned FieldAlign = 0;
1684
1685 if (!FType->isIncompleteArrayType()) {
1686
1687 // Bit size, align and offset of the type.
1688 FieldSize = Field->isBitField()
Eric Christopher35f1f9f2013-07-14 21:00:07 +00001689 ? Field->getBitWidthValue(CGM.getContext())
1690 : CGM.getContext().getTypeSize(FType);
Guy Benyei11169dd2012-12-18 14:30:41 +00001691 FieldAlign = CGM.getContext().getTypeAlign(FType);
1692 }
1693
1694 uint64_t FieldOffset;
1695 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1696 // We don't know the runtime offset of an ivar if we're using the
1697 // non-fragile ABI. For bitfields, use the bit offset into the first
1698 // byte of storage of the bitfield. For other fields, use zero.
1699 if (Field->isBitField()) {
1700 FieldOffset = CGM.getObjCRuntime().ComputeBitfieldBitOffset(
1701 CGM, ID, Field);
1702 FieldOffset %= CGM.getContext().getCharWidth();
1703 } else {
1704 FieldOffset = 0;
1705 }
1706 } else {
1707 FieldOffset = RL.getFieldOffset(FieldNo);
1708 }
1709
1710 unsigned Flags = 0;
1711 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1712 Flags = llvm::DIDescriptor::FlagProtected;
1713 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1714 Flags = llvm::DIDescriptor::FlagPrivate;
1715
1716 llvm::MDNode *PropertyNode = NULL;
1717 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001718 if (ObjCPropertyImplDecl *PImpD =
Guy Benyei11169dd2012-12-18 14:30:41 +00001719 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
1720 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
Eric Christopherc0c5d462013-02-21 22:35:08 +00001721 SourceLocation Loc = PD->getLocation();
1722 llvm::DIFile PUnit = getOrCreateFile(Loc);
1723 unsigned PLine = getLineNumber(Loc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001724 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1725 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1726 PropertyNode =
1727 DBuilder.createObjCProperty(PD->getName(),
1728 PUnit, PLine,
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001729 hasDefaultGetterName(PD, Getter) ? "" :
Guy Benyei11169dd2012-12-18 14:30:41 +00001730 getSelectorName(PD->getGetterName()),
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001731 hasDefaultSetterName(PD, Setter) ? "" :
Guy Benyei11169dd2012-12-18 14:30:41 +00001732 getSelectorName(PD->getSetterName()),
1733 PD->getPropertyAttributes(),
1734 getOrCreateType(PD->getType(), PUnit));
1735 }
1736 }
1737 }
1738 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
1739 FieldLine, FieldSize, FieldAlign,
1740 FieldOffset, Flags, FieldTy,
1741 PropertyNode);
1742 EltTys.push_back(FieldTy);
1743 }
1744
1745 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001746 RealDecl.setTypeArray(Elements);
Adrian Prantla03a85a2013-03-06 22:03:30 +00001747
1748 // If the implementation is not yet set, we do not want to mark it
1749 // as complete. An implementation may declare additional
1750 // private ivars that we would miss otherwise.
1751 if (ID->getImplementation() == 0)
1752 CompletedTypeCache.erase(QualTy.getAsOpaquePtr());
Eric Christopherb2a008c2013-05-16 00:45:12 +00001753
Guy Benyei11169dd2012-12-18 14:30:41 +00001754 LexicalBlockStack.pop_back();
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001755 return RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00001756}
1757
1758llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) {
1759 llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1760 int64_t Count = Ty->getNumElements();
1761 if (Count == 0)
1762 // If number of elements are not known then this is an unbounded array.
1763 // Use Count == -1 to express such arrays.
1764 Count = -1;
1765
1766 llvm::Value *Subscript = DBuilder.getOrCreateSubrange(0, Count);
1767 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1768
1769 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1770 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1771
1772 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1773}
1774
1775llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1776 llvm::DIFile Unit) {
1777 uint64_t Size;
1778 uint64_t Align;
1779
1780 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1781 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1782 Size = 0;
1783 Align =
1784 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1785 } else if (Ty->isIncompleteArrayType()) {
1786 Size = 0;
1787 if (Ty->getElementType()->isIncompleteType())
1788 Align = 0;
1789 else
1790 Align = CGM.getContext().getTypeAlign(Ty->getElementType());
David Blaikief03b2e82013-05-09 20:48:12 +00001791 } else if (Ty->isIncompleteType()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001792 Size = 0;
1793 Align = 0;
1794 } else {
1795 // Size and align of the whole array, not the element type.
1796 Size = CGM.getContext().getTypeSize(Ty);
1797 Align = CGM.getContext().getTypeAlign(Ty);
1798 }
1799
1800 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
1801 // interior arrays, do we care? Why aren't nested arrays represented the
1802 // obvious/recursive way?
1803 SmallVector<llvm::Value *, 8> Subscripts;
1804 QualType EltTy(Ty, 0);
1805 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1806 // If the number of elements is known, then count is that number. Otherwise,
1807 // it's -1. This allows us to represent a subrange with an array of 0
1808 // elements, like this:
1809 //
1810 // struct foo {
1811 // int x[0];
1812 // };
1813 int64_t Count = -1; // Count == -1 is an unbounded array.
1814 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1815 Count = CAT->getSize().getZExtValue();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001816
Guy Benyei11169dd2012-12-18 14:30:41 +00001817 // FIXME: Verify this is right for VLAs.
1818 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
1819 EltTy = Ty->getElementType();
1820 }
1821
1822 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1823
Eric Christopherb2a008c2013-05-16 00:45:12 +00001824 llvm::DIType DbgTy =
Guy Benyei11169dd2012-12-18 14:30:41 +00001825 DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1826 SubscriptArray);
1827 return DbgTy;
1828}
1829
Eric Christopherb2a008c2013-05-16 00:45:12 +00001830llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +00001831 llvm::DIFile Unit) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001832 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
Guy Benyei11169dd2012-12-18 14:30:41 +00001833 Ty, Ty->getPointeeType(), Unit);
1834}
1835
Eric Christopherb2a008c2013-05-16 00:45:12 +00001836llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +00001837 llvm::DIFile Unit) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001838 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
Guy Benyei11169dd2012-12-18 14:30:41 +00001839 Ty, Ty->getPointeeType(), Unit);
1840}
1841
Eric Christopherb2a008c2013-05-16 00:45:12 +00001842llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +00001843 llvm::DIFile U) {
David Blaikie2c705ca2013-01-19 19:20:56 +00001844 llvm::DIType ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
1845 if (!Ty->getPointeeType()->isFunctionType())
1846 return DBuilder.createMemberPointerType(
David Blaikie99dab3b2013-09-04 22:03:57 +00001847 getOrCreateType(Ty->getPointeeType(), U), ClassType);
Adrian Prantl0866acd2013-12-19 01:38:47 +00001848
1849 const FunctionProtoType *FPT =
1850 Ty->getPointeeType()->getAs<FunctionProtoType>();
David Blaikie2c705ca2013-01-19 19:20:56 +00001851 return DBuilder.createMemberPointerType(getOrCreateInstanceMethodType(
Adrian Prantl0866acd2013-12-19 01:38:47 +00001852 CGM.getContext().getPointerType(QualType(Ty->getClass(),
1853 FPT->getTypeQuals())),
1854 FPT, U), ClassType);
Guy Benyei11169dd2012-12-18 14:30:41 +00001855}
1856
Eric Christopherb2a008c2013-05-16 00:45:12 +00001857llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +00001858 llvm::DIFile U) {
1859 // Ignore the atomic wrapping
1860 // FIXME: What is the correct representation?
1861 return getOrCreateType(Ty->getValueType(), U);
1862}
1863
1864/// CreateEnumType - get enumeration type.
Manman Ren501ecf92013-08-28 21:46:36 +00001865llvm::DIType CGDebugInfo::CreateEnumType(const EnumType *Ty) {
Manman Ren1b457022013-08-28 21:20:28 +00001866 const EnumDecl *ED = Ty->getDecl();
Guy Benyei11169dd2012-12-18 14:30:41 +00001867 uint64_t Size = 0;
1868 uint64_t Align = 0;
1869 if (!ED->getTypeForDecl()->isIncompleteType()) {
1870 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1871 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1872 }
1873
Manman Rene0064d82013-08-29 23:19:58 +00001874 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
1875
Guy Benyei11169dd2012-12-18 14:30:41 +00001876 // If this is just a forward declaration, construct an appropriately
1877 // marked node and just return it.
1878 if (!ED->getDefinition()) {
1879 llvm::DIDescriptor EDContext;
1880 EDContext = getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1881 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1882 unsigned Line = getLineNumber(ED->getLocation());
1883 StringRef EDName = ED->getName();
1884 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_enumeration_type,
1885 EDName, EDContext, DefUnit, Line, 0,
Manman Rene0064d82013-08-29 23:19:58 +00001886 Size, Align, FullName);
Guy Benyei11169dd2012-12-18 14:30:41 +00001887 }
1888
1889 // Create DIEnumerator elements for each enumerator.
1890 SmallVector<llvm::Value *, 16> Enumerators;
1891 ED = ED->getDefinition();
1892 for (EnumDecl::enumerator_iterator
1893 Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
1894 Enum != EnumEnd; ++Enum) {
1895 Enumerators.push_back(
1896 DBuilder.createEnumerator(Enum->getName(),
David Blaikiece1ae382013-06-24 07:13:13 +00001897 Enum->getInitVal().getSExtValue()));
Guy Benyei11169dd2012-12-18 14:30:41 +00001898 }
1899
1900 // Return a CompositeType for the enum itself.
1901 llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1902
1903 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1904 unsigned Line = getLineNumber(ED->getLocation());
Eric Christopherb2a008c2013-05-16 00:45:12 +00001905 llvm::DIDescriptor EnumContext =
Guy Benyei11169dd2012-12-18 14:30:41 +00001906 getContextDescriptor(cast<Decl>(ED->getDeclContext()));
Adrian Prantlc60dc712013-04-19 19:56:39 +00001907 llvm::DIType ClassTy = ED->isFixed() ?
Guy Benyei11169dd2012-12-18 14:30:41 +00001908 getOrCreateType(ED->getIntegerType(), DefUnit) : llvm::DIType();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001909 llvm::DIType DbgTy =
Guy Benyei11169dd2012-12-18 14:30:41 +00001910 DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1911 Size, Align, EltArray,
Manman Rene0064d82013-08-29 23:19:58 +00001912 ClassTy, FullName);
Guy Benyei11169dd2012-12-18 14:30:41 +00001913 return DbgTy;
1914}
1915
David Blaikie05491062013-01-21 04:37:12 +00001916static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
1917 Qualifiers Quals;
Guy Benyei11169dd2012-12-18 14:30:41 +00001918 do {
Adrian Prantl179af902013-09-26 21:35:50 +00001919 Qualifiers InnerQuals = T.getLocalQualifiers();
1920 // Qualifiers::operator+() doesn't like it if you add a Qualifier
1921 // that is already there.
1922 Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals);
1923 Quals += InnerQuals;
Guy Benyei11169dd2012-12-18 14:30:41 +00001924 QualType LastT = T;
1925 switch (T->getTypeClass()) {
1926 default:
David Blaikie05491062013-01-21 04:37:12 +00001927 return C.getQualifiedType(T.getTypePtr(), Quals);
Guy Benyei11169dd2012-12-18 14:30:41 +00001928 case Type::TemplateSpecialization:
1929 T = cast<TemplateSpecializationType>(T)->desugar();
1930 break;
1931 case Type::TypeOfExpr:
1932 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1933 break;
1934 case Type::TypeOf:
1935 T = cast<TypeOfType>(T)->getUnderlyingType();
1936 break;
1937 case Type::Decltype:
1938 T = cast<DecltypeType>(T)->getUnderlyingType();
1939 break;
1940 case Type::UnaryTransform:
1941 T = cast<UnaryTransformType>(T)->getUnderlyingType();
1942 break;
1943 case Type::Attributed:
1944 T = cast<AttributedType>(T)->getEquivalentType();
1945 break;
1946 case Type::Elaborated:
1947 T = cast<ElaboratedType>(T)->getNamedType();
1948 break;
1949 case Type::Paren:
1950 T = cast<ParenType>(T)->getInnerType();
1951 break;
David Blaikie05491062013-01-21 04:37:12 +00001952 case Type::SubstTemplateTypeParm:
Guy Benyei11169dd2012-12-18 14:30:41 +00001953 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
Guy Benyei11169dd2012-12-18 14:30:41 +00001954 break;
1955 case Type::Auto:
David Blaikie22c460a02013-05-24 21:24:35 +00001956 QualType DT = cast<AutoType>(T)->getDeducedType();
1957 if (DT.isNull())
1958 return T;
1959 T = DT;
Guy Benyei11169dd2012-12-18 14:30:41 +00001960 break;
1961 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00001962
Guy Benyei11169dd2012-12-18 14:30:41 +00001963 assert(T != LastT && "Type unwrapping failed to unwrap!");
NAKAMURA Takumi3e0a3632013-01-21 10:51:28 +00001964 (void)LastT;
Guy Benyei11169dd2012-12-18 14:30:41 +00001965 } while (true);
1966}
1967
Eric Christopher0fdcb312013-05-16 00:52:20 +00001968/// getType - Get the type from the cache or return null type if it doesn't
1969/// exist.
Guy Benyei11169dd2012-12-18 14:30:41 +00001970llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) {
1971
1972 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00001973 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Eric Christopherb2a008c2013-05-16 00:45:12 +00001974
Guy Benyei11169dd2012-12-18 14:30:41 +00001975 // Check for existing entry.
Adrian Prantl73409ce2013-03-11 18:33:46 +00001976 if (Ty->getTypeClass() == Type::ObjCInterface) {
1977 llvm::Value *V = getCachedInterfaceTypeOrNull(Ty);
1978 if (V)
1979 return llvm::DIType(cast<llvm::MDNode>(V));
1980 else return llvm::DIType();
1981 }
1982
Guy Benyei11169dd2012-12-18 14:30:41 +00001983 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1984 TypeCache.find(Ty.getAsOpaquePtr());
1985 if (it != TypeCache.end()) {
1986 // Verify that the debug info still exists.
1987 if (llvm::Value *V = it->second)
1988 return llvm::DIType(cast<llvm::MDNode>(V));
1989 }
1990
1991 return llvm::DIType();
1992}
1993
1994/// getCompletedTypeOrNull - Get the type from the cache or return null if it
1995/// doesn't exist.
1996llvm::DIType CGDebugInfo::getCompletedTypeOrNull(QualType Ty) {
1997
1998 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00001999 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00002000
2001 // Check for existing entry.
Adrian Prantla03a85a2013-03-06 22:03:30 +00002002 llvm::Value *V = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00002003 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
2004 CompletedTypeCache.find(Ty.getAsOpaquePtr());
Adrian Prantla03a85a2013-03-06 22:03:30 +00002005 if (it != CompletedTypeCache.end())
2006 V = it->second;
2007 else {
Adrian Prantl73409ce2013-03-11 18:33:46 +00002008 V = getCachedInterfaceTypeOrNull(Ty);
Guy Benyei11169dd2012-12-18 14:30:41 +00002009 }
2010
Adrian Prantla03a85a2013-03-06 22:03:30 +00002011 // Verify that any cached debug info still exists.
David Blaikie80d28de2013-08-13 04:21:38 +00002012 return llvm::DIType(cast_or_null<llvm::MDNode>(V));
Guy Benyei11169dd2012-12-18 14:30:41 +00002013}
2014
Adrian Prantl73409ce2013-03-11 18:33:46 +00002015/// getCachedInterfaceTypeOrNull - Get the type from the interface
2016/// cache, unless it needs to regenerated. Otherwise return null.
2017llvm::Value *CGDebugInfo::getCachedInterfaceTypeOrNull(QualType Ty) {
2018 // Is there a cached interface that hasn't changed?
2019 llvm::DenseMap<void *, std::pair<llvm::WeakVH, unsigned > >
2020 ::iterator it1 = ObjCInterfaceCache.find(Ty.getAsOpaquePtr());
2021
2022 if (it1 != ObjCInterfaceCache.end())
2023 if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty))
2024 if (Checksum(Decl) == it1->second.second)
2025 // Return cached forward declaration.
2026 return it1->second.first;
2027
2028 return 0;
2029}
Guy Benyei11169dd2012-12-18 14:30:41 +00002030
2031/// getOrCreateType - Get the type from the cache or create a new
2032/// one if necessary.
David Blaikie99dab3b2013-09-04 22:03:57 +00002033llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002034 if (Ty.isNull())
2035 return llvm::DIType();
2036
2037 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00002038 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00002039
David Blaikie99dab3b2013-09-04 22:03:57 +00002040 if (llvm::DIType T = getCompletedTypeOrNull(Ty))
Guy Benyei11169dd2012-12-18 14:30:41 +00002041 return T;
2042
2043 // Otherwise create the type.
David Blaikie99dab3b2013-09-04 22:03:57 +00002044 llvm::DIType Res = CreateTypeNode(Ty, Unit);
Adrian Prantl73409ce2013-03-11 18:33:46 +00002045 void* TyPtr = Ty.getAsOpaquePtr();
2046
2047 // And update the type cache.
2048 TypeCache[TyPtr] = Res;
Guy Benyei11169dd2012-12-18 14:30:41 +00002049
David Blaikie6a723442013-08-15 21:21:19 +00002050 // FIXME: this getTypeOrNull call seems silly when we just inserted the type
2051 // into the cache - but getTypeOrNull has a special case for cached interface
2052 // types. We should probably just pull that out as a special case for the
2053 // "else" block below & skip the otherwise needless lookup.
Guy Benyei11169dd2012-12-18 14:30:41 +00002054 llvm::DIType TC = getTypeOrNull(Ty);
Eric Christopherf8bc4d82013-07-18 00:52:50 +00002055 if (TC && TC.isForwardDecl())
Adrian Prantl73409ce2013-03-11 18:33:46 +00002056 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
2057 else if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty)) {
2058 // Interface types may have elements added to them by a
2059 // subsequent implementation or extension, so we keep them in
2060 // the ObjCInterfaceCache together with a checksum. Instead of
Adrian Prantlc20237d2013-05-08 23:37:22 +00002061 // the (possibly) incomplete interface type, we return a forward
Adrian Prantl73409ce2013-03-11 18:33:46 +00002062 // declaration that gets RAUW'd in CGDebugInfo::finalize().
David Blaikie8e5939b2013-05-21 18:29:40 +00002063 std::pair<llvm::WeakVH, unsigned> &V = ObjCInterfaceCache[TyPtr];
2064 if (V.first)
2065 return llvm::DIType(cast<llvm::MDNode>(V.first));
2066 TC = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
2067 Decl->getName(), TheCU, Unit,
2068 getLineNumber(Decl->getLocation()),
2069 TheCU.getLanguage());
2070 // Store the forward declaration in the cache.
2071 V.first = TC;
2072 V.second = Checksum(Decl);
Adrian Prantl73409ce2013-03-11 18:33:46 +00002073
David Blaikie8e5939b2013-05-21 18:29:40 +00002074 // Register the type for replacement in finalize().
2075 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
2076
Adrian Prantl73409ce2013-03-11 18:33:46 +00002077 return TC;
Adrian Prantla03a85a2013-03-06 22:03:30 +00002078 }
2079
Guy Benyei11169dd2012-12-18 14:30:41 +00002080 if (!Res.isForwardDecl())
Adrian Prantl73409ce2013-03-11 18:33:46 +00002081 CompletedTypeCache[TyPtr] = Res;
Guy Benyei11169dd2012-12-18 14:30:41 +00002082
2083 return Res;
2084}
2085
Adrian Prantlc4de1ef2013-06-07 01:10:41 +00002086/// Currently the checksum of an interface includes the number of
2087/// ivars and property accessors.
Eric Christopher1ecc5632013-06-07 22:54:39 +00002088unsigned CGDebugInfo::Checksum(const ObjCInterfaceDecl *ID) {
Adrian Prantl817bbb32013-06-07 01:10:48 +00002089 // The assumption is that the number of ivars can only increase
2090 // monotonically, so it is safe to just use their current number as
2091 // a checksum.
Adrian Prantlc4de1ef2013-06-07 01:10:41 +00002092 unsigned Sum = 0;
2093 for (const ObjCIvarDecl *Ivar = ID->all_declared_ivar_begin();
2094 Ivar != 0; Ivar = Ivar->getNextIvar())
2095 ++Sum;
2096
2097 return Sum;
Adrian Prantla03a85a2013-03-06 22:03:30 +00002098}
2099
2100ObjCInterfaceDecl *CGDebugInfo::getObjCInterfaceDecl(QualType Ty) {
2101 switch (Ty->getTypeClass()) {
2102 case Type::ObjCObjectPointer:
Eric Christopher0fdcb312013-05-16 00:52:20 +00002103 return getObjCInterfaceDecl(cast<ObjCObjectPointerType>(Ty)
2104 ->getPointeeType());
Adrian Prantla03a85a2013-03-06 22:03:30 +00002105 case Type::ObjCInterface:
2106 return cast<ObjCInterfaceType>(Ty)->getDecl();
2107 default:
2108 return 0;
2109 }
2110}
2111
Guy Benyei11169dd2012-12-18 14:30:41 +00002112/// CreateTypeNode - Create a new debug type node.
David Blaikie99dab3b2013-09-04 22:03:57 +00002113llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002114 // Handle qualifiers, which recursively handles what they refer to.
2115 if (Ty.hasLocalQualifiers())
David Blaikie99dab3b2013-09-04 22:03:57 +00002116 return CreateQualifiedType(Ty, Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00002117
2118 const char *Diag = 0;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002119
Guy Benyei11169dd2012-12-18 14:30:41 +00002120 // Work out details of type.
2121 switch (Ty->getTypeClass()) {
2122#define TYPE(Class, Base)
2123#define ABSTRACT_TYPE(Class, Base)
2124#define NON_CANONICAL_TYPE(Class, Base)
2125#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2126#include "clang/AST/TypeNodes.def"
2127 llvm_unreachable("Dependent types cannot show up in debug information");
2128
2129 case Type::ExtVector:
2130 case Type::Vector:
2131 return CreateType(cast<VectorType>(Ty), Unit);
2132 case Type::ObjCObjectPointer:
2133 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
2134 case Type::ObjCObject:
2135 return CreateType(cast<ObjCObjectType>(Ty), Unit);
2136 case Type::ObjCInterface:
2137 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
2138 case Type::Builtin:
2139 return CreateType(cast<BuiltinType>(Ty));
2140 case Type::Complex:
2141 return CreateType(cast<ComplexType>(Ty));
2142 case Type::Pointer:
2143 return CreateType(cast<PointerType>(Ty), Unit);
Reid Kleckner0503a872013-12-05 01:23:43 +00002144 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00002145 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00002146 // Decayed and adjusted types use the adjusted type in LLVM and DWARF.
Reid Kleckner8a365022013-06-24 17:51:48 +00002147 return CreateType(
Reid Kleckner0503a872013-12-05 01:23:43 +00002148 cast<PointerType>(cast<AdjustedType>(Ty)->getAdjustedType()), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00002149 case Type::BlockPointer:
2150 return CreateType(cast<BlockPointerType>(Ty), Unit);
2151 case Type::Typedef:
David Blaikie99dab3b2013-09-04 22:03:57 +00002152 return CreateType(cast<TypedefType>(Ty), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00002153 case Type::Record:
David Blaikie99dab3b2013-09-04 22:03:57 +00002154 return CreateType(cast<RecordType>(Ty));
Guy Benyei11169dd2012-12-18 14:30:41 +00002155 case Type::Enum:
Manman Ren1b457022013-08-28 21:20:28 +00002156 return CreateEnumType(cast<EnumType>(Ty));
Guy Benyei11169dd2012-12-18 14:30:41 +00002157 case Type::FunctionProto:
2158 case Type::FunctionNoProto:
2159 return CreateType(cast<FunctionType>(Ty), Unit);
2160 case Type::ConstantArray:
2161 case Type::VariableArray:
2162 case Type::IncompleteArray:
2163 return CreateType(cast<ArrayType>(Ty), Unit);
2164
2165 case Type::LValueReference:
2166 return CreateType(cast<LValueReferenceType>(Ty), Unit);
2167 case Type::RValueReference:
2168 return CreateType(cast<RValueReferenceType>(Ty), Unit);
2169
2170 case Type::MemberPointer:
2171 return CreateType(cast<MemberPointerType>(Ty), Unit);
2172
2173 case Type::Atomic:
2174 return CreateType(cast<AtomicType>(Ty), Unit);
2175
2176 case Type::Attributed:
2177 case Type::TemplateSpecialization:
2178 case Type::Elaborated:
2179 case Type::Paren:
2180 case Type::SubstTemplateTypeParm:
2181 case Type::TypeOfExpr:
2182 case Type::TypeOf:
2183 case Type::Decltype:
2184 case Type::UnaryTransform:
David Blaikie66ed89d2013-07-13 21:08:08 +00002185 case Type::PackExpansion:
Guy Benyei11169dd2012-12-18 14:30:41 +00002186 llvm_unreachable("type should have been unwrapped!");
David Blaikie22c460a02013-05-24 21:24:35 +00002187 case Type::Auto:
2188 Diag = "auto";
2189 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002190 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00002191
Guy Benyei11169dd2012-12-18 14:30:41 +00002192 assert(Diag && "Fall through without a diagnostic?");
2193 unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error,
2194 "debug information for %0 is not yet supported");
2195 CGM.getDiags().Report(DiagID)
2196 << Diag;
2197 return llvm::DIType();
2198}
2199
2200/// getOrCreateLimitedType - Get the type from the cache or create a new
2201/// limited type if necessary.
David Blaikie4a2b5ef2013-08-12 22:24:20 +00002202llvm::DIType CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty,
Eric Christopherc0c5d462013-02-21 22:35:08 +00002203 llvm::DIFile Unit) {
David Blaikie4a2b5ef2013-08-12 22:24:20 +00002204 QualType QTy(Ty, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00002205
David Blaikie8d5e1282013-08-20 21:03:29 +00002206 llvm::DICompositeType T(getTypeOrNull(QTy));
Guy Benyei11169dd2012-12-18 14:30:41 +00002207
2208 // We may have cached a forward decl when we could have created
2209 // a non-forward decl. Go ahead and create a non-forward decl
2210 // now.
Eric Christopherf8bc4d82013-07-18 00:52:50 +00002211 if (T && !T.isForwardDecl()) return T;
Guy Benyei11169dd2012-12-18 14:30:41 +00002212
2213 // Otherwise create the type.
David Blaikie8d5e1282013-08-20 21:03:29 +00002214 llvm::DICompositeType Res = CreateLimitedType(Ty);
2215
2216 // Propagate members from the declaration to the definition
2217 // CreateType(const RecordType*) will overwrite this with the members in the
2218 // correct order if the full type is needed.
2219 Res.setTypeArray(T.getTypeArray());
Guy Benyei11169dd2012-12-18 14:30:41 +00002220
Eric Christopherf8bc4d82013-07-18 00:52:50 +00002221 if (T && T.isForwardDecl())
David Blaikie4a2b5ef2013-08-12 22:24:20 +00002222 ReplaceMap.push_back(
2223 std::make_pair(QTy.getAsOpaquePtr(), static_cast<llvm::Value *>(T)));
Guy Benyei11169dd2012-12-18 14:30:41 +00002224
2225 // And update the type cache.
David Blaikie4a2b5ef2013-08-12 22:24:20 +00002226 TypeCache[QTy.getAsOpaquePtr()] = Res;
Guy Benyei11169dd2012-12-18 14:30:41 +00002227 return Res;
2228}
2229
2230// TODO: Currently used for context chains when limiting debug info.
David Blaikie8d5e1282013-08-20 21:03:29 +00002231llvm::DICompositeType CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002232 RecordDecl *RD = Ty->getDecl();
Eric Christopherb2a008c2013-05-16 00:45:12 +00002233
Guy Benyei11169dd2012-12-18 14:30:41 +00002234 // Get overall information about the record type for the debug info.
2235 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
2236 unsigned Line = getLineNumber(RD->getLocation());
2237 StringRef RDName = getClassName(RD);
2238
Eric Christopher07429ff2013-10-15 21:22:34 +00002239 llvm::DIDescriptor RDContext =
2240 getContextDescriptor(cast<Decl>(RD->getDeclContext()));
Guy Benyei11169dd2012-12-18 14:30:41 +00002241
David Blaikied2785892013-08-18 17:36:19 +00002242 // If we ended up creating the type during the context chain construction,
2243 // just return that.
2244 // FIXME: this could be dealt with better if the type was recorded as
2245 // completed before we started this (see the CompletedTypeCache usage in
2246 // CGDebugInfo::CreateTypeDefinition(const RecordType*) - that would need to
2247 // be pushed to before context creation, but after it was known to be
2248 // destined for completion (might still have an issue if this caller only
2249 // required a declaration but the context construction ended up creating a
2250 // definition)
David Blaikie8d5e1282013-08-20 21:03:29 +00002251 llvm::DICompositeType T(getTypeOrNull(CGM.getContext().getRecordType(RD)));
2252 if (T && (!T.isForwardDecl() || !RD->getDefinition()))
David Blaikied2785892013-08-18 17:36:19 +00002253 return T;
2254
Adrian Prantl381e7552014-02-04 21:29:50 +00002255 // If this is just a forward or incomplete declaration, construct an
2256 // appropriately marked node and just return it.
2257 const RecordDecl *D = RD->getDefinition();
2258 if (!D || !D->isCompleteDefinition())
Manman Ren1b457022013-08-28 21:20:28 +00002259 return getOrCreateRecordFwdDecl(Ty, RDContext);
Guy Benyei11169dd2012-12-18 14:30:41 +00002260
2261 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2262 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
David Blaikie49ae6a72013-03-26 23:47:35 +00002263 llvm::DICompositeType RealDecl;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002264
Manman Rene0064d82013-08-29 23:19:58 +00002265 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
2266
Guy Benyei11169dd2012-12-18 14:30:41 +00002267 if (RD->isUnion())
2268 RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
Manman Rene0064d82013-08-29 23:19:58 +00002269 Size, Align, 0, llvm::DIArray(), 0,
2270 FullName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002271 else if (RD->isClass()) {
2272 // FIXME: This could be a struct type giving a default visibility different
2273 // than C++ class type, but needs llvm metadata changes first.
2274 RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
Eric Christopherc0c5d462013-02-21 22:35:08 +00002275 Size, Align, 0, 0, llvm::DIType(),
2276 llvm::DIArray(), llvm::DIType(),
Manman Rene0064d82013-08-29 23:19:58 +00002277 llvm::DIArray(), FullName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002278 } else
2279 RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line,
Eric Christopher0fdcb312013-05-16 00:52:20 +00002280 Size, Align, 0, llvm::DIType(),
David Blaikieba477362013-11-18 23:38:26 +00002281 llvm::DIArray(), 0, llvm::DIType(),
2282 FullName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002283
2284 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
David Blaikie49ae6a72013-03-26 23:47:35 +00002285 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00002286
David Blaikieadfbf992013-08-18 16:55:33 +00002287 if (const ClassTemplateSpecializationDecl *TSpecial =
2288 dyn_cast<ClassTemplateSpecializationDecl>(RD))
2289 RealDecl.setTypeArray(llvm::DIArray(),
2290 CollectCXXTemplateParams(TSpecial, DefUnit));
David Blaikie952dac32013-08-15 22:42:12 +00002291 return RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00002292}
2293
David Blaikieadfbf992013-08-18 16:55:33 +00002294void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,
2295 llvm::DICompositeType RealDecl) {
2296 // A class's primary base or the class itself contains the vtable.
2297 llvm::DICompositeType ContainingType;
2298 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2299 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
Alp Tokerd4733632013-12-05 04:47:09 +00002300 // Seek non-virtual primary base root.
David Blaikieadfbf992013-08-18 16:55:33 +00002301 while (1) {
2302 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
2303 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
2304 if (PBT && !BRL.isPrimaryBaseVirtual())
2305 PBase = PBT;
2306 else
2307 break;
2308 }
2309 ContainingType = llvm::DICompositeType(
2310 getOrCreateType(QualType(PBase->getTypeForDecl(), 0),
2311 getOrCreateFile(RD->getLocation())));
2312 } else if (RD->isDynamicClass())
2313 ContainingType = RealDecl;
2314
2315 RealDecl.setContainingType(ContainingType);
2316}
2317
Guy Benyei11169dd2012-12-18 14:30:41 +00002318/// CreateMemberType - Create new member and increase Offset by FType's size.
2319llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
2320 StringRef Name,
2321 uint64_t *Offset) {
2322 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2323 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
2324 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
2325 llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0,
2326 FieldSize, FieldAlign,
2327 *Offset, 0, FieldTy);
2328 *Offset += FieldSize;
2329 return Ty;
2330}
2331
David Blaikiebd483762013-05-20 04:58:53 +00002332llvm::DIDescriptor CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
2333 // We only need a declaration (not a definition) of the type - so use whatever
2334 // we would otherwise do to get a type for a pointee. (forward declarations in
2335 // limited debug info, full definitions (if the type definition is available)
2336 // in unlimited debug info)
David Blaikie6b7d060c2013-08-12 23:14:36 +00002337 if (const TypeDecl *TD = dyn_cast<TypeDecl>(D))
2338 return getOrCreateType(CGM.getContext().getTypeDeclType(TD),
David Blaikie99dab3b2013-09-04 22:03:57 +00002339 getOrCreateFile(TD->getLocation()));
David Blaikiebd483762013-05-20 04:58:53 +00002340 // Otherwise fall back to a fairly rudimentary cache of existing declarations.
2341 // This doesn't handle providing declarations (for functions or variables) for
2342 // entities without definitions in this TU, nor when the definition proceeds
2343 // the call to this function.
2344 // FIXME: This should be split out into more specific maps with support for
2345 // emitting forward declarations and merging definitions with declarations,
2346 // the same way as we do for types.
2347 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator I =
2348 DeclCache.find(D->getCanonicalDecl());
2349 if (I == DeclCache.end())
2350 return llvm::DIDescriptor();
2351 llvm::Value *V = I->second;
2352 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
2353}
2354
Guy Benyei11169dd2012-12-18 14:30:41 +00002355/// getFunctionDeclaration - Return debug info descriptor to describe method
2356/// declaration for the given method definition.
2357llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
David Blaikie18cfbc52013-06-22 00:09:36 +00002358 if (!D || DebugKind == CodeGenOptions::DebugLineTablesOnly)
2359 return llvm::DISubprogram();
2360
Guy Benyei11169dd2012-12-18 14:30:41 +00002361 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
2362 if (!FD) return llvm::DISubprogram();
2363
2364 // Setup context.
David Blaikiefd07c602013-08-09 17:20:05 +00002365 llvm::DIScope S = getContextDescriptor(cast<Decl>(D->getDeclContext()));
Guy Benyei11169dd2012-12-18 14:30:41 +00002366
2367 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2368 MI = SPCache.find(FD->getCanonicalDecl());
David Blaikiefd07c602013-08-09 17:20:05 +00002369 if (MI == SPCache.end()) {
Eric Christopherf86c4052013-08-28 23:12:10 +00002370 if (const CXXMethodDecl *MD =
2371 dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
David Blaikiefd07c602013-08-09 17:20:05 +00002372 llvm::DICompositeType T(S);
Eric Christopherf86c4052013-08-28 23:12:10 +00002373 llvm::DISubprogram SP =
2374 CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()), T);
David Blaikiefd07c602013-08-09 17:20:05 +00002375 return SP;
2376 }
2377 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002378 if (MI != SPCache.end()) {
2379 llvm::Value *V = MI->second;
2380 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
David Blaikie18cfbc52013-06-22 00:09:36 +00002381 if (SP.isSubprogram() && !SP.isDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00002382 return SP;
2383 }
2384
2385 for (FunctionDecl::redecl_iterator I = FD->redecls_begin(),
2386 E = FD->redecls_end(); I != E; ++I) {
2387 const FunctionDecl *NextFD = *I;
2388 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2389 MI = SPCache.find(NextFD->getCanonicalDecl());
2390 if (MI != SPCache.end()) {
2391 llvm::Value *V = MI->second;
2392 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
David Blaikie18cfbc52013-06-22 00:09:36 +00002393 if (SP.isSubprogram() && !SP.isDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00002394 return SP;
2395 }
2396 }
2397 return llvm::DISubprogram();
2398}
2399
2400// getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
2401// implicit parameter "this".
David Blaikie469f0792013-05-22 23:22:42 +00002402llvm::DICompositeType CGDebugInfo::getOrCreateFunctionType(const Decl *D,
2403 QualType FnType,
2404 llvm::DIFile F) {
David Blaikie18cfbc52013-06-22 00:09:36 +00002405 if (!D || DebugKind == CodeGenOptions::DebugLineTablesOnly)
2406 // Create fake but valid subroutine type. Otherwise
2407 // llvm::DISubprogram::Verify() would return false, and
2408 // subprogram DIE will miss DW_AT_decl_file and
2409 // DW_AT_decl_line fields.
2410 return DBuilder.createSubroutineType(F, DBuilder.getOrCreateArray(None));
Guy Benyei11169dd2012-12-18 14:30:41 +00002411
2412 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
2413 return getOrCreateMethodType(Method, F);
2414 if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
2415 // Add "self" and "_cmd"
2416 SmallVector<llvm::Value *, 16> Elts;
2417
2418 // First element is always return type. For 'void' functions it is NULL.
Alp Toker314cc812014-01-25 16:55:45 +00002419 QualType ResultTy = OMethod->getReturnType();
Adrian Prantl5f360102013-05-22 21:37:49 +00002420
2421 // Replace the instancetype keyword with the actual type.
2422 if (ResultTy == CGM.getContext().getObjCInstanceType())
2423 ResultTy = CGM.getContext().getPointerType(
2424 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
2425
Adrian Prantl7bec9032013-05-10 21:08:31 +00002426 Elts.push_back(getOrCreateType(ResultTy, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002427 // "self" pointer is always first argument.
Adrian Prantlde17db32013-03-29 19:20:29 +00002428 QualType SelfDeclTy = OMethod->getSelfDecl()->getType();
2429 llvm::DIType SelfTy = getOrCreateType(SelfDeclTy, F);
2430 Elts.push_back(CreateSelfType(SelfDeclTy, SelfTy));
Guy Benyei11169dd2012-12-18 14:30:41 +00002431 // "_cmd" pointer is always second argument.
2432 llvm::DIType CmdTy = getOrCreateType(OMethod->getCmdDecl()->getType(), F);
2433 Elts.push_back(DBuilder.createArtificialType(CmdTy));
2434 // Get rest of the arguments.
Eric Christopherb2a008c2013-05-16 00:45:12 +00002435 for (ObjCMethodDecl::param_const_iterator PI = OMethod->param_begin(),
Guy Benyei11169dd2012-12-18 14:30:41 +00002436 PE = OMethod->param_end(); PI != PE; ++PI)
2437 Elts.push_back(getOrCreateType((*PI)->getType(), F));
2438
2439 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2440 return DBuilder.createSubroutineType(F, EltTypeArray);
2441 }
Adrian Prantld45ba252014-02-25 19:38:11 +00002442
2443 // Variadic function.
2444 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2445 if (FD->isVariadic()) {
2446 SmallVector<llvm::Value *, 16> EltTys;
2447 EltTys.push_back(getOrCreateType(FD->getReturnType(), F));
2448 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FnType))
2449 for (unsigned i = 0, e = FPT->getNumParams(); i != e; ++i)
2450 EltTys.push_back(getOrCreateType(FPT->getParamType(i), F));
2451 EltTys.push_back(DBuilder.createUnspecifiedParameter());
2452 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
2453 return DBuilder.createSubroutineType(F, EltTypeArray);
2454 }
2455
David Blaikie469f0792013-05-22 23:22:42 +00002456 return llvm::DICompositeType(getOrCreateType(FnType, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002457}
2458
2459/// EmitFunctionStart - Constructs the debug code for entering a function.
2460void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
2461 llvm::Function *Fn,
2462 CGBuilderTy &Builder) {
2463
2464 StringRef Name;
2465 StringRef LinkageName;
2466
2467 FnBeginRegionCount.push_back(LexicalBlockStack.size());
2468
2469 const Decl *D = GD.getDecl();
2470 // Function may lack declaration in source code if it is created by Clang
2471 // CodeGen (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
2472 bool HasDecl = (D != 0);
2473 // Use the location of the declaration.
2474 SourceLocation Loc;
2475 if (HasDecl)
2476 Loc = D->getLocation();
2477
2478 unsigned Flags = 0;
2479 llvm::DIFile Unit = getOrCreateFile(Loc);
2480 llvm::DIDescriptor FDContext(Unit);
2481 llvm::DIArray TParamsArray;
2482 if (!HasDecl) {
2483 // Use llvm function name.
David Blaikieebe87e12013-08-27 23:57:18 +00002484 LinkageName = Fn->getName();
Guy Benyei11169dd2012-12-18 14:30:41 +00002485 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2486 // If there is a DISubprogram for this function available then use it.
2487 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2488 FI = SPCache.find(FD->getCanonicalDecl());
2489 if (FI != SPCache.end()) {
2490 llvm::Value *V = FI->second;
2491 llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(V));
2492 if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
2493 llvm::MDNode *SPN = SP;
2494 LexicalBlockStack.push_back(SPN);
2495 RegionMap[D] = llvm::WeakVH(SP);
2496 return;
2497 }
2498 }
2499 Name = getFunctionName(FD);
Nick Lewyckyc02bbb62013-03-20 01:38:16 +00002500 // Use mangled name as linkage name for C/C++ functions.
Guy Benyei11169dd2012-12-18 14:30:41 +00002501 if (FD->hasPrototype()) {
2502 LinkageName = CGM.getMangledName(GD);
2503 Flags |= llvm::DIDescriptor::FlagPrototyped;
2504 }
Nick Lewyckyc02bbb62013-03-20 01:38:16 +00002505 // No need to replicate the linkage name if it isn't different from the
2506 // subprogram name, no need to have it at all unless coverage is enabled or
2507 // debug is set to more than just line tables.
Guy Benyei11169dd2012-12-18 14:30:41 +00002508 if (LinkageName == Name ||
Nick Lewyckyc02bbb62013-03-20 01:38:16 +00002509 (!CGM.getCodeGenOpts().EmitGcovArcs &&
2510 !CGM.getCodeGenOpts().EmitGcovNotes &&
Eric Christopher75e17682013-05-16 00:45:23 +00002511 DebugKind <= CodeGenOptions::DebugLineTablesOnly))
Guy Benyei11169dd2012-12-18 14:30:41 +00002512 LinkageName = StringRef();
2513
Eric Christopher75e17682013-05-16 00:45:23 +00002514 if (DebugKind >= CodeGenOptions::LimitedDebugInfo) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002515 if (const NamespaceDecl *NSDecl =
Eric Christopher9e6f5f92013-10-17 01:31:21 +00002516 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
Guy Benyei11169dd2012-12-18 14:30:41 +00002517 FDContext = getOrCreateNameSpace(NSDecl);
2518 else if (const RecordDecl *RDecl =
Eric Christopher9e6f5f92013-10-17 01:31:21 +00002519 dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
2520 FDContext = getContextDescriptor(cast<Decl>(RDecl));
Guy Benyei11169dd2012-12-18 14:30:41 +00002521
2522 // Collect template parameters.
2523 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
2524 }
2525 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
2526 Name = getObjCMethodName(OMD);
2527 Flags |= llvm::DIDescriptor::FlagPrototyped;
2528 } else {
2529 // Use llvm function name.
2530 Name = Fn->getName();
2531 Flags |= llvm::DIDescriptor::FlagPrototyped;
2532 }
2533 if (!Name.empty() && Name[0] == '\01')
2534 Name = Name.substr(1);
2535
2536 unsigned LineNo = getLineNumber(Loc);
2537 if (!HasDecl || D->isImplicit())
2538 Flags |= llvm::DIDescriptor::FlagArtificial;
2539
Eric Christopher9e6f5f92013-10-17 01:31:21 +00002540 llvm::DISubprogram SP =
2541 DBuilder.createFunction(FDContext, Name, LinkageName, Unit, LineNo,
2542 getOrCreateFunctionType(D, FnType, Unit),
2543 Fn->hasInternalLinkage(), true /*definition*/,
2544 getLineNumber(CurLoc), Flags,
2545 CGM.getLangOpts().Optimize, Fn, TParamsArray,
2546 getFunctionDeclaration(D));
David Blaikiebd483762013-05-20 04:58:53 +00002547 if (HasDecl)
2548 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(SP)));
Guy Benyei11169dd2012-12-18 14:30:41 +00002549
2550 // Push function on region stack.
2551 llvm::MDNode *SPN = SP;
2552 LexicalBlockStack.push_back(SPN);
2553 if (HasDecl)
2554 RegionMap[D] = llvm::WeakVH(SP);
2555}
2556
2557/// EmitLocation - Emit metadata to indicate a change in line/column
Adrian Prantl02c0caa2013-07-18 00:27:59 +00002558/// information in the source file. If the location is invalid, the
2559/// previous location will be reused.
Adrian Prantlc7822422013-03-12 20:43:25 +00002560void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc,
Adrian Prantle83b1302014-01-07 22:05:52 +00002561 bool ForceColumnInfo) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002562 // Update our current location
2563 setLocation(Loc);
2564
2565 if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
2566
2567 // Don't bother if things are the same as last time.
2568 SourceManager &SM = CGM.getContext().getSourceManager();
2569 if (CurLoc == PrevLoc ||
2570 SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc))
2571 // New Builder may not be in sync with CGDebugInfo.
David Blaikie357aafb2013-02-01 19:09:49 +00002572 if (!Builder.getCurrentDebugLocation().isUnknown() &&
2573 Builder.getCurrentDebugLocation().getScope(CGM.getLLVMContext()) ==
2574 LexicalBlockStack.back())
Guy Benyei11169dd2012-12-18 14:30:41 +00002575 return;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002576
Guy Benyei11169dd2012-12-18 14:30:41 +00002577 // Update last state.
2578 PrevLoc = CurLoc;
2579
Adrian Prantle83b1302014-01-07 22:05:52 +00002580 llvm::MDNode *Scope = LexicalBlockStack.back();
Adrian Prantlc7822422013-03-12 20:43:25 +00002581 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get
2582 (getLineNumber(CurLoc),
2583 getColumnNumber(CurLoc, ForceColumnInfo),
2584 Scope));
Guy Benyei11169dd2012-12-18 14:30:41 +00002585}
2586
2587/// CreateLexicalBlock - Creates a new lexical block node and pushes it on
2588/// the stack.
2589void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
2590 llvm::DIDescriptor D =
2591 DBuilder.createLexicalBlock(LexicalBlockStack.empty() ?
2592 llvm::DIDescriptor() :
2593 llvm::DIDescriptor(LexicalBlockStack.back()),
2594 getOrCreateFile(CurLoc),
2595 getLineNumber(CurLoc),
2596 getColumnNumber(CurLoc));
2597 llvm::MDNode *DN = D;
2598 LexicalBlockStack.push_back(DN);
2599}
2600
2601/// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
2602/// region - beginning of a DW_TAG_lexical_block.
Eric Christopher0fdcb312013-05-16 00:52:20 +00002603void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
2604 SourceLocation Loc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002605 // Set our current location.
2606 setLocation(Loc);
2607
2608 // Create a new lexical block and push it on the stack.
2609 CreateLexicalBlock(Loc);
2610
2611 // Emit a line table change for the current location inside the new scope.
2612 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc),
2613 getColumnNumber(Loc),
2614 LexicalBlockStack.back()));
2615}
2616
2617/// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative
2618/// region - end of a DW_TAG_lexical_block.
Eric Christopher0fdcb312013-05-16 00:52:20 +00002619void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
2620 SourceLocation Loc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002621 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2622
2623 // Provide an entry in the line table for the end of the block.
2624 EmitLocation(Builder, Loc);
2625
2626 LexicalBlockStack.pop_back();
2627}
2628
2629/// EmitFunctionEnd - Constructs the debug code for exiting a function.
2630void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
2631 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2632 unsigned RCount = FnBeginRegionCount.back();
2633 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
2634
2635 // Pop all regions for this function.
2636 while (LexicalBlockStack.size() != RCount)
2637 EmitLexicalBlockEnd(Builder, CurLoc);
2638 FnBeginRegionCount.pop_back();
2639}
2640
Eric Christopherb2a008c2013-05-16 00:45:12 +00002641// EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
Guy Benyei11169dd2012-12-18 14:30:41 +00002642// See BuildByRefType.
2643llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
2644 uint64_t *XOffset) {
2645
2646 SmallVector<llvm::Value *, 5> EltTys;
2647 QualType FType;
2648 uint64_t FieldSize, FieldOffset;
2649 unsigned FieldAlign;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002650
Guy Benyei11169dd2012-12-18 14:30:41 +00002651 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
Eric Christopherb2a008c2013-05-16 00:45:12 +00002652 QualType Type = VD->getType();
Guy Benyei11169dd2012-12-18 14:30:41 +00002653
2654 FieldOffset = 0;
2655 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2656 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
2657 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
2658 FType = CGM.getContext().IntTy;
2659 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
2660 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
2661
2662 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
2663 if (HasCopyAndDispose) {
2664 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2665 EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
2666 &FieldOffset));
2667 EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
2668 &FieldOffset));
2669 }
2670 bool HasByrefExtendedLayout;
2671 Qualifiers::ObjCLifetime Lifetime;
2672 if (CGM.getContext().getByrefLifetime(Type,
2673 Lifetime, HasByrefExtendedLayout)
Adrian Prantlead2ba42013-07-23 00:12:14 +00002674 && HasByrefExtendedLayout) {
2675 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
Guy Benyei11169dd2012-12-18 14:30:41 +00002676 EltTys.push_back(CreateMemberType(Unit, FType,
2677 "__byref_variable_layout",
2678 &FieldOffset));
Adrian Prantlead2ba42013-07-23 00:12:14 +00002679 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00002680
Guy Benyei11169dd2012-12-18 14:30:41 +00002681 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2682 if (Align > CGM.getContext().toCharUnitsFromBits(
John McCallc8e01702013-04-16 22:48:15 +00002683 CGM.getTarget().getPointerAlign(0))) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00002684 CharUnits FieldOffsetInBytes
Guy Benyei11169dd2012-12-18 14:30:41 +00002685 = CGM.getContext().toCharUnitsFromBits(FieldOffset);
2686 CharUnits AlignedOffsetInBytes
2687 = FieldOffsetInBytes.RoundUpToAlignment(Align);
2688 CharUnits NumPaddingBytes
2689 = AlignedOffsetInBytes - FieldOffsetInBytes;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002690
Guy Benyei11169dd2012-12-18 14:30:41 +00002691 if (NumPaddingBytes.isPositive()) {
2692 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
2693 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
2694 pad, ArrayType::Normal, 0);
2695 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
2696 }
2697 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00002698
Guy Benyei11169dd2012-12-18 14:30:41 +00002699 FType = Type;
2700 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2701 FieldSize = CGM.getContext().getTypeSize(FType);
2702 FieldAlign = CGM.getContext().toBits(Align);
2703
Eric Christopherb2a008c2013-05-16 00:45:12 +00002704 *XOffset = FieldOffset;
Guy Benyei11169dd2012-12-18 14:30:41 +00002705 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit,
2706 0, FieldSize, FieldAlign,
2707 FieldOffset, 0, FieldTy);
2708 EltTys.push_back(FieldTy);
2709 FieldOffset += FieldSize;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002710
Guy Benyei11169dd2012-12-18 14:30:41 +00002711 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002712
Guy Benyei11169dd2012-12-18 14:30:41 +00002713 unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002714
Guy Benyei11169dd2012-12-18 14:30:41 +00002715 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
David Blaikie6d4fe152013-02-25 01:07:08 +00002716 llvm::DIType(), Elements);
Guy Benyei11169dd2012-12-18 14:30:41 +00002717}
2718
2719/// EmitDeclare - Emit local variable declaration debug info.
2720void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
Eric Christopherb2a008c2013-05-16 00:45:12 +00002721 llvm::Value *Storage,
Guy Benyei11169dd2012-12-18 14:30:41 +00002722 unsigned ArgNo, CGBuilderTy &Builder) {
Eric Christopher75e17682013-05-16 00:45:23 +00002723 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002724 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2725
David Blaikie7fceebf2013-08-19 03:37:48 +00002726 bool Unwritten =
2727 VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) &&
2728 cast<Decl>(VD->getDeclContext())->isImplicit());
2729 llvm::DIFile Unit;
2730 if (!Unwritten)
2731 Unit = getOrCreateFile(VD->getLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00002732 llvm::DIType Ty;
2733 uint64_t XOffset = 0;
2734 if (VD->hasAttr<BlocksAttr>())
2735 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002736 else
Guy Benyei11169dd2012-12-18 14:30:41 +00002737 Ty = getOrCreateType(VD->getType(), Unit);
2738
2739 // If there is no debug info for this type then do not emit debug info
2740 // for this variable.
2741 if (!Ty)
2742 return;
2743
Guy Benyei11169dd2012-12-18 14:30:41 +00002744 // Get location information.
David Blaikie7fceebf2013-08-19 03:37:48 +00002745 unsigned Line = 0;
2746 unsigned Column = 0;
2747 if (!Unwritten) {
2748 Line = getLineNumber(VD->getLocation());
2749 Column = getColumnNumber(VD->getLocation());
2750 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002751 unsigned Flags = 0;
2752 if (VD->isImplicit())
2753 Flags |= llvm::DIDescriptor::FlagArtificial;
2754 // If this is the first argument and it is implicit then
2755 // give it an object pointer flag.
2756 // FIXME: There has to be a better way to do this, but for static
2757 // functions there won't be an implicit param at arg1 and
2758 // otherwise it is 'self' or 'this'.
2759 if (isa<ImplicitParamDecl>(VD) && ArgNo == 1)
2760 Flags |= llvm::DIDescriptor::FlagObjectPointer;
David Blaikieb9c667d2013-06-19 21:53:53 +00002761 if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage))
Eric Christopherffdeb1e2013-07-17 22:52:53 +00002762 if (Arg->getType()->isPointerTy() && !Arg->hasByValAttr() &&
2763 !VD->getType()->isPointerType())
David Blaikieb9c667d2013-06-19 21:53:53 +00002764 Flags |= llvm::DIDescriptor::FlagIndirectVariable;
Guy Benyei11169dd2012-12-18 14:30:41 +00002765
2766 llvm::MDNode *Scope = LexicalBlockStack.back();
2767
2768 StringRef Name = VD->getName();
2769 if (!Name.empty()) {
2770 if (VD->hasAttr<BlocksAttr>()) {
2771 CharUnits offset = CharUnits::fromQuantity(32);
2772 SmallVector<llvm::Value *, 9> addr;
2773 llvm::Type *Int64Ty = CGM.Int64Ty;
2774 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2775 // offset of __forwarding field
2776 offset = CGM.getContext().toCharUnitsFromBits(
John McCallc8e01702013-04-16 22:48:15 +00002777 CGM.getTarget().getPointerWidth(0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002778 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2779 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2780 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2781 // offset of x field
2782 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2783 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2784
2785 // Create the descriptor for the variable.
2786 llvm::DIVariable D =
Eric Christopherb2a008c2013-05-16 00:45:12 +00002787 DBuilder.createComplexVariable(Tag,
Guy Benyei11169dd2012-12-18 14:30:41 +00002788 llvm::DIDescriptor(Scope),
2789 VD->getName(), Unit, Line, Ty,
2790 addr, ArgNo);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002791
Guy Benyei11169dd2012-12-18 14:30:41 +00002792 // Insert an llvm.dbg.declare into the current block.
2793 llvm::Instruction *Call =
2794 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2795 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2796 return;
Adrian Prantl7f2ef222013-09-18 22:18:17 +00002797 } else if (isa<VariableArrayType>(VD->getType()))
Adrian Prantl0315f382013-09-18 22:08:57 +00002798 Flags |= llvm::DIDescriptor::FlagIndirectVariable;
David Blaikiea76a7c92013-01-05 05:58:35 +00002799 } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2800 // If VD is an anonymous union then Storage represents value for
2801 // all union fields.
Guy Benyei11169dd2012-12-18 14:30:41 +00002802 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
David Blaikie219c7d92013-01-05 20:03:07 +00002803 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002804 for (RecordDecl::field_iterator I = RD->field_begin(),
2805 E = RD->field_end();
2806 I != E; ++I) {
2807 FieldDecl *Field = *I;
2808 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2809 StringRef FieldName = Field->getName();
Eric Christopherb2a008c2013-05-16 00:45:12 +00002810
Guy Benyei11169dd2012-12-18 14:30:41 +00002811 // Ignore unnamed fields. Do not ignore unnamed records.
2812 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2813 continue;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002814
Guy Benyei11169dd2012-12-18 14:30:41 +00002815 // Use VarDecl's Tag, Scope and Line number.
2816 llvm::DIVariable D =
2817 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
Eric Christopherb2a008c2013-05-16 00:45:12 +00002818 FieldName, Unit, Line, FieldTy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002819 CGM.getLangOpts().Optimize, Flags,
2820 ArgNo);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002821
Guy Benyei11169dd2012-12-18 14:30:41 +00002822 // Insert an llvm.dbg.declare into the current block.
2823 llvm::Instruction *Call =
2824 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2825 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2826 }
David Blaikie219c7d92013-01-05 20:03:07 +00002827 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00002828 }
2829 }
David Blaikiea76a7c92013-01-05 05:58:35 +00002830
2831 // Create the descriptor for the variable.
2832 llvm::DIVariable D =
2833 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2834 Name, Unit, Line, Ty,
2835 CGM.getLangOpts().Optimize, Flags, ArgNo);
2836
2837 // Insert an llvm.dbg.declare into the current block.
2838 llvm::Instruction *Call =
2839 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2840 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
Guy Benyei11169dd2012-12-18 14:30:41 +00002841}
2842
2843void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2844 llvm::Value *Storage,
2845 CGBuilderTy &Builder) {
Eric Christopher75e17682013-05-16 00:45:23 +00002846 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002847 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2848}
2849
Adrian Prantlde17db32013-03-29 19:20:29 +00002850/// Look up the completed type for a self pointer in the TypeCache and
2851/// create a copy of it with the ObjectPointer and Artificial flags
2852/// set. If the type is not cached, a new one is created. This should
2853/// never happen though, since creating a type for the implicit self
2854/// argument implies that we already parsed the interface definition
2855/// and the ivar declarations in the implementation.
Eric Christopher0fdcb312013-05-16 00:52:20 +00002856llvm::DIType CGDebugInfo::CreateSelfType(const QualType &QualTy,
2857 llvm::DIType Ty) {
Adrian Prantlde17db32013-03-29 19:20:29 +00002858 llvm::DIType CachedTy = getTypeOrNull(QualTy);
Eric Christopherf8bc4d82013-07-18 00:52:50 +00002859 if (CachedTy) Ty = CachedTy;
Adrian Prantlde17db32013-03-29 19:20:29 +00002860 else DEBUG(llvm::dbgs() << "No cached type for self.");
2861 return DBuilder.createObjectPointerType(Ty);
2862}
2863
Guy Benyei11169dd2012-12-18 14:30:41 +00002864void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(const VarDecl *VD,
2865 llvm::Value *Storage,
2866 CGBuilderTy &Builder,
2867 const CGBlockInfo &blockInfo) {
Eric Christopher75e17682013-05-16 00:45:23 +00002868 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002869 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
Eric Christopherb2a008c2013-05-16 00:45:12 +00002870
Guy Benyei11169dd2012-12-18 14:30:41 +00002871 if (Builder.GetInsertBlock() == 0)
2872 return;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002873
Guy Benyei11169dd2012-12-18 14:30:41 +00002874 bool isByRef = VD->hasAttr<BlocksAttr>();
Eric Christopherb2a008c2013-05-16 00:45:12 +00002875
Guy Benyei11169dd2012-12-18 14:30:41 +00002876 uint64_t XOffset = 0;
2877 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2878 llvm::DIType Ty;
2879 if (isByRef)
2880 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002881 else
Guy Benyei11169dd2012-12-18 14:30:41 +00002882 Ty = getOrCreateType(VD->getType(), Unit);
2883
2884 // Self is passed along as an implicit non-arg variable in a
2885 // block. Mark it as the object pointer.
2886 if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self")
Adrian Prantlde17db32013-03-29 19:20:29 +00002887 Ty = CreateSelfType(VD->getType(), Ty);
Guy Benyei11169dd2012-12-18 14:30:41 +00002888
2889 // Get location information.
2890 unsigned Line = getLineNumber(VD->getLocation());
2891 unsigned Column = getColumnNumber(VD->getLocation());
2892
2893 const llvm::DataLayout &target = CGM.getDataLayout();
2894
2895 CharUnits offset = CharUnits::fromQuantity(
2896 target.getStructLayout(blockInfo.StructureType)
2897 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2898
2899 SmallVector<llvm::Value *, 9> addr;
2900 llvm::Type *Int64Ty = CGM.Int64Ty;
Adrian Prantl0f6df002013-03-29 19:20:35 +00002901 if (isa<llvm::AllocaInst>(Storage))
2902 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
Guy Benyei11169dd2012-12-18 14:30:41 +00002903 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2904 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2905 if (isByRef) {
2906 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2907 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2908 // offset of __forwarding field
2909 offset = CGM.getContext()
2910 .toCharUnitsFromBits(target.getPointerSizeInBits(0));
2911 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2912 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2913 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2914 // offset of x field
2915 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2916 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2917 }
2918
2919 // Create the descriptor for the variable.
2920 llvm::DIVariable D =
Eric Christopherb2a008c2013-05-16 00:45:12 +00002921 DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable,
Guy Benyei11169dd2012-12-18 14:30:41 +00002922 llvm::DIDescriptor(LexicalBlockStack.back()),
2923 VD->getName(), Unit, Line, Ty, addr);
Adrian Prantl0f6df002013-03-29 19:20:35 +00002924
Guy Benyei11169dd2012-12-18 14:30:41 +00002925 // Insert an llvm.dbg.declare into the current block.
2926 llvm::Instruction *Call =
2927 DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
2928 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column,
2929 LexicalBlockStack.back()));
2930}
2931
2932/// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2933/// variable declaration.
2934void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2935 unsigned ArgNo,
2936 CGBuilderTy &Builder) {
Eric Christopher75e17682013-05-16 00:45:23 +00002937 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002938 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2939}
2940
2941namespace {
2942 struct BlockLayoutChunk {
2943 uint64_t OffsetInBits;
2944 const BlockDecl::Capture *Capture;
2945 };
2946 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2947 return l.OffsetInBits < r.OffsetInBits;
2948 }
2949}
2950
2951void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
Adrian Prantl51936dd2013-03-14 17:53:33 +00002952 llvm::Value *Arg,
2953 llvm::Value *LocalAddr,
Guy Benyei11169dd2012-12-18 14:30:41 +00002954 CGBuilderTy &Builder) {
Eric Christopher75e17682013-05-16 00:45:23 +00002955 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002956 ASTContext &C = CGM.getContext();
2957 const BlockDecl *blockDecl = block.getBlockDecl();
2958
2959 // Collect some general information about the block's location.
2960 SourceLocation loc = blockDecl->getCaretLocation();
2961 llvm::DIFile tunit = getOrCreateFile(loc);
2962 unsigned line = getLineNumber(loc);
2963 unsigned column = getColumnNumber(loc);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002964
Guy Benyei11169dd2012-12-18 14:30:41 +00002965 // Build the debug-info type for the block literal.
2966 getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
2967
2968 const llvm::StructLayout *blockLayout =
2969 CGM.getDataLayout().getStructLayout(block.StructureType);
2970
2971 SmallVector<llvm::Value*, 16> fields;
2972 fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
2973 blockLayout->getElementOffsetInBits(0),
2974 tunit, tunit));
2975 fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
2976 blockLayout->getElementOffsetInBits(1),
2977 tunit, tunit));
2978 fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
2979 blockLayout->getElementOffsetInBits(2),
2980 tunit, tunit));
2981 fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
2982 blockLayout->getElementOffsetInBits(3),
2983 tunit, tunit));
2984 fields.push_back(createFieldType("__descriptor",
2985 C.getPointerType(block.NeedsCopyDispose ?
2986 C.getBlockDescriptorExtendedType() :
2987 C.getBlockDescriptorType()),
2988 0, loc, AS_public,
2989 blockLayout->getElementOffsetInBits(4),
2990 tunit, tunit));
2991
2992 // We want to sort the captures by offset, not because DWARF
2993 // requires this, but because we're paranoid about debuggers.
2994 SmallVector<BlockLayoutChunk, 8> chunks;
2995
2996 // 'this' capture.
2997 if (blockDecl->capturesCXXThis()) {
2998 BlockLayoutChunk chunk;
2999 chunk.OffsetInBits =
3000 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
3001 chunk.Capture = 0;
3002 chunks.push_back(chunk);
3003 }
3004
3005 // Variable captures.
3006 for (BlockDecl::capture_const_iterator
3007 i = blockDecl->capture_begin(), e = blockDecl->capture_end();
3008 i != e; ++i) {
3009 const BlockDecl::Capture &capture = *i;
3010 const VarDecl *variable = capture.getVariable();
3011 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
3012
3013 // Ignore constant captures.
3014 if (captureInfo.isConstant())
3015 continue;
3016
3017 BlockLayoutChunk chunk;
3018 chunk.OffsetInBits =
3019 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
3020 chunk.Capture = &capture;
3021 chunks.push_back(chunk);
3022 }
3023
3024 // Sort by offset.
3025 llvm::array_pod_sort(chunks.begin(), chunks.end());
3026
3027 for (SmallVectorImpl<BlockLayoutChunk>::iterator
3028 i = chunks.begin(), e = chunks.end(); i != e; ++i) {
3029 uint64_t offsetInBits = i->OffsetInBits;
3030 const BlockDecl::Capture *capture = i->Capture;
3031
3032 // If we have a null capture, this must be the C++ 'this' capture.
3033 if (!capture) {
3034 const CXXMethodDecl *method =
3035 cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
3036 QualType type = method->getThisType(C);
3037
3038 fields.push_back(createFieldType("this", type, 0, loc, AS_public,
3039 offsetInBits, tunit, tunit));
3040 continue;
3041 }
3042
3043 const VarDecl *variable = capture->getVariable();
3044 StringRef name = variable->getName();
3045
3046 llvm::DIType fieldType;
3047 if (capture->isByRef()) {
3048 std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
3049
3050 // FIXME: this creates a second copy of this type!
3051 uint64_t xoffset;
3052 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
3053 fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
3054 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
3055 ptrInfo.first, ptrInfo.second,
3056 offsetInBits, 0, fieldType);
3057 } else {
3058 fieldType = createFieldType(name, variable->getType(), 0,
3059 loc, AS_public, offsetInBits, tunit, tunit);
3060 }
3061 fields.push_back(fieldType);
3062 }
3063
3064 SmallString<36> typeName;
3065 llvm::raw_svector_ostream(typeName)
3066 << "__block_literal_" << CGM.getUniqueBlockCount();
3067
3068 llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
3069
3070 llvm::DIType type =
3071 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
3072 CGM.getContext().toBits(block.BlockSize),
3073 CGM.getContext().toBits(block.BlockAlign),
David Blaikie6d4fe152013-02-25 01:07:08 +00003074 0, llvm::DIType(), fieldsArray);
Guy Benyei11169dd2012-12-18 14:30:41 +00003075 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
3076
3077 // Get overall information about the block.
3078 unsigned flags = llvm::DIDescriptor::FlagArtificial;
3079 llvm::MDNode *scope = LexicalBlockStack.back();
Guy Benyei11169dd2012-12-18 14:30:41 +00003080
3081 // Create the descriptor for the parameter.
3082 llvm::DIVariable debugVar =
3083 DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
Eric Christopherb2a008c2013-05-16 00:45:12 +00003084 llvm::DIDescriptor(scope),
Adrian Prantl51936dd2013-03-14 17:53:33 +00003085 Arg->getName(), tunit, line, type,
Guy Benyei11169dd2012-12-18 14:30:41 +00003086 CGM.getLangOpts().Optimize, flags,
Adrian Prantl51936dd2013-03-14 17:53:33 +00003087 cast<llvm::Argument>(Arg)->getArgNo() + 1);
3088
Adrian Prantl616bef42013-03-14 21:52:59 +00003089 if (LocalAddr) {
Adrian Prantl51936dd2013-03-14 17:53:33 +00003090 // Insert an llvm.dbg.value into the current block.
Adrian Prantl616bef42013-03-14 21:52:59 +00003091 llvm::Instruction *DbgVal =
3092 DBuilder.insertDbgValueIntrinsic(LocalAddr, 0, debugVar,
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00003093 Builder.GetInsertBlock());
Adrian Prantl616bef42013-03-14 21:52:59 +00003094 DbgVal->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
3095 }
Adrian Prantl51936dd2013-03-14 17:53:33 +00003096
Adrian Prantl616bef42013-03-14 21:52:59 +00003097 // Insert an llvm.dbg.declare into the current block.
3098 llvm::Instruction *DbgDecl =
3099 DBuilder.insertDeclare(Arg, debugVar, Builder.GetInsertBlock());
3100 DbgDecl->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
Guy Benyei11169dd2012-12-18 14:30:41 +00003101}
3102
David Blaikie6943dea2013-08-20 01:28:15 +00003103/// If D is an out-of-class definition of a static data member of a class, find
3104/// its corresponding in-class declaration.
3105llvm::DIDerivedType
3106CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {
3107 if (!D->isStaticDataMember())
3108 return llvm::DIDerivedType();
3109 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator MI =
3110 StaticDataMemberCache.find(D->getCanonicalDecl());
3111 if (MI != StaticDataMemberCache.end()) {
3112 assert(MI->second && "Static data member declaration should still exist");
3113 return llvm::DIDerivedType(cast<llvm::MDNode>(MI->second));
Evgeniy Stepanov37b3f732013-08-16 10:35:31 +00003114 }
David Blaikiece763042013-08-20 21:49:21 +00003115
3116 // If the member wasn't found in the cache, lazily construct and add it to the
3117 // type (used when a limited form of the type is emitted).
David Blaikie6943dea2013-08-20 01:28:15 +00003118 llvm::DICompositeType Ctxt(
3119 getContextDescriptor(cast<Decl>(D->getDeclContext())));
3120 llvm::DIDerivedType T = CreateRecordStaticField(D, Ctxt);
David Blaikie6943dea2013-08-20 01:28:15 +00003121 return T;
3122}
3123
Guy Benyei11169dd2012-12-18 14:30:41 +00003124/// EmitGlobalVariable - Emit information about a global variable.
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003125void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
Guy Benyei11169dd2012-12-18 14:30:41 +00003126 const VarDecl *D) {
Eric Christopher75e17682013-05-16 00:45:23 +00003127 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00003128 // Create global variable debug descriptor.
3129 llvm::DIFile Unit = getOrCreateFile(D->getLocation());
3130 unsigned LineNo = getLineNumber(D->getLocation());
3131
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003132 setLocation(D->getLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00003133
3134 QualType T = D->getType();
3135 if (T->isIncompleteArrayType()) {
3136
3137 // CodeGen turns int[] into int[1] so we'll do the same here.
3138 llvm::APInt ConstVal(32, 1);
3139 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3140
3141 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3142 ArrayType::Normal, 0);
3143 }
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003144 StringRef DeclName = D->getName();
3145 StringRef LinkageName;
3146 if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext())
3147 && !isa<ObjCMethodDecl>(D->getDeclContext()))
3148 LinkageName = Var->getName();
3149 if (LinkageName == DeclName)
3150 LinkageName = StringRef();
Eric Christopherb2a008c2013-05-16 00:45:12 +00003151 llvm::DIDescriptor DContext =
Guy Benyei11169dd2012-12-18 14:30:41 +00003152 getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
David Blaikie6943dea2013-08-20 01:28:15 +00003153 llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(
3154 DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003155 Var->hasInternalLinkage(), Var,
David Blaikie6943dea2013-08-20 01:28:15 +00003156 getOrCreateStaticDataMemberDeclarationOrNull(D));
David Blaikiebd483762013-05-20 04:58:53 +00003157 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(GV)));
Guy Benyei11169dd2012-12-18 14:30:41 +00003158}
3159
3160/// EmitGlobalVariable - Emit information about an objective-c interface.
3161void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
3162 ObjCInterfaceDecl *ID) {
Eric Christopher75e17682013-05-16 00:45:23 +00003163 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00003164 // Create global variable debug descriptor.
3165 llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
3166 unsigned LineNo = getLineNumber(ID->getLocation());
3167
3168 StringRef Name = ID->getName();
3169
3170 QualType T = CGM.getContext().getObjCInterfaceType(ID);
3171 if (T->isIncompleteArrayType()) {
3172
3173 // CodeGen turns int[] into int[1] so we'll do the same here.
3174 llvm::APInt ConstVal(32, 1);
3175 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3176
3177 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3178 ArrayType::Normal, 0);
3179 }
3180
3181 DBuilder.createGlobalVariable(Name, Unit, LineNo,
3182 getOrCreateType(T, Unit),
3183 Var->hasInternalLinkage(), Var);
3184}
3185
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003186/// EmitGlobalVariable - Emit global variable's debug info.
3187void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
3188 llvm::Constant *Init) {
Eric Christopher75e17682013-05-16 00:45:23 +00003189 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003190 // Create the descriptor for the variable.
3191 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
3192 StringRef Name = VD->getName();
3193 llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
3194 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
3195 const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext());
3196 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
3197 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
3198 }
3199 // Do not use DIGlobalVariable for enums.
3200 if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
3201 return;
3202 llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(
3203 Unit, Name, Name, Unit, getLineNumber(VD->getLocation()), Ty, true, Init,
3204 getOrCreateStaticDataMemberDeclarationOrNull(cast<VarDecl>(VD)));
3205 DeclCache.insert(std::make_pair(VD->getCanonicalDecl(), llvm::WeakVH(GV)));
David Blaikiebd483762013-05-20 04:58:53 +00003206}
3207
3208llvm::DIScope CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
3209 if (!LexicalBlockStack.empty())
3210 return llvm::DIScope(LexicalBlockStack.back());
3211 return getContextDescriptor(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00003212}
3213
David Blaikie9f88fe82013-04-22 06:13:21 +00003214void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
David Blaikiebd483762013-05-20 04:58:53 +00003215 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3216 return;
David Blaikie9f88fe82013-04-22 06:13:21 +00003217 DBuilder.createImportedModule(
David Blaikiebd483762013-05-20 04:58:53 +00003218 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
3219 getOrCreateNameSpace(UD.getNominatedNamespace()),
David Blaikie9f88fe82013-04-22 06:13:21 +00003220 getLineNumber(UD.getLocation()));
3221}
3222
David Blaikiebd483762013-05-20 04:58:53 +00003223void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
3224 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3225 return;
3226 assert(UD.shadow_size() &&
3227 "We shouldn't be codegening an invalid UsingDecl containing no decls");
3228 // Emitting one decl is sufficient - debuggers can detect that this is an
3229 // overloaded name & provide lookup for all the overloads.
3230 const UsingShadowDecl &USD = **UD.shadow_begin();
Eric Christopher1ecc5632013-06-07 22:54:39 +00003231 if (llvm::DIDescriptor Target =
3232 getDeclarationOrDefinition(USD.getUnderlyingDecl()))
David Blaikiebd483762013-05-20 04:58:53 +00003233 DBuilder.createImportedDeclaration(
3234 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
3235 getLineNumber(USD.getLocation()));
3236}
3237
David Blaikief121b932013-05-20 22:50:41 +00003238llvm::DIImportedEntity
3239CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
3240 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3241 return llvm::DIImportedEntity(0);
3242 llvm::WeakVH &VH = NamespaceAliasCache[&NA];
3243 if (VH)
3244 return llvm::DIImportedEntity(cast<llvm::MDNode>(VH));
3245 llvm::DIImportedEntity R(0);
3246 if (const NamespaceAliasDecl *Underlying =
3247 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
3248 // This could cache & dedup here rather than relying on metadata deduping.
3249 R = DBuilder.createImportedModule(
3250 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3251 EmitNamespaceAlias(*Underlying), getLineNumber(NA.getLocation()),
3252 NA.getName());
3253 else
3254 R = DBuilder.createImportedModule(
3255 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3256 getOrCreateNameSpace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
3257 getLineNumber(NA.getLocation()), NA.getName());
3258 VH = R;
3259 return R;
3260}
3261
Guy Benyei11169dd2012-12-18 14:30:41 +00003262/// getOrCreateNamesSpace - Return namespace descriptor for the given
3263/// namespace decl.
Eric Christopherb2a008c2013-05-16 00:45:12 +00003264llvm::DINameSpace
Guy Benyei11169dd2012-12-18 14:30:41 +00003265CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
David Blaikie9fdedec2013-08-16 22:52:07 +00003266 NSDecl = NSDecl->getCanonicalDecl();
Eric Christopherb2a008c2013-05-16 00:45:12 +00003267 llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
Guy Benyei11169dd2012-12-18 14:30:41 +00003268 NameSpaceCache.find(NSDecl);
3269 if (I != NameSpaceCache.end())
3270 return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
Eric Christopherb2a008c2013-05-16 00:45:12 +00003271
Guy Benyei11169dd2012-12-18 14:30:41 +00003272 unsigned LineNo = getLineNumber(NSDecl->getLocation());
3273 llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
Eric Christopherb2a008c2013-05-16 00:45:12 +00003274 llvm::DIDescriptor Context =
Guy Benyei11169dd2012-12-18 14:30:41 +00003275 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
3276 llvm::DINameSpace NS =
3277 DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
3278 NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
3279 return NS;
3280}
3281
3282void CGDebugInfo::finalize() {
3283 for (std::vector<std::pair<void *, llvm::WeakVH> >::const_iterator VI
3284 = ReplaceMap.begin(), VE = ReplaceMap.end(); VI != VE; ++VI) {
3285 llvm::DIType Ty, RepTy;
3286 // Verify that the debug info still exists.
3287 if (llvm::Value *V = VI->second)
3288 Ty = llvm::DIType(cast<llvm::MDNode>(V));
Eric Christopherb2a008c2013-05-16 00:45:12 +00003289
Guy Benyei11169dd2012-12-18 14:30:41 +00003290 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
3291 TypeCache.find(VI->first);
3292 if (it != TypeCache.end()) {
3293 // Verify that the debug info still exists.
3294 if (llvm::Value *V = it->second)
3295 RepTy = llvm::DIType(cast<llvm::MDNode>(V));
3296 }
Adrian Prantl73409ce2013-03-11 18:33:46 +00003297
Eric Christopherf8bc4d82013-07-18 00:52:50 +00003298 if (Ty && Ty.isForwardDecl() && RepTy)
Guy Benyei11169dd2012-12-18 14:30:41 +00003299 Ty.replaceAllUsesWith(RepTy);
Guy Benyei11169dd2012-12-18 14:30:41 +00003300 }
Adrian Prantl73409ce2013-03-11 18:33:46 +00003301
3302 // We keep our own list of retained types, because we need to look
3303 // up the final type in the type cache.
3304 for (std::vector<void *>::const_iterator RI = RetainedTypes.begin(),
3305 RE = RetainedTypes.end(); RI != RE; ++RI)
Manman Renf801f802013-08-29 20:48:48 +00003306 DBuilder.retainType(llvm::DIType(cast<llvm::MDNode>(TypeCache[*RI])));
Adrian Prantl73409ce2013-03-11 18:33:46 +00003307
Guy Benyei11169dd2012-12-18 14:30:41 +00003308 DBuilder.finalize();
3309}