blob: 132c841890290982dc4e7696023f7fb4ec05b38d [file] [log] [blame]
Guy Benyei11169dd2012-12-18 14:30:41 +00001//===--- CGDebugInfo.cpp - Emit Debug Information for a Module ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the debug information generation while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGDebugInfo.h"
15#include "CGBlocks.h"
David Blaikie38079fd2013-05-10 21:53:14 +000016#include "CGCXXABI.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000017#include "CGObjCRuntime.h"
18#include "CodeGenFunction.h"
19#include "CodeGenModule.h"
20#include "clang/AST/ASTContext.h"
21#include "clang/AST/DeclFriend.h"
22#include "clang/AST/DeclObjC.h"
23#include "clang/AST/DeclTemplate.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/RecordLayout.h"
26#include "clang/Basic/FileManager.h"
27#include "clang/Basic/SourceManager.h"
28#include "clang/Basic/Version.h"
29#include "clang/Frontend/CodeGenOptions.h"
30#include "llvm/ADT/SmallVector.h"
31#include "llvm/ADT/StringExtras.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000032#include "llvm/IR/Constants.h"
33#include "llvm/IR/DataLayout.h"
34#include "llvm/IR/DerivedTypes.h"
35#include "llvm/IR/Instructions.h"
36#include "llvm/IR/Intrinsics.h"
37#include "llvm/IR/Module.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000038#include "llvm/Support/Dwarf.h"
39#include "llvm/Support/FileSystem.h"
Adrian Prantl0630eb72013-12-18 21:48:18 +000040#include "llvm/Support/Path.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000041using namespace clang;
42using namespace clang::CodeGen;
43
44CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
Eric Christopher324bbbd2013-07-14 21:12:44 +000045 : CGM(CGM), DebugKind(CGM.getCodeGenOpts().getDebugInfo()),
46 DBuilder(CGM.getModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +000047 CreateCompileUnit();
48}
49
50CGDebugInfo::~CGDebugInfo() {
51 assert(LexicalBlockStack.empty() &&
52 "Region stack mismatch, stack not empty!");
53}
54
Eric Christopher0a1301f2014-02-26 02:49:36 +000055SaveAndRestoreLocation::SaveAndRestoreLocation(CodeGenFunction &CGF,
56 CGBuilderTy &B)
57 : DI(CGF.getDebugInfo()), Builder(B) {
Adrian Prantl2e0637f2013-07-18 00:28:02 +000058 if (DI) {
59 SavedLoc = DI->getLocation();
60 DI->CurLoc = SourceLocation();
Adrian Prantl2e0637f2013-07-18 00:28:02 +000061 }
62}
63
Adrian Prantld1b151e2014-01-17 00:15:10 +000064SaveAndRestoreLocation::~SaveAndRestoreLocation() {
65 if (DI)
66 DI->EmitLocation(Builder, SavedLoc);
67}
68
69NoLocation::NoLocation(CodeGenFunction &CGF, CGBuilderTy &B)
70 : SaveAndRestoreLocation(CGF, B) {
71 if (DI)
72 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
73}
74
Adrian Prantl2e0637f2013-07-18 00:28:02 +000075NoLocation::~NoLocation() {
Adrian Prantld1b151e2014-01-17 00:15:10 +000076 if (DI)
Adrian Prantl2e0637f2013-07-18 00:28:02 +000077 assert(Builder.getCurrentDebugLocation().isUnknown());
Adrian Prantl2e0637f2013-07-18 00:28:02 +000078}
79
Adrian Prantlb75016d2013-07-18 01:36:04 +000080ArtificialLocation::ArtificialLocation(CodeGenFunction &CGF, CGBuilderTy &B)
Adrian Prantld1b151e2014-01-17 00:15:10 +000081 : SaveAndRestoreLocation(CGF, B) {
82 if (DI)
Adrian Prantl49a78562013-07-24 20:34:39 +000083 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
Adrian Prantl49a78562013-07-24 20:34:39 +000084}
85
86void ArtificialLocation::Emit() {
87 if (DI) {
Adrian Prantl2e0637f2013-07-18 00:28:02 +000088 // Sync the Builder.
89 DI->EmitLocation(Builder, SavedLoc);
90 DI->CurLoc = SourceLocation();
91 // Construct a location that has a valid scope, but no line info.
Adrian Prantl49a78562013-07-24 20:34:39 +000092 assert(!DI->LexicalBlockStack.empty());
93 llvm::DIDescriptor Scope(DI->LexicalBlockStack.back());
Adrian Prantl2e0637f2013-07-18 00:28:02 +000094 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(0, 0, Scope));
95 }
96}
97
Adrian Prantlb75016d2013-07-18 01:36:04 +000098ArtificialLocation::~ArtificialLocation() {
Adrian Prantld1b151e2014-01-17 00:15:10 +000099 if (DI)
Adrian Prantl2e0637f2013-07-18 00:28:02 +0000100 assert(Builder.getCurrentDebugLocation().getLine() == 0);
Adrian Prantl2e0637f2013-07-18 00:28:02 +0000101}
102
Guy Benyei11169dd2012-12-18 14:30:41 +0000103void CGDebugInfo::setLocation(SourceLocation Loc) {
104 // If the new location isn't valid return.
Adrian Prantlb1b3bfc2013-07-18 00:27:56 +0000105 if (Loc.isInvalid()) return;
Guy Benyei11169dd2012-12-18 14:30:41 +0000106
107 CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc);
108
109 // If we've changed files in the middle of a lexical scope go ahead
110 // and create a new lexical scope with file node if it's different
111 // from the one in the scope.
112 if (LexicalBlockStack.empty()) return;
113
114 SourceManager &SM = CGM.getContext().getSourceManager();
115 PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
116 PresumedLoc PPLoc = SM.getPresumedLoc(PrevLoc);
117
118 if (PCLoc.isInvalid() || PPLoc.isInvalid() ||
119 !strcmp(PPLoc.getFilename(), PCLoc.getFilename()))
120 return;
121
122 llvm::MDNode *LB = LexicalBlockStack.back();
123 llvm::DIScope Scope = llvm::DIScope(LB);
124 if (Scope.isLexicalBlockFile()) {
125 llvm::DILexicalBlockFile LBF = llvm::DILexicalBlockFile(LB);
126 llvm::DIDescriptor D
127 = DBuilder.createLexicalBlockFile(LBF.getScope(),
128 getOrCreateFile(CurLoc));
129 llvm::MDNode *N = D;
130 LexicalBlockStack.pop_back();
131 LexicalBlockStack.push_back(N);
David Blaikie0a21d0d2013-01-26 22:16:26 +0000132 } else if (Scope.isLexicalBlock() || Scope.isSubprogram()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000133 llvm::DIDescriptor D
134 = DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc));
135 llvm::MDNode *N = D;
136 LexicalBlockStack.pop_back();
137 LexicalBlockStack.push_back(N);
138 }
139}
140
141/// getContextDescriptor - Get context info for the decl.
David Blaikiebfa52742013-04-19 06:56:38 +0000142llvm::DIScope CGDebugInfo::getContextDescriptor(const Decl *Context) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000143 if (!Context)
144 return TheCU;
145
146 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
147 I = RegionMap.find(Context);
148 if (I != RegionMap.end()) {
149 llvm::Value *V = I->second;
David Blaikiebfa52742013-04-19 06:56:38 +0000150 return llvm::DIScope(dyn_cast_or_null<llvm::MDNode>(V));
Guy Benyei11169dd2012-12-18 14:30:41 +0000151 }
152
153 // Check namespace.
154 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
David Blaikiebfa52742013-04-19 06:56:38 +0000155 return getOrCreateNameSpace(NSDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +0000156
David Blaikiebfa52742013-04-19 06:56:38 +0000157 if (const RecordDecl *RDecl = dyn_cast<RecordDecl>(Context))
158 if (!RDecl->isDependentType())
159 return getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
Guy Benyei11169dd2012-12-18 14:30:41 +0000160 getOrCreateMainFile());
Guy Benyei11169dd2012-12-18 14:30:41 +0000161 return TheCU;
162}
163
164/// getFunctionName - Get function name for the given FunctionDecl. If the
Benjamin Kramer60509af2013-09-09 14:48:42 +0000165/// name is constructed on demand (e.g. C++ destructor) then the name
Guy Benyei11169dd2012-12-18 14:30:41 +0000166/// is stored on the side.
167StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
168 assert (FD && "Invalid FunctionDecl!");
169 IdentifierInfo *FII = FD->getIdentifier();
170 FunctionTemplateSpecializationInfo *Info
171 = FD->getTemplateSpecializationInfo();
172 if (!Info && FII)
173 return FII->getName();
174
175 // Otherwise construct human readable name for debug info.
Benjamin Kramer9170e912013-02-22 15:46:01 +0000176 SmallString<128> NS;
177 llvm::raw_svector_ostream OS(NS);
178 FD->printName(OS);
Guy Benyei11169dd2012-12-18 14:30:41 +0000179
180 // Add any template specialization args.
181 if (Info) {
182 const TemplateArgumentList *TArgs = Info->TemplateArguments;
183 const TemplateArgument *Args = TArgs->data();
184 unsigned NumArgs = TArgs->size();
185 PrintingPolicy Policy(CGM.getLangOpts());
Benjamin Kramer9170e912013-02-22 15:46:01 +0000186 TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs,
187 Policy);
Guy Benyei11169dd2012-12-18 14:30:41 +0000188 }
189
190 // Copy this name on the side and use its reference.
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +0000191 return internString(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +0000192}
193
194StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
195 SmallString<256> MethodName;
196 llvm::raw_svector_ostream OS(MethodName);
197 OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
198 const DeclContext *DC = OMD->getDeclContext();
Eric Christopherb2a008c2013-05-16 00:45:12 +0000199 if (const ObjCImplementationDecl *OID =
Guy Benyei11169dd2012-12-18 14:30:41 +0000200 dyn_cast<const ObjCImplementationDecl>(DC)) {
201 OS << OID->getName();
Eric Christopherb2a008c2013-05-16 00:45:12 +0000202 } else if (const ObjCInterfaceDecl *OID =
Guy Benyei11169dd2012-12-18 14:30:41 +0000203 dyn_cast<const ObjCInterfaceDecl>(DC)) {
204 OS << OID->getName();
Eric Christopherb2a008c2013-05-16 00:45:12 +0000205 } else if (const ObjCCategoryImplDecl *OCD =
Guy Benyei11169dd2012-12-18 14:30:41 +0000206 dyn_cast<const ObjCCategoryImplDecl>(DC)){
207 OS << ((const NamedDecl *)OCD)->getIdentifier()->getNameStart() << '(' <<
208 OCD->getIdentifier()->getNameStart() << ')';
Adrian Prantlb39fc142013-05-17 23:58:45 +0000209 } else if (isa<ObjCProtocolDecl>(DC)) {
Adrian Prantl6e785ec2013-05-17 23:49:10 +0000210 // We can extract the type of the class from the self pointer.
211 if (ImplicitParamDecl* SelfDecl = OMD->getSelfDecl()) {
212 QualType ClassTy =
213 cast<ObjCObjectPointerType>(SelfDecl->getType())->getPointeeType();
214 ClassTy.print(OS, PrintingPolicy(LangOptions()));
215 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000216 }
217 OS << ' ' << OMD->getSelector().getAsString() << ']';
218
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +0000219 return internString(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +0000220}
221
222/// getSelectorName - Return selector name. This is used for debugging
223/// info.
224StringRef CGDebugInfo::getSelectorName(Selector S) {
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +0000225 return internString(S.getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +0000226}
227
228/// getClassName - Get class name including template argument list.
Eric Christopherb2a008c2013-05-16 00:45:12 +0000229StringRef
Guy Benyei11169dd2012-12-18 14:30:41 +0000230CGDebugInfo::getClassName(const RecordDecl *RD) {
David Blaikie65813a32014-04-02 18:21:09 +0000231 // quick optimization to avoid having to intern strings that are already
232 // stored reliably elsewhere
233 if (!isa<ClassTemplateSpecializationDecl>(RD))
Guy Benyei11169dd2012-12-18 14:30:41 +0000234 return RD->getName();
235
David Blaikie65813a32014-04-02 18:21:09 +0000236 SmallString<128> Name;
Benjamin Kramer9170e912013-02-22 15:46:01 +0000237 {
David Blaikie65813a32014-04-02 18:21:09 +0000238 llvm::raw_svector_ostream OS(Name);
239 RD->getNameForDiagnostic(OS, CGM.getContext().getPrintingPolicy(),
240 /*Qualified*/ false);
Benjamin Kramer9170e912013-02-22 15:46:01 +0000241 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000242
243 // Copy this name on the side and use its reference.
David Blaikie65813a32014-04-02 18:21:09 +0000244 return internString(Name);
Guy Benyei11169dd2012-12-18 14:30:41 +0000245}
246
247/// getOrCreateFile - Get the file debug info descriptor for the input location.
248llvm::DIFile CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
249 if (!Loc.isValid())
250 // If Location is not valid then use main input file.
251 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
252
253 SourceManager &SM = CGM.getContext().getSourceManager();
254 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
255
256 if (PLoc.isInvalid() || StringRef(PLoc.getFilename()).empty())
257 // If the location is not valid then use main input file.
258 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
259
260 // Cache the results.
261 const char *fname = PLoc.getFilename();
262 llvm::DenseMap<const char *, llvm::WeakVH>::iterator it =
263 DIFileCache.find(fname);
264
265 if (it != DIFileCache.end()) {
266 // Verify that the information still exists.
267 if (llvm::Value *V = it->second)
268 return llvm::DIFile(cast<llvm::MDNode>(V));
269 }
270
271 llvm::DIFile F = DBuilder.createFile(PLoc.getFilename(), getCurrentDirname());
272
273 DIFileCache[fname] = F;
274 return F;
275}
276
277/// getOrCreateMainFile - Get the file info for main compile unit.
278llvm::DIFile CGDebugInfo::getOrCreateMainFile() {
279 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
280}
281
282/// getLineNumber - Get line number for the location. If location is invalid
283/// then use current location.
284unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
285 if (Loc.isInvalid() && CurLoc.isInvalid())
286 return 0;
287 SourceManager &SM = CGM.getContext().getSourceManager();
288 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
289 return PLoc.isValid()? PLoc.getLine() : 0;
290}
291
292/// getColumnNumber - Get column number for the location.
Adrian Prantlc7822422013-03-12 20:43:25 +0000293unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000294 // We may not want column information at all.
Adrian Prantlc7822422013-03-12 20:43:25 +0000295 if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo)
Guy Benyei11169dd2012-12-18 14:30:41 +0000296 return 0;
297
298 // If the location is invalid then use the current column.
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.getColumn() : 0;
304}
305
306StringRef CGDebugInfo::getCurrentDirname() {
307 if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
308 return CGM.getCodeGenOpts().DebugCompilationDir;
309
310 if (!CWDName.empty())
311 return CWDName;
312 SmallString<256> CWD;
313 llvm::sys::fs::current_path(CWD);
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +0000314 return CWDName = internString(CWD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000315}
316
317/// CreateCompileUnit - Create new compile unit.
318void CGDebugInfo::CreateCompileUnit() {
319
320 // Get absolute path name.
321 SourceManager &SM = CGM.getContext().getSourceManager();
322 std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
323 if (MainFileName.empty())
324 MainFileName = "<unknown>";
325
326 // The main file name provided via the "-main-file-name" option contains just
327 // the file name itself with no path information. This file name may have had
328 // a relative path, so we look into the actual file entry for the main
329 // file to determine the real absolute path for the file.
330 std::string MainFileDir;
331 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
332 MainFileDir = MainFile->getDir()->getName();
Yaron Keren9fb7e902013-10-21 20:07:37 +0000333 if (MainFileDir != ".") {
Eric Christopher0a1301f2014-02-26 02:49:36 +0000334 llvm::SmallString<1024> MainFileDirSS(MainFileDir);
335 llvm::sys::path::append(MainFileDirSS, MainFileName);
336 MainFileName = MainFileDirSS.str();
Yaron Keren9fb7e902013-10-21 20:07:37 +0000337 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000338 }
339
340 // Save filename string.
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +0000341 StringRef Filename = internString(MainFileName);
Eric Christopherf1545832013-02-22 23:50:16 +0000342
343 // Save split dwarf file string.
344 std::string SplitDwarfFile = CGM.getCodeGenOpts().SplitDwarfFile;
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +0000345 StringRef SplitDwarfFilename = internString(SplitDwarfFile);
Eric Christopherb2a008c2013-05-16 00:45:12 +0000346
Guy Benyei11169dd2012-12-18 14:30:41 +0000347 unsigned LangTag;
348 const LangOptions &LO = CGM.getLangOpts();
349 if (LO.CPlusPlus) {
350 if (LO.ObjC1)
351 LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
352 else
353 LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
354 } else if (LO.ObjC1) {
355 LangTag = llvm::dwarf::DW_LANG_ObjC;
356 } else if (LO.C99) {
357 LangTag = llvm::dwarf::DW_LANG_C99;
358 } else {
359 LangTag = llvm::dwarf::DW_LANG_C89;
360 }
361
362 std::string Producer = getClangFullVersion();
363
364 // Figure out which version of the ObjC runtime we have.
365 unsigned RuntimeVers = 0;
366 if (LO.ObjC1)
367 RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
368
369 // Create new compile unit.
Guy Benyei11169dd2012-12-18 14:30:41 +0000370 // FIXME - Eliminate TheCU.
Eric Christophere4200a22014-02-27 01:25:08 +0000371 TheCU = DBuilder.createCompileUnit(
372 LangTag, Filename, getCurrentDirname(), Producer, LO.Optimize,
373 CGM.getCodeGenOpts().DwarfDebugFlags, RuntimeVers, SplitDwarfFilename,
374 DebugKind == CodeGenOptions::DebugLineTablesOnly
375 ? llvm::DIBuilder::LineTablesOnly
376 : llvm::DIBuilder::FullDebug);
Guy Benyei11169dd2012-12-18 14:30:41 +0000377}
378
379/// CreateType - Get the Basic type from the cache or create a new
380/// one if necessary.
381llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT) {
382 unsigned Encoding = 0;
383 StringRef BTName;
384 switch (BT->getKind()) {
385#define BUILTIN_TYPE(Id, SingletonId)
386#define PLACEHOLDER_TYPE(Id, SingletonId) \
387 case BuiltinType::Id:
388#include "clang/AST/BuiltinTypes.def"
389 case BuiltinType::Dependent:
390 llvm_unreachable("Unexpected builtin type");
391 case BuiltinType::NullPtr:
Peter Collingbourne5c5e6172013-06-27 22:51:01 +0000392 return DBuilder.createNullPtrType();
Guy Benyei11169dd2012-12-18 14:30:41 +0000393 case BuiltinType::Void:
394 return llvm::DIType();
395 case BuiltinType::ObjCClass:
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000396 if (ClassTy)
Guy Benyei11169dd2012-12-18 14:30:41 +0000397 return ClassTy;
398 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
399 "objc_class", TheCU,
400 getOrCreateMainFile(), 0);
401 return ClassTy;
402 case BuiltinType::ObjCId: {
403 // typedef struct objc_class *Class;
404 // typedef struct objc_object {
405 // Class isa;
406 // } *id;
407
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000408 if (ObjTy)
Guy Benyei11169dd2012-12-18 14:30:41 +0000409 return ObjTy;
410
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000411 if (!ClassTy)
Guy Benyei11169dd2012-12-18 14:30:41 +0000412 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
413 "objc_class", TheCU,
414 getOrCreateMainFile(), 0);
415
416 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
Eric Christopherb2a008c2013-05-16 00:45:12 +0000417
Guy Benyei11169dd2012-12-18 14:30:41 +0000418 llvm::DIType ISATy = DBuilder.createPointerType(ClassTy, Size);
419
Eric Christopher5c7ee8b2013-04-02 22:59:11 +0000420 ObjTy =
David Blaikie6d4fe152013-02-25 01:07:08 +0000421 DBuilder.createStructType(TheCU, "objc_object", getOrCreateMainFile(),
422 0, 0, 0, 0, llvm::DIType(), llvm::DIArray());
Guy Benyei11169dd2012-12-18 14:30:41 +0000423
Eric Christopher5c7ee8b2013-04-02 22:59:11 +0000424 ObjTy.setTypeArray(DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
425 ObjTy, "isa", getOrCreateMainFile(), 0, Size, 0, 0, 0, ISATy)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000426 return ObjTy;
427 }
428 case BuiltinType::ObjCSel: {
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000429 if (SelTy)
Guy Benyei11169dd2012-12-18 14:30:41 +0000430 return SelTy;
431 SelTy =
432 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
433 "objc_selector", TheCU, getOrCreateMainFile(),
434 0);
435 return SelTy;
436 }
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000437
438 case BuiltinType::OCLImage1d:
439 return getOrCreateStructPtrType("opencl_image1d_t",
440 OCLImage1dDITy);
441 case BuiltinType::OCLImage1dArray:
Eric Christopherb2a008c2013-05-16 00:45:12 +0000442 return getOrCreateStructPtrType("opencl_image1d_array_t",
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000443 OCLImage1dArrayDITy);
444 case BuiltinType::OCLImage1dBuffer:
445 return getOrCreateStructPtrType("opencl_image1d_buffer_t",
446 OCLImage1dBufferDITy);
447 case BuiltinType::OCLImage2d:
448 return getOrCreateStructPtrType("opencl_image2d_t",
449 OCLImage2dDITy);
450 case BuiltinType::OCLImage2dArray:
451 return getOrCreateStructPtrType("opencl_image2d_array_t",
452 OCLImage2dArrayDITy);
453 case BuiltinType::OCLImage3d:
454 return getOrCreateStructPtrType("opencl_image3d_t",
455 OCLImage3dDITy);
Guy Benyei61054192013-02-07 10:55:47 +0000456 case BuiltinType::OCLSampler:
457 return DBuilder.createBasicType("opencl_sampler_t",
458 CGM.getContext().getTypeSize(BT),
459 CGM.getContext().getTypeAlign(BT),
460 llvm::dwarf::DW_ATE_unsigned);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +0000461 case BuiltinType::OCLEvent:
462 return getOrCreateStructPtrType("opencl_event_t",
463 OCLEventDITy);
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000464
Guy Benyei11169dd2012-12-18 14:30:41 +0000465 case BuiltinType::UChar:
466 case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
467 case BuiltinType::Char_S:
468 case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
469 case BuiltinType::Char16:
470 case BuiltinType::Char32: Encoding = llvm::dwarf::DW_ATE_UTF; break;
471 case BuiltinType::UShort:
472 case BuiltinType::UInt:
473 case BuiltinType::UInt128:
474 case BuiltinType::ULong:
475 case BuiltinType::WChar_U:
476 case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
477 case BuiltinType::Short:
478 case BuiltinType::Int:
479 case BuiltinType::Int128:
480 case BuiltinType::Long:
481 case BuiltinType::WChar_S:
482 case BuiltinType::LongLong: Encoding = llvm::dwarf::DW_ATE_signed; break;
483 case BuiltinType::Bool: Encoding = llvm::dwarf::DW_ATE_boolean; break;
484 case BuiltinType::Half:
485 case BuiltinType::Float:
486 case BuiltinType::LongDouble:
487 case BuiltinType::Double: Encoding = llvm::dwarf::DW_ATE_float; break;
488 }
489
490 switch (BT->getKind()) {
491 case BuiltinType::Long: BTName = "long int"; break;
492 case BuiltinType::LongLong: BTName = "long long int"; break;
493 case BuiltinType::ULong: BTName = "long unsigned int"; break;
494 case BuiltinType::ULongLong: BTName = "long long unsigned int"; break;
495 default:
496 BTName = BT->getName(CGM.getLangOpts());
497 break;
498 }
499 // Bit size, align and offset of the type.
500 uint64_t Size = CGM.getContext().getTypeSize(BT);
501 uint64_t Align = CGM.getContext().getTypeAlign(BT);
Eric Christopherb2a008c2013-05-16 00:45:12 +0000502 llvm::DIType DbgTy =
Guy Benyei11169dd2012-12-18 14:30:41 +0000503 DBuilder.createBasicType(BTName, Size, Align, Encoding);
504 return DbgTy;
505}
506
507llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty) {
508 // Bit size, align and offset of the type.
509 unsigned Encoding = llvm::dwarf::DW_ATE_complex_float;
510 if (Ty->isComplexIntegerType())
511 Encoding = llvm::dwarf::DW_ATE_lo_user;
512
513 uint64_t Size = CGM.getContext().getTypeSize(Ty);
514 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
Eric Christopherb2a008c2013-05-16 00:45:12 +0000515 llvm::DIType DbgTy =
Guy Benyei11169dd2012-12-18 14:30:41 +0000516 DBuilder.createBasicType("complex", Size, Align, Encoding);
517
518 return DbgTy;
519}
520
521/// CreateCVRType - Get the qualified type from the cache or create
522/// a new one if necessary.
David Blaikie99dab3b2013-09-04 22:03:57 +0000523llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000524 QualifierCollector Qc;
525 const Type *T = Qc.strip(Ty);
526
527 // Ignore these qualifiers for now.
528 Qc.removeObjCGCAttr();
529 Qc.removeAddressSpace();
530 Qc.removeObjCLifetime();
531
532 // We will create one Derived type for one qualifier and recurse to handle any
533 // additional ones.
534 unsigned Tag;
535 if (Qc.hasConst()) {
536 Tag = llvm::dwarf::DW_TAG_const_type;
537 Qc.removeConst();
538 } else if (Qc.hasVolatile()) {
539 Tag = llvm::dwarf::DW_TAG_volatile_type;
540 Qc.removeVolatile();
541 } else if (Qc.hasRestrict()) {
542 Tag = llvm::dwarf::DW_TAG_restrict_type;
543 Qc.removeRestrict();
544 } else {
545 assert(Qc.empty() && "Unknown type qualifier for debug info");
546 return getOrCreateType(QualType(T, 0), Unit);
547 }
548
David Blaikie99dab3b2013-09-04 22:03:57 +0000549 llvm::DIType FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +0000550
551 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
552 // CVR derived types.
553 llvm::DIType DbgTy = DBuilder.createQualifiedType(Tag, FromTy);
Eric Christopherb2a008c2013-05-16 00:45:12 +0000554
Guy Benyei11169dd2012-12-18 14:30:41 +0000555 return DbgTy;
556}
557
558llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
559 llvm::DIFile Unit) {
Fariborz Jahanian65f1fa12013-02-21 20:42:11 +0000560
561 // The frontend treats 'id' as a typedef to an ObjCObjectType,
562 // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
563 // debug info, we want to emit 'id' in both cases.
564 if (Ty->isObjCQualifiedIdType())
565 return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
566
Guy Benyei11169dd2012-12-18 14:30:41 +0000567 llvm::DIType DbgTy =
Eric Christopherb2a008c2013-05-16 00:45:12 +0000568 CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +0000569 Ty->getPointeeType(), Unit);
570 return DbgTy;
571}
572
573llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
574 llvm::DIFile Unit) {
Eric Christopherb2a008c2013-05-16 00:45:12 +0000575 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +0000576 Ty->getPointeeType(), Unit);
577}
578
Manman Rene0064d82013-08-29 23:19:58 +0000579/// In C++ mode, types have linkage, so we can rely on the ODR and
580/// on their mangled names, if they're external.
581static SmallString<256>
582getUniqueTagTypeName(const TagType *Ty, CodeGenModule &CGM,
583 llvm::DICompileUnit TheCU) {
584 SmallString<256> FullName;
585 // FIXME: ODR should apply to ObjC++ exactly the same wasy it does to C++.
586 // For now, only apply ODR with C++.
587 const TagDecl *TD = Ty->getDecl();
588 if (TheCU.getLanguage() != llvm::dwarf::DW_LANG_C_plus_plus ||
589 !TD->isExternallyVisible())
590 return FullName;
591 // Microsoft Mangler does not have support for mangleCXXRTTIName yet.
592 if (CGM.getTarget().getCXXABI().isMicrosoft())
593 return FullName;
594
595 // TODO: This is using the RTTI name. Is there a better way to get
596 // a unique string for a type?
597 llvm::raw_svector_ostream Out(FullName);
598 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(QualType(Ty, 0), Out);
599 Out.flush();
600 return FullName;
601}
602
Guy Benyei11169dd2012-12-18 14:30:41 +0000603// Creates a forward declaration for a RecordDecl in the given context.
David Blaikie8d5e1282013-08-20 21:03:29 +0000604llvm::DICompositeType
Manman Ren1b457022013-08-28 21:20:28 +0000605CGDebugInfo::getOrCreateRecordFwdDecl(const RecordType *Ty,
David Blaikie8d5e1282013-08-20 21:03:29 +0000606 llvm::DIDescriptor Ctx) {
Manman Ren1b457022013-08-28 21:20:28 +0000607 const RecordDecl *RD = Ty->getDecl();
David Blaikie4e7ef802013-08-15 20:17:25 +0000608 if (llvm::DIType T = getTypeOrNull(CGM.getContext().getRecordType(RD)))
David Blaikie8d5e1282013-08-20 21:03:29 +0000609 return llvm::DICompositeType(T);
Guy Benyei11169dd2012-12-18 14:30:41 +0000610 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
611 unsigned Line = getLineNumber(RD->getLocation());
612 StringRef RDName = getClassName(RD);
613
614 unsigned Tag = 0;
615 if (RD->isStruct() || RD->isInterface())
616 Tag = llvm::dwarf::DW_TAG_structure_type;
617 else if (RD->isUnion())
618 Tag = llvm::dwarf::DW_TAG_union_type;
619 else {
620 assert(RD->isClass());
621 Tag = llvm::dwarf::DW_TAG_class_type;
622 }
623
624 // Create the type.
Manman Rene0064d82013-08-29 23:19:58 +0000625 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
626 return DBuilder.createForwardDecl(Tag, RDName, Ctx, DefUnit, Line, 0, 0, 0,
627 FullName);
Guy Benyei11169dd2012-12-18 14:30:41 +0000628}
629
Guy Benyei11169dd2012-12-18 14:30:41 +0000630llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag,
Eric Christopherb2a008c2013-05-16 00:45:12 +0000631 const Type *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +0000632 QualType PointeeTy,
633 llvm::DIFile Unit) {
634 if (Tag == llvm::dwarf::DW_TAG_reference_type ||
635 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
David Blaikie99dab3b2013-09-04 22:03:57 +0000636 return DBuilder.createReferenceType(Tag, getOrCreateType(PointeeTy, Unit));
Fariborz Jahanian65f1fa12013-02-21 20:42:11 +0000637
Guy Benyei11169dd2012-12-18 14:30:41 +0000638 // Bit size, align and offset of the type.
639 // Size is always the size of a pointer. We can't use getTypeSize here
640 // because that does not return the correct value for references.
641 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCallc8e01702013-04-16 22:48:15 +0000642 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
Guy Benyei11169dd2012-12-18 14:30:41 +0000643 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
644
David Blaikie99dab3b2013-09-04 22:03:57 +0000645 return DBuilder.createPointerType(getOrCreateType(PointeeTy, Unit), Size,
646 Align);
Guy Benyei11169dd2012-12-18 14:30:41 +0000647}
648
Eric Christopher0fdcb312013-05-16 00:52:20 +0000649llvm::DIType CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
650 llvm::DIType &Cache) {
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000651 if (Cache)
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000652 return Cache;
David Blaikiefefc7f72013-05-21 17:58:54 +0000653 Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
654 TheCU, getOrCreateMainFile(), 0);
655 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
656 Cache = DBuilder.createPointerType(Cache, Size);
657 return Cache;
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000658}
659
Guy Benyei11169dd2012-12-18 14:30:41 +0000660llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
661 llvm::DIFile Unit) {
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000662 if (BlockLiteralGeneric)
Guy Benyei11169dd2012-12-18 14:30:41 +0000663 return BlockLiteralGeneric;
664
665 SmallVector<llvm::Value *, 8> EltTys;
666 llvm::DIType FieldTy;
667 QualType FType;
668 uint64_t FieldSize, FieldOffset;
669 unsigned FieldAlign;
670 llvm::DIArray Elements;
671 llvm::DIType EltTy, DescTy;
672
673 FieldOffset = 0;
674 FType = CGM.getContext().UnsignedLongTy;
675 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
676 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
677
678 Elements = DBuilder.getOrCreateArray(EltTys);
679 EltTys.clear();
680
681 unsigned Flags = llvm::DIDescriptor::FlagAppleBlock;
682 unsigned LineNo = getLineNumber(CurLoc);
683
684 EltTy = DBuilder.createStructType(Unit, "__block_descriptor",
685 Unit, LineNo, FieldOffset, 0,
David Blaikie6d4fe152013-02-25 01:07:08 +0000686 Flags, llvm::DIType(), Elements);
Guy Benyei11169dd2012-12-18 14:30:41 +0000687
688 // Bit size, align and offset of the type.
689 uint64_t Size = CGM.getContext().getTypeSize(Ty);
690
691 DescTy = DBuilder.createPointerType(EltTy, Size);
692
693 FieldOffset = 0;
694 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
695 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
696 FType = CGM.getContext().IntTy;
697 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
698 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
699 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
700 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
701
702 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
703 FieldTy = DescTy;
704 FieldSize = CGM.getContext().getTypeSize(Ty);
705 FieldAlign = CGM.getContext().getTypeAlign(Ty);
706 FieldTy = DBuilder.createMemberType(Unit, "__descriptor", Unit,
707 LineNo, FieldSize, FieldAlign,
708 FieldOffset, 0, FieldTy);
709 EltTys.push_back(FieldTy);
710
711 FieldOffset += FieldSize;
712 Elements = DBuilder.getOrCreateArray(EltTys);
713
714 EltTy = DBuilder.createStructType(Unit, "__block_literal_generic",
715 Unit, LineNo, FieldOffset, 0,
David Blaikie6d4fe152013-02-25 01:07:08 +0000716 Flags, llvm::DIType(), Elements);
Guy Benyei11169dd2012-12-18 14:30:41 +0000717
Guy Benyei11169dd2012-12-18 14:30:41 +0000718 BlockLiteralGeneric = DBuilder.createPointerType(EltTy, Size);
719 return BlockLiteralGeneric;
720}
721
David Blaikief1b382e2014-04-06 17:14:06 +0000722llvm::DIType CGDebugInfo::CreateType(const TemplateSpecializationType *Ty, llvm::DIFile Unit) {
723 assert(Ty->isTypeAlias());
724 llvm::DIType Src = getOrCreateType(Ty->getAliasedType(), Unit);
725 assert(Src);
726
727 SmallString<128> NS;
728 llvm::raw_svector_ostream OS(NS);
729 Ty->getTemplateName().print(OS, CGM.getContext().getPrintingPolicy(), /*qualified*/ false);
730
731 TemplateSpecializationType::PrintTemplateArgumentList(
732 OS, Ty->getArgs(), Ty->getNumArgs(),
733 CGM.getContext().getPrintingPolicy());
734
735 TypeAliasDecl *AliasDecl =
736 cast<TypeAliasTemplateDecl>(Ty->getTemplateName().getAsTemplateDecl())
737 ->getTemplatedDecl();
738
739 SourceLocation Loc = AliasDecl->getLocation();
740 llvm::DIFile File = getOrCreateFile(Loc);
741 unsigned Line = getLineNumber(Loc);
742
743 llvm::DIDescriptor Ctxt = getContextDescriptor(cast<Decl>(AliasDecl->getDeclContext()));
744
745 return DBuilder.createTypedef(Src, internString(OS.str()), File, Line, Ctxt);
746}
747
David Blaikie99dab3b2013-09-04 22:03:57 +0000748llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty, llvm::DIFile Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000749 // Typedefs are derived from some other type. If we have a typedef of a
750 // typedef, make sure to emit the whole chain.
David Blaikie99dab3b2013-09-04 22:03:57 +0000751 llvm::DIType Src = getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000752 if (!Src)
Guy Benyei11169dd2012-12-18 14:30:41 +0000753 return llvm::DIType();
754 // We don't set size information, but do specify where the typedef was
755 // declared.
Adrian Prantl3eff2252014-01-21 18:42:27 +0000756 SourceLocation Loc = Ty->getDecl()->getLocation();
757 llvm::DIFile File = getOrCreateFile(Loc);
758 unsigned Line = getLineNumber(Loc);
Guy Benyei11169dd2012-12-18 14:30:41 +0000759 const TypedefNameDecl *TyDecl = Ty->getDecl();
Eric Christopherb2a008c2013-05-16 00:45:12 +0000760
Guy Benyei11169dd2012-12-18 14:30:41 +0000761 llvm::DIDescriptor TypedefContext =
762 getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext()));
Eric Christopherb2a008c2013-05-16 00:45:12 +0000763
Guy Benyei11169dd2012-12-18 14:30:41 +0000764 return
Adrian Prantl3eff2252014-01-21 18:42:27 +0000765 DBuilder.createTypedef(Src, TyDecl->getName(), File, Line, TypedefContext);
Guy Benyei11169dd2012-12-18 14:30:41 +0000766}
767
768llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
769 llvm::DIFile Unit) {
770 SmallVector<llvm::Value *, 16> EltTys;
771
772 // Add the result type at least.
Alp Toker314cc812014-01-25 16:55:45 +0000773 EltTys.push_back(getOrCreateType(Ty->getReturnType(), Unit));
Guy Benyei11169dd2012-12-18 14:30:41 +0000774
775 // Set up remainder of arguments if there is a prototype.
Adrian Prantl800faef2014-02-25 23:42:18 +0000776 // otherwise emit it as a variadic function.
Guy Benyei11169dd2012-12-18 14:30:41 +0000777 if (isa<FunctionNoProtoType>(Ty))
778 EltTys.push_back(DBuilder.createUnspecifiedParameter());
779 else if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Ty)) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000780 for (unsigned i = 0, e = FPT->getNumParams(); i != e; ++i)
781 EltTys.push_back(getOrCreateType(FPT->getParamType(i), Unit));
Adrian Prantld45ba252014-02-25 19:38:11 +0000782 if (FPT->isVariadic())
783 EltTys.push_back(DBuilder.createUnspecifiedParameter());
Guy Benyei11169dd2012-12-18 14:30:41 +0000784 }
785
786 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
787 return DBuilder.createSubroutineType(Unit, EltTypeArray);
788}
789
790
Guy Benyei11169dd2012-12-18 14:30:41 +0000791llvm::DIType CGDebugInfo::createFieldType(StringRef name,
792 QualType type,
793 uint64_t sizeInBitsOverride,
794 SourceLocation loc,
795 AccessSpecifier AS,
796 uint64_t offsetInBits,
797 llvm::DIFile tunit,
Manman Ren2c826dc2013-09-08 03:45:05 +0000798 llvm::DIScope scope) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000799 llvm::DIType debugType = getOrCreateType(type, tunit);
800
801 // Get the location for the field.
802 llvm::DIFile file = getOrCreateFile(loc);
803 unsigned line = getLineNumber(loc);
804
805 uint64_t sizeInBits = 0;
806 unsigned alignInBits = 0;
807 if (!type->isIncompleteArrayType()) {
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000808 std::tie(sizeInBits, alignInBits) = CGM.getContext().getTypeInfo(type);
Guy Benyei11169dd2012-12-18 14:30:41 +0000809
810 if (sizeInBitsOverride)
811 sizeInBits = sizeInBitsOverride;
812 }
813
814 unsigned flags = 0;
815 if (AS == clang::AS_private)
816 flags |= llvm::DIDescriptor::FlagPrivate;
817 else if (AS == clang::AS_protected)
818 flags |= llvm::DIDescriptor::FlagProtected;
819
820 return DBuilder.createMemberType(scope, name, file, line, sizeInBits,
821 alignInBits, offsetInBits, flags, debugType);
822}
823
Eric Christopher91a31902013-01-16 01:22:32 +0000824/// CollectRecordLambdaFields - Helper for CollectRecordFields.
825void CGDebugInfo::
826CollectRecordLambdaFields(const CXXRecordDecl *CXXDecl,
827 SmallVectorImpl<llvm::Value *> &elements,
828 llvm::DIType RecordTy) {
829 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
830 // has the name and the location of the variable so we should iterate over
831 // both concurrently.
832 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
833 RecordDecl::field_iterator Field = CXXDecl->field_begin();
834 unsigned fieldno = 0;
835 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
836 E = CXXDecl->captures_end(); I != E; ++I, ++Field, ++fieldno) {
837 const LambdaExpr::Capture C = *I;
838 if (C.capturesVariable()) {
839 VarDecl *V = C.getCapturedVar();
840 llvm::DIFile VUnit = getOrCreateFile(C.getLocation());
841 StringRef VName = V->getName();
842 uint64_t SizeInBitsOverride = 0;
843 if (Field->isBitField()) {
844 SizeInBitsOverride = Field->getBitWidthValue(CGM.getContext());
845 assert(SizeInBitsOverride && "found named 0-width bitfield");
846 }
847 llvm::DIType fieldType
848 = createFieldType(VName, Field->getType(), SizeInBitsOverride,
849 C.getLocation(), Field->getAccess(),
850 layout.getFieldOffset(fieldno), VUnit, RecordTy);
851 elements.push_back(fieldType);
852 } else {
853 // TODO: Need to handle 'this' in some way by probably renaming the
854 // this of the lambda class and having a field member of 'this' or
855 // by using AT_object_pointer for the function and having that be
856 // used as 'this' for semantic references.
857 assert(C.capturesThis() && "Field that isn't captured and isn't this?");
858 FieldDecl *f = *Field;
859 llvm::DIFile VUnit = getOrCreateFile(f->getLocation());
860 QualType type = f->getType();
861 llvm::DIType fieldType
862 = createFieldType("this", type, 0, f->getLocation(), f->getAccess(),
863 layout.getFieldOffset(fieldno), VUnit, RecordTy);
864
865 elements.push_back(fieldType);
866 }
867 }
868}
869
David Blaikie6943dea2013-08-20 01:28:15 +0000870/// Helper for CollectRecordFields.
David Blaikieae019462013-08-15 22:50:29 +0000871llvm::DIDerivedType
872CGDebugInfo::CreateRecordStaticField(const VarDecl *Var,
873 llvm::DIType RecordTy) {
Eric Christopher91a31902013-01-16 01:22:32 +0000874 // Create the descriptor for the static variable, with or without
875 // constant initializers.
876 llvm::DIFile VUnit = getOrCreateFile(Var->getLocation());
877 llvm::DIType VTy = getOrCreateType(Var->getType(), VUnit);
878
Eric Christopher91a31902013-01-16 01:22:32 +0000879 unsigned LineNumber = getLineNumber(Var->getLocation());
880 StringRef VName = Var->getName();
David Blaikied42917f2013-01-20 01:19:17 +0000881 llvm::Constant *C = NULL;
Eric Christopher91a31902013-01-16 01:22:32 +0000882 if (Var->getInit()) {
883 const APValue *Value = Var->evaluateValue();
David Blaikied42917f2013-01-20 01:19:17 +0000884 if (Value) {
885 if (Value->isInt())
886 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
887 if (Value->isFloat())
888 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
889 }
Eric Christopher91a31902013-01-16 01:22:32 +0000890 }
891
892 unsigned Flags = 0;
893 AccessSpecifier Access = Var->getAccess();
894 if (Access == clang::AS_private)
895 Flags |= llvm::DIDescriptor::FlagPrivate;
896 else if (Access == clang::AS_protected)
897 Flags |= llvm::DIDescriptor::FlagProtected;
898
David Blaikieae019462013-08-15 22:50:29 +0000899 llvm::DIDerivedType GV = DBuilder.createStaticMemberType(
900 RecordTy, VName, VUnit, LineNumber, VTy, Flags, C);
Eric Christopher91a31902013-01-16 01:22:32 +0000901 StaticDataMemberCache[Var->getCanonicalDecl()] = llvm::WeakVH(GV);
David Blaikieae019462013-08-15 22:50:29 +0000902 return GV;
Eric Christopher91a31902013-01-16 01:22:32 +0000903}
904
905/// CollectRecordNormalField - Helper for CollectRecordFields.
906void CGDebugInfo::
907CollectRecordNormalField(const FieldDecl *field, uint64_t OffsetInBits,
908 llvm::DIFile tunit,
909 SmallVectorImpl<llvm::Value *> &elements,
910 llvm::DIType RecordTy) {
911 StringRef name = field->getName();
912 QualType type = field->getType();
913
914 // Ignore unnamed fields unless they're anonymous structs/unions.
915 if (name.empty() && !type->isRecordType())
916 return;
917
918 uint64_t SizeInBitsOverride = 0;
919 if (field->isBitField()) {
920 SizeInBitsOverride = field->getBitWidthValue(CGM.getContext());
921 assert(SizeInBitsOverride && "found named 0-width bitfield");
922 }
923
924 llvm::DIType fieldType
925 = createFieldType(name, type, SizeInBitsOverride,
926 field->getLocation(), field->getAccess(),
927 OffsetInBits, tunit, RecordTy);
928
929 elements.push_back(fieldType);
930}
931
Guy Benyei11169dd2012-12-18 14:30:41 +0000932/// CollectRecordFields - A helper function to collect debug info for
933/// record fields. This is used while creating debug info entry for a Record.
David Blaikieab255bb2013-08-16 20:40:25 +0000934void CGDebugInfo::CollectRecordFields(const RecordDecl *record,
935 llvm::DIFile tunit,
936 SmallVectorImpl<llvm::Value *> &elements,
937 llvm::DICompositeType RecordTy) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000938 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(record);
939
Eric Christopher91a31902013-01-16 01:22:32 +0000940 if (CXXDecl && CXXDecl->isLambda())
941 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
942 else {
943 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
Guy Benyei11169dd2012-12-18 14:30:41 +0000944
Eric Christopher91a31902013-01-16 01:22:32 +0000945 // Field number for non-static fields.
Eric Christopher0f7594372013-01-04 17:59:07 +0000946 unsigned fieldNo = 0;
Eric Christopher91a31902013-01-16 01:22:32 +0000947
Eric Christopher91a31902013-01-16 01:22:32 +0000948 // Static and non-static members should appear in the same order as
949 // the corresponding declarations in the source program.
Aaron Ballman629afae2014-03-07 19:56:05 +0000950 for (const auto *I : record->decls())
951 if (const auto *V = dyn_cast<VarDecl>(I)) {
David Blaikiece763042013-08-20 21:49:21 +0000952 // Reuse the existing static member declaration if one exists
953 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator MI =
954 StaticDataMemberCache.find(V->getCanonicalDecl());
955 if (MI != StaticDataMemberCache.end()) {
956 assert(MI->second &&
957 "Static data member declaration should still exist");
958 elements.push_back(
959 llvm::DIDerivedType(cast<llvm::MDNode>(MI->second)));
960 } else
961 elements.push_back(CreateRecordStaticField(V, RecordTy));
Aaron Ballman629afae2014-03-07 19:56:05 +0000962 } else if (const auto *field = dyn_cast<FieldDecl>(I)) {
Eric Christopher91a31902013-01-16 01:22:32 +0000963 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo),
964 tunit, elements, RecordTy);
965
966 // Bump field number for next field.
967 ++fieldNo;
Guy Benyei11169dd2012-12-18 14:30:41 +0000968 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000969 }
970}
971
972/// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
973/// function type is not updated to include implicit "this" pointer. Use this
974/// routine to get a method type which includes "this" pointer.
David Blaikie469f0792013-05-22 23:22:42 +0000975llvm::DICompositeType
Guy Benyei11169dd2012-12-18 14:30:41 +0000976CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
977 llvm::DIFile Unit) {
David Blaikie7eb06852013-01-07 23:06:35 +0000978 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
David Blaikie2aaf0652013-01-07 22:24:59 +0000979 if (Method->isStatic())
David Blaikie469f0792013-05-22 23:22:42 +0000980 return llvm::DICompositeType(getOrCreateType(QualType(Func, 0), Unit));
David Blaikie7eb06852013-01-07 23:06:35 +0000981 return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()),
982 Func, Unit);
983}
David Blaikie2aaf0652013-01-07 22:24:59 +0000984
David Blaikie469f0792013-05-22 23:22:42 +0000985llvm::DICompositeType CGDebugInfo::getOrCreateInstanceMethodType(
David Blaikie7eb06852013-01-07 23:06:35 +0000986 QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000987 // Add "this" pointer.
David Blaikie7eb06852013-01-07 23:06:35 +0000988 llvm::DIArray Args = llvm::DICompositeType(
989 getOrCreateType(QualType(Func, 0), Unit)).getTypeArray();
Guy Benyei11169dd2012-12-18 14:30:41 +0000990 assert (Args.getNumElements() && "Invalid number of arguments!");
991
992 SmallVector<llvm::Value *, 16> Elts;
993
994 // First element is always return type. For 'void' functions it is NULL.
995 Elts.push_back(Args.getElement(0));
996
David Blaikie2aaf0652013-01-07 22:24:59 +0000997 // "this" pointer is always first argument.
David Blaikie7eb06852013-01-07 23:06:35 +0000998 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
David Blaikie2aaf0652013-01-07 22:24:59 +0000999 if (isa<ClassTemplateSpecializationDecl>(RD)) {
1000 // Create pointer type directly in this case.
1001 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
1002 QualType PointeeTy = ThisPtrTy->getPointeeType();
1003 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCallc8e01702013-04-16 22:48:15 +00001004 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
David Blaikie2aaf0652013-01-07 22:24:59 +00001005 uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy);
1006 llvm::DIType PointeeType = getOrCreateType(PointeeTy, Unit);
Eric Christopher0fdcb312013-05-16 00:52:20 +00001007 llvm::DIType ThisPtrType =
1008 DBuilder.createPointerType(PointeeType, Size, Align);
David Blaikie2aaf0652013-01-07 22:24:59 +00001009 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
1010 // TODO: This and the artificial type below are misleading, the
1011 // types aren't artificial the argument is, but the current
1012 // metadata doesn't represent that.
1013 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1014 Elts.push_back(ThisPtrType);
1015 } else {
1016 llvm::DIType ThisPtrType = getOrCreateType(ThisPtr, Unit);
1017 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
1018 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1019 Elts.push_back(ThisPtrType);
Guy Benyei11169dd2012-12-18 14:30:41 +00001020 }
1021
1022 // Copy rest of the arguments.
1023 for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
1024 Elts.push_back(Args.getElement(i));
1025
1026 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
1027
Adrian Prantl0630eb72013-12-18 21:48:18 +00001028 unsigned Flags = 0;
1029 if (Func->getExtProtoInfo().RefQualifier == RQ_LValue)
1030 Flags |= llvm::DIDescriptor::FlagLValueReference;
1031 if (Func->getExtProtoInfo().RefQualifier == RQ_RValue)
1032 Flags |= llvm::DIDescriptor::FlagRValueReference;
1033
1034 return DBuilder.createSubroutineType(Unit, EltTypeArray, Flags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001035}
1036
Eric Christopherb2a008c2013-05-16 00:45:12 +00001037/// isFunctionLocalClass - Return true if CXXRecordDecl is defined
Guy Benyei11169dd2012-12-18 14:30:41 +00001038/// inside a function.
1039static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
1040 if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
1041 return isFunctionLocalClass(NRD);
1042 if (isa<FunctionDecl>(RD->getDeclContext()))
1043 return true;
1044 return false;
1045}
1046
1047/// CreateCXXMemberFunction - A helper function to create a DISubprogram for
1048/// a single member function GlobalDecl.
1049llvm::DISubprogram
1050CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
1051 llvm::DIFile Unit,
1052 llvm::DIType RecordTy) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001053 bool IsCtorOrDtor =
Guy Benyei11169dd2012-12-18 14:30:41 +00001054 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
Eric Christopherb2a008c2013-05-16 00:45:12 +00001055
Guy Benyei11169dd2012-12-18 14:30:41 +00001056 StringRef MethodName = getFunctionName(Method);
David Blaikie469f0792013-05-22 23:22:42 +00001057 llvm::DICompositeType MethodTy = getOrCreateMethodType(Method, Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00001058
1059 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1060 // make sense to give a single ctor/dtor a linkage name.
1061 StringRef MethodLinkageName;
1062 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1063 MethodLinkageName = CGM.getMangledName(Method);
1064
1065 // Get the location for the method.
David Blaikie7fceebf2013-08-19 03:37:48 +00001066 llvm::DIFile MethodDefUnit;
1067 unsigned MethodLine = 0;
1068 if (!Method->isImplicit()) {
1069 MethodDefUnit = getOrCreateFile(Method->getLocation());
1070 MethodLine = getLineNumber(Method->getLocation());
1071 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001072
1073 // Collect virtual method info.
1074 llvm::DIType ContainingType;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001075 unsigned Virtuality = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00001076 unsigned VIndex = 0;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001077
Guy Benyei11169dd2012-12-18 14:30:41 +00001078 if (Method->isVirtual()) {
1079 if (Method->isPure())
1080 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
1081 else
1082 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001083
Guy Benyei11169dd2012-12-18 14:30:41 +00001084 // It doesn't make sense to give a virtual destructor a vtable index,
1085 // since a single destructor has two entries in the vtable.
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001086 // FIXME: Add proper support for debug info for virtual calls in
1087 // the Microsoft ABI, where we may use multiple vptrs to make a vftable
1088 // lookup if we have multiple or virtual inheritance.
1089 if (!isa<CXXDestructorDecl>(Method) &&
1090 !CGM.getTarget().getCXXABI().isMicrosoft())
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001091 VIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(Method);
Guy Benyei11169dd2012-12-18 14:30:41 +00001092 ContainingType = RecordTy;
1093 }
1094
1095 unsigned Flags = 0;
1096 if (Method->isImplicit())
1097 Flags |= llvm::DIDescriptor::FlagArtificial;
1098 AccessSpecifier Access = Method->getAccess();
1099 if (Access == clang::AS_private)
1100 Flags |= llvm::DIDescriptor::FlagPrivate;
1101 else if (Access == clang::AS_protected)
1102 Flags |= llvm::DIDescriptor::FlagProtected;
1103 if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1104 if (CXXC->isExplicit())
1105 Flags |= llvm::DIDescriptor::FlagExplicit;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001106 } else if (const CXXConversionDecl *CXXC =
Guy Benyei11169dd2012-12-18 14:30:41 +00001107 dyn_cast<CXXConversionDecl>(Method)) {
1108 if (CXXC->isExplicit())
1109 Flags |= llvm::DIDescriptor::FlagExplicit;
1110 }
1111 if (Method->hasPrototype())
1112 Flags |= llvm::DIDescriptor::FlagPrototyped;
Adrian Prantl0630eb72013-12-18 21:48:18 +00001113 if (Method->getRefQualifier() == RQ_LValue)
1114 Flags |= llvm::DIDescriptor::FlagLValueReference;
1115 if (Method->getRefQualifier() == RQ_RValue)
1116 Flags |= llvm::DIDescriptor::FlagRValueReference;
Guy Benyei11169dd2012-12-18 14:30:41 +00001117
1118 llvm::DIArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1119 llvm::DISubprogram SP =
Eric Christopherb2a008c2013-05-16 00:45:12 +00001120 DBuilder.createMethod(RecordTy, MethodName, MethodLinkageName,
Guy Benyei11169dd2012-12-18 14:30:41 +00001121 MethodDefUnit, MethodLine,
Eric Christopherb2a008c2013-05-16 00:45:12 +00001122 MethodTy, /*isLocalToUnit=*/false,
Guy Benyei11169dd2012-12-18 14:30:41 +00001123 /* isDefinition=*/ false,
1124 Virtuality, VIndex, ContainingType,
1125 Flags, CGM.getLangOpts().Optimize, NULL,
1126 TParamsArray);
Eric Christopherb2a008c2013-05-16 00:45:12 +00001127
Guy Benyei11169dd2012-12-18 14:30:41 +00001128 SPCache[Method->getCanonicalDecl()] = llvm::WeakVH(SP);
1129
1130 return SP;
1131}
1132
1133/// CollectCXXMemberFunctions - A helper function to collect debug info for
Eric Christopherb2a008c2013-05-16 00:45:12 +00001134/// C++ member functions. This is used while creating debug info entry for
Guy Benyei11169dd2012-12-18 14:30:41 +00001135/// a Record.
1136void CGDebugInfo::
1137CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
1138 SmallVectorImpl<llvm::Value *> &EltTys,
1139 llvm::DIType RecordTy) {
1140
1141 // Since we want more than just the individual member decls if we
1142 // have templated functions iterate over every declaration to gather
1143 // the functions.
Aaron Ballman629afae2014-03-07 19:56:05 +00001144 for(const auto *I : RD->decls()) {
1145 if (const auto *Method = dyn_cast<CXXMethodDecl>(I)) {
David Blaikiea6cc8212013-08-28 20:58:00 +00001146 // Reuse the existing member function declaration if it exists.
David Blaikie8c8e8e22013-08-28 20:24:55 +00001147 // It may be associated with the declaration of the type & should be
1148 // reused as we're building the definition.
David Blaikiea6cc8212013-08-28 20:58:00 +00001149 //
1150 // This situation can arise in the vtable-based debug info reduction where
1151 // implicit members are emitted in a non-vtable TU.
David Blaikie6943dea2013-08-20 01:28:15 +00001152 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator MI =
1153 SPCache.find(Method->getCanonicalDecl());
David Blaikiefae219a2013-08-28 17:27:13 +00001154 if (MI == SPCache.end()) {
David Blaikie8c8e8e22013-08-28 20:24:55 +00001155 // If the member is implicit, lazily create it when we see the
1156 // definition, not before. (an ODR-used implicit default ctor that's
1157 // never actually code generated should not produce debug info)
David Blaikiefae219a2013-08-28 17:27:13 +00001158 if (!Method->isImplicit())
1159 EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
1160 } else
David Blaikie6943dea2013-08-20 01:28:15 +00001161 EltTys.push_back(MI->second);
Aaron Ballman629afae2014-03-07 19:56:05 +00001162 } else if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(I)) {
David Blaikief2053af2013-08-28 23:06:52 +00001163 // Add any template specializations that have already been seen. Like
1164 // implicit member functions, these may have been added to a declaration
1165 // in the case of vtable-based debug info reduction.
Aaron Ballmanb8733c52014-03-14 16:05:56 +00001166 for (const auto *SI : FTD->specializations()) {
David Blaikief2053af2013-08-28 23:06:52 +00001167 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator MI =
Aaron Ballmanb8733c52014-03-14 16:05:56 +00001168 SPCache.find(cast<CXXMethodDecl>(SI)->getCanonicalDecl());
David Blaikief2053af2013-08-28 23:06:52 +00001169 if (MI != SPCache.end())
1170 EltTys.push_back(MI->second);
1171 }
David Blaikie6943dea2013-08-20 01:28:15 +00001172 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001173 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00001174}
Guy Benyei11169dd2012-12-18 14:30:41 +00001175
Guy Benyei11169dd2012-12-18 14:30:41 +00001176/// CollectCXXBases - A helper function to collect debug info for
Eric Christopherb2a008c2013-05-16 00:45:12 +00001177/// C++ base classes. This is used while creating debug info entry for
Guy Benyei11169dd2012-12-18 14:30:41 +00001178/// a Record.
1179void CGDebugInfo::
1180CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
1181 SmallVectorImpl<llvm::Value *> &EltTys,
1182 llvm::DIType RecordTy) {
1183
1184 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
Aaron Ballman574705e2014-03-13 15:41:46 +00001185 for (const auto &BI : RD->bases()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001186 unsigned BFlags = 0;
1187 uint64_t BaseOffset;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001188
Guy Benyei11169dd2012-12-18 14:30:41 +00001189 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00001190 cast<CXXRecordDecl>(BI.getType()->getAs<RecordType>()->getDecl());
Eric Christopherb2a008c2013-05-16 00:45:12 +00001191
Aaron Ballman574705e2014-03-13 15:41:46 +00001192 if (BI.isVirtual()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001193 // virtual base offset offset is -ve. The code generator emits dwarf
1194 // expression where it expects +ve number.
Eric Christopherb2a008c2013-05-16 00:45:12 +00001195 BaseOffset =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001196 0 - CGM.getItaniumVTableContext()
Guy Benyei11169dd2012-12-18 14:30:41 +00001197 .getVirtualBaseOffsetOffset(RD, Base).getQuantity();
1198 BFlags = llvm::DIDescriptor::FlagVirtual;
1199 } else
1200 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1201 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1202 // BI->isVirtual() and bits when not.
Eric Christopherb2a008c2013-05-16 00:45:12 +00001203
Aaron Ballman574705e2014-03-13 15:41:46 +00001204 AccessSpecifier Access = BI.getAccessSpecifier();
Guy Benyei11169dd2012-12-18 14:30:41 +00001205 if (Access == clang::AS_private)
1206 BFlags |= llvm::DIDescriptor::FlagPrivate;
1207 else if (Access == clang::AS_protected)
1208 BFlags |= llvm::DIDescriptor::FlagProtected;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001209
1210 llvm::DIType DTy =
1211 DBuilder.createInheritance(RecordTy,
Aaron Ballman574705e2014-03-13 15:41:46 +00001212 getOrCreateType(BI.getType(), Unit),
Guy Benyei11169dd2012-12-18 14:30:41 +00001213 BaseOffset, BFlags);
1214 EltTys.push_back(DTy);
1215 }
1216}
1217
1218/// CollectTemplateParams - A helper function to collect template parameters.
1219llvm::DIArray CGDebugInfo::
1220CollectTemplateParams(const TemplateParameterList *TPList,
David Blaikie47c11502013-06-22 18:59:18 +00001221 ArrayRef<TemplateArgument> TAList,
Guy Benyei11169dd2012-12-18 14:30:41 +00001222 llvm::DIFile Unit) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001223 SmallVector<llvm::Value *, 16> TemplateParams;
Guy Benyei11169dd2012-12-18 14:30:41 +00001224 for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1225 const TemplateArgument &TA = TAList[i];
David Blaikie47c11502013-06-22 18:59:18 +00001226 StringRef Name;
1227 if (TPList)
1228 Name = TPList->getParam(i)->getName();
David Blaikie38079fd2013-05-10 21:53:14 +00001229 switch (TA.getKind()) {
1230 case TemplateArgument::Type: {
Guy Benyei11169dd2012-12-18 14:30:41 +00001231 llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit);
1232 llvm::DITemplateTypeParameter TTP =
David Blaikie47c11502013-06-22 18:59:18 +00001233 DBuilder.createTemplateTypeParameter(TheCU, Name, TTy);
Guy Benyei11169dd2012-12-18 14:30:41 +00001234 TemplateParams.push_back(TTP);
David Blaikie38079fd2013-05-10 21:53:14 +00001235 } break;
1236 case TemplateArgument::Integral: {
Guy Benyei11169dd2012-12-18 14:30:41 +00001237 llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit);
1238 llvm::DITemplateValueParameter TVP =
David Blaikie38079fd2013-05-10 21:53:14 +00001239 DBuilder.createTemplateValueParameter(
David Blaikie47c11502013-06-22 18:59:18 +00001240 TheCU, Name, TTy,
David Blaikie38079fd2013-05-10 21:53:14 +00001241 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral()));
1242 TemplateParams.push_back(TVP);
1243 } break;
1244 case TemplateArgument::Declaration: {
1245 const ValueDecl *D = TA.getAsDecl();
1246 bool InstanceMember = D->isCXXInstanceMember();
1247 QualType T = InstanceMember
1248 ? CGM.getContext().getMemberPointerType(
1249 D->getType(), cast<RecordDecl>(D->getDeclContext())
1250 ->getTypeForDecl())
1251 : CGM.getContext().getPointerType(D->getType());
1252 llvm::DIType TTy = getOrCreateType(T, Unit);
1253 llvm::Value *V = 0;
1254 // Variable pointer template parameters have a value that is the address
1255 // of the variable.
1256 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1257 V = CGM.GetAddrOfGlobalVar(VD);
1258 // Member function pointers have special support for building them, though
1259 // this is currently unsupported in LLVM CodeGen.
David Blaikied900f982013-05-13 06:57:50 +00001260 if (InstanceMember) {
David Blaikie38079fd2013-05-10 21:53:14 +00001261 if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(D))
1262 V = CGM.getCXXABI().EmitMemberPointer(method);
David Blaikied900f982013-05-13 06:57:50 +00001263 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1264 V = CGM.GetAddrOfFunction(FD);
David Blaikie38079fd2013-05-10 21:53:14 +00001265 // Member data pointers have special handling too to compute the fixed
1266 // offset within the object.
Adrian Prantlefb88052014-04-01 17:52:06 +00001267 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) {
David Blaikie38079fd2013-05-10 21:53:14 +00001268 // These five lines (& possibly the above member function pointer
1269 // handling) might be able to be refactored to use similar code in
1270 // CodeGenModule::getMemberPointerConstant
1271 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
1272 CharUnits chars =
1273 CGM.getContext().toCharUnitsFromBits((int64_t) fieldOffset);
1274 V = CGM.getCXXABI().EmitMemberDataPointer(
1275 cast<MemberPointerType>(T.getTypePtr()), chars);
1276 }
1277 llvm::DITemplateValueParameter TVP =
David Majnemera3644d62013-08-25 22:13:27 +00001278 DBuilder.createTemplateValueParameter(TheCU, Name, TTy,
1279 V->stripPointerCasts());
David Blaikie38079fd2013-05-10 21:53:14 +00001280 TemplateParams.push_back(TVP);
1281 } break;
1282 case TemplateArgument::NullPtr: {
1283 QualType T = TA.getNullPtrType();
1284 llvm::DIType TTy = getOrCreateType(T, Unit);
1285 llvm::Value *V = 0;
1286 // Special case member data pointer null values since they're actually -1
1287 // instead of zero.
1288 if (const MemberPointerType *MPT =
1289 dyn_cast<MemberPointerType>(T.getTypePtr()))
1290 // But treat member function pointers as simple zero integers because
1291 // it's easier than having a special case in LLVM's CodeGen. If LLVM
1292 // CodeGen grows handling for values of non-null member function
1293 // pointers then perhaps we could remove this special case and rely on
1294 // EmitNullMemberPointer for member function pointers.
1295 if (MPT->isMemberDataPointer())
1296 V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1297 if (!V)
1298 V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
1299 llvm::DITemplateValueParameter TVP =
David Blaikie47c11502013-06-22 18:59:18 +00001300 DBuilder.createTemplateValueParameter(TheCU, Name, TTy, V);
David Blaikie38079fd2013-05-10 21:53:14 +00001301 TemplateParams.push_back(TVP);
1302 } break;
David Blaikie47c11502013-06-22 18:59:18 +00001303 case TemplateArgument::Template: {
1304 llvm::DITemplateValueParameter TVP =
1305 DBuilder.createTemplateTemplateParameter(
1306 TheCU, Name, llvm::DIType(),
1307 TA.getAsTemplate().getAsTemplateDecl()
1308 ->getQualifiedNameAsString());
1309 TemplateParams.push_back(TVP);
1310 } break;
1311 case TemplateArgument::Pack: {
1312 llvm::DITemplateValueParameter TVP =
1313 DBuilder.createTemplateParameterPack(
1314 TheCU, Name, llvm::DIType(),
1315 CollectTemplateParams(NULL, TA.getPackAsArray(), Unit));
1316 TemplateParams.push_back(TVP);
1317 } break;
David Majnemer5559d472013-08-24 08:21:10 +00001318 case TemplateArgument::Expression: {
1319 const Expr *E = TA.getAsExpr();
1320 QualType T = E->getType();
1321 llvm::Value *V = CGM.EmitConstantExpr(E, T);
1322 assert(V && "Expression in template argument isn't constant");
1323 llvm::DIType TTy = getOrCreateType(T, Unit);
1324 llvm::DITemplateValueParameter TVP =
1325 DBuilder.createTemplateValueParameter(TheCU, Name, TTy,
1326 V->stripPointerCasts());
1327 TemplateParams.push_back(TVP);
1328 } break;
David Blaikie2b93c542013-05-10 23:36:06 +00001329 // And the following should never occur:
David Blaikie38079fd2013-05-10 21:53:14 +00001330 case TemplateArgument::TemplateExpansion:
David Blaikie38079fd2013-05-10 21:53:14 +00001331 case TemplateArgument::Null:
1332 llvm_unreachable(
1333 "These argument types shouldn't exist in concrete types");
Guy Benyei11169dd2012-12-18 14:30:41 +00001334 }
1335 }
1336 return DBuilder.getOrCreateArray(TemplateParams);
1337}
1338
1339/// CollectFunctionTemplateParams - A helper function to collect debug
1340/// info for function template parameters.
1341llvm::DIArray CGDebugInfo::
1342CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) {
1343 if (FD->getTemplatedKind() ==
1344 FunctionDecl::TK_FunctionTemplateSpecialization) {
1345 const TemplateParameterList *TList =
1346 FD->getTemplateSpecializationInfo()->getTemplate()
1347 ->getTemplateParameters();
David Blaikie47c11502013-06-22 18:59:18 +00001348 return CollectTemplateParams(
1349 TList, FD->getTemplateSpecializationArgs()->asArray(), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00001350 }
1351 return llvm::DIArray();
1352}
1353
1354/// CollectCXXTemplateParams - A helper function to collect debug info for
1355/// template parameters.
1356llvm::DIArray CGDebugInfo::
1357CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial,
1358 llvm::DIFile Unit) {
Adrian Prantl649f0302014-04-17 01:04:01 +00001359 // Always get the full list of parameters, not just the ones from
1360 // the specialization.
1361 TemplateParameterList *TPList =
1362 TSpecial->getSpecializedTemplate()->getTemplateParameters();
Adrian Prantl2c92e9c2014-04-17 00:30:48 +00001363 const TemplateArgumentList &TAList = TSpecial->getTemplateArgs();
David Blaikie47c11502013-06-22 18:59:18 +00001364 return CollectTemplateParams(TPList, TAList.asArray(), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00001365}
1366
1367/// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
1368llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
1369 if (VTablePtrType.isValid())
1370 return VTablePtrType;
1371
1372 ASTContext &Context = CGM.getContext();
1373
1374 /* Function type */
1375 llvm::Value *STy = getOrCreateType(Context.IntTy, Unit);
1376 llvm::DIArray SElements = DBuilder.getOrCreateArray(STy);
1377 llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements);
1378 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1379 llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0,
1380 "__vtbl_ptr_type");
1381 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1382 return VTablePtrType;
1383}
1384
1385/// getVTableName - Get vtable name for the given Class.
1386StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +00001387 // Copy the gdb compatible name on the side and use its reference.
1388 return internString("_vptr$", RD->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00001389}
1390
1391
1392/// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
1393/// debug info entry in EltTys vector.
1394void CGDebugInfo::
1395CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
1396 SmallVectorImpl<llvm::Value *> &EltTys) {
1397 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1398
1399 // If there is a primary base then it will hold vtable info.
1400 if (RL.getPrimaryBase())
1401 return;
1402
1403 // If this class is not dynamic then there is not any vtable info to collect.
1404 if (!RD->isDynamicClass())
1405 return;
1406
1407 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1408 llvm::DIType VPTR
1409 = DBuilder.createMemberType(Unit, getVTableName(RD), Unit,
Eric Christopher0fdcb312013-05-16 00:52:20 +00001410 0, Size, 0, 0,
1411 llvm::DIDescriptor::FlagArtificial,
Guy Benyei11169dd2012-12-18 14:30:41 +00001412 getOrCreateVTablePtrType(Unit));
1413 EltTys.push_back(VPTR);
1414}
1415
Eric Christopherb2a008c2013-05-16 00:45:12 +00001416/// getOrCreateRecordType - Emit record type's standalone debug info.
1417llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy,
Guy Benyei11169dd2012-12-18 14:30:41 +00001418 SourceLocation Loc) {
Eric Christopher75e17682013-05-16 00:45:23 +00001419 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00001420 llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc));
1421 return T;
1422}
1423
1424/// getOrCreateInterfaceType - Emit an objective c interface type standalone
1425/// debug info.
1426llvm::DIType CGDebugInfo::getOrCreateInterfaceType(QualType D,
Eric Christopherc0c5d462013-02-21 22:35:08 +00001427 SourceLocation Loc) {
Eric Christopher75e17682013-05-16 00:45:23 +00001428 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00001429 llvm::DIType T = getOrCreateType(D, getOrCreateFile(Loc));
Adrian Prantl73409ce2013-03-11 18:33:46 +00001430 RetainedTypes.push_back(D.getAsOpaquePtr());
Guy Benyei11169dd2012-12-18 14:30:41 +00001431 return T;
1432}
1433
David Blaikieb2e86eb2013-08-15 20:49:17 +00001434void CGDebugInfo::completeType(const RecordDecl *RD) {
1435 if (DebugKind > CodeGenOptions::LimitedDebugInfo ||
1436 !CGM.getLangOpts().CPlusPlus)
1437 completeRequiredType(RD);
1438}
1439
1440void CGDebugInfo::completeRequiredType(const RecordDecl *RD) {
David Blaikie0856f662014-03-04 22:01:08 +00001441 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
1442 return;
1443
David Blaikie6943dea2013-08-20 01:28:15 +00001444 if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
1445 if (CXXDecl->isDynamicClass())
1446 return;
1447
David Blaikieb2e86eb2013-08-15 20:49:17 +00001448 QualType Ty = CGM.getContext().getRecordType(RD);
1449 llvm::DIType T = getTypeOrNull(Ty);
David Blaikie6943dea2013-08-20 01:28:15 +00001450 if (T && T.isForwardDecl())
1451 completeClassData(RD);
1452}
1453
1454void CGDebugInfo::completeClassData(const RecordDecl *RD) {
1455 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
Michael Gottesman349542b2013-08-19 18:46:16 +00001456 return;
David Blaikie6943dea2013-08-20 01:28:15 +00001457 QualType Ty = CGM.getContext().getRecordType(RD);
David Blaikieb2e86eb2013-08-15 20:49:17 +00001458 void* TyPtr = Ty.getAsOpaquePtr();
1459 if (CompletedTypeCache.count(TyPtr))
1460 return;
1461 llvm::DIType Res = CreateTypeDefinition(Ty->castAs<RecordType>());
1462 assert(!Res.isForwardDecl());
1463 CompletedTypeCache[TyPtr] = Res;
1464 TypeCache[TyPtr] = Res;
1465}
1466
David Blaikie0e716b42014-03-03 23:48:23 +00001467static bool hasExplicitMemberDefinition(CXXRecordDecl::method_iterator I,
1468 CXXRecordDecl::method_iterator End) {
1469 for (; I != End; ++I)
1470 if (FunctionDecl *Tmpl = I->getInstantiatedFromMemberFunction())
David Blaikief7f21852014-03-04 03:08:14 +00001471 if (!Tmpl->isImplicit() && Tmpl->isThisDeclarationADefinition() &&
1472 !I->getMemberSpecializationInfo()->isExplicitSpecialization())
David Blaikie0e716b42014-03-03 23:48:23 +00001473 return true;
1474 return false;
1475}
1476
1477static bool shouldOmitDefinition(CodeGenOptions::DebugInfoKind DebugKind,
1478 const RecordDecl *RD,
1479 const LangOptions &LangOpts) {
1480 if (DebugKind > CodeGenOptions::LimitedDebugInfo)
1481 return false;
1482
1483 if (!LangOpts.CPlusPlus)
1484 return false;
1485
1486 if (!RD->isCompleteDefinitionRequired())
1487 return true;
1488
1489 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1490
1491 if (!CXXDecl)
1492 return false;
1493
1494 if (CXXDecl->hasDefinition() && CXXDecl->isDynamicClass())
1495 return true;
1496
1497 TemplateSpecializationKind Spec = TSK_Undeclared;
1498 if (const ClassTemplateSpecializationDecl *SD =
1499 dyn_cast<ClassTemplateSpecializationDecl>(RD))
1500 Spec = SD->getSpecializationKind();
1501
1502 if (Spec == TSK_ExplicitInstantiationDeclaration &&
1503 hasExplicitMemberDefinition(CXXDecl->method_begin(),
1504 CXXDecl->method_end()))
1505 return true;
1506
1507 return false;
1508}
1509
Guy Benyei11169dd2012-12-18 14:30:41 +00001510/// CreateType - get structure or union type.
David Blaikie99dab3b2013-09-04 22:03:57 +00001511llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001512 RecordDecl *RD = Ty->getDecl();
David Blaikie3b1cc9b2013-09-06 06:45:04 +00001513 llvm::DICompositeType T(getTypeOrNull(QualType(Ty, 0)));
David Blaikie0e716b42014-03-03 23:48:23 +00001514 if (T || shouldOmitDefinition(DebugKind, RD, CGM.getLangOpts())) {
David Blaikie3b1cc9b2013-09-06 06:45:04 +00001515 if (!T)
David Blaikie65ec94e2014-02-18 20:52:05 +00001516 T = getOrCreateRecordFwdDecl(
1517 Ty, getContextDescriptor(cast<Decl>(RD->getDeclContext())));
David Blaikie3b1cc9b2013-09-06 06:45:04 +00001518 return T;
David Blaikiee36464c2013-06-05 05:32:23 +00001519 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001520
David Blaikieb2e86eb2013-08-15 20:49:17 +00001521 return CreateTypeDefinition(Ty);
1522}
1523
1524llvm::DIType CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {
1525 RecordDecl *RD = Ty->getDecl();
1526
Guy Benyei11169dd2012-12-18 14:30:41 +00001527 // Get overall information about the record type for the debug info.
1528 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1529
1530 // Records and classes and unions can all be recursive. To handle them, we
1531 // first generate a debug descriptor for the struct as a forward declaration.
1532 // Then (if it is a definition) we go through and get debug info for all of
1533 // its members. Finally, we create a descriptor for the complete type (which
1534 // may refer to the forward decl if the struct is recursive) and replace all
1535 // uses of the forward declaration with the final definition.
1536
David Blaikie4a2b5ef2013-08-12 22:24:20 +00001537 llvm::DICompositeType FwdDecl(getOrCreateLimitedType(Ty, DefUnit));
Manman Ren0d441f12013-07-02 19:01:53 +00001538 assert(FwdDecl.isCompositeType() &&
David Blaikie469f0792013-05-22 23:22:42 +00001539 "The debug type of a RecordType should be a llvm::DICompositeType");
Guy Benyei11169dd2012-12-18 14:30:41 +00001540
1541 if (FwdDecl.isForwardDecl())
1542 return FwdDecl;
1543
David Blaikieadfbf992013-08-18 16:55:33 +00001544 if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
1545 CollectContainingType(CXXDecl, FwdDecl);
1546
Guy Benyei11169dd2012-12-18 14:30:41 +00001547 // Push the struct on region stack.
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001548 LexicalBlockStack.push_back(&*FwdDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00001549 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1550
Adrian Prantla03a85a2013-03-06 22:03:30 +00001551 // Add this to the completed-type cache while we're completing it recursively.
Guy Benyei11169dd2012-12-18 14:30:41 +00001552 CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1553
1554 // Convert all the elements.
1555 SmallVector<llvm::Value *, 16> EltTys;
David Blaikie6943dea2013-08-20 01:28:15 +00001556 // what about nested types?
Guy Benyei11169dd2012-12-18 14:30:41 +00001557
1558 // Note: The split of CXXDecl information here is intentional, the
1559 // gdb tests will depend on a certain ordering at printout. The debug
1560 // information offsets are still correct if we merge them all together
1561 // though.
1562 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1563 if (CXXDecl) {
1564 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1565 CollectVTableInfo(CXXDecl, DefUnit, EltTys);
1566 }
1567
Eric Christopher91a31902013-01-16 01:22:32 +00001568 // Collect data fields (including static variables and any initializers).
Guy Benyei11169dd2012-12-18 14:30:41 +00001569 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
Eric Christopher2df080e2013-10-11 18:16:51 +00001570 if (CXXDecl)
Guy Benyei11169dd2012-12-18 14:30:41 +00001571 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00001572
1573 LexicalBlockStack.pop_back();
1574 RegionMap.erase(Ty->getDecl());
1575
1576 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
David Blaikie4a5b8952013-08-01 20:31:40 +00001577 FwdDecl.setTypeArray(Elements);
Guy Benyei11169dd2012-12-18 14:30:41 +00001578
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001579 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1580 return FwdDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00001581}
1582
1583/// CreateType - get objective-c object type.
1584llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1585 llvm::DIFile Unit) {
1586 // Ignore protocols.
1587 return getOrCreateType(Ty->getBaseType(), Unit);
1588}
1589
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001590
1591/// \return true if Getter has the default name for the property PD.
1592static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
1593 const ObjCMethodDecl *Getter) {
1594 assert(PD);
1595 if (!Getter)
1596 return true;
1597
1598 assert(Getter->getDeclName().isObjCZeroArgSelector());
1599 return PD->getName() ==
1600 Getter->getDeclName().getObjCSelector().getNameForSlot(0);
1601}
1602
1603/// \return true if Setter has the default name for the property PD.
1604static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
1605 const ObjCMethodDecl *Setter) {
1606 assert(PD);
1607 if (!Setter)
1608 return true;
1609
1610 assert(Setter->getDeclName().isObjCOneArgSelector());
Adrian Prantla4ce9062013-06-07 22:29:12 +00001611 return SelectorTable::constructSetterName(PD->getName()) ==
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001612 Setter->getDeclName().getObjCSelector().getNameForSlot(0);
1613}
1614
Guy Benyei11169dd2012-12-18 14:30:41 +00001615/// CreateType - get objective-c interface type.
1616llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1617 llvm::DIFile Unit) {
1618 ObjCInterfaceDecl *ID = Ty->getDecl();
1619 if (!ID)
1620 return llvm::DIType();
1621
1622 // Get overall information about the record type for the debug info.
1623 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1624 unsigned Line = getLineNumber(ID->getLocation());
1625 unsigned RuntimeLang = TheCU.getLanguage();
1626
1627 // If this is just a forward declaration return a special forward-declaration
1628 // debug type since we won't be able to lay out the entire type.
1629 ObjCInterfaceDecl *Def = ID->getDefinition();
1630 if (!Def) {
1631 llvm::DIType FwdDecl =
1632 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
Eric Christopherc0c5d462013-02-21 22:35:08 +00001633 ID->getName(), TheCU, DefUnit, Line,
1634 RuntimeLang);
Guy Benyei11169dd2012-12-18 14:30:41 +00001635 return FwdDecl;
1636 }
1637
1638 ID = Def;
1639
1640 // Bit size, align and offset of the type.
1641 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1642 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1643
1644 unsigned Flags = 0;
1645 if (ID->getImplementation())
1646 Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
1647
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001648 llvm::DICompositeType RealDecl =
Guy Benyei11169dd2012-12-18 14:30:41 +00001649 DBuilder.createStructType(Unit, ID->getName(), DefUnit,
1650 Line, Size, Align, Flags,
David Blaikie6d4fe152013-02-25 01:07:08 +00001651 llvm::DIType(), llvm::DIArray(), RuntimeLang);
Guy Benyei11169dd2012-12-18 14:30:41 +00001652
1653 // Otherwise, insert it into the CompletedTypeCache so that recursive uses
1654 // will find it and we're emitting the complete type.
Adrian Prantla03a85a2013-03-06 22:03:30 +00001655 QualType QualTy = QualType(Ty, 0);
1656 CompletedTypeCache[QualTy.getAsOpaquePtr()] = RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00001657
Eric Christopher35f1f9f2013-07-14 21:00:07 +00001658 // Push the struct on region stack.
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001659 LexicalBlockStack.push_back(static_cast<llvm::MDNode*>(RealDecl));
Guy Benyei11169dd2012-12-18 14:30:41 +00001660 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1661
1662 // Convert all the elements.
1663 SmallVector<llvm::Value *, 16> EltTys;
1664
1665 ObjCInterfaceDecl *SClass = ID->getSuperClass();
1666 if (SClass) {
1667 llvm::DIType SClassTy =
1668 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1669 if (!SClassTy.isValid())
1670 return llvm::DIType();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001671
Guy Benyei11169dd2012-12-18 14:30:41 +00001672 llvm::DIType InhTag =
1673 DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
1674 EltTys.push_back(InhTag);
1675 }
1676
Eric Christopher35f1f9f2013-07-14 21:00:07 +00001677 // Create entries for all of the properties.
Aaron Ballmand174edf2014-03-13 19:11:50 +00001678 for (const auto *PD : ID->properties()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001679 SourceLocation Loc = PD->getLocation();
1680 llvm::DIFile PUnit = getOrCreateFile(Loc);
1681 unsigned PLine = getLineNumber(Loc);
1682 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1683 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1684 llvm::MDNode *PropertyNode =
1685 DBuilder.createObjCProperty(PD->getName(),
Eric Christopherc0c5d462013-02-21 22:35:08 +00001686 PUnit, PLine,
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001687 hasDefaultGetterName(PD, Getter) ? "" :
Guy Benyei11169dd2012-12-18 14:30:41 +00001688 getSelectorName(PD->getGetterName()),
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001689 hasDefaultSetterName(PD, Setter) ? "" :
Guy Benyei11169dd2012-12-18 14:30:41 +00001690 getSelectorName(PD->getSetterName()),
1691 PD->getPropertyAttributes(),
Eric Christopherc0c5d462013-02-21 22:35:08 +00001692 getOrCreateType(PD->getType(), PUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00001693 EltTys.push_back(PropertyNode);
1694 }
1695
1696 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1697 unsigned FieldNo = 0;
1698 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1699 Field = Field->getNextIvar(), ++FieldNo) {
1700 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1701 if (!FieldTy.isValid())
1702 return llvm::DIType();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001703
Guy Benyei11169dd2012-12-18 14:30:41 +00001704 StringRef FieldName = Field->getName();
1705
1706 // Ignore unnamed fields.
1707 if (FieldName.empty())
1708 continue;
1709
1710 // Get the location for the field.
1711 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1712 unsigned FieldLine = getLineNumber(Field->getLocation());
1713 QualType FType = Field->getType();
1714 uint64_t FieldSize = 0;
1715 unsigned FieldAlign = 0;
1716
1717 if (!FType->isIncompleteArrayType()) {
1718
1719 // Bit size, align and offset of the type.
1720 FieldSize = Field->isBitField()
Eric Christopher35f1f9f2013-07-14 21:00:07 +00001721 ? Field->getBitWidthValue(CGM.getContext())
1722 : CGM.getContext().getTypeSize(FType);
Guy Benyei11169dd2012-12-18 14:30:41 +00001723 FieldAlign = CGM.getContext().getTypeAlign(FType);
1724 }
1725
1726 uint64_t FieldOffset;
1727 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1728 // We don't know the runtime offset of an ivar if we're using the
1729 // non-fragile ABI. For bitfields, use the bit offset into the first
1730 // byte of storage of the bitfield. For other fields, use zero.
1731 if (Field->isBitField()) {
1732 FieldOffset = CGM.getObjCRuntime().ComputeBitfieldBitOffset(
1733 CGM, ID, Field);
1734 FieldOffset %= CGM.getContext().getCharWidth();
1735 } else {
1736 FieldOffset = 0;
1737 }
1738 } else {
1739 FieldOffset = RL.getFieldOffset(FieldNo);
1740 }
1741
1742 unsigned Flags = 0;
1743 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1744 Flags = llvm::DIDescriptor::FlagProtected;
1745 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1746 Flags = llvm::DIDescriptor::FlagPrivate;
1747
1748 llvm::MDNode *PropertyNode = NULL;
1749 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001750 if (ObjCPropertyImplDecl *PImpD =
Guy Benyei11169dd2012-12-18 14:30:41 +00001751 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
1752 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
Eric Christopherc0c5d462013-02-21 22:35:08 +00001753 SourceLocation Loc = PD->getLocation();
1754 llvm::DIFile PUnit = getOrCreateFile(Loc);
1755 unsigned PLine = getLineNumber(Loc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001756 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1757 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1758 PropertyNode =
1759 DBuilder.createObjCProperty(PD->getName(),
1760 PUnit, PLine,
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001761 hasDefaultGetterName(PD, Getter) ? "" :
Guy Benyei11169dd2012-12-18 14:30:41 +00001762 getSelectorName(PD->getGetterName()),
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001763 hasDefaultSetterName(PD, Setter) ? "" :
Guy Benyei11169dd2012-12-18 14:30:41 +00001764 getSelectorName(PD->getSetterName()),
1765 PD->getPropertyAttributes(),
1766 getOrCreateType(PD->getType(), PUnit));
1767 }
1768 }
1769 }
1770 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
1771 FieldLine, FieldSize, FieldAlign,
1772 FieldOffset, Flags, FieldTy,
1773 PropertyNode);
1774 EltTys.push_back(FieldTy);
1775 }
1776
1777 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001778 RealDecl.setTypeArray(Elements);
Adrian Prantla03a85a2013-03-06 22:03:30 +00001779
1780 // If the implementation is not yet set, we do not want to mark it
1781 // as complete. An implementation may declare additional
1782 // private ivars that we would miss otherwise.
1783 if (ID->getImplementation() == 0)
1784 CompletedTypeCache.erase(QualTy.getAsOpaquePtr());
Eric Christopherb2a008c2013-05-16 00:45:12 +00001785
Guy Benyei11169dd2012-12-18 14:30:41 +00001786 LexicalBlockStack.pop_back();
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001787 return RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00001788}
1789
1790llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) {
1791 llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1792 int64_t Count = Ty->getNumElements();
1793 if (Count == 0)
1794 // If number of elements are not known then this is an unbounded array.
1795 // Use Count == -1 to express such arrays.
1796 Count = -1;
1797
1798 llvm::Value *Subscript = DBuilder.getOrCreateSubrange(0, Count);
1799 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1800
1801 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1802 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1803
1804 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1805}
1806
1807llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1808 llvm::DIFile Unit) {
1809 uint64_t Size;
1810 uint64_t Align;
1811
1812 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1813 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1814 Size = 0;
1815 Align =
1816 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1817 } else if (Ty->isIncompleteArrayType()) {
1818 Size = 0;
1819 if (Ty->getElementType()->isIncompleteType())
1820 Align = 0;
1821 else
1822 Align = CGM.getContext().getTypeAlign(Ty->getElementType());
David Blaikief03b2e82013-05-09 20:48:12 +00001823 } else if (Ty->isIncompleteType()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001824 Size = 0;
1825 Align = 0;
1826 } else {
1827 // Size and align of the whole array, not the element type.
1828 Size = CGM.getContext().getTypeSize(Ty);
1829 Align = CGM.getContext().getTypeAlign(Ty);
1830 }
1831
1832 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
1833 // interior arrays, do we care? Why aren't nested arrays represented the
1834 // obvious/recursive way?
1835 SmallVector<llvm::Value *, 8> Subscripts;
1836 QualType EltTy(Ty, 0);
1837 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1838 // If the number of elements is known, then count is that number. Otherwise,
1839 // it's -1. This allows us to represent a subrange with an array of 0
1840 // elements, like this:
1841 //
1842 // struct foo {
1843 // int x[0];
1844 // };
1845 int64_t Count = -1; // Count == -1 is an unbounded array.
1846 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1847 Count = CAT->getSize().getZExtValue();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001848
Guy Benyei11169dd2012-12-18 14:30:41 +00001849 // FIXME: Verify this is right for VLAs.
1850 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
1851 EltTy = Ty->getElementType();
1852 }
1853
1854 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1855
Eric Christopherb2a008c2013-05-16 00:45:12 +00001856 llvm::DIType DbgTy =
Guy Benyei11169dd2012-12-18 14:30:41 +00001857 DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1858 SubscriptArray);
1859 return DbgTy;
1860}
1861
Eric Christopherb2a008c2013-05-16 00:45:12 +00001862llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +00001863 llvm::DIFile Unit) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001864 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
Guy Benyei11169dd2012-12-18 14:30:41 +00001865 Ty, Ty->getPointeeType(), Unit);
1866}
1867
Eric Christopherb2a008c2013-05-16 00:45:12 +00001868llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +00001869 llvm::DIFile Unit) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001870 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
Guy Benyei11169dd2012-12-18 14:30:41 +00001871 Ty, Ty->getPointeeType(), Unit);
1872}
1873
Eric Christopherb2a008c2013-05-16 00:45:12 +00001874llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +00001875 llvm::DIFile U) {
David Blaikie2c705ca2013-01-19 19:20:56 +00001876 llvm::DIType ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
1877 if (!Ty->getPointeeType()->isFunctionType())
1878 return DBuilder.createMemberPointerType(
David Blaikie99dab3b2013-09-04 22:03:57 +00001879 getOrCreateType(Ty->getPointeeType(), U), ClassType);
Adrian Prantl0866acd2013-12-19 01:38:47 +00001880
1881 const FunctionProtoType *FPT =
1882 Ty->getPointeeType()->getAs<FunctionProtoType>();
David Blaikie2c705ca2013-01-19 19:20:56 +00001883 return DBuilder.createMemberPointerType(getOrCreateInstanceMethodType(
Adrian Prantl0866acd2013-12-19 01:38:47 +00001884 CGM.getContext().getPointerType(QualType(Ty->getClass(),
1885 FPT->getTypeQuals())),
1886 FPT, U), ClassType);
Guy Benyei11169dd2012-12-18 14:30:41 +00001887}
1888
Eric Christopherb2a008c2013-05-16 00:45:12 +00001889llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +00001890 llvm::DIFile U) {
1891 // Ignore the atomic wrapping
1892 // FIXME: What is the correct representation?
1893 return getOrCreateType(Ty->getValueType(), U);
1894}
1895
1896/// CreateEnumType - get enumeration type.
Manman Ren501ecf92013-08-28 21:46:36 +00001897llvm::DIType CGDebugInfo::CreateEnumType(const EnumType *Ty) {
Manman Ren1b457022013-08-28 21:20:28 +00001898 const EnumDecl *ED = Ty->getDecl();
Guy Benyei11169dd2012-12-18 14:30:41 +00001899 uint64_t Size = 0;
1900 uint64_t Align = 0;
1901 if (!ED->getTypeForDecl()->isIncompleteType()) {
1902 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1903 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1904 }
1905
Manman Rene0064d82013-08-29 23:19:58 +00001906 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
1907
Guy Benyei11169dd2012-12-18 14:30:41 +00001908 // If this is just a forward declaration, construct an appropriately
1909 // marked node and just return it.
1910 if (!ED->getDefinition()) {
1911 llvm::DIDescriptor EDContext;
1912 EDContext = getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1913 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1914 unsigned Line = getLineNumber(ED->getLocation());
1915 StringRef EDName = ED->getName();
1916 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_enumeration_type,
1917 EDName, EDContext, DefUnit, Line, 0,
Manman Rene0064d82013-08-29 23:19:58 +00001918 Size, Align, FullName);
Guy Benyei11169dd2012-12-18 14:30:41 +00001919 }
1920
1921 // Create DIEnumerator elements for each enumerator.
1922 SmallVector<llvm::Value *, 16> Enumerators;
1923 ED = ED->getDefinition();
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001924 for (const auto *Enum : ED->enumerators()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001925 Enumerators.push_back(
1926 DBuilder.createEnumerator(Enum->getName(),
David Blaikiece1ae382013-06-24 07:13:13 +00001927 Enum->getInitVal().getSExtValue()));
Guy Benyei11169dd2012-12-18 14:30:41 +00001928 }
1929
1930 // Return a CompositeType for the enum itself.
1931 llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1932
1933 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1934 unsigned Line = getLineNumber(ED->getLocation());
Eric Christopherb2a008c2013-05-16 00:45:12 +00001935 llvm::DIDescriptor EnumContext =
Guy Benyei11169dd2012-12-18 14:30:41 +00001936 getContextDescriptor(cast<Decl>(ED->getDeclContext()));
Adrian Prantlc60dc712013-04-19 19:56:39 +00001937 llvm::DIType ClassTy = ED->isFixed() ?
Guy Benyei11169dd2012-12-18 14:30:41 +00001938 getOrCreateType(ED->getIntegerType(), DefUnit) : llvm::DIType();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001939 llvm::DIType DbgTy =
Guy Benyei11169dd2012-12-18 14:30:41 +00001940 DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1941 Size, Align, EltArray,
Manman Rene0064d82013-08-29 23:19:58 +00001942 ClassTy, FullName);
Guy Benyei11169dd2012-12-18 14:30:41 +00001943 return DbgTy;
1944}
1945
David Blaikie05491062013-01-21 04:37:12 +00001946static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
1947 Qualifiers Quals;
Guy Benyei11169dd2012-12-18 14:30:41 +00001948 do {
Adrian Prantl179af902013-09-26 21:35:50 +00001949 Qualifiers InnerQuals = T.getLocalQualifiers();
1950 // Qualifiers::operator+() doesn't like it if you add a Qualifier
1951 // that is already there.
1952 Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals);
1953 Quals += InnerQuals;
Guy Benyei11169dd2012-12-18 14:30:41 +00001954 QualType LastT = T;
1955 switch (T->getTypeClass()) {
1956 default:
David Blaikie05491062013-01-21 04:37:12 +00001957 return C.getQualifiedType(T.getTypePtr(), Quals);
David Blaikief1b382e2014-04-06 17:14:06 +00001958 case Type::TemplateSpecialization: {
1959 const auto *Spec = cast<TemplateSpecializationType>(T);
1960 if (Spec->isTypeAlias())
1961 return C.getQualifiedType(T.getTypePtr(), Quals);
1962 T = Spec->desugar();
1963 break; }
Guy Benyei11169dd2012-12-18 14:30:41 +00001964 case Type::TypeOfExpr:
1965 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1966 break;
1967 case Type::TypeOf:
1968 T = cast<TypeOfType>(T)->getUnderlyingType();
1969 break;
1970 case Type::Decltype:
1971 T = cast<DecltypeType>(T)->getUnderlyingType();
1972 break;
1973 case Type::UnaryTransform:
1974 T = cast<UnaryTransformType>(T)->getUnderlyingType();
1975 break;
1976 case Type::Attributed:
1977 T = cast<AttributedType>(T)->getEquivalentType();
1978 break;
1979 case Type::Elaborated:
1980 T = cast<ElaboratedType>(T)->getNamedType();
1981 break;
1982 case Type::Paren:
1983 T = cast<ParenType>(T)->getInnerType();
1984 break;
David Blaikie05491062013-01-21 04:37:12 +00001985 case Type::SubstTemplateTypeParm:
Guy Benyei11169dd2012-12-18 14:30:41 +00001986 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
Guy Benyei11169dd2012-12-18 14:30:41 +00001987 break;
1988 case Type::Auto:
David Blaikie22c460a02013-05-24 21:24:35 +00001989 QualType DT = cast<AutoType>(T)->getDeducedType();
1990 if (DT.isNull())
1991 return T;
1992 T = DT;
Guy Benyei11169dd2012-12-18 14:30:41 +00001993 break;
1994 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00001995
Guy Benyei11169dd2012-12-18 14:30:41 +00001996 assert(T != LastT && "Type unwrapping failed to unwrap!");
NAKAMURA Takumi3e0a3632013-01-21 10:51:28 +00001997 (void)LastT;
Guy Benyei11169dd2012-12-18 14:30:41 +00001998 } while (true);
1999}
2000
Eric Christopher0fdcb312013-05-16 00:52:20 +00002001/// getType - Get the type from the cache or return null type if it doesn't
2002/// exist.
Guy Benyei11169dd2012-12-18 14:30:41 +00002003llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) {
2004
2005 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00002006 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Eric Christopherb2a008c2013-05-16 00:45:12 +00002007
Guy Benyei11169dd2012-12-18 14:30:41 +00002008 // Check for existing entry.
Adrian Prantl73409ce2013-03-11 18:33:46 +00002009 if (Ty->getTypeClass() == Type::ObjCInterface) {
2010 llvm::Value *V = getCachedInterfaceTypeOrNull(Ty);
2011 if (V)
2012 return llvm::DIType(cast<llvm::MDNode>(V));
2013 else return llvm::DIType();
2014 }
2015
Guy Benyei11169dd2012-12-18 14:30:41 +00002016 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
2017 TypeCache.find(Ty.getAsOpaquePtr());
2018 if (it != TypeCache.end()) {
2019 // Verify that the debug info still exists.
2020 if (llvm::Value *V = it->second)
2021 return llvm::DIType(cast<llvm::MDNode>(V));
2022 }
2023
2024 return llvm::DIType();
2025}
2026
2027/// getCompletedTypeOrNull - Get the type from the cache or return null if it
2028/// doesn't exist.
2029llvm::DIType CGDebugInfo::getCompletedTypeOrNull(QualType Ty) {
2030
2031 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00002032 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00002033
2034 // Check for existing entry.
Adrian Prantla03a85a2013-03-06 22:03:30 +00002035 llvm::Value *V = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00002036 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
2037 CompletedTypeCache.find(Ty.getAsOpaquePtr());
Adrian Prantla03a85a2013-03-06 22:03:30 +00002038 if (it != CompletedTypeCache.end())
2039 V = it->second;
2040 else {
Adrian Prantl73409ce2013-03-11 18:33:46 +00002041 V = getCachedInterfaceTypeOrNull(Ty);
Guy Benyei11169dd2012-12-18 14:30:41 +00002042 }
2043
Adrian Prantla03a85a2013-03-06 22:03:30 +00002044 // Verify that any cached debug info still exists.
David Blaikie80d28de2013-08-13 04:21:38 +00002045 return llvm::DIType(cast_or_null<llvm::MDNode>(V));
Guy Benyei11169dd2012-12-18 14:30:41 +00002046}
2047
David Blaikie0e716b42014-03-03 23:48:23 +00002048void CGDebugInfo::completeTemplateDefinition(
2049 const ClassTemplateSpecializationDecl &SD) {
David Blaikie0856f662014-03-04 22:01:08 +00002050 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
2051 return;
2052
David Blaikie0e716b42014-03-03 23:48:23 +00002053 completeClassData(&SD);
2054 // In case this type has no member function definitions being emitted, ensure
2055 // it is retained
2056 RetainedTypes.push_back(CGM.getContext().getRecordType(&SD).getAsOpaquePtr());
2057}
2058
Adrian Prantl73409ce2013-03-11 18:33:46 +00002059/// getCachedInterfaceTypeOrNull - Get the type from the interface
2060/// cache, unless it needs to regenerated. Otherwise return null.
2061llvm::Value *CGDebugInfo::getCachedInterfaceTypeOrNull(QualType Ty) {
2062 // Is there a cached interface that hasn't changed?
2063 llvm::DenseMap<void *, std::pair<llvm::WeakVH, unsigned > >
2064 ::iterator it1 = ObjCInterfaceCache.find(Ty.getAsOpaquePtr());
2065
2066 if (it1 != ObjCInterfaceCache.end())
2067 if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty))
2068 if (Checksum(Decl) == it1->second.second)
2069 // Return cached forward declaration.
2070 return it1->second.first;
2071
2072 return 0;
2073}
Guy Benyei11169dd2012-12-18 14:30:41 +00002074
2075/// getOrCreateType - Get the type from the cache or create a new
2076/// one if necessary.
David Blaikie99dab3b2013-09-04 22:03:57 +00002077llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002078 if (Ty.isNull())
2079 return llvm::DIType();
2080
2081 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00002082 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00002083
David Blaikie99dab3b2013-09-04 22:03:57 +00002084 if (llvm::DIType T = getCompletedTypeOrNull(Ty))
Guy Benyei11169dd2012-12-18 14:30:41 +00002085 return T;
2086
2087 // Otherwise create the type.
David Blaikie99dab3b2013-09-04 22:03:57 +00002088 llvm::DIType Res = CreateTypeNode(Ty, Unit);
Adrian Prantl73409ce2013-03-11 18:33:46 +00002089 void* TyPtr = Ty.getAsOpaquePtr();
2090
2091 // And update the type cache.
2092 TypeCache[TyPtr] = Res;
Guy Benyei11169dd2012-12-18 14:30:41 +00002093
David Blaikie6a723442013-08-15 21:21:19 +00002094 // FIXME: this getTypeOrNull call seems silly when we just inserted the type
2095 // into the cache - but getTypeOrNull has a special case for cached interface
2096 // types. We should probably just pull that out as a special case for the
2097 // "else" block below & skip the otherwise needless lookup.
Guy Benyei11169dd2012-12-18 14:30:41 +00002098 llvm::DIType TC = getTypeOrNull(Ty);
Eric Christopherf8bc4d82013-07-18 00:52:50 +00002099 if (TC && TC.isForwardDecl())
Adrian Prantl73409ce2013-03-11 18:33:46 +00002100 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
2101 else if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty)) {
2102 // Interface types may have elements added to them by a
2103 // subsequent implementation or extension, so we keep them in
2104 // the ObjCInterfaceCache together with a checksum. Instead of
Adrian Prantlc20237d2013-05-08 23:37:22 +00002105 // the (possibly) incomplete interface type, we return a forward
Adrian Prantl73409ce2013-03-11 18:33:46 +00002106 // declaration that gets RAUW'd in CGDebugInfo::finalize().
David Blaikie8e5939b2013-05-21 18:29:40 +00002107 std::pair<llvm::WeakVH, unsigned> &V = ObjCInterfaceCache[TyPtr];
2108 if (V.first)
2109 return llvm::DIType(cast<llvm::MDNode>(V.first));
2110 TC = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
2111 Decl->getName(), TheCU, Unit,
2112 getLineNumber(Decl->getLocation()),
2113 TheCU.getLanguage());
2114 // Store the forward declaration in the cache.
2115 V.first = TC;
2116 V.second = Checksum(Decl);
Adrian Prantl73409ce2013-03-11 18:33:46 +00002117
David Blaikie8e5939b2013-05-21 18:29:40 +00002118 // Register the type for replacement in finalize().
2119 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
2120
Adrian Prantl73409ce2013-03-11 18:33:46 +00002121 return TC;
Adrian Prantla03a85a2013-03-06 22:03:30 +00002122 }
2123
Guy Benyei11169dd2012-12-18 14:30:41 +00002124 if (!Res.isForwardDecl())
Adrian Prantl73409ce2013-03-11 18:33:46 +00002125 CompletedTypeCache[TyPtr] = Res;
Guy Benyei11169dd2012-12-18 14:30:41 +00002126
2127 return Res;
2128}
2129
Adrian Prantlc4de1ef2013-06-07 01:10:41 +00002130/// Currently the checksum of an interface includes the number of
2131/// ivars and property accessors.
Eric Christopher1ecc5632013-06-07 22:54:39 +00002132unsigned CGDebugInfo::Checksum(const ObjCInterfaceDecl *ID) {
Adrian Prantl817bbb32013-06-07 01:10:48 +00002133 // The assumption is that the number of ivars can only increase
2134 // monotonically, so it is safe to just use their current number as
2135 // a checksum.
Adrian Prantlc4de1ef2013-06-07 01:10:41 +00002136 unsigned Sum = 0;
2137 for (const ObjCIvarDecl *Ivar = ID->all_declared_ivar_begin();
2138 Ivar != 0; Ivar = Ivar->getNextIvar())
2139 ++Sum;
2140
2141 return Sum;
Adrian Prantla03a85a2013-03-06 22:03:30 +00002142}
2143
2144ObjCInterfaceDecl *CGDebugInfo::getObjCInterfaceDecl(QualType Ty) {
2145 switch (Ty->getTypeClass()) {
2146 case Type::ObjCObjectPointer:
Eric Christopher0fdcb312013-05-16 00:52:20 +00002147 return getObjCInterfaceDecl(cast<ObjCObjectPointerType>(Ty)
2148 ->getPointeeType());
Adrian Prantla03a85a2013-03-06 22:03:30 +00002149 case Type::ObjCInterface:
2150 return cast<ObjCInterfaceType>(Ty)->getDecl();
2151 default:
2152 return 0;
2153 }
2154}
2155
Guy Benyei11169dd2012-12-18 14:30:41 +00002156/// CreateTypeNode - Create a new debug type node.
David Blaikie99dab3b2013-09-04 22:03:57 +00002157llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002158 // Handle qualifiers, which recursively handles what they refer to.
2159 if (Ty.hasLocalQualifiers())
David Blaikie99dab3b2013-09-04 22:03:57 +00002160 return CreateQualifiedType(Ty, Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00002161
2162 const char *Diag = 0;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002163
Guy Benyei11169dd2012-12-18 14:30:41 +00002164 // Work out details of type.
2165 switch (Ty->getTypeClass()) {
2166#define TYPE(Class, Base)
2167#define ABSTRACT_TYPE(Class, Base)
2168#define NON_CANONICAL_TYPE(Class, Base)
2169#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2170#include "clang/AST/TypeNodes.def"
2171 llvm_unreachable("Dependent types cannot show up in debug information");
2172
2173 case Type::ExtVector:
2174 case Type::Vector:
2175 return CreateType(cast<VectorType>(Ty), Unit);
2176 case Type::ObjCObjectPointer:
2177 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
2178 case Type::ObjCObject:
2179 return CreateType(cast<ObjCObjectType>(Ty), Unit);
2180 case Type::ObjCInterface:
2181 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
2182 case Type::Builtin:
2183 return CreateType(cast<BuiltinType>(Ty));
2184 case Type::Complex:
2185 return CreateType(cast<ComplexType>(Ty));
2186 case Type::Pointer:
2187 return CreateType(cast<PointerType>(Ty), Unit);
Reid Kleckner0503a872013-12-05 01:23:43 +00002188 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00002189 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00002190 // Decayed and adjusted types use the adjusted type in LLVM and DWARF.
Reid Kleckner8a365022013-06-24 17:51:48 +00002191 return CreateType(
Reid Kleckner0503a872013-12-05 01:23:43 +00002192 cast<PointerType>(cast<AdjustedType>(Ty)->getAdjustedType()), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00002193 case Type::BlockPointer:
2194 return CreateType(cast<BlockPointerType>(Ty), Unit);
2195 case Type::Typedef:
David Blaikie99dab3b2013-09-04 22:03:57 +00002196 return CreateType(cast<TypedefType>(Ty), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00002197 case Type::Record:
David Blaikie99dab3b2013-09-04 22:03:57 +00002198 return CreateType(cast<RecordType>(Ty));
Guy Benyei11169dd2012-12-18 14:30:41 +00002199 case Type::Enum:
Manman Ren1b457022013-08-28 21:20:28 +00002200 return CreateEnumType(cast<EnumType>(Ty));
Guy Benyei11169dd2012-12-18 14:30:41 +00002201 case Type::FunctionProto:
2202 case Type::FunctionNoProto:
2203 return CreateType(cast<FunctionType>(Ty), Unit);
2204 case Type::ConstantArray:
2205 case Type::VariableArray:
2206 case Type::IncompleteArray:
2207 return CreateType(cast<ArrayType>(Ty), Unit);
2208
2209 case Type::LValueReference:
2210 return CreateType(cast<LValueReferenceType>(Ty), Unit);
2211 case Type::RValueReference:
2212 return CreateType(cast<RValueReferenceType>(Ty), Unit);
2213
2214 case Type::MemberPointer:
2215 return CreateType(cast<MemberPointerType>(Ty), Unit);
2216
2217 case Type::Atomic:
2218 return CreateType(cast<AtomicType>(Ty), Unit);
2219
Guy Benyei11169dd2012-12-18 14:30:41 +00002220 case Type::TemplateSpecialization:
David Blaikief1b382e2014-04-06 17:14:06 +00002221 return CreateType(cast<TemplateSpecializationType>(Ty), Unit);
2222
2223 case Type::Attributed:
Guy Benyei11169dd2012-12-18 14:30:41 +00002224 case Type::Elaborated:
2225 case Type::Paren:
2226 case Type::SubstTemplateTypeParm:
2227 case Type::TypeOfExpr:
2228 case Type::TypeOf:
2229 case Type::Decltype:
2230 case Type::UnaryTransform:
David Blaikie66ed89d2013-07-13 21:08:08 +00002231 case Type::PackExpansion:
Guy Benyei11169dd2012-12-18 14:30:41 +00002232 llvm_unreachable("type should have been unwrapped!");
David Blaikie22c460a02013-05-24 21:24:35 +00002233 case Type::Auto:
2234 Diag = "auto";
2235 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002236 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00002237
Guy Benyei11169dd2012-12-18 14:30:41 +00002238 assert(Diag && "Fall through without a diagnostic?");
2239 unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error,
2240 "debug information for %0 is not yet supported");
2241 CGM.getDiags().Report(DiagID)
2242 << Diag;
2243 return llvm::DIType();
2244}
2245
2246/// getOrCreateLimitedType - Get the type from the cache or create a new
2247/// limited type if necessary.
David Blaikie4a2b5ef2013-08-12 22:24:20 +00002248llvm::DIType CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty,
Eric Christopherc0c5d462013-02-21 22:35:08 +00002249 llvm::DIFile Unit) {
David Blaikie4a2b5ef2013-08-12 22:24:20 +00002250 QualType QTy(Ty, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00002251
David Blaikie8d5e1282013-08-20 21:03:29 +00002252 llvm::DICompositeType T(getTypeOrNull(QTy));
Guy Benyei11169dd2012-12-18 14:30:41 +00002253
2254 // We may have cached a forward decl when we could have created
2255 // a non-forward decl. Go ahead and create a non-forward decl
2256 // now.
Eric Christopherf8bc4d82013-07-18 00:52:50 +00002257 if (T && !T.isForwardDecl()) return T;
Guy Benyei11169dd2012-12-18 14:30:41 +00002258
2259 // Otherwise create the type.
David Blaikie8d5e1282013-08-20 21:03:29 +00002260 llvm::DICompositeType Res = CreateLimitedType(Ty);
2261
2262 // Propagate members from the declaration to the definition
2263 // CreateType(const RecordType*) will overwrite this with the members in the
2264 // correct order if the full type is needed.
2265 Res.setTypeArray(T.getTypeArray());
Guy Benyei11169dd2012-12-18 14:30:41 +00002266
Eric Christopherf8bc4d82013-07-18 00:52:50 +00002267 if (T && T.isForwardDecl())
David Blaikie4a2b5ef2013-08-12 22:24:20 +00002268 ReplaceMap.push_back(
2269 std::make_pair(QTy.getAsOpaquePtr(), static_cast<llvm::Value *>(T)));
Guy Benyei11169dd2012-12-18 14:30:41 +00002270
2271 // And update the type cache.
David Blaikie4a2b5ef2013-08-12 22:24:20 +00002272 TypeCache[QTy.getAsOpaquePtr()] = Res;
Guy Benyei11169dd2012-12-18 14:30:41 +00002273 return Res;
2274}
2275
2276// TODO: Currently used for context chains when limiting debug info.
David Blaikie8d5e1282013-08-20 21:03:29 +00002277llvm::DICompositeType CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002278 RecordDecl *RD = Ty->getDecl();
Eric Christopherb2a008c2013-05-16 00:45:12 +00002279
Guy Benyei11169dd2012-12-18 14:30:41 +00002280 // Get overall information about the record type for the debug info.
2281 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
2282 unsigned Line = getLineNumber(RD->getLocation());
2283 StringRef RDName = getClassName(RD);
2284
Eric Christopher07429ff2013-10-15 21:22:34 +00002285 llvm::DIDescriptor RDContext =
2286 getContextDescriptor(cast<Decl>(RD->getDeclContext()));
Guy Benyei11169dd2012-12-18 14:30:41 +00002287
David Blaikied2785892013-08-18 17:36:19 +00002288 // If we ended up creating the type during the context chain construction,
2289 // just return that.
2290 // FIXME: this could be dealt with better if the type was recorded as
2291 // completed before we started this (see the CompletedTypeCache usage in
2292 // CGDebugInfo::CreateTypeDefinition(const RecordType*) - that would need to
2293 // be pushed to before context creation, but after it was known to be
2294 // destined for completion (might still have an issue if this caller only
2295 // required a declaration but the context construction ended up creating a
2296 // definition)
David Blaikie8d5e1282013-08-20 21:03:29 +00002297 llvm::DICompositeType T(getTypeOrNull(CGM.getContext().getRecordType(RD)));
2298 if (T && (!T.isForwardDecl() || !RD->getDefinition()))
David Blaikied2785892013-08-18 17:36:19 +00002299 return T;
2300
Adrian Prantl381e7552014-02-04 21:29:50 +00002301 // If this is just a forward or incomplete declaration, construct an
2302 // appropriately marked node and just return it.
2303 const RecordDecl *D = RD->getDefinition();
2304 if (!D || !D->isCompleteDefinition())
Manman Ren1b457022013-08-28 21:20:28 +00002305 return getOrCreateRecordFwdDecl(Ty, RDContext);
Guy Benyei11169dd2012-12-18 14:30:41 +00002306
2307 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2308 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
David Blaikie49ae6a72013-03-26 23:47:35 +00002309 llvm::DICompositeType RealDecl;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002310
Manman Rene0064d82013-08-29 23:19:58 +00002311 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
2312
Guy Benyei11169dd2012-12-18 14:30:41 +00002313 if (RD->isUnion())
2314 RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
Manman Rene0064d82013-08-29 23:19:58 +00002315 Size, Align, 0, llvm::DIArray(), 0,
2316 FullName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002317 else if (RD->isClass()) {
2318 // FIXME: This could be a struct type giving a default visibility different
2319 // than C++ class type, but needs llvm metadata changes first.
2320 RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
Eric Christopherc0c5d462013-02-21 22:35:08 +00002321 Size, Align, 0, 0, llvm::DIType(),
2322 llvm::DIArray(), llvm::DIType(),
Manman Rene0064d82013-08-29 23:19:58 +00002323 llvm::DIArray(), FullName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002324 } else
2325 RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line,
Eric Christopher0fdcb312013-05-16 00:52:20 +00002326 Size, Align, 0, llvm::DIType(),
David Blaikieba477362013-11-18 23:38:26 +00002327 llvm::DIArray(), 0, llvm::DIType(),
2328 FullName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002329
2330 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
David Blaikie49ae6a72013-03-26 23:47:35 +00002331 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00002332
David Blaikieadfbf992013-08-18 16:55:33 +00002333 if (const ClassTemplateSpecializationDecl *TSpecial =
2334 dyn_cast<ClassTemplateSpecializationDecl>(RD))
2335 RealDecl.setTypeArray(llvm::DIArray(),
2336 CollectCXXTemplateParams(TSpecial, DefUnit));
David Blaikie952dac32013-08-15 22:42:12 +00002337 return RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00002338}
2339
David Blaikieadfbf992013-08-18 16:55:33 +00002340void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,
2341 llvm::DICompositeType RealDecl) {
2342 // A class's primary base or the class itself contains the vtable.
2343 llvm::DICompositeType ContainingType;
2344 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2345 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
Alp Tokerd4733632013-12-05 04:47:09 +00002346 // Seek non-virtual primary base root.
David Blaikieadfbf992013-08-18 16:55:33 +00002347 while (1) {
2348 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
2349 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
2350 if (PBT && !BRL.isPrimaryBaseVirtual())
2351 PBase = PBT;
2352 else
2353 break;
2354 }
2355 ContainingType = llvm::DICompositeType(
2356 getOrCreateType(QualType(PBase->getTypeForDecl(), 0),
2357 getOrCreateFile(RD->getLocation())));
2358 } else if (RD->isDynamicClass())
2359 ContainingType = RealDecl;
2360
2361 RealDecl.setContainingType(ContainingType);
2362}
2363
Guy Benyei11169dd2012-12-18 14:30:41 +00002364/// CreateMemberType - Create new member and increase Offset by FType's size.
2365llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
2366 StringRef Name,
2367 uint64_t *Offset) {
2368 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2369 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
2370 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
2371 llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0,
2372 FieldSize, FieldAlign,
2373 *Offset, 0, FieldTy);
2374 *Offset += FieldSize;
2375 return Ty;
2376}
2377
Adrian Prantl6cdce9e2014-04-01 03:41:01 +00002378llvm::DIScope CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
David Blaikiebd483762013-05-20 04:58:53 +00002379 // We only need a declaration (not a definition) of the type - so use whatever
2380 // we would otherwise do to get a type for a pointee. (forward declarations in
2381 // limited debug info, full definitions (if the type definition is available)
2382 // in unlimited debug info)
David Blaikie6b7d060c2013-08-12 23:14:36 +00002383 if (const TypeDecl *TD = dyn_cast<TypeDecl>(D))
2384 return getOrCreateType(CGM.getContext().getTypeDeclType(TD),
David Blaikie99dab3b2013-09-04 22:03:57 +00002385 getOrCreateFile(TD->getLocation()));
David Blaikiebd483762013-05-20 04:58:53 +00002386 // Otherwise fall back to a fairly rudimentary cache of existing declarations.
2387 // This doesn't handle providing declarations (for functions or variables) for
2388 // entities without definitions in this TU, nor when the definition proceeds
2389 // the call to this function.
2390 // FIXME: This should be split out into more specific maps with support for
2391 // emitting forward declarations and merging definitions with declarations,
2392 // the same way as we do for types.
2393 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator I =
2394 DeclCache.find(D->getCanonicalDecl());
2395 if (I == DeclCache.end())
Adrian Prantl6cdce9e2014-04-01 03:41:01 +00002396 return llvm::DIScope();
David Blaikiebd483762013-05-20 04:58:53 +00002397 llvm::Value *V = I->second;
Adrian Prantl6cdce9e2014-04-01 03:41:01 +00002398 return llvm::DIScope(dyn_cast_or_null<llvm::MDNode>(V));
David Blaikiebd483762013-05-20 04:58:53 +00002399}
2400
Guy Benyei11169dd2012-12-18 14:30:41 +00002401/// getFunctionDeclaration - Return debug info descriptor to describe method
2402/// declaration for the given method definition.
2403llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
David Blaikie18cfbc52013-06-22 00:09:36 +00002404 if (!D || DebugKind == CodeGenOptions::DebugLineTablesOnly)
2405 return llvm::DISubprogram();
2406
Guy Benyei11169dd2012-12-18 14:30:41 +00002407 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
2408 if (!FD) return llvm::DISubprogram();
2409
2410 // Setup context.
David Blaikiefd07c602013-08-09 17:20:05 +00002411 llvm::DIScope S = getContextDescriptor(cast<Decl>(D->getDeclContext()));
Guy Benyei11169dd2012-12-18 14:30:41 +00002412
2413 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2414 MI = SPCache.find(FD->getCanonicalDecl());
David Blaikiefd07c602013-08-09 17:20:05 +00002415 if (MI == SPCache.end()) {
Eric Christopherf86c4052013-08-28 23:12:10 +00002416 if (const CXXMethodDecl *MD =
2417 dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
David Blaikiefd07c602013-08-09 17:20:05 +00002418 llvm::DICompositeType T(S);
Eric Christopherf86c4052013-08-28 23:12:10 +00002419 llvm::DISubprogram SP =
2420 CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()), T);
David Blaikiefd07c602013-08-09 17:20:05 +00002421 return SP;
2422 }
2423 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002424 if (MI != SPCache.end()) {
2425 llvm::Value *V = MI->second;
2426 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
David Blaikie18cfbc52013-06-22 00:09:36 +00002427 if (SP.isSubprogram() && !SP.isDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00002428 return SP;
2429 }
2430
Aaron Ballman86c93902014-03-06 23:45:36 +00002431 for (auto NextFD : FD->redecls()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002432 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2433 MI = SPCache.find(NextFD->getCanonicalDecl());
2434 if (MI != SPCache.end()) {
2435 llvm::Value *V = MI->second;
2436 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
David Blaikie18cfbc52013-06-22 00:09:36 +00002437 if (SP.isSubprogram() && !SP.isDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00002438 return SP;
2439 }
2440 }
2441 return llvm::DISubprogram();
2442}
2443
2444// getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
2445// implicit parameter "this".
David Blaikie469f0792013-05-22 23:22:42 +00002446llvm::DICompositeType CGDebugInfo::getOrCreateFunctionType(const Decl *D,
2447 QualType FnType,
2448 llvm::DIFile F) {
David Blaikie18cfbc52013-06-22 00:09:36 +00002449 if (!D || DebugKind == CodeGenOptions::DebugLineTablesOnly)
2450 // Create fake but valid subroutine type. Otherwise
2451 // llvm::DISubprogram::Verify() would return false, and
2452 // subprogram DIE will miss DW_AT_decl_file and
2453 // DW_AT_decl_line fields.
2454 return DBuilder.createSubroutineType(F, DBuilder.getOrCreateArray(None));
Guy Benyei11169dd2012-12-18 14:30:41 +00002455
2456 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
2457 return getOrCreateMethodType(Method, F);
2458 if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
2459 // Add "self" and "_cmd"
2460 SmallVector<llvm::Value *, 16> Elts;
2461
2462 // First element is always return type. For 'void' functions it is NULL.
Alp Toker314cc812014-01-25 16:55:45 +00002463 QualType ResultTy = OMethod->getReturnType();
Adrian Prantl5f360102013-05-22 21:37:49 +00002464
2465 // Replace the instancetype keyword with the actual type.
2466 if (ResultTy == CGM.getContext().getObjCInstanceType())
2467 ResultTy = CGM.getContext().getPointerType(
2468 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
2469
Adrian Prantl7bec9032013-05-10 21:08:31 +00002470 Elts.push_back(getOrCreateType(ResultTy, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002471 // "self" pointer is always first argument.
Adrian Prantlde17db32013-03-29 19:20:29 +00002472 QualType SelfDeclTy = OMethod->getSelfDecl()->getType();
2473 llvm::DIType SelfTy = getOrCreateType(SelfDeclTy, F);
2474 Elts.push_back(CreateSelfType(SelfDeclTy, SelfTy));
Guy Benyei11169dd2012-12-18 14:30:41 +00002475 // "_cmd" pointer is always second argument.
2476 llvm::DIType CmdTy = getOrCreateType(OMethod->getCmdDecl()->getType(), F);
2477 Elts.push_back(DBuilder.createArtificialType(CmdTy));
2478 // Get rest of the arguments.
Aaron Ballman43b68be2014-03-07 17:50:17 +00002479 for (const auto *PI : OMethod->params())
2480 Elts.push_back(getOrCreateType(PI->getType(), F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002481
2482 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2483 return DBuilder.createSubroutineType(F, EltTypeArray);
2484 }
Adrian Prantld45ba252014-02-25 19:38:11 +00002485
Adrian Prantl800faef2014-02-25 23:42:18 +00002486 // Handle variadic function types; they need an additional
2487 // unspecified parameter.
Adrian Prantld45ba252014-02-25 19:38:11 +00002488 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2489 if (FD->isVariadic()) {
2490 SmallVector<llvm::Value *, 16> EltTys;
2491 EltTys.push_back(getOrCreateType(FD->getReturnType(), F));
2492 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FnType))
2493 for (unsigned i = 0, e = FPT->getNumParams(); i != e; ++i)
2494 EltTys.push_back(getOrCreateType(FPT->getParamType(i), F));
2495 EltTys.push_back(DBuilder.createUnspecifiedParameter());
2496 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
2497 return DBuilder.createSubroutineType(F, EltTypeArray);
2498 }
2499
David Blaikie469f0792013-05-22 23:22:42 +00002500 return llvm::DICompositeType(getOrCreateType(FnType, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002501}
2502
2503/// EmitFunctionStart - Constructs the debug code for entering a function.
Adrian Prantl42d71b92014-04-10 23:21:53 +00002504void CGDebugInfo::EmitFunctionStart(GlobalDecl GD,
2505 SourceLocation Loc,
2506 SourceLocation ScopeLoc,
2507 QualType FnType,
Guy Benyei11169dd2012-12-18 14:30:41 +00002508 llvm::Function *Fn,
2509 CGBuilderTy &Builder) {
2510
2511 StringRef Name;
2512 StringRef LinkageName;
2513
2514 FnBeginRegionCount.push_back(LexicalBlockStack.size());
2515
2516 const Decl *D = GD.getDecl();
Guy Benyei11169dd2012-12-18 14:30:41 +00002517 bool HasDecl = (D != 0);
Eric Christopher885c41b2014-04-01 22:25:28 +00002518
Guy Benyei11169dd2012-12-18 14:30:41 +00002519 unsigned Flags = 0;
2520 llvm::DIFile Unit = getOrCreateFile(Loc);
2521 llvm::DIDescriptor FDContext(Unit);
2522 llvm::DIArray TParamsArray;
2523 if (!HasDecl) {
2524 // Use llvm function name.
David Blaikieebe87e12013-08-27 23:57:18 +00002525 LinkageName = Fn->getName();
Guy Benyei11169dd2012-12-18 14:30:41 +00002526 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2527 // If there is a DISubprogram for this function available then use it.
2528 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2529 FI = SPCache.find(FD->getCanonicalDecl());
2530 if (FI != SPCache.end()) {
2531 llvm::Value *V = FI->second;
2532 llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(V));
2533 if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
2534 llvm::MDNode *SPN = SP;
2535 LexicalBlockStack.push_back(SPN);
2536 RegionMap[D] = llvm::WeakVH(SP);
2537 return;
2538 }
2539 }
2540 Name = getFunctionName(FD);
Nick Lewyckyc02bbb62013-03-20 01:38:16 +00002541 // Use mangled name as linkage name for C/C++ functions.
Guy Benyei11169dd2012-12-18 14:30:41 +00002542 if (FD->hasPrototype()) {
2543 LinkageName = CGM.getMangledName(GD);
2544 Flags |= llvm::DIDescriptor::FlagPrototyped;
2545 }
Nick Lewyckyc02bbb62013-03-20 01:38:16 +00002546 // No need to replicate the linkage name if it isn't different from the
2547 // subprogram name, no need to have it at all unless coverage is enabled or
2548 // debug is set to more than just line tables.
Guy Benyei11169dd2012-12-18 14:30:41 +00002549 if (LinkageName == Name ||
Nick Lewyckyc02bbb62013-03-20 01:38:16 +00002550 (!CGM.getCodeGenOpts().EmitGcovArcs &&
2551 !CGM.getCodeGenOpts().EmitGcovNotes &&
Eric Christopher75e17682013-05-16 00:45:23 +00002552 DebugKind <= CodeGenOptions::DebugLineTablesOnly))
Guy Benyei11169dd2012-12-18 14:30:41 +00002553 LinkageName = StringRef();
2554
Eric Christopher75e17682013-05-16 00:45:23 +00002555 if (DebugKind >= CodeGenOptions::LimitedDebugInfo) {
Eric Christopher4cbd0d9d2014-03-27 05:29:34 +00002556 if (const NamespaceDecl *NSDecl =
2557 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
2558 FDContext = getOrCreateNameSpace(NSDecl);
2559 else if (const RecordDecl *RDecl =
2560 dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
2561 FDContext = getContextDescriptor(cast<Decl>(RDecl));
2562
2563 // Collect template parameters.
Guy Benyei11169dd2012-12-18 14:30:41 +00002564 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
2565 }
2566 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
2567 Name = getObjCMethodName(OMD);
2568 Flags |= llvm::DIDescriptor::FlagPrototyped;
2569 } else {
2570 // Use llvm function name.
2571 Name = Fn->getName();
2572 Flags |= llvm::DIDescriptor::FlagPrototyped;
2573 }
2574 if (!Name.empty() && Name[0] == '\01')
2575 Name = Name.substr(1);
2576
Adrian Prantl42d71b92014-04-10 23:21:53 +00002577 if (!HasDecl || D->isImplicit()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002578 Flags |= llvm::DIDescriptor::FlagArtificial;
Adrian Prantl42d71b92014-04-10 23:21:53 +00002579 // Artificial functions without a location should not silently reuse CurLoc.
2580 if (Loc.isInvalid())
2581 CurLoc = SourceLocation();
2582 }
2583 unsigned LineNo = getLineNumber(Loc);
2584 unsigned ScopeLine = getLineNumber(ScopeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00002585
Eric Christopher8018e412014-03-27 18:50:35 +00002586 // FIXME: The function declaration we're constructing here is mostly reusing
2587 // declarations from CXXMethodDecl and not constructing new ones for arbitrary
2588 // FunctionDecls. When/if we fix this we can have FDContext be TheCU/null for
2589 // all subprograms instead of the actual context since subprogram definitions
2590 // are emitted as CU level entities by the backend.
Eric Christopher9e6f5f92013-10-17 01:31:21 +00002591 llvm::DISubprogram SP =
2592 DBuilder.createFunction(FDContext, Name, LinkageName, Unit, LineNo,
2593 getOrCreateFunctionType(D, FnType, Unit),
2594 Fn->hasInternalLinkage(), true /*definition*/,
Adrian Prantl42d71b92014-04-10 23:21:53 +00002595 ScopeLine, Flags,
Eric Christopher9e6f5f92013-10-17 01:31:21 +00002596 CGM.getLangOpts().Optimize, Fn, TParamsArray,
2597 getFunctionDeclaration(D));
David Blaikiebd483762013-05-20 04:58:53 +00002598 if (HasDecl)
2599 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(SP)));
Guy Benyei11169dd2012-12-18 14:30:41 +00002600
Adrian Prantlbebb8932014-03-21 21:01:58 +00002601 // Push the function onto the lexical block stack.
Guy Benyei11169dd2012-12-18 14:30:41 +00002602 llvm::MDNode *SPN = SP;
2603 LexicalBlockStack.push_back(SPN);
Adrian Prantlbebb8932014-03-21 21:01:58 +00002604
Guy Benyei11169dd2012-12-18 14:30:41 +00002605 if (HasDecl)
2606 RegionMap[D] = llvm::WeakVH(SP);
2607}
2608
2609/// EmitLocation - Emit metadata to indicate a change in line/column
Adrian Prantl02c0caa2013-07-18 00:27:59 +00002610/// information in the source file. If the location is invalid, the
2611/// previous location will be reused.
Adrian Prantlc7822422013-03-12 20:43:25 +00002612void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc,
Adrian Prantle83b1302014-01-07 22:05:52 +00002613 bool ForceColumnInfo) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002614 // Update our current location
2615 setLocation(Loc);
2616
2617 if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
2618
2619 // Don't bother if things are the same as last time.
2620 SourceManager &SM = CGM.getContext().getSourceManager();
2621 if (CurLoc == PrevLoc ||
2622 SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc))
2623 // New Builder may not be in sync with CGDebugInfo.
David Blaikie357aafb2013-02-01 19:09:49 +00002624 if (!Builder.getCurrentDebugLocation().isUnknown() &&
2625 Builder.getCurrentDebugLocation().getScope(CGM.getLLVMContext()) ==
2626 LexicalBlockStack.back())
Guy Benyei11169dd2012-12-18 14:30:41 +00002627 return;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002628
Guy Benyei11169dd2012-12-18 14:30:41 +00002629 // Update last state.
2630 PrevLoc = CurLoc;
2631
Adrian Prantle83b1302014-01-07 22:05:52 +00002632 llvm::MDNode *Scope = LexicalBlockStack.back();
Adrian Prantlc7822422013-03-12 20:43:25 +00002633 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get
2634 (getLineNumber(CurLoc),
2635 getColumnNumber(CurLoc, ForceColumnInfo),
2636 Scope));
Guy Benyei11169dd2012-12-18 14:30:41 +00002637}
2638
2639/// CreateLexicalBlock - Creates a new lexical block node and pushes it on
2640/// the stack.
2641void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
2642 llvm::DIDescriptor D =
2643 DBuilder.createLexicalBlock(LexicalBlockStack.empty() ?
2644 llvm::DIDescriptor() :
2645 llvm::DIDescriptor(LexicalBlockStack.back()),
2646 getOrCreateFile(CurLoc),
2647 getLineNumber(CurLoc),
Diego Novilloe6d398182014-03-03 18:53:32 +00002648 getColumnNumber(CurLoc),
2649 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00002650 llvm::MDNode *DN = D;
2651 LexicalBlockStack.push_back(DN);
2652}
2653
2654/// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
2655/// region - beginning of a DW_TAG_lexical_block.
Eric Christopher0fdcb312013-05-16 00:52:20 +00002656void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
2657 SourceLocation Loc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002658 // Set our current location.
2659 setLocation(Loc);
2660
2661 // Create a new lexical block and push it on the stack.
2662 CreateLexicalBlock(Loc);
2663
2664 // Emit a line table change for the current location inside the new scope.
2665 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc),
2666 getColumnNumber(Loc),
2667 LexicalBlockStack.back()));
2668}
2669
2670/// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative
2671/// region - end of a DW_TAG_lexical_block.
Eric Christopher0fdcb312013-05-16 00:52:20 +00002672void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
2673 SourceLocation Loc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002674 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2675
2676 // Provide an entry in the line table for the end of the block.
2677 EmitLocation(Builder, Loc);
2678
2679 LexicalBlockStack.pop_back();
2680}
2681
2682/// EmitFunctionEnd - Constructs the debug code for exiting a function.
2683void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
2684 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2685 unsigned RCount = FnBeginRegionCount.back();
2686 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
2687
2688 // Pop all regions for this function.
2689 while (LexicalBlockStack.size() != RCount)
2690 EmitLexicalBlockEnd(Builder, CurLoc);
2691 FnBeginRegionCount.pop_back();
2692}
2693
Eric Christopherb2a008c2013-05-16 00:45:12 +00002694// EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
Guy Benyei11169dd2012-12-18 14:30:41 +00002695// See BuildByRefType.
2696llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
2697 uint64_t *XOffset) {
2698
2699 SmallVector<llvm::Value *, 5> EltTys;
2700 QualType FType;
2701 uint64_t FieldSize, FieldOffset;
2702 unsigned FieldAlign;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002703
Guy Benyei11169dd2012-12-18 14:30:41 +00002704 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
Eric Christopherb2a008c2013-05-16 00:45:12 +00002705 QualType Type = VD->getType();
Guy Benyei11169dd2012-12-18 14:30:41 +00002706
2707 FieldOffset = 0;
2708 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2709 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
2710 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
2711 FType = CGM.getContext().IntTy;
2712 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
2713 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
2714
2715 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
2716 if (HasCopyAndDispose) {
2717 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2718 EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
2719 &FieldOffset));
2720 EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
2721 &FieldOffset));
2722 }
2723 bool HasByrefExtendedLayout;
2724 Qualifiers::ObjCLifetime Lifetime;
2725 if (CGM.getContext().getByrefLifetime(Type,
2726 Lifetime, HasByrefExtendedLayout)
Adrian Prantlead2ba42013-07-23 00:12:14 +00002727 && HasByrefExtendedLayout) {
2728 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
Guy Benyei11169dd2012-12-18 14:30:41 +00002729 EltTys.push_back(CreateMemberType(Unit, FType,
2730 "__byref_variable_layout",
2731 &FieldOffset));
Adrian Prantlead2ba42013-07-23 00:12:14 +00002732 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00002733
Guy Benyei11169dd2012-12-18 14:30:41 +00002734 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2735 if (Align > CGM.getContext().toCharUnitsFromBits(
John McCallc8e01702013-04-16 22:48:15 +00002736 CGM.getTarget().getPointerAlign(0))) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00002737 CharUnits FieldOffsetInBytes
Guy Benyei11169dd2012-12-18 14:30:41 +00002738 = CGM.getContext().toCharUnitsFromBits(FieldOffset);
2739 CharUnits AlignedOffsetInBytes
2740 = FieldOffsetInBytes.RoundUpToAlignment(Align);
2741 CharUnits NumPaddingBytes
2742 = AlignedOffsetInBytes - FieldOffsetInBytes;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002743
Guy Benyei11169dd2012-12-18 14:30:41 +00002744 if (NumPaddingBytes.isPositive()) {
2745 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
2746 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
2747 pad, ArrayType::Normal, 0);
2748 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
2749 }
2750 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00002751
Guy Benyei11169dd2012-12-18 14:30:41 +00002752 FType = Type;
2753 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2754 FieldSize = CGM.getContext().getTypeSize(FType);
2755 FieldAlign = CGM.getContext().toBits(Align);
2756
Eric Christopherb2a008c2013-05-16 00:45:12 +00002757 *XOffset = FieldOffset;
Guy Benyei11169dd2012-12-18 14:30:41 +00002758 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit,
2759 0, FieldSize, FieldAlign,
2760 FieldOffset, 0, FieldTy);
2761 EltTys.push_back(FieldTy);
2762 FieldOffset += FieldSize;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002763
Guy Benyei11169dd2012-12-18 14:30:41 +00002764 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002765
Guy Benyei11169dd2012-12-18 14:30:41 +00002766 unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002767
Guy Benyei11169dd2012-12-18 14:30:41 +00002768 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
David Blaikie6d4fe152013-02-25 01:07:08 +00002769 llvm::DIType(), Elements);
Guy Benyei11169dd2012-12-18 14:30:41 +00002770}
2771
2772/// EmitDeclare - Emit local variable declaration debug info.
2773void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
Eric Christopherb2a008c2013-05-16 00:45:12 +00002774 llvm::Value *Storage,
Guy Benyei11169dd2012-12-18 14:30:41 +00002775 unsigned ArgNo, CGBuilderTy &Builder) {
Eric Christopher75e17682013-05-16 00:45:23 +00002776 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002777 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2778
David Blaikie7fceebf2013-08-19 03:37:48 +00002779 bool Unwritten =
2780 VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) &&
2781 cast<Decl>(VD->getDeclContext())->isImplicit());
2782 llvm::DIFile Unit;
2783 if (!Unwritten)
2784 Unit = getOrCreateFile(VD->getLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00002785 llvm::DIType Ty;
2786 uint64_t XOffset = 0;
2787 if (VD->hasAttr<BlocksAttr>())
2788 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002789 else
Guy Benyei11169dd2012-12-18 14:30:41 +00002790 Ty = getOrCreateType(VD->getType(), Unit);
2791
2792 // If there is no debug info for this type then do not emit debug info
2793 // for this variable.
2794 if (!Ty)
2795 return;
2796
Guy Benyei11169dd2012-12-18 14:30:41 +00002797 // Get location information.
David Blaikie7fceebf2013-08-19 03:37:48 +00002798 unsigned Line = 0;
2799 unsigned Column = 0;
2800 if (!Unwritten) {
2801 Line = getLineNumber(VD->getLocation());
2802 Column = getColumnNumber(VD->getLocation());
2803 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002804 unsigned Flags = 0;
2805 if (VD->isImplicit())
2806 Flags |= llvm::DIDescriptor::FlagArtificial;
2807 // If this is the first argument and it is implicit then
2808 // give it an object pointer flag.
2809 // FIXME: There has to be a better way to do this, but for static
2810 // functions there won't be an implicit param at arg1 and
2811 // otherwise it is 'self' or 'this'.
2812 if (isa<ImplicitParamDecl>(VD) && ArgNo == 1)
2813 Flags |= llvm::DIDescriptor::FlagObjectPointer;
David Blaikieb9c667d2013-06-19 21:53:53 +00002814 if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage))
Eric Christopherffdeb1e2013-07-17 22:52:53 +00002815 if (Arg->getType()->isPointerTy() && !Arg->hasByValAttr() &&
2816 !VD->getType()->isPointerType())
David Blaikieb9c667d2013-06-19 21:53:53 +00002817 Flags |= llvm::DIDescriptor::FlagIndirectVariable;
Guy Benyei11169dd2012-12-18 14:30:41 +00002818
2819 llvm::MDNode *Scope = LexicalBlockStack.back();
2820
2821 StringRef Name = VD->getName();
2822 if (!Name.empty()) {
2823 if (VD->hasAttr<BlocksAttr>()) {
2824 CharUnits offset = CharUnits::fromQuantity(32);
2825 SmallVector<llvm::Value *, 9> addr;
2826 llvm::Type *Int64Ty = CGM.Int64Ty;
2827 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2828 // offset of __forwarding field
2829 offset = CGM.getContext().toCharUnitsFromBits(
John McCallc8e01702013-04-16 22:48:15 +00002830 CGM.getTarget().getPointerWidth(0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002831 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2832 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2833 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2834 // offset of x field
2835 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2836 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2837
2838 // Create the descriptor for the variable.
2839 llvm::DIVariable D =
Eric Christopherb2a008c2013-05-16 00:45:12 +00002840 DBuilder.createComplexVariable(Tag,
Guy Benyei11169dd2012-12-18 14:30:41 +00002841 llvm::DIDescriptor(Scope),
2842 VD->getName(), Unit, Line, Ty,
2843 addr, ArgNo);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002844
Guy Benyei11169dd2012-12-18 14:30:41 +00002845 // Insert an llvm.dbg.declare into the current block.
2846 llvm::Instruction *Call =
2847 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2848 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2849 return;
Adrian Prantl7f2ef222013-09-18 22:18:17 +00002850 } else if (isa<VariableArrayType>(VD->getType()))
Adrian Prantl0315f382013-09-18 22:08:57 +00002851 Flags |= llvm::DIDescriptor::FlagIndirectVariable;
David Blaikiea76a7c92013-01-05 05:58:35 +00002852 } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2853 // If VD is an anonymous union then Storage represents value for
2854 // all union fields.
Guy Benyei11169dd2012-12-18 14:30:41 +00002855 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
David Blaikie219c7d92013-01-05 20:03:07 +00002856 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00002857 for (const auto *Field : RD->fields()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002858 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2859 StringRef FieldName = Field->getName();
Eric Christopherb2a008c2013-05-16 00:45:12 +00002860
Guy Benyei11169dd2012-12-18 14:30:41 +00002861 // Ignore unnamed fields. Do not ignore unnamed records.
2862 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2863 continue;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002864
Guy Benyei11169dd2012-12-18 14:30:41 +00002865 // Use VarDecl's Tag, Scope and Line number.
2866 llvm::DIVariable D =
2867 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
Eric Christopherb2a008c2013-05-16 00:45:12 +00002868 FieldName, Unit, Line, FieldTy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002869 CGM.getLangOpts().Optimize, Flags,
2870 ArgNo);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002871
Guy Benyei11169dd2012-12-18 14:30:41 +00002872 // Insert an llvm.dbg.declare into the current block.
2873 llvm::Instruction *Call =
2874 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2875 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2876 }
David Blaikie219c7d92013-01-05 20:03:07 +00002877 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00002878 }
2879 }
David Blaikiea76a7c92013-01-05 05:58:35 +00002880
2881 // Create the descriptor for the variable.
2882 llvm::DIVariable D =
2883 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2884 Name, Unit, Line, Ty,
2885 CGM.getLangOpts().Optimize, Flags, ArgNo);
2886
2887 // Insert an llvm.dbg.declare into the current block.
2888 llvm::Instruction *Call =
2889 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2890 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
Guy Benyei11169dd2012-12-18 14:30:41 +00002891}
2892
2893void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2894 llvm::Value *Storage,
2895 CGBuilderTy &Builder) {
Eric Christopher75e17682013-05-16 00:45:23 +00002896 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002897 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2898}
2899
Adrian Prantlde17db32013-03-29 19:20:29 +00002900/// Look up the completed type for a self pointer in the TypeCache and
2901/// create a copy of it with the ObjectPointer and Artificial flags
2902/// set. If the type is not cached, a new one is created. This should
2903/// never happen though, since creating a type for the implicit self
2904/// argument implies that we already parsed the interface definition
2905/// and the ivar declarations in the implementation.
Eric Christopher0fdcb312013-05-16 00:52:20 +00002906llvm::DIType CGDebugInfo::CreateSelfType(const QualType &QualTy,
2907 llvm::DIType Ty) {
Adrian Prantlde17db32013-03-29 19:20:29 +00002908 llvm::DIType CachedTy = getTypeOrNull(QualTy);
Eric Christopherf8bc4d82013-07-18 00:52:50 +00002909 if (CachedTy) Ty = CachedTy;
Adrian Prantlde17db32013-03-29 19:20:29 +00002910 else DEBUG(llvm::dbgs() << "No cached type for self.");
2911 return DBuilder.createObjectPointerType(Ty);
2912}
2913
Guy Benyei11169dd2012-12-18 14:30:41 +00002914void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(const VarDecl *VD,
2915 llvm::Value *Storage,
2916 CGBuilderTy &Builder,
2917 const CGBlockInfo &blockInfo) {
Eric Christopher75e17682013-05-16 00:45:23 +00002918 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002919 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
Eric Christopherb2a008c2013-05-16 00:45:12 +00002920
Guy Benyei11169dd2012-12-18 14:30:41 +00002921 if (Builder.GetInsertBlock() == 0)
2922 return;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002923
Guy Benyei11169dd2012-12-18 14:30:41 +00002924 bool isByRef = VD->hasAttr<BlocksAttr>();
Eric Christopherb2a008c2013-05-16 00:45:12 +00002925
Guy Benyei11169dd2012-12-18 14:30:41 +00002926 uint64_t XOffset = 0;
2927 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2928 llvm::DIType Ty;
2929 if (isByRef)
2930 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002931 else
Guy Benyei11169dd2012-12-18 14:30:41 +00002932 Ty = getOrCreateType(VD->getType(), Unit);
2933
2934 // Self is passed along as an implicit non-arg variable in a
2935 // block. Mark it as the object pointer.
2936 if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self")
Adrian Prantlde17db32013-03-29 19:20:29 +00002937 Ty = CreateSelfType(VD->getType(), Ty);
Guy Benyei11169dd2012-12-18 14:30:41 +00002938
2939 // Get location information.
2940 unsigned Line = getLineNumber(VD->getLocation());
2941 unsigned Column = getColumnNumber(VD->getLocation());
2942
2943 const llvm::DataLayout &target = CGM.getDataLayout();
2944
2945 CharUnits offset = CharUnits::fromQuantity(
2946 target.getStructLayout(blockInfo.StructureType)
2947 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2948
2949 SmallVector<llvm::Value *, 9> addr;
2950 llvm::Type *Int64Ty = CGM.Int64Ty;
Adrian Prantl0f6df002013-03-29 19:20:35 +00002951 if (isa<llvm::AllocaInst>(Storage))
2952 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
Guy Benyei11169dd2012-12-18 14:30:41 +00002953 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2954 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2955 if (isByRef) {
2956 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2957 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2958 // offset of __forwarding field
2959 offset = CGM.getContext()
2960 .toCharUnitsFromBits(target.getPointerSizeInBits(0));
2961 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2962 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2963 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2964 // offset of x field
2965 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2966 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2967 }
2968
2969 // Create the descriptor for the variable.
2970 llvm::DIVariable D =
Eric Christopherb2a008c2013-05-16 00:45:12 +00002971 DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable,
Guy Benyei11169dd2012-12-18 14:30:41 +00002972 llvm::DIDescriptor(LexicalBlockStack.back()),
2973 VD->getName(), Unit, Line, Ty, addr);
Adrian Prantl0f6df002013-03-29 19:20:35 +00002974
Guy Benyei11169dd2012-12-18 14:30:41 +00002975 // Insert an llvm.dbg.declare into the current block.
2976 llvm::Instruction *Call =
2977 DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
2978 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column,
2979 LexicalBlockStack.back()));
2980}
2981
2982/// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2983/// variable declaration.
2984void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2985 unsigned ArgNo,
2986 CGBuilderTy &Builder) {
Eric Christopher75e17682013-05-16 00:45:23 +00002987 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002988 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2989}
2990
2991namespace {
2992 struct BlockLayoutChunk {
2993 uint64_t OffsetInBits;
2994 const BlockDecl::Capture *Capture;
2995 };
2996 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2997 return l.OffsetInBits < r.OffsetInBits;
2998 }
2999}
3000
3001void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
Adrian Prantl51936dd2013-03-14 17:53:33 +00003002 llvm::Value *Arg,
3003 llvm::Value *LocalAddr,
Guy Benyei11169dd2012-12-18 14:30:41 +00003004 CGBuilderTy &Builder) {
Eric Christopher75e17682013-05-16 00:45:23 +00003005 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00003006 ASTContext &C = CGM.getContext();
3007 const BlockDecl *blockDecl = block.getBlockDecl();
3008
3009 // Collect some general information about the block's location.
3010 SourceLocation loc = blockDecl->getCaretLocation();
3011 llvm::DIFile tunit = getOrCreateFile(loc);
3012 unsigned line = getLineNumber(loc);
3013 unsigned column = getColumnNumber(loc);
Eric Christopherb2a008c2013-05-16 00:45:12 +00003014
Guy Benyei11169dd2012-12-18 14:30:41 +00003015 // Build the debug-info type for the block literal.
3016 getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
3017
3018 const llvm::StructLayout *blockLayout =
3019 CGM.getDataLayout().getStructLayout(block.StructureType);
3020
3021 SmallVector<llvm::Value*, 16> fields;
3022 fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
3023 blockLayout->getElementOffsetInBits(0),
3024 tunit, tunit));
3025 fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
3026 blockLayout->getElementOffsetInBits(1),
3027 tunit, tunit));
3028 fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
3029 blockLayout->getElementOffsetInBits(2),
3030 tunit, tunit));
3031 fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
3032 blockLayout->getElementOffsetInBits(3),
3033 tunit, tunit));
3034 fields.push_back(createFieldType("__descriptor",
3035 C.getPointerType(block.NeedsCopyDispose ?
3036 C.getBlockDescriptorExtendedType() :
3037 C.getBlockDescriptorType()),
3038 0, loc, AS_public,
3039 blockLayout->getElementOffsetInBits(4),
3040 tunit, tunit));
3041
3042 // We want to sort the captures by offset, not because DWARF
3043 // requires this, but because we're paranoid about debuggers.
3044 SmallVector<BlockLayoutChunk, 8> chunks;
3045
3046 // 'this' capture.
3047 if (blockDecl->capturesCXXThis()) {
3048 BlockLayoutChunk chunk;
3049 chunk.OffsetInBits =
3050 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
3051 chunk.Capture = 0;
3052 chunks.push_back(chunk);
3053 }
3054
3055 // Variable captures.
Aaron Ballman9371dd22014-03-14 18:34:04 +00003056 for (const auto &capture : blockDecl->captures()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003057 const VarDecl *variable = capture.getVariable();
3058 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
3059
3060 // Ignore constant captures.
3061 if (captureInfo.isConstant())
3062 continue;
3063
3064 BlockLayoutChunk chunk;
3065 chunk.OffsetInBits =
3066 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
3067 chunk.Capture = &capture;
3068 chunks.push_back(chunk);
3069 }
3070
3071 // Sort by offset.
3072 llvm::array_pod_sort(chunks.begin(), chunks.end());
3073
3074 for (SmallVectorImpl<BlockLayoutChunk>::iterator
3075 i = chunks.begin(), e = chunks.end(); i != e; ++i) {
3076 uint64_t offsetInBits = i->OffsetInBits;
3077 const BlockDecl::Capture *capture = i->Capture;
3078
3079 // If we have a null capture, this must be the C++ 'this' capture.
3080 if (!capture) {
3081 const CXXMethodDecl *method =
3082 cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
3083 QualType type = method->getThisType(C);
3084
3085 fields.push_back(createFieldType("this", type, 0, loc, AS_public,
3086 offsetInBits, tunit, tunit));
3087 continue;
3088 }
3089
3090 const VarDecl *variable = capture->getVariable();
3091 StringRef name = variable->getName();
3092
3093 llvm::DIType fieldType;
3094 if (capture->isByRef()) {
3095 std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
3096
3097 // FIXME: this creates a second copy of this type!
3098 uint64_t xoffset;
3099 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
3100 fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
3101 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
3102 ptrInfo.first, ptrInfo.second,
3103 offsetInBits, 0, fieldType);
3104 } else {
3105 fieldType = createFieldType(name, variable->getType(), 0,
3106 loc, AS_public, offsetInBits, tunit, tunit);
3107 }
3108 fields.push_back(fieldType);
3109 }
3110
3111 SmallString<36> typeName;
3112 llvm::raw_svector_ostream(typeName)
3113 << "__block_literal_" << CGM.getUniqueBlockCount();
3114
3115 llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
3116
3117 llvm::DIType type =
3118 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
3119 CGM.getContext().toBits(block.BlockSize),
3120 CGM.getContext().toBits(block.BlockAlign),
David Blaikie6d4fe152013-02-25 01:07:08 +00003121 0, llvm::DIType(), fieldsArray);
Guy Benyei11169dd2012-12-18 14:30:41 +00003122 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
3123
3124 // Get overall information about the block.
3125 unsigned flags = llvm::DIDescriptor::FlagArtificial;
3126 llvm::MDNode *scope = LexicalBlockStack.back();
Guy Benyei11169dd2012-12-18 14:30:41 +00003127
3128 // Create the descriptor for the parameter.
3129 llvm::DIVariable debugVar =
3130 DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
Eric Christopherb2a008c2013-05-16 00:45:12 +00003131 llvm::DIDescriptor(scope),
Adrian Prantl51936dd2013-03-14 17:53:33 +00003132 Arg->getName(), tunit, line, type,
Guy Benyei11169dd2012-12-18 14:30:41 +00003133 CGM.getLangOpts().Optimize, flags,
Adrian Prantl51936dd2013-03-14 17:53:33 +00003134 cast<llvm::Argument>(Arg)->getArgNo() + 1);
3135
Adrian Prantl616bef42013-03-14 21:52:59 +00003136 if (LocalAddr) {
Adrian Prantl51936dd2013-03-14 17:53:33 +00003137 // Insert an llvm.dbg.value into the current block.
Adrian Prantl616bef42013-03-14 21:52:59 +00003138 llvm::Instruction *DbgVal =
3139 DBuilder.insertDbgValueIntrinsic(LocalAddr, 0, debugVar,
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00003140 Builder.GetInsertBlock());
Adrian Prantl616bef42013-03-14 21:52:59 +00003141 DbgVal->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
3142 }
Adrian Prantl51936dd2013-03-14 17:53:33 +00003143
Adrian Prantl616bef42013-03-14 21:52:59 +00003144 // Insert an llvm.dbg.declare into the current block.
3145 llvm::Instruction *DbgDecl =
3146 DBuilder.insertDeclare(Arg, debugVar, Builder.GetInsertBlock());
3147 DbgDecl->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
Guy Benyei11169dd2012-12-18 14:30:41 +00003148}
3149
David Blaikie6943dea2013-08-20 01:28:15 +00003150/// If D is an out-of-class definition of a static data member of a class, find
3151/// its corresponding in-class declaration.
3152llvm::DIDerivedType
3153CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {
3154 if (!D->isStaticDataMember())
3155 return llvm::DIDerivedType();
3156 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator MI =
3157 StaticDataMemberCache.find(D->getCanonicalDecl());
3158 if (MI != StaticDataMemberCache.end()) {
3159 assert(MI->second && "Static data member declaration should still exist");
3160 return llvm::DIDerivedType(cast<llvm::MDNode>(MI->second));
Evgeniy Stepanov37b3f732013-08-16 10:35:31 +00003161 }
David Blaikiece763042013-08-20 21:49:21 +00003162
3163 // If the member wasn't found in the cache, lazily construct and add it to the
3164 // type (used when a limited form of the type is emitted).
David Blaikie6943dea2013-08-20 01:28:15 +00003165 llvm::DICompositeType Ctxt(
3166 getContextDescriptor(cast<Decl>(D->getDeclContext())));
3167 llvm::DIDerivedType T = CreateRecordStaticField(D, Ctxt);
David Blaikie6943dea2013-08-20 01:28:15 +00003168 return T;
3169}
3170
Eric Christophercab9fae2014-04-10 05:20:00 +00003171/// Recursively collect all of the member fields of a global anonymous decl and
3172/// create static variables for them. The first time this is called it needs
3173/// to be on a union and then from there we can have additional unnamed fields.
3174llvm::DIGlobalVariable
3175CGDebugInfo::CollectAnonRecordDecls(const RecordDecl *RD, llvm::DIFile Unit,
3176 unsigned LineNo, StringRef LinkageName,
3177 llvm::GlobalVariable *Var,
3178 llvm::DIDescriptor DContext) {
3179 llvm::DIGlobalVariable GV;
3180
3181 for (const auto *Field : RD->fields()) {
3182 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
3183 StringRef FieldName = Field->getName();
3184
3185 // Ignore unnamed fields, but recurse into anonymous records.
3186 if (FieldName.empty()) {
3187 const RecordType *RT = dyn_cast<RecordType>(Field->getType());
3188 if (RT)
3189 GV = CollectAnonRecordDecls(RT->getDecl(), Unit, LineNo, LinkageName,
3190 Var, DContext);
3191 continue;
3192 }
3193 // Use VarDecl's Tag, Scope and Line number.
3194 GV = DBuilder.createStaticVariable(DContext, FieldName, LinkageName, Unit,
3195 LineNo, FieldTy,
3196 Var->hasInternalLinkage(), Var,
3197 llvm::DIDerivedType());
3198 }
3199 return GV;
3200}
3201
Guy Benyei11169dd2012-12-18 14:30:41 +00003202/// EmitGlobalVariable - Emit information about a global variable.
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003203void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
Guy Benyei11169dd2012-12-18 14:30:41 +00003204 const VarDecl *D) {
Eric Christopher75e17682013-05-16 00:45:23 +00003205 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00003206 // Create global variable debug descriptor.
3207 llvm::DIFile Unit = getOrCreateFile(D->getLocation());
3208 unsigned LineNo = getLineNumber(D->getLocation());
3209
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003210 setLocation(D->getLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00003211
3212 QualType T = D->getType();
3213 if (T->isIncompleteArrayType()) {
3214
3215 // CodeGen turns int[] into int[1] so we'll do the same here.
3216 llvm::APInt ConstVal(32, 1);
3217 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3218
3219 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3220 ArrayType::Normal, 0);
3221 }
Eric Christophercab9fae2014-04-10 05:20:00 +00003222
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003223 StringRef DeclName = D->getName();
3224 StringRef LinkageName;
Eric Christophercab9fae2014-04-10 05:20:00 +00003225 if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext()) &&
3226 !isa<ObjCMethodDecl>(D->getDeclContext()))
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003227 LinkageName = Var->getName();
3228 if (LinkageName == DeclName)
3229 LinkageName = StringRef();
Eric Christophercab9fae2014-04-10 05:20:00 +00003230
Eric Christopherb2a008c2013-05-16 00:45:12 +00003231 llvm::DIDescriptor DContext =
Guy Benyei11169dd2012-12-18 14:30:41 +00003232 getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
Eric Christophercab9fae2014-04-10 05:20:00 +00003233
3234 // Attempt to store one global variable for the declaration - even if we
3235 // emit a lot of fields.
3236 llvm::DIGlobalVariable GV;
3237
3238 // If this is an anonymous union then we'll want to emit a global
3239 // variable for each member of the anonymous union so that it's possible
3240 // to find the name of any field in the union.
3241 if (T->isUnionType() && DeclName.empty()) {
3242 const RecordDecl *RD = cast<RecordType>(T)->getDecl();
3243 assert(RD->isAnonymousStructOrUnion() && "unnamed non-anonymous struct or union?");
3244 GV = CollectAnonRecordDecls(RD, Unit, LineNo, LinkageName, Var, DContext);
3245 } else {
3246 GV = DBuilder.createStaticVariable(
3247 DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
3248 Var->hasInternalLinkage(), Var,
3249 getOrCreateStaticDataMemberDeclarationOrNull(D));
3250 }
David Blaikiebd483762013-05-20 04:58:53 +00003251 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(GV)));
Guy Benyei11169dd2012-12-18 14:30:41 +00003252}
3253
3254/// EmitGlobalVariable - Emit information about an objective-c interface.
3255void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
3256 ObjCInterfaceDecl *ID) {
Eric Christopher75e17682013-05-16 00:45:23 +00003257 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00003258 // Create global variable debug descriptor.
3259 llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
3260 unsigned LineNo = getLineNumber(ID->getLocation());
3261
3262 StringRef Name = ID->getName();
3263
3264 QualType T = CGM.getContext().getObjCInterfaceType(ID);
3265 if (T->isIncompleteArrayType()) {
3266
3267 // CodeGen turns int[] into int[1] so we'll do the same here.
3268 llvm::APInt ConstVal(32, 1);
3269 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3270
3271 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3272 ArrayType::Normal, 0);
3273 }
3274
3275 DBuilder.createGlobalVariable(Name, Unit, LineNo,
3276 getOrCreateType(T, Unit),
3277 Var->hasInternalLinkage(), Var);
3278}
3279
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003280/// EmitGlobalVariable - Emit global variable's debug info.
3281void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
3282 llvm::Constant *Init) {
Eric Christopher75e17682013-05-16 00:45:23 +00003283 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003284 // Create the descriptor for the variable.
3285 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
3286 StringRef Name = VD->getName();
3287 llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
3288 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
3289 const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext());
3290 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
3291 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
3292 }
3293 // Do not use DIGlobalVariable for enums.
3294 if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
3295 return;
David Blaikiea15565562014-04-04 20:56:17 +00003296 // Do not emit separate definitions for function local const/statics.
3297 if (isa<FunctionDecl>(VD->getDeclContext()))
3298 return;
David Blaikiebb113912014-04-05 07:23:17 +00003299 VD = cast<ValueDecl>(VD->getCanonicalDecl());
3300 auto pair = DeclCache.insert(std::make_pair(VD, llvm::WeakVH()));
3301 if (!pair.second)
3302 return;
David Blaikie506a7452014-04-05 07:46:57 +00003303 llvm::DIDescriptor DContext =
3304 getContextDescriptor(dyn_cast<Decl>(VD->getDeclContext()));
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003305 llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(
David Blaikie506a7452014-04-05 07:46:57 +00003306 DContext, Name, StringRef(), Unit, getLineNumber(VD->getLocation()), Ty,
3307 true, Init,
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003308 getOrCreateStaticDataMemberDeclarationOrNull(cast<VarDecl>(VD)));
David Blaikiebb113912014-04-05 07:23:17 +00003309 pair.first->second = llvm::WeakVH(GV);
David Blaikiebd483762013-05-20 04:58:53 +00003310}
3311
3312llvm::DIScope CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
3313 if (!LexicalBlockStack.empty())
3314 return llvm::DIScope(LexicalBlockStack.back());
3315 return getContextDescriptor(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00003316}
3317
David Blaikie9f88fe82013-04-22 06:13:21 +00003318void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
David Blaikiebd483762013-05-20 04:58:53 +00003319 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3320 return;
David Blaikie9f88fe82013-04-22 06:13:21 +00003321 DBuilder.createImportedModule(
David Blaikiebd483762013-05-20 04:58:53 +00003322 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
3323 getOrCreateNameSpace(UD.getNominatedNamespace()),
David Blaikie9f88fe82013-04-22 06:13:21 +00003324 getLineNumber(UD.getLocation()));
3325}
3326
David Blaikiebd483762013-05-20 04:58:53 +00003327void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
3328 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3329 return;
3330 assert(UD.shadow_size() &&
3331 "We shouldn't be codegening an invalid UsingDecl containing no decls");
3332 // Emitting one decl is sufficient - debuggers can detect that this is an
3333 // overloaded name & provide lookup for all the overloads.
3334 const UsingShadowDecl &USD = **UD.shadow_begin();
Adrian Prantl6cdce9e2014-04-01 03:41:01 +00003335 if (llvm::DIScope Target =
Eric Christopher1ecc5632013-06-07 22:54:39 +00003336 getDeclarationOrDefinition(USD.getUnderlyingDecl()))
David Blaikiebd483762013-05-20 04:58:53 +00003337 DBuilder.createImportedDeclaration(
3338 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
3339 getLineNumber(USD.getLocation()));
3340}
3341
David Blaikief121b932013-05-20 22:50:41 +00003342llvm::DIImportedEntity
3343CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
3344 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3345 return llvm::DIImportedEntity(0);
3346 llvm::WeakVH &VH = NamespaceAliasCache[&NA];
3347 if (VH)
3348 return llvm::DIImportedEntity(cast<llvm::MDNode>(VH));
3349 llvm::DIImportedEntity R(0);
3350 if (const NamespaceAliasDecl *Underlying =
3351 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
3352 // This could cache & dedup here rather than relying on metadata deduping.
David Blaikie551fb0a2014-04-06 06:30:03 +00003353 R = DBuilder.createImportedDeclaration(
David Blaikief121b932013-05-20 22:50:41 +00003354 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3355 EmitNamespaceAlias(*Underlying), getLineNumber(NA.getLocation()),
3356 NA.getName());
3357 else
David Blaikie551fb0a2014-04-06 06:30:03 +00003358 R = DBuilder.createImportedDeclaration(
David Blaikief121b932013-05-20 22:50:41 +00003359 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3360 getOrCreateNameSpace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
3361 getLineNumber(NA.getLocation()), NA.getName());
3362 VH = R;
3363 return R;
3364}
3365
Guy Benyei11169dd2012-12-18 14:30:41 +00003366/// getOrCreateNamesSpace - Return namespace descriptor for the given
3367/// namespace decl.
Eric Christopherb2a008c2013-05-16 00:45:12 +00003368llvm::DINameSpace
Guy Benyei11169dd2012-12-18 14:30:41 +00003369CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
David Blaikie9fdedec2013-08-16 22:52:07 +00003370 NSDecl = NSDecl->getCanonicalDecl();
Eric Christopherb2a008c2013-05-16 00:45:12 +00003371 llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
Guy Benyei11169dd2012-12-18 14:30:41 +00003372 NameSpaceCache.find(NSDecl);
3373 if (I != NameSpaceCache.end())
3374 return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
Eric Christopherb2a008c2013-05-16 00:45:12 +00003375
Guy Benyei11169dd2012-12-18 14:30:41 +00003376 unsigned LineNo = getLineNumber(NSDecl->getLocation());
3377 llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
Eric Christopherb2a008c2013-05-16 00:45:12 +00003378 llvm::DIDescriptor Context =
Guy Benyei11169dd2012-12-18 14:30:41 +00003379 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
3380 llvm::DINameSpace NS =
3381 DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
3382 NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
3383 return NS;
3384}
3385
3386void CGDebugInfo::finalize() {
3387 for (std::vector<std::pair<void *, llvm::WeakVH> >::const_iterator VI
3388 = ReplaceMap.begin(), VE = ReplaceMap.end(); VI != VE; ++VI) {
3389 llvm::DIType Ty, RepTy;
3390 // Verify that the debug info still exists.
3391 if (llvm::Value *V = VI->second)
3392 Ty = llvm::DIType(cast<llvm::MDNode>(V));
Eric Christopherb2a008c2013-05-16 00:45:12 +00003393
Guy Benyei11169dd2012-12-18 14:30:41 +00003394 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
3395 TypeCache.find(VI->first);
3396 if (it != TypeCache.end()) {
3397 // Verify that the debug info still exists.
3398 if (llvm::Value *V = it->second)
3399 RepTy = llvm::DIType(cast<llvm::MDNode>(V));
3400 }
Adrian Prantl73409ce2013-03-11 18:33:46 +00003401
Eric Christopherf8bc4d82013-07-18 00:52:50 +00003402 if (Ty && Ty.isForwardDecl() && RepTy)
Guy Benyei11169dd2012-12-18 14:30:41 +00003403 Ty.replaceAllUsesWith(RepTy);
Guy Benyei11169dd2012-12-18 14:30:41 +00003404 }
Adrian Prantl73409ce2013-03-11 18:33:46 +00003405
3406 // We keep our own list of retained types, because we need to look
3407 // up the final type in the type cache.
3408 for (std::vector<void *>::const_iterator RI = RetainedTypes.begin(),
3409 RE = RetainedTypes.end(); RI != RE; ++RI)
David Blaikie0856f662014-03-04 22:01:08 +00003410 DBuilder.retainType(llvm::DIType(cast<llvm::MDNode>(TypeCache[*RI])));
Adrian Prantl73409ce2013-03-11 18:33:46 +00003411
Guy Benyei11169dd2012-12-18 14:30:41 +00003412 DBuilder.finalize();
3413}