blob: f41fac80a273eafc60dd86477bdf1332f3184c87 [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);
David Blaikief1b382e2014-04-06 17:14:06 +0000725
726 SmallString<128> NS;
727 llvm::raw_svector_ostream OS(NS);
728 Ty->getTemplateName().print(OS, CGM.getContext().getPrintingPolicy(), /*qualified*/ false);
729
730 TemplateSpecializationType::PrintTemplateArgumentList(
731 OS, Ty->getArgs(), Ty->getNumArgs(),
732 CGM.getContext().getPrintingPolicy());
733
734 TypeAliasDecl *AliasDecl =
735 cast<TypeAliasTemplateDecl>(Ty->getTemplateName().getAsTemplateDecl())
736 ->getTemplatedDecl();
737
738 SourceLocation Loc = AliasDecl->getLocation();
739 llvm::DIFile File = getOrCreateFile(Loc);
740 unsigned Line = getLineNumber(Loc);
741
742 llvm::DIDescriptor Ctxt = getContextDescriptor(cast<Decl>(AliasDecl->getDeclContext()));
743
744 return DBuilder.createTypedef(Src, internString(OS.str()), File, Line, Ctxt);
745}
746
David Blaikie99dab3b2013-09-04 22:03:57 +0000747llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty, llvm::DIFile Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000748 // Typedefs are derived from some other type. If we have a typedef of a
749 // typedef, make sure to emit the whole chain.
David Blaikie99dab3b2013-09-04 22:03:57 +0000750 llvm::DIType Src = getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +0000751 // We don't set size information, but do specify where the typedef was
752 // declared.
Adrian Prantl3eff2252014-01-21 18:42:27 +0000753 SourceLocation Loc = Ty->getDecl()->getLocation();
754 llvm::DIFile File = getOrCreateFile(Loc);
755 unsigned Line = getLineNumber(Loc);
Guy Benyei11169dd2012-12-18 14:30:41 +0000756 const TypedefNameDecl *TyDecl = Ty->getDecl();
Eric Christopherb2a008c2013-05-16 00:45:12 +0000757
Guy Benyei11169dd2012-12-18 14:30:41 +0000758 llvm::DIDescriptor TypedefContext =
759 getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext()));
Eric Christopherb2a008c2013-05-16 00:45:12 +0000760
Guy Benyei11169dd2012-12-18 14:30:41 +0000761 return
Adrian Prantl3eff2252014-01-21 18:42:27 +0000762 DBuilder.createTypedef(Src, TyDecl->getName(), File, Line, TypedefContext);
Guy Benyei11169dd2012-12-18 14:30:41 +0000763}
764
765llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
766 llvm::DIFile Unit) {
767 SmallVector<llvm::Value *, 16> EltTys;
768
769 // Add the result type at least.
Alp Toker314cc812014-01-25 16:55:45 +0000770 EltTys.push_back(getOrCreateType(Ty->getReturnType(), Unit));
Guy Benyei11169dd2012-12-18 14:30:41 +0000771
772 // Set up remainder of arguments if there is a prototype.
Adrian Prantl800faef2014-02-25 23:42:18 +0000773 // otherwise emit it as a variadic function.
Guy Benyei11169dd2012-12-18 14:30:41 +0000774 if (isa<FunctionNoProtoType>(Ty))
775 EltTys.push_back(DBuilder.createUnspecifiedParameter());
776 else if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Ty)) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000777 for (unsigned i = 0, e = FPT->getNumParams(); i != e; ++i)
778 EltTys.push_back(getOrCreateType(FPT->getParamType(i), Unit));
Adrian Prantld45ba252014-02-25 19:38:11 +0000779 if (FPT->isVariadic())
780 EltTys.push_back(DBuilder.createUnspecifiedParameter());
Guy Benyei11169dd2012-12-18 14:30:41 +0000781 }
782
783 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
784 return DBuilder.createSubroutineType(Unit, EltTypeArray);
785}
786
787
Guy Benyei11169dd2012-12-18 14:30:41 +0000788llvm::DIType CGDebugInfo::createFieldType(StringRef name,
789 QualType type,
790 uint64_t sizeInBitsOverride,
791 SourceLocation loc,
792 AccessSpecifier AS,
793 uint64_t offsetInBits,
794 llvm::DIFile tunit,
Manman Ren2c826dc2013-09-08 03:45:05 +0000795 llvm::DIScope scope) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000796 llvm::DIType debugType = getOrCreateType(type, tunit);
797
798 // Get the location for the field.
799 llvm::DIFile file = getOrCreateFile(loc);
800 unsigned line = getLineNumber(loc);
801
802 uint64_t sizeInBits = 0;
803 unsigned alignInBits = 0;
804 if (!type->isIncompleteArrayType()) {
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000805 std::tie(sizeInBits, alignInBits) = CGM.getContext().getTypeInfo(type);
Guy Benyei11169dd2012-12-18 14:30:41 +0000806
807 if (sizeInBitsOverride)
808 sizeInBits = sizeInBitsOverride;
809 }
810
811 unsigned flags = 0;
812 if (AS == clang::AS_private)
813 flags |= llvm::DIDescriptor::FlagPrivate;
814 else if (AS == clang::AS_protected)
815 flags |= llvm::DIDescriptor::FlagProtected;
816
817 return DBuilder.createMemberType(scope, name, file, line, sizeInBits,
818 alignInBits, offsetInBits, flags, debugType);
819}
820
Eric Christopher91a31902013-01-16 01:22:32 +0000821/// CollectRecordLambdaFields - Helper for CollectRecordFields.
822void CGDebugInfo::
823CollectRecordLambdaFields(const CXXRecordDecl *CXXDecl,
824 SmallVectorImpl<llvm::Value *> &elements,
825 llvm::DIType RecordTy) {
826 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
827 // has the name and the location of the variable so we should iterate over
828 // both concurrently.
829 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
830 RecordDecl::field_iterator Field = CXXDecl->field_begin();
831 unsigned fieldno = 0;
832 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
833 E = CXXDecl->captures_end(); I != E; ++I, ++Field, ++fieldno) {
834 const LambdaExpr::Capture C = *I;
835 if (C.capturesVariable()) {
836 VarDecl *V = C.getCapturedVar();
837 llvm::DIFile VUnit = getOrCreateFile(C.getLocation());
838 StringRef VName = V->getName();
839 uint64_t SizeInBitsOverride = 0;
840 if (Field->isBitField()) {
841 SizeInBitsOverride = Field->getBitWidthValue(CGM.getContext());
842 assert(SizeInBitsOverride && "found named 0-width bitfield");
843 }
844 llvm::DIType fieldType
845 = createFieldType(VName, Field->getType(), SizeInBitsOverride,
846 C.getLocation(), Field->getAccess(),
847 layout.getFieldOffset(fieldno), VUnit, RecordTy);
848 elements.push_back(fieldType);
849 } else {
850 // TODO: Need to handle 'this' in some way by probably renaming the
851 // this of the lambda class and having a field member of 'this' or
852 // by using AT_object_pointer for the function and having that be
853 // used as 'this' for semantic references.
854 assert(C.capturesThis() && "Field that isn't captured and isn't this?");
855 FieldDecl *f = *Field;
856 llvm::DIFile VUnit = getOrCreateFile(f->getLocation());
857 QualType type = f->getType();
858 llvm::DIType fieldType
859 = createFieldType("this", type, 0, f->getLocation(), f->getAccess(),
860 layout.getFieldOffset(fieldno), VUnit, RecordTy);
861
862 elements.push_back(fieldType);
863 }
864 }
865}
866
David Blaikie6943dea2013-08-20 01:28:15 +0000867/// Helper for CollectRecordFields.
David Blaikieae019462013-08-15 22:50:29 +0000868llvm::DIDerivedType
869CGDebugInfo::CreateRecordStaticField(const VarDecl *Var,
870 llvm::DIType RecordTy) {
Eric Christopher91a31902013-01-16 01:22:32 +0000871 // Create the descriptor for the static variable, with or without
872 // constant initializers.
873 llvm::DIFile VUnit = getOrCreateFile(Var->getLocation());
874 llvm::DIType VTy = getOrCreateType(Var->getType(), VUnit);
875
Eric Christopher91a31902013-01-16 01:22:32 +0000876 unsigned LineNumber = getLineNumber(Var->getLocation());
877 StringRef VName = Var->getName();
David Blaikied42917f2013-01-20 01:19:17 +0000878 llvm::Constant *C = NULL;
Eric Christopher91a31902013-01-16 01:22:32 +0000879 if (Var->getInit()) {
880 const APValue *Value = Var->evaluateValue();
David Blaikied42917f2013-01-20 01:19:17 +0000881 if (Value) {
882 if (Value->isInt())
883 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
884 if (Value->isFloat())
885 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
886 }
Eric Christopher91a31902013-01-16 01:22:32 +0000887 }
888
889 unsigned Flags = 0;
890 AccessSpecifier Access = Var->getAccess();
891 if (Access == clang::AS_private)
892 Flags |= llvm::DIDescriptor::FlagPrivate;
893 else if (Access == clang::AS_protected)
894 Flags |= llvm::DIDescriptor::FlagProtected;
895
David Blaikieae019462013-08-15 22:50:29 +0000896 llvm::DIDerivedType GV = DBuilder.createStaticMemberType(
897 RecordTy, VName, VUnit, LineNumber, VTy, Flags, C);
Eric Christopher91a31902013-01-16 01:22:32 +0000898 StaticDataMemberCache[Var->getCanonicalDecl()] = llvm::WeakVH(GV);
David Blaikieae019462013-08-15 22:50:29 +0000899 return GV;
Eric Christopher91a31902013-01-16 01:22:32 +0000900}
901
902/// CollectRecordNormalField - Helper for CollectRecordFields.
903void CGDebugInfo::
904CollectRecordNormalField(const FieldDecl *field, uint64_t OffsetInBits,
905 llvm::DIFile tunit,
906 SmallVectorImpl<llvm::Value *> &elements,
907 llvm::DIType RecordTy) {
908 StringRef name = field->getName();
909 QualType type = field->getType();
910
911 // Ignore unnamed fields unless they're anonymous structs/unions.
912 if (name.empty() && !type->isRecordType())
913 return;
914
915 uint64_t SizeInBitsOverride = 0;
916 if (field->isBitField()) {
917 SizeInBitsOverride = field->getBitWidthValue(CGM.getContext());
918 assert(SizeInBitsOverride && "found named 0-width bitfield");
919 }
920
921 llvm::DIType fieldType
922 = createFieldType(name, type, SizeInBitsOverride,
923 field->getLocation(), field->getAccess(),
924 OffsetInBits, tunit, RecordTy);
925
926 elements.push_back(fieldType);
927}
928
Guy Benyei11169dd2012-12-18 14:30:41 +0000929/// CollectRecordFields - A helper function to collect debug info for
930/// record fields. This is used while creating debug info entry for a Record.
David Blaikieab255bb2013-08-16 20:40:25 +0000931void CGDebugInfo::CollectRecordFields(const RecordDecl *record,
932 llvm::DIFile tunit,
933 SmallVectorImpl<llvm::Value *> &elements,
934 llvm::DICompositeType RecordTy) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000935 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(record);
936
Eric Christopher91a31902013-01-16 01:22:32 +0000937 if (CXXDecl && CXXDecl->isLambda())
938 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
939 else {
940 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
Guy Benyei11169dd2012-12-18 14:30:41 +0000941
Eric Christopher91a31902013-01-16 01:22:32 +0000942 // Field number for non-static fields.
Eric Christopher0f7594372013-01-04 17:59:07 +0000943 unsigned fieldNo = 0;
Eric Christopher91a31902013-01-16 01:22:32 +0000944
Eric Christopher91a31902013-01-16 01:22:32 +0000945 // Static and non-static members should appear in the same order as
946 // the corresponding declarations in the source program.
Aaron Ballman629afae2014-03-07 19:56:05 +0000947 for (const auto *I : record->decls())
948 if (const auto *V = dyn_cast<VarDecl>(I)) {
David Blaikiece763042013-08-20 21:49:21 +0000949 // Reuse the existing static member declaration if one exists
950 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator MI =
951 StaticDataMemberCache.find(V->getCanonicalDecl());
952 if (MI != StaticDataMemberCache.end()) {
953 assert(MI->second &&
954 "Static data member declaration should still exist");
955 elements.push_back(
956 llvm::DIDerivedType(cast<llvm::MDNode>(MI->second)));
957 } else
958 elements.push_back(CreateRecordStaticField(V, RecordTy));
Aaron Ballman629afae2014-03-07 19:56:05 +0000959 } else if (const auto *field = dyn_cast<FieldDecl>(I)) {
Eric Christopher91a31902013-01-16 01:22:32 +0000960 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo),
961 tunit, elements, RecordTy);
962
963 // Bump field number for next field.
964 ++fieldNo;
Guy Benyei11169dd2012-12-18 14:30:41 +0000965 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000966 }
967}
968
969/// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
970/// function type is not updated to include implicit "this" pointer. Use this
971/// routine to get a method type which includes "this" pointer.
David Blaikie469f0792013-05-22 23:22:42 +0000972llvm::DICompositeType
Guy Benyei11169dd2012-12-18 14:30:41 +0000973CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
974 llvm::DIFile Unit) {
David Blaikie7eb06852013-01-07 23:06:35 +0000975 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
David Blaikie2aaf0652013-01-07 22:24:59 +0000976 if (Method->isStatic())
David Blaikie469f0792013-05-22 23:22:42 +0000977 return llvm::DICompositeType(getOrCreateType(QualType(Func, 0), Unit));
David Blaikie7eb06852013-01-07 23:06:35 +0000978 return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()),
979 Func, Unit);
980}
David Blaikie2aaf0652013-01-07 22:24:59 +0000981
David Blaikie469f0792013-05-22 23:22:42 +0000982llvm::DICompositeType CGDebugInfo::getOrCreateInstanceMethodType(
David Blaikie7eb06852013-01-07 23:06:35 +0000983 QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000984 // Add "this" pointer.
David Blaikie7eb06852013-01-07 23:06:35 +0000985 llvm::DIArray Args = llvm::DICompositeType(
986 getOrCreateType(QualType(Func, 0), Unit)).getTypeArray();
Guy Benyei11169dd2012-12-18 14:30:41 +0000987 assert (Args.getNumElements() && "Invalid number of arguments!");
988
989 SmallVector<llvm::Value *, 16> Elts;
990
991 // First element is always return type. For 'void' functions it is NULL.
992 Elts.push_back(Args.getElement(0));
993
David Blaikie2aaf0652013-01-07 22:24:59 +0000994 // "this" pointer is always first argument.
David Blaikie7eb06852013-01-07 23:06:35 +0000995 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
David Blaikie2aaf0652013-01-07 22:24:59 +0000996 if (isa<ClassTemplateSpecializationDecl>(RD)) {
997 // Create pointer type directly in this case.
998 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
999 QualType PointeeTy = ThisPtrTy->getPointeeType();
1000 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCallc8e01702013-04-16 22:48:15 +00001001 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
David Blaikie2aaf0652013-01-07 22:24:59 +00001002 uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy);
1003 llvm::DIType PointeeType = getOrCreateType(PointeeTy, Unit);
Eric Christopher0fdcb312013-05-16 00:52:20 +00001004 llvm::DIType ThisPtrType =
1005 DBuilder.createPointerType(PointeeType, Size, Align);
David Blaikie2aaf0652013-01-07 22:24:59 +00001006 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
1007 // TODO: This and the artificial type below are misleading, the
1008 // types aren't artificial the argument is, but the current
1009 // metadata doesn't represent that.
1010 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1011 Elts.push_back(ThisPtrType);
1012 } else {
1013 llvm::DIType ThisPtrType = getOrCreateType(ThisPtr, Unit);
1014 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
1015 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1016 Elts.push_back(ThisPtrType);
Guy Benyei11169dd2012-12-18 14:30:41 +00001017 }
1018
1019 // Copy rest of the arguments.
1020 for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
1021 Elts.push_back(Args.getElement(i));
1022
1023 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
1024
Adrian Prantl0630eb72013-12-18 21:48:18 +00001025 unsigned Flags = 0;
1026 if (Func->getExtProtoInfo().RefQualifier == RQ_LValue)
1027 Flags |= llvm::DIDescriptor::FlagLValueReference;
1028 if (Func->getExtProtoInfo().RefQualifier == RQ_RValue)
1029 Flags |= llvm::DIDescriptor::FlagRValueReference;
1030
1031 return DBuilder.createSubroutineType(Unit, EltTypeArray, Flags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001032}
1033
Eric Christopherb2a008c2013-05-16 00:45:12 +00001034/// isFunctionLocalClass - Return true if CXXRecordDecl is defined
Guy Benyei11169dd2012-12-18 14:30:41 +00001035/// inside a function.
1036static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
1037 if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
1038 return isFunctionLocalClass(NRD);
1039 if (isa<FunctionDecl>(RD->getDeclContext()))
1040 return true;
1041 return false;
1042}
1043
1044/// CreateCXXMemberFunction - A helper function to create a DISubprogram for
1045/// a single member function GlobalDecl.
1046llvm::DISubprogram
1047CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
1048 llvm::DIFile Unit,
1049 llvm::DIType RecordTy) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001050 bool IsCtorOrDtor =
Guy Benyei11169dd2012-12-18 14:30:41 +00001051 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
Eric Christopherb2a008c2013-05-16 00:45:12 +00001052
Guy Benyei11169dd2012-12-18 14:30:41 +00001053 StringRef MethodName = getFunctionName(Method);
David Blaikie469f0792013-05-22 23:22:42 +00001054 llvm::DICompositeType MethodTy = getOrCreateMethodType(Method, Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00001055
1056 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1057 // make sense to give a single ctor/dtor a linkage name.
1058 StringRef MethodLinkageName;
1059 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1060 MethodLinkageName = CGM.getMangledName(Method);
1061
1062 // Get the location for the method.
David Blaikie7fceebf2013-08-19 03:37:48 +00001063 llvm::DIFile MethodDefUnit;
1064 unsigned MethodLine = 0;
1065 if (!Method->isImplicit()) {
1066 MethodDefUnit = getOrCreateFile(Method->getLocation());
1067 MethodLine = getLineNumber(Method->getLocation());
1068 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001069
1070 // Collect virtual method info.
1071 llvm::DIType ContainingType;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001072 unsigned Virtuality = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00001073 unsigned VIndex = 0;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001074
Guy Benyei11169dd2012-12-18 14:30:41 +00001075 if (Method->isVirtual()) {
1076 if (Method->isPure())
1077 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
1078 else
1079 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001080
Guy Benyei11169dd2012-12-18 14:30:41 +00001081 // It doesn't make sense to give a virtual destructor a vtable index,
1082 // since a single destructor has two entries in the vtable.
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001083 // FIXME: Add proper support for debug info for virtual calls in
1084 // the Microsoft ABI, where we may use multiple vptrs to make a vftable
1085 // lookup if we have multiple or virtual inheritance.
1086 if (!isa<CXXDestructorDecl>(Method) &&
1087 !CGM.getTarget().getCXXABI().isMicrosoft())
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001088 VIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(Method);
Guy Benyei11169dd2012-12-18 14:30:41 +00001089 ContainingType = RecordTy;
1090 }
1091
1092 unsigned Flags = 0;
1093 if (Method->isImplicit())
1094 Flags |= llvm::DIDescriptor::FlagArtificial;
1095 AccessSpecifier Access = Method->getAccess();
1096 if (Access == clang::AS_private)
1097 Flags |= llvm::DIDescriptor::FlagPrivate;
1098 else if (Access == clang::AS_protected)
1099 Flags |= llvm::DIDescriptor::FlagProtected;
1100 if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1101 if (CXXC->isExplicit())
1102 Flags |= llvm::DIDescriptor::FlagExplicit;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001103 } else if (const CXXConversionDecl *CXXC =
Guy Benyei11169dd2012-12-18 14:30:41 +00001104 dyn_cast<CXXConversionDecl>(Method)) {
1105 if (CXXC->isExplicit())
1106 Flags |= llvm::DIDescriptor::FlagExplicit;
1107 }
1108 if (Method->hasPrototype())
1109 Flags |= llvm::DIDescriptor::FlagPrototyped;
Adrian Prantl0630eb72013-12-18 21:48:18 +00001110 if (Method->getRefQualifier() == RQ_LValue)
1111 Flags |= llvm::DIDescriptor::FlagLValueReference;
1112 if (Method->getRefQualifier() == RQ_RValue)
1113 Flags |= llvm::DIDescriptor::FlagRValueReference;
Guy Benyei11169dd2012-12-18 14:30:41 +00001114
1115 llvm::DIArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1116 llvm::DISubprogram SP =
Eric Christopherb2a008c2013-05-16 00:45:12 +00001117 DBuilder.createMethod(RecordTy, MethodName, MethodLinkageName,
Guy Benyei11169dd2012-12-18 14:30:41 +00001118 MethodDefUnit, MethodLine,
Eric Christopherb2a008c2013-05-16 00:45:12 +00001119 MethodTy, /*isLocalToUnit=*/false,
Guy Benyei11169dd2012-12-18 14:30:41 +00001120 /* isDefinition=*/ false,
1121 Virtuality, VIndex, ContainingType,
1122 Flags, CGM.getLangOpts().Optimize, NULL,
1123 TParamsArray);
Eric Christopherb2a008c2013-05-16 00:45:12 +00001124
Guy Benyei11169dd2012-12-18 14:30:41 +00001125 SPCache[Method->getCanonicalDecl()] = llvm::WeakVH(SP);
1126
1127 return SP;
1128}
1129
1130/// CollectCXXMemberFunctions - A helper function to collect debug info for
Eric Christopherb2a008c2013-05-16 00:45:12 +00001131/// C++ member functions. This is used while creating debug info entry for
Guy Benyei11169dd2012-12-18 14:30:41 +00001132/// a Record.
1133void CGDebugInfo::
1134CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
1135 SmallVectorImpl<llvm::Value *> &EltTys,
1136 llvm::DIType RecordTy) {
1137
1138 // Since we want more than just the individual member decls if we
1139 // have templated functions iterate over every declaration to gather
1140 // the functions.
Aaron Ballman629afae2014-03-07 19:56:05 +00001141 for(const auto *I : RD->decls()) {
1142 if (const auto *Method = dyn_cast<CXXMethodDecl>(I)) {
David Blaikiea6cc8212013-08-28 20:58:00 +00001143 // Reuse the existing member function declaration if it exists.
David Blaikie8c8e8e22013-08-28 20:24:55 +00001144 // It may be associated with the declaration of the type & should be
1145 // reused as we're building the definition.
David Blaikiea6cc8212013-08-28 20:58:00 +00001146 //
1147 // This situation can arise in the vtable-based debug info reduction where
1148 // implicit members are emitted in a non-vtable TU.
David Blaikie6943dea2013-08-20 01:28:15 +00001149 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator MI =
1150 SPCache.find(Method->getCanonicalDecl());
David Blaikiefae219a2013-08-28 17:27:13 +00001151 if (MI == SPCache.end()) {
David Blaikie8c8e8e22013-08-28 20:24:55 +00001152 // If the member is implicit, lazily create it when we see the
1153 // definition, not before. (an ODR-used implicit default ctor that's
1154 // never actually code generated should not produce debug info)
David Blaikiefae219a2013-08-28 17:27:13 +00001155 if (!Method->isImplicit())
1156 EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
1157 } else
David Blaikie6943dea2013-08-20 01:28:15 +00001158 EltTys.push_back(MI->second);
Aaron Ballman629afae2014-03-07 19:56:05 +00001159 } else if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(I)) {
David Blaikief2053af2013-08-28 23:06:52 +00001160 // Add any template specializations that have already been seen. Like
1161 // implicit member functions, these may have been added to a declaration
1162 // in the case of vtable-based debug info reduction.
Aaron Ballmanb8733c52014-03-14 16:05:56 +00001163 for (const auto *SI : FTD->specializations()) {
David Blaikief2053af2013-08-28 23:06:52 +00001164 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator MI =
Aaron Ballmanb8733c52014-03-14 16:05:56 +00001165 SPCache.find(cast<CXXMethodDecl>(SI)->getCanonicalDecl());
David Blaikief2053af2013-08-28 23:06:52 +00001166 if (MI != SPCache.end())
1167 EltTys.push_back(MI->second);
1168 }
David Blaikie6943dea2013-08-20 01:28:15 +00001169 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001170 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00001171}
Guy Benyei11169dd2012-12-18 14:30:41 +00001172
Guy Benyei11169dd2012-12-18 14:30:41 +00001173/// CollectCXXBases - A helper function to collect debug info for
Eric Christopherb2a008c2013-05-16 00:45:12 +00001174/// C++ base classes. This is used while creating debug info entry for
Guy Benyei11169dd2012-12-18 14:30:41 +00001175/// a Record.
1176void CGDebugInfo::
1177CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
1178 SmallVectorImpl<llvm::Value *> &EltTys,
1179 llvm::DIType RecordTy) {
1180
1181 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
Aaron Ballman574705e2014-03-13 15:41:46 +00001182 for (const auto &BI : RD->bases()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001183 unsigned BFlags = 0;
1184 uint64_t BaseOffset;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001185
Guy Benyei11169dd2012-12-18 14:30:41 +00001186 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00001187 cast<CXXRecordDecl>(BI.getType()->getAs<RecordType>()->getDecl());
Eric Christopherb2a008c2013-05-16 00:45:12 +00001188
Aaron Ballman574705e2014-03-13 15:41:46 +00001189 if (BI.isVirtual()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001190 // virtual base offset offset is -ve. The code generator emits dwarf
1191 // expression where it expects +ve number.
Eric Christopherb2a008c2013-05-16 00:45:12 +00001192 BaseOffset =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001193 0 - CGM.getItaniumVTableContext()
Guy Benyei11169dd2012-12-18 14:30:41 +00001194 .getVirtualBaseOffsetOffset(RD, Base).getQuantity();
1195 BFlags = llvm::DIDescriptor::FlagVirtual;
1196 } else
1197 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1198 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1199 // BI->isVirtual() and bits when not.
Eric Christopherb2a008c2013-05-16 00:45:12 +00001200
Aaron Ballman574705e2014-03-13 15:41:46 +00001201 AccessSpecifier Access = BI.getAccessSpecifier();
Guy Benyei11169dd2012-12-18 14:30:41 +00001202 if (Access == clang::AS_private)
1203 BFlags |= llvm::DIDescriptor::FlagPrivate;
1204 else if (Access == clang::AS_protected)
1205 BFlags |= llvm::DIDescriptor::FlagProtected;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001206
1207 llvm::DIType DTy =
1208 DBuilder.createInheritance(RecordTy,
Aaron Ballman574705e2014-03-13 15:41:46 +00001209 getOrCreateType(BI.getType(), Unit),
Guy Benyei11169dd2012-12-18 14:30:41 +00001210 BaseOffset, BFlags);
1211 EltTys.push_back(DTy);
1212 }
1213}
1214
1215/// CollectTemplateParams - A helper function to collect template parameters.
1216llvm::DIArray CGDebugInfo::
1217CollectTemplateParams(const TemplateParameterList *TPList,
David Blaikie47c11502013-06-22 18:59:18 +00001218 ArrayRef<TemplateArgument> TAList,
Guy Benyei11169dd2012-12-18 14:30:41 +00001219 llvm::DIFile Unit) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001220 SmallVector<llvm::Value *, 16> TemplateParams;
Guy Benyei11169dd2012-12-18 14:30:41 +00001221 for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1222 const TemplateArgument &TA = TAList[i];
David Blaikie47c11502013-06-22 18:59:18 +00001223 StringRef Name;
1224 if (TPList)
1225 Name = TPList->getParam(i)->getName();
David Blaikie38079fd2013-05-10 21:53:14 +00001226 switch (TA.getKind()) {
1227 case TemplateArgument::Type: {
Guy Benyei11169dd2012-12-18 14:30:41 +00001228 llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit);
1229 llvm::DITemplateTypeParameter TTP =
David Blaikie47c11502013-06-22 18:59:18 +00001230 DBuilder.createTemplateTypeParameter(TheCU, Name, TTy);
Guy Benyei11169dd2012-12-18 14:30:41 +00001231 TemplateParams.push_back(TTP);
David Blaikie38079fd2013-05-10 21:53:14 +00001232 } break;
1233 case TemplateArgument::Integral: {
Guy Benyei11169dd2012-12-18 14:30:41 +00001234 llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit);
1235 llvm::DITemplateValueParameter TVP =
David Blaikie38079fd2013-05-10 21:53:14 +00001236 DBuilder.createTemplateValueParameter(
David Blaikie47c11502013-06-22 18:59:18 +00001237 TheCU, Name, TTy,
David Blaikie38079fd2013-05-10 21:53:14 +00001238 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral()));
1239 TemplateParams.push_back(TVP);
1240 } break;
1241 case TemplateArgument::Declaration: {
1242 const ValueDecl *D = TA.getAsDecl();
1243 bool InstanceMember = D->isCXXInstanceMember();
1244 QualType T = InstanceMember
1245 ? CGM.getContext().getMemberPointerType(
1246 D->getType(), cast<RecordDecl>(D->getDeclContext())
1247 ->getTypeForDecl())
1248 : CGM.getContext().getPointerType(D->getType());
1249 llvm::DIType TTy = getOrCreateType(T, Unit);
1250 llvm::Value *V = 0;
1251 // Variable pointer template parameters have a value that is the address
1252 // of the variable.
1253 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1254 V = CGM.GetAddrOfGlobalVar(VD);
1255 // Member function pointers have special support for building them, though
1256 // this is currently unsupported in LLVM CodeGen.
David Blaikied900f982013-05-13 06:57:50 +00001257 if (InstanceMember) {
David Blaikie38079fd2013-05-10 21:53:14 +00001258 if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(D))
1259 V = CGM.getCXXABI().EmitMemberPointer(method);
David Blaikied900f982013-05-13 06:57:50 +00001260 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1261 V = CGM.GetAddrOfFunction(FD);
David Blaikie38079fd2013-05-10 21:53:14 +00001262 // Member data pointers have special handling too to compute the fixed
1263 // offset within the object.
Adrian Prantlefb88052014-04-01 17:52:06 +00001264 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) {
David Blaikie38079fd2013-05-10 21:53:14 +00001265 // These five lines (& possibly the above member function pointer
1266 // handling) might be able to be refactored to use similar code in
1267 // CodeGenModule::getMemberPointerConstant
1268 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
1269 CharUnits chars =
1270 CGM.getContext().toCharUnitsFromBits((int64_t) fieldOffset);
1271 V = CGM.getCXXABI().EmitMemberDataPointer(
1272 cast<MemberPointerType>(T.getTypePtr()), chars);
1273 }
1274 llvm::DITemplateValueParameter TVP =
David Majnemera3644d62013-08-25 22:13:27 +00001275 DBuilder.createTemplateValueParameter(TheCU, Name, TTy,
1276 V->stripPointerCasts());
David Blaikie38079fd2013-05-10 21:53:14 +00001277 TemplateParams.push_back(TVP);
1278 } break;
1279 case TemplateArgument::NullPtr: {
1280 QualType T = TA.getNullPtrType();
1281 llvm::DIType TTy = getOrCreateType(T, Unit);
1282 llvm::Value *V = 0;
1283 // Special case member data pointer null values since they're actually -1
1284 // instead of zero.
1285 if (const MemberPointerType *MPT =
1286 dyn_cast<MemberPointerType>(T.getTypePtr()))
1287 // But treat member function pointers as simple zero integers because
1288 // it's easier than having a special case in LLVM's CodeGen. If LLVM
1289 // CodeGen grows handling for values of non-null member function
1290 // pointers then perhaps we could remove this special case and rely on
1291 // EmitNullMemberPointer for member function pointers.
1292 if (MPT->isMemberDataPointer())
1293 V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1294 if (!V)
1295 V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
1296 llvm::DITemplateValueParameter TVP =
David Blaikie47c11502013-06-22 18:59:18 +00001297 DBuilder.createTemplateValueParameter(TheCU, Name, TTy, V);
David Blaikie38079fd2013-05-10 21:53:14 +00001298 TemplateParams.push_back(TVP);
1299 } break;
David Blaikie47c11502013-06-22 18:59:18 +00001300 case TemplateArgument::Template: {
1301 llvm::DITemplateValueParameter TVP =
1302 DBuilder.createTemplateTemplateParameter(
1303 TheCU, Name, llvm::DIType(),
1304 TA.getAsTemplate().getAsTemplateDecl()
1305 ->getQualifiedNameAsString());
1306 TemplateParams.push_back(TVP);
1307 } break;
1308 case TemplateArgument::Pack: {
1309 llvm::DITemplateValueParameter TVP =
1310 DBuilder.createTemplateParameterPack(
1311 TheCU, Name, llvm::DIType(),
1312 CollectTemplateParams(NULL, TA.getPackAsArray(), Unit));
1313 TemplateParams.push_back(TVP);
1314 } break;
David Majnemer5559d472013-08-24 08:21:10 +00001315 case TemplateArgument::Expression: {
1316 const Expr *E = TA.getAsExpr();
1317 QualType T = E->getType();
1318 llvm::Value *V = CGM.EmitConstantExpr(E, T);
1319 assert(V && "Expression in template argument isn't constant");
1320 llvm::DIType TTy = getOrCreateType(T, Unit);
1321 llvm::DITemplateValueParameter TVP =
1322 DBuilder.createTemplateValueParameter(TheCU, Name, TTy,
1323 V->stripPointerCasts());
1324 TemplateParams.push_back(TVP);
1325 } break;
David Blaikie2b93c542013-05-10 23:36:06 +00001326 // And the following should never occur:
David Blaikie38079fd2013-05-10 21:53:14 +00001327 case TemplateArgument::TemplateExpansion:
David Blaikie38079fd2013-05-10 21:53:14 +00001328 case TemplateArgument::Null:
1329 llvm_unreachable(
1330 "These argument types shouldn't exist in concrete types");
Guy Benyei11169dd2012-12-18 14:30:41 +00001331 }
1332 }
1333 return DBuilder.getOrCreateArray(TemplateParams);
1334}
1335
1336/// CollectFunctionTemplateParams - A helper function to collect debug
1337/// info for function template parameters.
1338llvm::DIArray CGDebugInfo::
1339CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) {
1340 if (FD->getTemplatedKind() ==
1341 FunctionDecl::TK_FunctionTemplateSpecialization) {
1342 const TemplateParameterList *TList =
1343 FD->getTemplateSpecializationInfo()->getTemplate()
1344 ->getTemplateParameters();
David Blaikie47c11502013-06-22 18:59:18 +00001345 return CollectTemplateParams(
1346 TList, FD->getTemplateSpecializationArgs()->asArray(), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00001347 }
1348 return llvm::DIArray();
1349}
1350
1351/// CollectCXXTemplateParams - A helper function to collect debug info for
1352/// template parameters.
1353llvm::DIArray CGDebugInfo::
1354CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial,
1355 llvm::DIFile Unit) {
Adrian Prantl649f0302014-04-17 01:04:01 +00001356 // Always get the full list of parameters, not just the ones from
1357 // the specialization.
1358 TemplateParameterList *TPList =
1359 TSpecial->getSpecializedTemplate()->getTemplateParameters();
Adrian Prantl2c92e9c2014-04-17 00:30:48 +00001360 const TemplateArgumentList &TAList = TSpecial->getTemplateArgs();
David Blaikie47c11502013-06-22 18:59:18 +00001361 return CollectTemplateParams(TPList, TAList.asArray(), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00001362}
1363
1364/// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
1365llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
1366 if (VTablePtrType.isValid())
1367 return VTablePtrType;
1368
1369 ASTContext &Context = CGM.getContext();
1370
1371 /* Function type */
1372 llvm::Value *STy = getOrCreateType(Context.IntTy, Unit);
1373 llvm::DIArray SElements = DBuilder.getOrCreateArray(STy);
1374 llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements);
1375 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1376 llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0,
1377 "__vtbl_ptr_type");
1378 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1379 return VTablePtrType;
1380}
1381
1382/// getVTableName - Get vtable name for the given Class.
1383StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +00001384 // Copy the gdb compatible name on the side and use its reference.
1385 return internString("_vptr$", RD->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00001386}
1387
1388
1389/// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
1390/// debug info entry in EltTys vector.
1391void CGDebugInfo::
1392CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
1393 SmallVectorImpl<llvm::Value *> &EltTys) {
1394 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1395
1396 // If there is a primary base then it will hold vtable info.
1397 if (RL.getPrimaryBase())
1398 return;
1399
1400 // If this class is not dynamic then there is not any vtable info to collect.
1401 if (!RD->isDynamicClass())
1402 return;
1403
1404 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1405 llvm::DIType VPTR
1406 = DBuilder.createMemberType(Unit, getVTableName(RD), Unit,
Eric Christopher0fdcb312013-05-16 00:52:20 +00001407 0, Size, 0, 0,
1408 llvm::DIDescriptor::FlagArtificial,
Guy Benyei11169dd2012-12-18 14:30:41 +00001409 getOrCreateVTablePtrType(Unit));
1410 EltTys.push_back(VPTR);
1411}
1412
Eric Christopherb2a008c2013-05-16 00:45:12 +00001413/// getOrCreateRecordType - Emit record type's standalone debug info.
1414llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy,
Guy Benyei11169dd2012-12-18 14:30:41 +00001415 SourceLocation Loc) {
Eric Christopher75e17682013-05-16 00:45:23 +00001416 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00001417 llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc));
1418 return T;
1419}
1420
1421/// getOrCreateInterfaceType - Emit an objective c interface type standalone
1422/// debug info.
1423llvm::DIType CGDebugInfo::getOrCreateInterfaceType(QualType D,
Eric Christopherc0c5d462013-02-21 22:35:08 +00001424 SourceLocation Loc) {
Eric Christopher75e17682013-05-16 00:45:23 +00001425 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00001426 llvm::DIType T = getOrCreateType(D, getOrCreateFile(Loc));
Adrian Prantl73409ce2013-03-11 18:33:46 +00001427 RetainedTypes.push_back(D.getAsOpaquePtr());
Guy Benyei11169dd2012-12-18 14:30:41 +00001428 return T;
1429}
1430
David Blaikieb2e86eb2013-08-15 20:49:17 +00001431void CGDebugInfo::completeType(const RecordDecl *RD) {
1432 if (DebugKind > CodeGenOptions::LimitedDebugInfo ||
1433 !CGM.getLangOpts().CPlusPlus)
1434 completeRequiredType(RD);
1435}
1436
1437void CGDebugInfo::completeRequiredType(const RecordDecl *RD) {
David Blaikie0856f662014-03-04 22:01:08 +00001438 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
1439 return;
1440
David Blaikie6943dea2013-08-20 01:28:15 +00001441 if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
1442 if (CXXDecl->isDynamicClass())
1443 return;
1444
David Blaikieb2e86eb2013-08-15 20:49:17 +00001445 QualType Ty = CGM.getContext().getRecordType(RD);
1446 llvm::DIType T = getTypeOrNull(Ty);
David Blaikie6943dea2013-08-20 01:28:15 +00001447 if (T && T.isForwardDecl())
1448 completeClassData(RD);
1449}
1450
1451void CGDebugInfo::completeClassData(const RecordDecl *RD) {
1452 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
Michael Gottesman349542b2013-08-19 18:46:16 +00001453 return;
David Blaikie6943dea2013-08-20 01:28:15 +00001454 QualType Ty = CGM.getContext().getRecordType(RD);
David Blaikieb2e86eb2013-08-15 20:49:17 +00001455 void* TyPtr = Ty.getAsOpaquePtr();
1456 if (CompletedTypeCache.count(TyPtr))
1457 return;
1458 llvm::DIType Res = CreateTypeDefinition(Ty->castAs<RecordType>());
1459 assert(!Res.isForwardDecl());
1460 CompletedTypeCache[TyPtr] = Res;
1461 TypeCache[TyPtr] = Res;
1462}
1463
David Blaikie0e716b42014-03-03 23:48:23 +00001464static bool hasExplicitMemberDefinition(CXXRecordDecl::method_iterator I,
1465 CXXRecordDecl::method_iterator End) {
1466 for (; I != End; ++I)
1467 if (FunctionDecl *Tmpl = I->getInstantiatedFromMemberFunction())
David Blaikief7f21852014-03-04 03:08:14 +00001468 if (!Tmpl->isImplicit() && Tmpl->isThisDeclarationADefinition() &&
1469 !I->getMemberSpecializationInfo()->isExplicitSpecialization())
David Blaikie0e716b42014-03-03 23:48:23 +00001470 return true;
1471 return false;
1472}
1473
1474static bool shouldOmitDefinition(CodeGenOptions::DebugInfoKind DebugKind,
1475 const RecordDecl *RD,
1476 const LangOptions &LangOpts) {
1477 if (DebugKind > CodeGenOptions::LimitedDebugInfo)
1478 return false;
1479
1480 if (!LangOpts.CPlusPlus)
1481 return false;
1482
1483 if (!RD->isCompleteDefinitionRequired())
1484 return true;
1485
1486 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1487
1488 if (!CXXDecl)
1489 return false;
1490
1491 if (CXXDecl->hasDefinition() && CXXDecl->isDynamicClass())
1492 return true;
1493
1494 TemplateSpecializationKind Spec = TSK_Undeclared;
1495 if (const ClassTemplateSpecializationDecl *SD =
1496 dyn_cast<ClassTemplateSpecializationDecl>(RD))
1497 Spec = SD->getSpecializationKind();
1498
1499 if (Spec == TSK_ExplicitInstantiationDeclaration &&
1500 hasExplicitMemberDefinition(CXXDecl->method_begin(),
1501 CXXDecl->method_end()))
1502 return true;
1503
1504 return false;
1505}
1506
Guy Benyei11169dd2012-12-18 14:30:41 +00001507/// CreateType - get structure or union type.
David Blaikie99dab3b2013-09-04 22:03:57 +00001508llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001509 RecordDecl *RD = Ty->getDecl();
David Blaikie3b1cc9b2013-09-06 06:45:04 +00001510 llvm::DICompositeType T(getTypeOrNull(QualType(Ty, 0)));
David Blaikie0e716b42014-03-03 23:48:23 +00001511 if (T || shouldOmitDefinition(DebugKind, RD, CGM.getLangOpts())) {
David Blaikie3b1cc9b2013-09-06 06:45:04 +00001512 if (!T)
David Blaikie65ec94e2014-02-18 20:52:05 +00001513 T = getOrCreateRecordFwdDecl(
1514 Ty, getContextDescriptor(cast<Decl>(RD->getDeclContext())));
David Blaikie3b1cc9b2013-09-06 06:45:04 +00001515 return T;
David Blaikiee36464c2013-06-05 05:32:23 +00001516 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001517
David Blaikieb2e86eb2013-08-15 20:49:17 +00001518 return CreateTypeDefinition(Ty);
1519}
1520
1521llvm::DIType CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {
1522 RecordDecl *RD = Ty->getDecl();
1523
Guy Benyei11169dd2012-12-18 14:30:41 +00001524 // Get overall information about the record type for the debug info.
1525 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1526
1527 // Records and classes and unions can all be recursive. To handle them, we
1528 // first generate a debug descriptor for the struct as a forward declaration.
1529 // Then (if it is a definition) we go through and get debug info for all of
1530 // its members. Finally, we create a descriptor for the complete type (which
1531 // may refer to the forward decl if the struct is recursive) and replace all
1532 // uses of the forward declaration with the final definition.
1533
David Blaikie4a2b5ef2013-08-12 22:24:20 +00001534 llvm::DICompositeType FwdDecl(getOrCreateLimitedType(Ty, DefUnit));
Manman Ren0d441f12013-07-02 19:01:53 +00001535 assert(FwdDecl.isCompositeType() &&
David Blaikie469f0792013-05-22 23:22:42 +00001536 "The debug type of a RecordType should be a llvm::DICompositeType");
Guy Benyei11169dd2012-12-18 14:30:41 +00001537
1538 if (FwdDecl.isForwardDecl())
1539 return FwdDecl;
1540
David Blaikieadfbf992013-08-18 16:55:33 +00001541 if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
1542 CollectContainingType(CXXDecl, FwdDecl);
1543
Guy Benyei11169dd2012-12-18 14:30:41 +00001544 // Push the struct on region stack.
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001545 LexicalBlockStack.push_back(&*FwdDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00001546 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1547
Adrian Prantla03a85a2013-03-06 22:03:30 +00001548 // Add this to the completed-type cache while we're completing it recursively.
Guy Benyei11169dd2012-12-18 14:30:41 +00001549 CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1550
1551 // Convert all the elements.
1552 SmallVector<llvm::Value *, 16> EltTys;
David Blaikie6943dea2013-08-20 01:28:15 +00001553 // what about nested types?
Guy Benyei11169dd2012-12-18 14:30:41 +00001554
1555 // Note: The split of CXXDecl information here is intentional, the
1556 // gdb tests will depend on a certain ordering at printout. The debug
1557 // information offsets are still correct if we merge them all together
1558 // though.
1559 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1560 if (CXXDecl) {
1561 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1562 CollectVTableInfo(CXXDecl, DefUnit, EltTys);
1563 }
1564
Eric Christopher91a31902013-01-16 01:22:32 +00001565 // Collect data fields (including static variables and any initializers).
Guy Benyei11169dd2012-12-18 14:30:41 +00001566 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
Eric Christopher2df080e2013-10-11 18:16:51 +00001567 if (CXXDecl)
Guy Benyei11169dd2012-12-18 14:30:41 +00001568 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00001569
1570 LexicalBlockStack.pop_back();
1571 RegionMap.erase(Ty->getDecl());
1572
1573 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
David Blaikie4a5b8952013-08-01 20:31:40 +00001574 FwdDecl.setTypeArray(Elements);
Guy Benyei11169dd2012-12-18 14:30:41 +00001575
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001576 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1577 return FwdDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00001578}
1579
1580/// CreateType - get objective-c object type.
1581llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1582 llvm::DIFile Unit) {
1583 // Ignore protocols.
1584 return getOrCreateType(Ty->getBaseType(), Unit);
1585}
1586
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001587
1588/// \return true if Getter has the default name for the property PD.
1589static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
1590 const ObjCMethodDecl *Getter) {
1591 assert(PD);
1592 if (!Getter)
1593 return true;
1594
1595 assert(Getter->getDeclName().isObjCZeroArgSelector());
1596 return PD->getName() ==
1597 Getter->getDeclName().getObjCSelector().getNameForSlot(0);
1598}
1599
1600/// \return true if Setter has the default name for the property PD.
1601static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
1602 const ObjCMethodDecl *Setter) {
1603 assert(PD);
1604 if (!Setter)
1605 return true;
1606
1607 assert(Setter->getDeclName().isObjCOneArgSelector());
Adrian Prantla4ce9062013-06-07 22:29:12 +00001608 return SelectorTable::constructSetterName(PD->getName()) ==
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001609 Setter->getDeclName().getObjCSelector().getNameForSlot(0);
1610}
1611
Guy Benyei11169dd2012-12-18 14:30:41 +00001612/// CreateType - get objective-c interface type.
1613llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1614 llvm::DIFile Unit) {
1615 ObjCInterfaceDecl *ID = Ty->getDecl();
1616 if (!ID)
1617 return llvm::DIType();
1618
1619 // Get overall information about the record type for the debug info.
1620 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1621 unsigned Line = getLineNumber(ID->getLocation());
1622 unsigned RuntimeLang = TheCU.getLanguage();
1623
1624 // If this is just a forward declaration return a special forward-declaration
1625 // debug type since we won't be able to lay out the entire type.
1626 ObjCInterfaceDecl *Def = ID->getDefinition();
1627 if (!Def) {
1628 llvm::DIType FwdDecl =
1629 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
Eric Christopherc0c5d462013-02-21 22:35:08 +00001630 ID->getName(), TheCU, DefUnit, Line,
1631 RuntimeLang);
Guy Benyei11169dd2012-12-18 14:30:41 +00001632 return FwdDecl;
1633 }
1634
1635 ID = Def;
1636
1637 // Bit size, align and offset of the type.
1638 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1639 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1640
1641 unsigned Flags = 0;
1642 if (ID->getImplementation())
1643 Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
1644
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001645 llvm::DICompositeType RealDecl =
Guy Benyei11169dd2012-12-18 14:30:41 +00001646 DBuilder.createStructType(Unit, ID->getName(), DefUnit,
1647 Line, Size, Align, Flags,
David Blaikie6d4fe152013-02-25 01:07:08 +00001648 llvm::DIType(), llvm::DIArray(), RuntimeLang);
Guy Benyei11169dd2012-12-18 14:30:41 +00001649
1650 // Otherwise, insert it into the CompletedTypeCache so that recursive uses
1651 // will find it and we're emitting the complete type.
Adrian Prantla03a85a2013-03-06 22:03:30 +00001652 QualType QualTy = QualType(Ty, 0);
1653 CompletedTypeCache[QualTy.getAsOpaquePtr()] = RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00001654
Eric Christopher35f1f9f2013-07-14 21:00:07 +00001655 // Push the struct on region stack.
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001656 LexicalBlockStack.push_back(static_cast<llvm::MDNode*>(RealDecl));
Guy Benyei11169dd2012-12-18 14:30:41 +00001657 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1658
1659 // Convert all the elements.
1660 SmallVector<llvm::Value *, 16> EltTys;
1661
1662 ObjCInterfaceDecl *SClass = ID->getSuperClass();
1663 if (SClass) {
1664 llvm::DIType SClassTy =
1665 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1666 if (!SClassTy.isValid())
1667 return llvm::DIType();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001668
Guy Benyei11169dd2012-12-18 14:30:41 +00001669 llvm::DIType InhTag =
1670 DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
1671 EltTys.push_back(InhTag);
1672 }
1673
Eric Christopher35f1f9f2013-07-14 21:00:07 +00001674 // Create entries for all of the properties.
Aaron Ballmand174edf2014-03-13 19:11:50 +00001675 for (const auto *PD : ID->properties()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001676 SourceLocation Loc = PD->getLocation();
1677 llvm::DIFile PUnit = getOrCreateFile(Loc);
1678 unsigned PLine = getLineNumber(Loc);
1679 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1680 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1681 llvm::MDNode *PropertyNode =
1682 DBuilder.createObjCProperty(PD->getName(),
Eric Christopherc0c5d462013-02-21 22:35:08 +00001683 PUnit, PLine,
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001684 hasDefaultGetterName(PD, Getter) ? "" :
Guy Benyei11169dd2012-12-18 14:30:41 +00001685 getSelectorName(PD->getGetterName()),
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001686 hasDefaultSetterName(PD, Setter) ? "" :
Guy Benyei11169dd2012-12-18 14:30:41 +00001687 getSelectorName(PD->getSetterName()),
1688 PD->getPropertyAttributes(),
Eric Christopherc0c5d462013-02-21 22:35:08 +00001689 getOrCreateType(PD->getType(), PUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00001690 EltTys.push_back(PropertyNode);
1691 }
1692
1693 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1694 unsigned FieldNo = 0;
1695 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1696 Field = Field->getNextIvar(), ++FieldNo) {
1697 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1698 if (!FieldTy.isValid())
1699 return llvm::DIType();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001700
Guy Benyei11169dd2012-12-18 14:30:41 +00001701 StringRef FieldName = Field->getName();
1702
1703 // Ignore unnamed fields.
1704 if (FieldName.empty())
1705 continue;
1706
1707 // Get the location for the field.
1708 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1709 unsigned FieldLine = getLineNumber(Field->getLocation());
1710 QualType FType = Field->getType();
1711 uint64_t FieldSize = 0;
1712 unsigned FieldAlign = 0;
1713
1714 if (!FType->isIncompleteArrayType()) {
1715
1716 // Bit size, align and offset of the type.
1717 FieldSize = Field->isBitField()
Eric Christopher35f1f9f2013-07-14 21:00:07 +00001718 ? Field->getBitWidthValue(CGM.getContext())
1719 : CGM.getContext().getTypeSize(FType);
Guy Benyei11169dd2012-12-18 14:30:41 +00001720 FieldAlign = CGM.getContext().getTypeAlign(FType);
1721 }
1722
1723 uint64_t FieldOffset;
1724 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1725 // We don't know the runtime offset of an ivar if we're using the
1726 // non-fragile ABI. For bitfields, use the bit offset into the first
1727 // byte of storage of the bitfield. For other fields, use zero.
1728 if (Field->isBitField()) {
1729 FieldOffset = CGM.getObjCRuntime().ComputeBitfieldBitOffset(
1730 CGM, ID, Field);
1731 FieldOffset %= CGM.getContext().getCharWidth();
1732 } else {
1733 FieldOffset = 0;
1734 }
1735 } else {
1736 FieldOffset = RL.getFieldOffset(FieldNo);
1737 }
1738
1739 unsigned Flags = 0;
1740 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1741 Flags = llvm::DIDescriptor::FlagProtected;
1742 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1743 Flags = llvm::DIDescriptor::FlagPrivate;
1744
1745 llvm::MDNode *PropertyNode = NULL;
1746 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001747 if (ObjCPropertyImplDecl *PImpD =
Guy Benyei11169dd2012-12-18 14:30:41 +00001748 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
1749 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
Eric Christopherc0c5d462013-02-21 22:35:08 +00001750 SourceLocation Loc = PD->getLocation();
1751 llvm::DIFile PUnit = getOrCreateFile(Loc);
1752 unsigned PLine = getLineNumber(Loc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001753 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1754 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1755 PropertyNode =
1756 DBuilder.createObjCProperty(PD->getName(),
1757 PUnit, PLine,
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001758 hasDefaultGetterName(PD, Getter) ? "" :
Guy Benyei11169dd2012-12-18 14:30:41 +00001759 getSelectorName(PD->getGetterName()),
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001760 hasDefaultSetterName(PD, Setter) ? "" :
Guy Benyei11169dd2012-12-18 14:30:41 +00001761 getSelectorName(PD->getSetterName()),
1762 PD->getPropertyAttributes(),
1763 getOrCreateType(PD->getType(), PUnit));
1764 }
1765 }
1766 }
1767 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
1768 FieldLine, FieldSize, FieldAlign,
1769 FieldOffset, Flags, FieldTy,
1770 PropertyNode);
1771 EltTys.push_back(FieldTy);
1772 }
1773
1774 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001775 RealDecl.setTypeArray(Elements);
Adrian Prantla03a85a2013-03-06 22:03:30 +00001776
1777 // If the implementation is not yet set, we do not want to mark it
1778 // as complete. An implementation may declare additional
1779 // private ivars that we would miss otherwise.
1780 if (ID->getImplementation() == 0)
1781 CompletedTypeCache.erase(QualTy.getAsOpaquePtr());
Eric Christopherb2a008c2013-05-16 00:45:12 +00001782
Guy Benyei11169dd2012-12-18 14:30:41 +00001783 LexicalBlockStack.pop_back();
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001784 return RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00001785}
1786
1787llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) {
1788 llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1789 int64_t Count = Ty->getNumElements();
1790 if (Count == 0)
1791 // If number of elements are not known then this is an unbounded array.
1792 // Use Count == -1 to express such arrays.
1793 Count = -1;
1794
1795 llvm::Value *Subscript = DBuilder.getOrCreateSubrange(0, Count);
1796 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1797
1798 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1799 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1800
1801 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1802}
1803
1804llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1805 llvm::DIFile Unit) {
1806 uint64_t Size;
1807 uint64_t Align;
1808
1809 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1810 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1811 Size = 0;
1812 Align =
1813 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1814 } else if (Ty->isIncompleteArrayType()) {
1815 Size = 0;
1816 if (Ty->getElementType()->isIncompleteType())
1817 Align = 0;
1818 else
1819 Align = CGM.getContext().getTypeAlign(Ty->getElementType());
David Blaikief03b2e82013-05-09 20:48:12 +00001820 } else if (Ty->isIncompleteType()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001821 Size = 0;
1822 Align = 0;
1823 } else {
1824 // Size and align of the whole array, not the element type.
1825 Size = CGM.getContext().getTypeSize(Ty);
1826 Align = CGM.getContext().getTypeAlign(Ty);
1827 }
1828
1829 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
1830 // interior arrays, do we care? Why aren't nested arrays represented the
1831 // obvious/recursive way?
1832 SmallVector<llvm::Value *, 8> Subscripts;
1833 QualType EltTy(Ty, 0);
1834 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1835 // If the number of elements is known, then count is that number. Otherwise,
1836 // it's -1. This allows us to represent a subrange with an array of 0
1837 // elements, like this:
1838 //
1839 // struct foo {
1840 // int x[0];
1841 // };
1842 int64_t Count = -1; // Count == -1 is an unbounded array.
1843 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1844 Count = CAT->getSize().getZExtValue();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001845
Guy Benyei11169dd2012-12-18 14:30:41 +00001846 // FIXME: Verify this is right for VLAs.
1847 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
1848 EltTy = Ty->getElementType();
1849 }
1850
1851 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1852
Eric Christopherb2a008c2013-05-16 00:45:12 +00001853 llvm::DIType DbgTy =
Guy Benyei11169dd2012-12-18 14:30:41 +00001854 DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1855 SubscriptArray);
1856 return DbgTy;
1857}
1858
Eric Christopherb2a008c2013-05-16 00:45:12 +00001859llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +00001860 llvm::DIFile Unit) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001861 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
Guy Benyei11169dd2012-12-18 14:30:41 +00001862 Ty, Ty->getPointeeType(), Unit);
1863}
1864
Eric Christopherb2a008c2013-05-16 00:45:12 +00001865llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +00001866 llvm::DIFile Unit) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001867 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
Guy Benyei11169dd2012-12-18 14:30:41 +00001868 Ty, Ty->getPointeeType(), Unit);
1869}
1870
Eric Christopherb2a008c2013-05-16 00:45:12 +00001871llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +00001872 llvm::DIFile U) {
David Blaikie2c705ca2013-01-19 19:20:56 +00001873 llvm::DIType ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
1874 if (!Ty->getPointeeType()->isFunctionType())
1875 return DBuilder.createMemberPointerType(
David Blaikie99dab3b2013-09-04 22:03:57 +00001876 getOrCreateType(Ty->getPointeeType(), U), ClassType);
Adrian Prantl0866acd2013-12-19 01:38:47 +00001877
1878 const FunctionProtoType *FPT =
1879 Ty->getPointeeType()->getAs<FunctionProtoType>();
David Blaikie2c705ca2013-01-19 19:20:56 +00001880 return DBuilder.createMemberPointerType(getOrCreateInstanceMethodType(
Adrian Prantl0866acd2013-12-19 01:38:47 +00001881 CGM.getContext().getPointerType(QualType(Ty->getClass(),
1882 FPT->getTypeQuals())),
1883 FPT, U), ClassType);
Guy Benyei11169dd2012-12-18 14:30:41 +00001884}
1885
Eric Christopherb2a008c2013-05-16 00:45:12 +00001886llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +00001887 llvm::DIFile U) {
1888 // Ignore the atomic wrapping
1889 // FIXME: What is the correct representation?
1890 return getOrCreateType(Ty->getValueType(), U);
1891}
1892
1893/// CreateEnumType - get enumeration type.
Manman Ren501ecf92013-08-28 21:46:36 +00001894llvm::DIType CGDebugInfo::CreateEnumType(const EnumType *Ty) {
Manman Ren1b457022013-08-28 21:20:28 +00001895 const EnumDecl *ED = Ty->getDecl();
Guy Benyei11169dd2012-12-18 14:30:41 +00001896 uint64_t Size = 0;
1897 uint64_t Align = 0;
1898 if (!ED->getTypeForDecl()->isIncompleteType()) {
1899 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1900 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1901 }
1902
Manman Rene0064d82013-08-29 23:19:58 +00001903 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
1904
Guy Benyei11169dd2012-12-18 14:30:41 +00001905 // If this is just a forward declaration, construct an appropriately
1906 // marked node and just return it.
1907 if (!ED->getDefinition()) {
1908 llvm::DIDescriptor EDContext;
1909 EDContext = getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1910 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1911 unsigned Line = getLineNumber(ED->getLocation());
1912 StringRef EDName = ED->getName();
1913 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_enumeration_type,
1914 EDName, EDContext, DefUnit, Line, 0,
Manman Rene0064d82013-08-29 23:19:58 +00001915 Size, Align, FullName);
Guy Benyei11169dd2012-12-18 14:30:41 +00001916 }
1917
1918 // Create DIEnumerator elements for each enumerator.
1919 SmallVector<llvm::Value *, 16> Enumerators;
1920 ED = ED->getDefinition();
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001921 for (const auto *Enum : ED->enumerators()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001922 Enumerators.push_back(
1923 DBuilder.createEnumerator(Enum->getName(),
David Blaikiece1ae382013-06-24 07:13:13 +00001924 Enum->getInitVal().getSExtValue()));
Guy Benyei11169dd2012-12-18 14:30:41 +00001925 }
1926
1927 // Return a CompositeType for the enum itself.
1928 llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1929
1930 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1931 unsigned Line = getLineNumber(ED->getLocation());
Eric Christopherb2a008c2013-05-16 00:45:12 +00001932 llvm::DIDescriptor EnumContext =
Guy Benyei11169dd2012-12-18 14:30:41 +00001933 getContextDescriptor(cast<Decl>(ED->getDeclContext()));
Adrian Prantlc60dc712013-04-19 19:56:39 +00001934 llvm::DIType ClassTy = ED->isFixed() ?
Guy Benyei11169dd2012-12-18 14:30:41 +00001935 getOrCreateType(ED->getIntegerType(), DefUnit) : llvm::DIType();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001936 llvm::DIType DbgTy =
Guy Benyei11169dd2012-12-18 14:30:41 +00001937 DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1938 Size, Align, EltArray,
Manman Rene0064d82013-08-29 23:19:58 +00001939 ClassTy, FullName);
Guy Benyei11169dd2012-12-18 14:30:41 +00001940 return DbgTy;
1941}
1942
David Blaikie05491062013-01-21 04:37:12 +00001943static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
1944 Qualifiers Quals;
Guy Benyei11169dd2012-12-18 14:30:41 +00001945 do {
Adrian Prantl179af902013-09-26 21:35:50 +00001946 Qualifiers InnerQuals = T.getLocalQualifiers();
1947 // Qualifiers::operator+() doesn't like it if you add a Qualifier
1948 // that is already there.
1949 Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals);
1950 Quals += InnerQuals;
Guy Benyei11169dd2012-12-18 14:30:41 +00001951 QualType LastT = T;
1952 switch (T->getTypeClass()) {
1953 default:
David Blaikie05491062013-01-21 04:37:12 +00001954 return C.getQualifiedType(T.getTypePtr(), Quals);
David Blaikief1b382e2014-04-06 17:14:06 +00001955 case Type::TemplateSpecialization: {
1956 const auto *Spec = cast<TemplateSpecializationType>(T);
1957 if (Spec->isTypeAlias())
1958 return C.getQualifiedType(T.getTypePtr(), Quals);
1959 T = Spec->desugar();
1960 break; }
Guy Benyei11169dd2012-12-18 14:30:41 +00001961 case Type::TypeOfExpr:
1962 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1963 break;
1964 case Type::TypeOf:
1965 T = cast<TypeOfType>(T)->getUnderlyingType();
1966 break;
1967 case Type::Decltype:
1968 T = cast<DecltypeType>(T)->getUnderlyingType();
1969 break;
1970 case Type::UnaryTransform:
1971 T = cast<UnaryTransformType>(T)->getUnderlyingType();
1972 break;
1973 case Type::Attributed:
1974 T = cast<AttributedType>(T)->getEquivalentType();
1975 break;
1976 case Type::Elaborated:
1977 T = cast<ElaboratedType>(T)->getNamedType();
1978 break;
1979 case Type::Paren:
1980 T = cast<ParenType>(T)->getInnerType();
1981 break;
David Blaikie05491062013-01-21 04:37:12 +00001982 case Type::SubstTemplateTypeParm:
Guy Benyei11169dd2012-12-18 14:30:41 +00001983 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
Guy Benyei11169dd2012-12-18 14:30:41 +00001984 break;
1985 case Type::Auto:
David Blaikie22c460a02013-05-24 21:24:35 +00001986 QualType DT = cast<AutoType>(T)->getDeducedType();
1987 if (DT.isNull())
1988 return T;
1989 T = DT;
Guy Benyei11169dd2012-12-18 14:30:41 +00001990 break;
1991 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00001992
Guy Benyei11169dd2012-12-18 14:30:41 +00001993 assert(T != LastT && "Type unwrapping failed to unwrap!");
NAKAMURA Takumi3e0a3632013-01-21 10:51:28 +00001994 (void)LastT;
Guy Benyei11169dd2012-12-18 14:30:41 +00001995 } while (true);
1996}
1997
Eric Christopher0fdcb312013-05-16 00:52:20 +00001998/// getType - Get the type from the cache or return null type if it doesn't
1999/// exist.
Guy Benyei11169dd2012-12-18 14:30:41 +00002000llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) {
2001
2002 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00002003 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Eric Christopherb2a008c2013-05-16 00:45:12 +00002004
Guy Benyei11169dd2012-12-18 14:30:41 +00002005 // Check for existing entry.
Adrian Prantl73409ce2013-03-11 18:33:46 +00002006 if (Ty->getTypeClass() == Type::ObjCInterface) {
2007 llvm::Value *V = getCachedInterfaceTypeOrNull(Ty);
2008 if (V)
2009 return llvm::DIType(cast<llvm::MDNode>(V));
2010 else return llvm::DIType();
2011 }
2012
Guy Benyei11169dd2012-12-18 14:30:41 +00002013 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
2014 TypeCache.find(Ty.getAsOpaquePtr());
2015 if (it != TypeCache.end()) {
2016 // Verify that the debug info still exists.
2017 if (llvm::Value *V = it->second)
2018 return llvm::DIType(cast<llvm::MDNode>(V));
2019 }
2020
2021 return llvm::DIType();
2022}
2023
2024/// getCompletedTypeOrNull - Get the type from the cache or return null if it
2025/// doesn't exist.
2026llvm::DIType CGDebugInfo::getCompletedTypeOrNull(QualType Ty) {
2027
2028 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00002029 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00002030
2031 // Check for existing entry.
Adrian Prantla03a85a2013-03-06 22:03:30 +00002032 llvm::Value *V = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00002033 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
2034 CompletedTypeCache.find(Ty.getAsOpaquePtr());
Adrian Prantla03a85a2013-03-06 22:03:30 +00002035 if (it != CompletedTypeCache.end())
2036 V = it->second;
2037 else {
Adrian Prantl73409ce2013-03-11 18:33:46 +00002038 V = getCachedInterfaceTypeOrNull(Ty);
Guy Benyei11169dd2012-12-18 14:30:41 +00002039 }
2040
Adrian Prantla03a85a2013-03-06 22:03:30 +00002041 // Verify that any cached debug info still exists.
David Blaikie80d28de2013-08-13 04:21:38 +00002042 return llvm::DIType(cast_or_null<llvm::MDNode>(V));
Guy Benyei11169dd2012-12-18 14:30:41 +00002043}
2044
David Blaikie0e716b42014-03-03 23:48:23 +00002045void CGDebugInfo::completeTemplateDefinition(
2046 const ClassTemplateSpecializationDecl &SD) {
David Blaikie0856f662014-03-04 22:01:08 +00002047 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
2048 return;
2049
David Blaikie0e716b42014-03-03 23:48:23 +00002050 completeClassData(&SD);
2051 // In case this type has no member function definitions being emitted, ensure
2052 // it is retained
2053 RetainedTypes.push_back(CGM.getContext().getRecordType(&SD).getAsOpaquePtr());
2054}
2055
Adrian Prantl73409ce2013-03-11 18:33:46 +00002056/// getCachedInterfaceTypeOrNull - Get the type from the interface
2057/// cache, unless it needs to regenerated. Otherwise return null.
2058llvm::Value *CGDebugInfo::getCachedInterfaceTypeOrNull(QualType Ty) {
2059 // Is there a cached interface that hasn't changed?
2060 llvm::DenseMap<void *, std::pair<llvm::WeakVH, unsigned > >
2061 ::iterator it1 = ObjCInterfaceCache.find(Ty.getAsOpaquePtr());
2062
2063 if (it1 != ObjCInterfaceCache.end())
2064 if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty))
2065 if (Checksum(Decl) == it1->second.second)
2066 // Return cached forward declaration.
2067 return it1->second.first;
2068
2069 return 0;
2070}
Guy Benyei11169dd2012-12-18 14:30:41 +00002071
2072/// getOrCreateType - Get the type from the cache or create a new
2073/// one if necessary.
David Blaikie99dab3b2013-09-04 22:03:57 +00002074llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002075 if (Ty.isNull())
2076 return llvm::DIType();
2077
2078 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00002079 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00002080
David Blaikie99dab3b2013-09-04 22:03:57 +00002081 if (llvm::DIType T = getCompletedTypeOrNull(Ty))
Guy Benyei11169dd2012-12-18 14:30:41 +00002082 return T;
2083
2084 // Otherwise create the type.
David Blaikie99dab3b2013-09-04 22:03:57 +00002085 llvm::DIType Res = CreateTypeNode(Ty, Unit);
Adrian Prantl73409ce2013-03-11 18:33:46 +00002086 void* TyPtr = Ty.getAsOpaquePtr();
2087
2088 // And update the type cache.
2089 TypeCache[TyPtr] = Res;
Guy Benyei11169dd2012-12-18 14:30:41 +00002090
David Blaikie6a723442013-08-15 21:21:19 +00002091 // FIXME: this getTypeOrNull call seems silly when we just inserted the type
2092 // into the cache - but getTypeOrNull has a special case for cached interface
2093 // types. We should probably just pull that out as a special case for the
2094 // "else" block below & skip the otherwise needless lookup.
Guy Benyei11169dd2012-12-18 14:30:41 +00002095 llvm::DIType TC = getTypeOrNull(Ty);
Eric Christopherf8bc4d82013-07-18 00:52:50 +00002096 if (TC && TC.isForwardDecl())
Adrian Prantl73409ce2013-03-11 18:33:46 +00002097 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
2098 else if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty)) {
2099 // Interface types may have elements added to them by a
2100 // subsequent implementation or extension, so we keep them in
2101 // the ObjCInterfaceCache together with a checksum. Instead of
Adrian Prantlc20237d2013-05-08 23:37:22 +00002102 // the (possibly) incomplete interface type, we return a forward
Adrian Prantl73409ce2013-03-11 18:33:46 +00002103 // declaration that gets RAUW'd in CGDebugInfo::finalize().
David Blaikie8e5939b2013-05-21 18:29:40 +00002104 std::pair<llvm::WeakVH, unsigned> &V = ObjCInterfaceCache[TyPtr];
2105 if (V.first)
2106 return llvm::DIType(cast<llvm::MDNode>(V.first));
2107 TC = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
2108 Decl->getName(), TheCU, Unit,
2109 getLineNumber(Decl->getLocation()),
2110 TheCU.getLanguage());
2111 // Store the forward declaration in the cache.
2112 V.first = TC;
2113 V.second = Checksum(Decl);
Adrian Prantl73409ce2013-03-11 18:33:46 +00002114
David Blaikie8e5939b2013-05-21 18:29:40 +00002115 // Register the type for replacement in finalize().
2116 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
2117
Adrian Prantl73409ce2013-03-11 18:33:46 +00002118 return TC;
Adrian Prantla03a85a2013-03-06 22:03:30 +00002119 }
2120
Guy Benyei11169dd2012-12-18 14:30:41 +00002121 if (!Res.isForwardDecl())
Adrian Prantl73409ce2013-03-11 18:33:46 +00002122 CompletedTypeCache[TyPtr] = Res;
Guy Benyei11169dd2012-12-18 14:30:41 +00002123
2124 return Res;
2125}
2126
Adrian Prantlc4de1ef2013-06-07 01:10:41 +00002127/// Currently the checksum of an interface includes the number of
2128/// ivars and property accessors.
Eric Christopher1ecc5632013-06-07 22:54:39 +00002129unsigned CGDebugInfo::Checksum(const ObjCInterfaceDecl *ID) {
Adrian Prantl817bbb32013-06-07 01:10:48 +00002130 // The assumption is that the number of ivars can only increase
2131 // monotonically, so it is safe to just use their current number as
2132 // a checksum.
Adrian Prantlc4de1ef2013-06-07 01:10:41 +00002133 unsigned Sum = 0;
2134 for (const ObjCIvarDecl *Ivar = ID->all_declared_ivar_begin();
2135 Ivar != 0; Ivar = Ivar->getNextIvar())
2136 ++Sum;
2137
2138 return Sum;
Adrian Prantla03a85a2013-03-06 22:03:30 +00002139}
2140
2141ObjCInterfaceDecl *CGDebugInfo::getObjCInterfaceDecl(QualType Ty) {
2142 switch (Ty->getTypeClass()) {
2143 case Type::ObjCObjectPointer:
Eric Christopher0fdcb312013-05-16 00:52:20 +00002144 return getObjCInterfaceDecl(cast<ObjCObjectPointerType>(Ty)
2145 ->getPointeeType());
Adrian Prantla03a85a2013-03-06 22:03:30 +00002146 case Type::ObjCInterface:
2147 return cast<ObjCInterfaceType>(Ty)->getDecl();
2148 default:
2149 return 0;
2150 }
2151}
2152
Guy Benyei11169dd2012-12-18 14:30:41 +00002153/// CreateTypeNode - Create a new debug type node.
David Blaikie99dab3b2013-09-04 22:03:57 +00002154llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002155 // Handle qualifiers, which recursively handles what they refer to.
2156 if (Ty.hasLocalQualifiers())
David Blaikie99dab3b2013-09-04 22:03:57 +00002157 return CreateQualifiedType(Ty, Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00002158
2159 const char *Diag = 0;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002160
Guy Benyei11169dd2012-12-18 14:30:41 +00002161 // Work out details of type.
2162 switch (Ty->getTypeClass()) {
2163#define TYPE(Class, Base)
2164#define ABSTRACT_TYPE(Class, Base)
2165#define NON_CANONICAL_TYPE(Class, Base)
2166#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2167#include "clang/AST/TypeNodes.def"
2168 llvm_unreachable("Dependent types cannot show up in debug information");
2169
2170 case Type::ExtVector:
2171 case Type::Vector:
2172 return CreateType(cast<VectorType>(Ty), Unit);
2173 case Type::ObjCObjectPointer:
2174 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
2175 case Type::ObjCObject:
2176 return CreateType(cast<ObjCObjectType>(Ty), Unit);
2177 case Type::ObjCInterface:
2178 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
2179 case Type::Builtin:
2180 return CreateType(cast<BuiltinType>(Ty));
2181 case Type::Complex:
2182 return CreateType(cast<ComplexType>(Ty));
2183 case Type::Pointer:
2184 return CreateType(cast<PointerType>(Ty), Unit);
Reid Kleckner0503a872013-12-05 01:23:43 +00002185 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00002186 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00002187 // Decayed and adjusted types use the adjusted type in LLVM and DWARF.
Reid Kleckner8a365022013-06-24 17:51:48 +00002188 return CreateType(
Reid Kleckner0503a872013-12-05 01:23:43 +00002189 cast<PointerType>(cast<AdjustedType>(Ty)->getAdjustedType()), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00002190 case Type::BlockPointer:
2191 return CreateType(cast<BlockPointerType>(Ty), Unit);
2192 case Type::Typedef:
David Blaikie99dab3b2013-09-04 22:03:57 +00002193 return CreateType(cast<TypedefType>(Ty), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00002194 case Type::Record:
David Blaikie99dab3b2013-09-04 22:03:57 +00002195 return CreateType(cast<RecordType>(Ty));
Guy Benyei11169dd2012-12-18 14:30:41 +00002196 case Type::Enum:
Manman Ren1b457022013-08-28 21:20:28 +00002197 return CreateEnumType(cast<EnumType>(Ty));
Guy Benyei11169dd2012-12-18 14:30:41 +00002198 case Type::FunctionProto:
2199 case Type::FunctionNoProto:
2200 return CreateType(cast<FunctionType>(Ty), Unit);
2201 case Type::ConstantArray:
2202 case Type::VariableArray:
2203 case Type::IncompleteArray:
2204 return CreateType(cast<ArrayType>(Ty), Unit);
2205
2206 case Type::LValueReference:
2207 return CreateType(cast<LValueReferenceType>(Ty), Unit);
2208 case Type::RValueReference:
2209 return CreateType(cast<RValueReferenceType>(Ty), Unit);
2210
2211 case Type::MemberPointer:
2212 return CreateType(cast<MemberPointerType>(Ty), Unit);
2213
2214 case Type::Atomic:
2215 return CreateType(cast<AtomicType>(Ty), Unit);
2216
Guy Benyei11169dd2012-12-18 14:30:41 +00002217 case Type::TemplateSpecialization:
David Blaikief1b382e2014-04-06 17:14:06 +00002218 return CreateType(cast<TemplateSpecializationType>(Ty), Unit);
2219
2220 case Type::Attributed:
Guy Benyei11169dd2012-12-18 14:30:41 +00002221 case Type::Elaborated:
2222 case Type::Paren:
2223 case Type::SubstTemplateTypeParm:
2224 case Type::TypeOfExpr:
2225 case Type::TypeOf:
2226 case Type::Decltype:
2227 case Type::UnaryTransform:
David Blaikie66ed89d2013-07-13 21:08:08 +00002228 case Type::PackExpansion:
Guy Benyei11169dd2012-12-18 14:30:41 +00002229 llvm_unreachable("type should have been unwrapped!");
David Blaikie22c460a02013-05-24 21:24:35 +00002230 case Type::Auto:
2231 Diag = "auto";
2232 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002233 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00002234
Guy Benyei11169dd2012-12-18 14:30:41 +00002235 assert(Diag && "Fall through without a diagnostic?");
2236 unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error,
2237 "debug information for %0 is not yet supported");
2238 CGM.getDiags().Report(DiagID)
2239 << Diag;
2240 return llvm::DIType();
2241}
2242
2243/// getOrCreateLimitedType - Get the type from the cache or create a new
2244/// limited type if necessary.
David Blaikie4a2b5ef2013-08-12 22:24:20 +00002245llvm::DIType CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty,
Eric Christopherc0c5d462013-02-21 22:35:08 +00002246 llvm::DIFile Unit) {
David Blaikie4a2b5ef2013-08-12 22:24:20 +00002247 QualType QTy(Ty, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00002248
David Blaikie8d5e1282013-08-20 21:03:29 +00002249 llvm::DICompositeType T(getTypeOrNull(QTy));
Guy Benyei11169dd2012-12-18 14:30:41 +00002250
2251 // We may have cached a forward decl when we could have created
2252 // a non-forward decl. Go ahead and create a non-forward decl
2253 // now.
Eric Christopherf8bc4d82013-07-18 00:52:50 +00002254 if (T && !T.isForwardDecl()) return T;
Guy Benyei11169dd2012-12-18 14:30:41 +00002255
2256 // Otherwise create the type.
David Blaikie8d5e1282013-08-20 21:03:29 +00002257 llvm::DICompositeType Res = CreateLimitedType(Ty);
2258
2259 // Propagate members from the declaration to the definition
2260 // CreateType(const RecordType*) will overwrite this with the members in the
2261 // correct order if the full type is needed.
2262 Res.setTypeArray(T.getTypeArray());
Guy Benyei11169dd2012-12-18 14:30:41 +00002263
Eric Christopherf8bc4d82013-07-18 00:52:50 +00002264 if (T && T.isForwardDecl())
David Blaikie4a2b5ef2013-08-12 22:24:20 +00002265 ReplaceMap.push_back(
2266 std::make_pair(QTy.getAsOpaquePtr(), static_cast<llvm::Value *>(T)));
Guy Benyei11169dd2012-12-18 14:30:41 +00002267
2268 // And update the type cache.
David Blaikie4a2b5ef2013-08-12 22:24:20 +00002269 TypeCache[QTy.getAsOpaquePtr()] = Res;
Guy Benyei11169dd2012-12-18 14:30:41 +00002270 return Res;
2271}
2272
2273// TODO: Currently used for context chains when limiting debug info.
David Blaikie8d5e1282013-08-20 21:03:29 +00002274llvm::DICompositeType CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002275 RecordDecl *RD = Ty->getDecl();
Eric Christopherb2a008c2013-05-16 00:45:12 +00002276
Guy Benyei11169dd2012-12-18 14:30:41 +00002277 // Get overall information about the record type for the debug info.
2278 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
2279 unsigned Line = getLineNumber(RD->getLocation());
2280 StringRef RDName = getClassName(RD);
2281
Eric Christopher07429ff2013-10-15 21:22:34 +00002282 llvm::DIDescriptor RDContext =
2283 getContextDescriptor(cast<Decl>(RD->getDeclContext()));
Guy Benyei11169dd2012-12-18 14:30:41 +00002284
David Blaikied2785892013-08-18 17:36:19 +00002285 // If we ended up creating the type during the context chain construction,
2286 // just return that.
2287 // FIXME: this could be dealt with better if the type was recorded as
2288 // completed before we started this (see the CompletedTypeCache usage in
2289 // CGDebugInfo::CreateTypeDefinition(const RecordType*) - that would need to
2290 // be pushed to before context creation, but after it was known to be
2291 // destined for completion (might still have an issue if this caller only
2292 // required a declaration but the context construction ended up creating a
2293 // definition)
David Blaikie8d5e1282013-08-20 21:03:29 +00002294 llvm::DICompositeType T(getTypeOrNull(CGM.getContext().getRecordType(RD)));
2295 if (T && (!T.isForwardDecl() || !RD->getDefinition()))
David Blaikied2785892013-08-18 17:36:19 +00002296 return T;
2297
Adrian Prantl381e7552014-02-04 21:29:50 +00002298 // If this is just a forward or incomplete declaration, construct an
2299 // appropriately marked node and just return it.
2300 const RecordDecl *D = RD->getDefinition();
2301 if (!D || !D->isCompleteDefinition())
Manman Ren1b457022013-08-28 21:20:28 +00002302 return getOrCreateRecordFwdDecl(Ty, RDContext);
Guy Benyei11169dd2012-12-18 14:30:41 +00002303
2304 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2305 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
David Blaikie49ae6a72013-03-26 23:47:35 +00002306 llvm::DICompositeType RealDecl;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002307
Manman Rene0064d82013-08-29 23:19:58 +00002308 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
2309
Guy Benyei11169dd2012-12-18 14:30:41 +00002310 if (RD->isUnion())
2311 RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
Manman Rene0064d82013-08-29 23:19:58 +00002312 Size, Align, 0, llvm::DIArray(), 0,
2313 FullName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002314 else if (RD->isClass()) {
2315 // FIXME: This could be a struct type giving a default visibility different
2316 // than C++ class type, but needs llvm metadata changes first.
2317 RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
Eric Christopherc0c5d462013-02-21 22:35:08 +00002318 Size, Align, 0, 0, llvm::DIType(),
2319 llvm::DIArray(), llvm::DIType(),
Manman Rene0064d82013-08-29 23:19:58 +00002320 llvm::DIArray(), FullName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002321 } else
2322 RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line,
Eric Christopher0fdcb312013-05-16 00:52:20 +00002323 Size, Align, 0, llvm::DIType(),
David Blaikieba477362013-11-18 23:38:26 +00002324 llvm::DIArray(), 0, llvm::DIType(),
2325 FullName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002326
2327 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
David Blaikie49ae6a72013-03-26 23:47:35 +00002328 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00002329
David Blaikieadfbf992013-08-18 16:55:33 +00002330 if (const ClassTemplateSpecializationDecl *TSpecial =
2331 dyn_cast<ClassTemplateSpecializationDecl>(RD))
2332 RealDecl.setTypeArray(llvm::DIArray(),
2333 CollectCXXTemplateParams(TSpecial, DefUnit));
David Blaikie952dac32013-08-15 22:42:12 +00002334 return RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00002335}
2336
David Blaikieadfbf992013-08-18 16:55:33 +00002337void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,
2338 llvm::DICompositeType RealDecl) {
2339 // A class's primary base or the class itself contains the vtable.
2340 llvm::DICompositeType ContainingType;
2341 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2342 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
Alp Tokerd4733632013-12-05 04:47:09 +00002343 // Seek non-virtual primary base root.
David Blaikieadfbf992013-08-18 16:55:33 +00002344 while (1) {
2345 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
2346 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
2347 if (PBT && !BRL.isPrimaryBaseVirtual())
2348 PBase = PBT;
2349 else
2350 break;
2351 }
2352 ContainingType = llvm::DICompositeType(
2353 getOrCreateType(QualType(PBase->getTypeForDecl(), 0),
2354 getOrCreateFile(RD->getLocation())));
2355 } else if (RD->isDynamicClass())
2356 ContainingType = RealDecl;
2357
2358 RealDecl.setContainingType(ContainingType);
2359}
2360
Guy Benyei11169dd2012-12-18 14:30:41 +00002361/// CreateMemberType - Create new member and increase Offset by FType's size.
2362llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
2363 StringRef Name,
2364 uint64_t *Offset) {
2365 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2366 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
2367 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
2368 llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0,
2369 FieldSize, FieldAlign,
2370 *Offset, 0, FieldTy);
2371 *Offset += FieldSize;
2372 return Ty;
2373}
2374
Adrian Prantl6cdce9e2014-04-01 03:41:01 +00002375llvm::DIScope CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
David Blaikiebd483762013-05-20 04:58:53 +00002376 // We only need a declaration (not a definition) of the type - so use whatever
2377 // we would otherwise do to get a type for a pointee. (forward declarations in
2378 // limited debug info, full definitions (if the type definition is available)
2379 // in unlimited debug info)
David Blaikie6b7d060c2013-08-12 23:14:36 +00002380 if (const TypeDecl *TD = dyn_cast<TypeDecl>(D))
2381 return getOrCreateType(CGM.getContext().getTypeDeclType(TD),
David Blaikie99dab3b2013-09-04 22:03:57 +00002382 getOrCreateFile(TD->getLocation()));
David Blaikiebd483762013-05-20 04:58:53 +00002383 // Otherwise fall back to a fairly rudimentary cache of existing declarations.
2384 // This doesn't handle providing declarations (for functions or variables) for
2385 // entities without definitions in this TU, nor when the definition proceeds
2386 // the call to this function.
2387 // FIXME: This should be split out into more specific maps with support for
2388 // emitting forward declarations and merging definitions with declarations,
2389 // the same way as we do for types.
2390 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator I =
2391 DeclCache.find(D->getCanonicalDecl());
2392 if (I == DeclCache.end())
Adrian Prantl6cdce9e2014-04-01 03:41:01 +00002393 return llvm::DIScope();
David Blaikiebd483762013-05-20 04:58:53 +00002394 llvm::Value *V = I->second;
Adrian Prantl6cdce9e2014-04-01 03:41:01 +00002395 return llvm::DIScope(dyn_cast_or_null<llvm::MDNode>(V));
David Blaikiebd483762013-05-20 04:58:53 +00002396}
2397
Guy Benyei11169dd2012-12-18 14:30:41 +00002398/// getFunctionDeclaration - Return debug info descriptor to describe method
2399/// declaration for the given method definition.
2400llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
David Blaikie18cfbc52013-06-22 00:09:36 +00002401 if (!D || DebugKind == CodeGenOptions::DebugLineTablesOnly)
2402 return llvm::DISubprogram();
2403
Guy Benyei11169dd2012-12-18 14:30:41 +00002404 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
2405 if (!FD) return llvm::DISubprogram();
2406
2407 // Setup context.
David Blaikiefd07c602013-08-09 17:20:05 +00002408 llvm::DIScope S = getContextDescriptor(cast<Decl>(D->getDeclContext()));
Guy Benyei11169dd2012-12-18 14:30:41 +00002409
2410 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2411 MI = SPCache.find(FD->getCanonicalDecl());
David Blaikiefd07c602013-08-09 17:20:05 +00002412 if (MI == SPCache.end()) {
Eric Christopherf86c4052013-08-28 23:12:10 +00002413 if (const CXXMethodDecl *MD =
2414 dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
David Blaikiefd07c602013-08-09 17:20:05 +00002415 llvm::DICompositeType T(S);
Eric Christopherf86c4052013-08-28 23:12:10 +00002416 llvm::DISubprogram SP =
2417 CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()), T);
David Blaikiefd07c602013-08-09 17:20:05 +00002418 return SP;
2419 }
2420 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002421 if (MI != SPCache.end()) {
2422 llvm::Value *V = MI->second;
2423 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
David Blaikie18cfbc52013-06-22 00:09:36 +00002424 if (SP.isSubprogram() && !SP.isDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00002425 return SP;
2426 }
2427
Aaron Ballman86c93902014-03-06 23:45:36 +00002428 for (auto NextFD : FD->redecls()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002429 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2430 MI = SPCache.find(NextFD->getCanonicalDecl());
2431 if (MI != SPCache.end()) {
2432 llvm::Value *V = MI->second;
2433 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
David Blaikie18cfbc52013-06-22 00:09:36 +00002434 if (SP.isSubprogram() && !SP.isDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00002435 return SP;
2436 }
2437 }
2438 return llvm::DISubprogram();
2439}
2440
2441// getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
2442// implicit parameter "this".
David Blaikie469f0792013-05-22 23:22:42 +00002443llvm::DICompositeType CGDebugInfo::getOrCreateFunctionType(const Decl *D,
2444 QualType FnType,
2445 llvm::DIFile F) {
David Blaikie18cfbc52013-06-22 00:09:36 +00002446 if (!D || DebugKind == CodeGenOptions::DebugLineTablesOnly)
2447 // Create fake but valid subroutine type. Otherwise
2448 // llvm::DISubprogram::Verify() would return false, and
2449 // subprogram DIE will miss DW_AT_decl_file and
2450 // DW_AT_decl_line fields.
2451 return DBuilder.createSubroutineType(F, DBuilder.getOrCreateArray(None));
Guy Benyei11169dd2012-12-18 14:30:41 +00002452
2453 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
2454 return getOrCreateMethodType(Method, F);
2455 if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
2456 // Add "self" and "_cmd"
2457 SmallVector<llvm::Value *, 16> Elts;
2458
2459 // First element is always return type. For 'void' functions it is NULL.
Alp Toker314cc812014-01-25 16:55:45 +00002460 QualType ResultTy = OMethod->getReturnType();
Adrian Prantl5f360102013-05-22 21:37:49 +00002461
2462 // Replace the instancetype keyword with the actual type.
2463 if (ResultTy == CGM.getContext().getObjCInstanceType())
2464 ResultTy = CGM.getContext().getPointerType(
2465 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
2466
Adrian Prantl7bec9032013-05-10 21:08:31 +00002467 Elts.push_back(getOrCreateType(ResultTy, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002468 // "self" pointer is always first argument.
Adrian Prantlde17db32013-03-29 19:20:29 +00002469 QualType SelfDeclTy = OMethod->getSelfDecl()->getType();
2470 llvm::DIType SelfTy = getOrCreateType(SelfDeclTy, F);
2471 Elts.push_back(CreateSelfType(SelfDeclTy, SelfTy));
Guy Benyei11169dd2012-12-18 14:30:41 +00002472 // "_cmd" pointer is always second argument.
2473 llvm::DIType CmdTy = getOrCreateType(OMethod->getCmdDecl()->getType(), F);
2474 Elts.push_back(DBuilder.createArtificialType(CmdTy));
2475 // Get rest of the arguments.
Aaron Ballman43b68be2014-03-07 17:50:17 +00002476 for (const auto *PI : OMethod->params())
2477 Elts.push_back(getOrCreateType(PI->getType(), F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002478
2479 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2480 return DBuilder.createSubroutineType(F, EltTypeArray);
2481 }
Adrian Prantld45ba252014-02-25 19:38:11 +00002482
Adrian Prantl800faef2014-02-25 23:42:18 +00002483 // Handle variadic function types; they need an additional
2484 // unspecified parameter.
Adrian Prantld45ba252014-02-25 19:38:11 +00002485 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2486 if (FD->isVariadic()) {
2487 SmallVector<llvm::Value *, 16> EltTys;
2488 EltTys.push_back(getOrCreateType(FD->getReturnType(), F));
2489 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FnType))
2490 for (unsigned i = 0, e = FPT->getNumParams(); i != e; ++i)
2491 EltTys.push_back(getOrCreateType(FPT->getParamType(i), F));
2492 EltTys.push_back(DBuilder.createUnspecifiedParameter());
2493 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
2494 return DBuilder.createSubroutineType(F, EltTypeArray);
2495 }
2496
David Blaikie469f0792013-05-22 23:22:42 +00002497 return llvm::DICompositeType(getOrCreateType(FnType, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002498}
2499
2500/// EmitFunctionStart - Constructs the debug code for entering a function.
Adrian Prantl42d71b92014-04-10 23:21:53 +00002501void CGDebugInfo::EmitFunctionStart(GlobalDecl GD,
2502 SourceLocation Loc,
2503 SourceLocation ScopeLoc,
2504 QualType FnType,
Guy Benyei11169dd2012-12-18 14:30:41 +00002505 llvm::Function *Fn,
2506 CGBuilderTy &Builder) {
2507
2508 StringRef Name;
2509 StringRef LinkageName;
2510
2511 FnBeginRegionCount.push_back(LexicalBlockStack.size());
2512
2513 const Decl *D = GD.getDecl();
Guy Benyei11169dd2012-12-18 14:30:41 +00002514 bool HasDecl = (D != 0);
Eric Christopher885c41b2014-04-01 22:25:28 +00002515
Guy Benyei11169dd2012-12-18 14:30:41 +00002516 unsigned Flags = 0;
2517 llvm::DIFile Unit = getOrCreateFile(Loc);
2518 llvm::DIDescriptor FDContext(Unit);
2519 llvm::DIArray TParamsArray;
2520 if (!HasDecl) {
2521 // Use llvm function name.
David Blaikieebe87e12013-08-27 23:57:18 +00002522 LinkageName = Fn->getName();
Guy Benyei11169dd2012-12-18 14:30:41 +00002523 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2524 // If there is a DISubprogram for this function available then use it.
2525 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2526 FI = SPCache.find(FD->getCanonicalDecl());
2527 if (FI != SPCache.end()) {
2528 llvm::Value *V = FI->second;
2529 llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(V));
2530 if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
2531 llvm::MDNode *SPN = SP;
2532 LexicalBlockStack.push_back(SPN);
2533 RegionMap[D] = llvm::WeakVH(SP);
2534 return;
2535 }
2536 }
2537 Name = getFunctionName(FD);
Nick Lewyckyc02bbb62013-03-20 01:38:16 +00002538 // Use mangled name as linkage name for C/C++ functions.
Guy Benyei11169dd2012-12-18 14:30:41 +00002539 if (FD->hasPrototype()) {
2540 LinkageName = CGM.getMangledName(GD);
2541 Flags |= llvm::DIDescriptor::FlagPrototyped;
2542 }
Nick Lewyckyc02bbb62013-03-20 01:38:16 +00002543 // No need to replicate the linkage name if it isn't different from the
2544 // subprogram name, no need to have it at all unless coverage is enabled or
2545 // debug is set to more than just line tables.
Guy Benyei11169dd2012-12-18 14:30:41 +00002546 if (LinkageName == Name ||
Nick Lewyckyc02bbb62013-03-20 01:38:16 +00002547 (!CGM.getCodeGenOpts().EmitGcovArcs &&
2548 !CGM.getCodeGenOpts().EmitGcovNotes &&
Eric Christopher75e17682013-05-16 00:45:23 +00002549 DebugKind <= CodeGenOptions::DebugLineTablesOnly))
Guy Benyei11169dd2012-12-18 14:30:41 +00002550 LinkageName = StringRef();
2551
Eric Christopher75e17682013-05-16 00:45:23 +00002552 if (DebugKind >= CodeGenOptions::LimitedDebugInfo) {
Eric Christopher4cbd0d9d2014-03-27 05:29:34 +00002553 if (const NamespaceDecl *NSDecl =
2554 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
2555 FDContext = getOrCreateNameSpace(NSDecl);
2556 else if (const RecordDecl *RDecl =
2557 dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
2558 FDContext = getContextDescriptor(cast<Decl>(RDecl));
2559
2560 // Collect template parameters.
Guy Benyei11169dd2012-12-18 14:30:41 +00002561 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
2562 }
2563 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
2564 Name = getObjCMethodName(OMD);
2565 Flags |= llvm::DIDescriptor::FlagPrototyped;
2566 } else {
2567 // Use llvm function name.
2568 Name = Fn->getName();
2569 Flags |= llvm::DIDescriptor::FlagPrototyped;
2570 }
2571 if (!Name.empty() && Name[0] == '\01')
2572 Name = Name.substr(1);
2573
Adrian Prantl42d71b92014-04-10 23:21:53 +00002574 if (!HasDecl || D->isImplicit()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002575 Flags |= llvm::DIDescriptor::FlagArtificial;
Adrian Prantl42d71b92014-04-10 23:21:53 +00002576 // Artificial functions without a location should not silently reuse CurLoc.
2577 if (Loc.isInvalid())
2578 CurLoc = SourceLocation();
2579 }
2580 unsigned LineNo = getLineNumber(Loc);
2581 unsigned ScopeLine = getLineNumber(ScopeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00002582
Eric Christopher8018e412014-03-27 18:50:35 +00002583 // FIXME: The function declaration we're constructing here is mostly reusing
2584 // declarations from CXXMethodDecl and not constructing new ones for arbitrary
2585 // FunctionDecls. When/if we fix this we can have FDContext be TheCU/null for
2586 // all subprograms instead of the actual context since subprogram definitions
2587 // are emitted as CU level entities by the backend.
Eric Christopher9e6f5f92013-10-17 01:31:21 +00002588 llvm::DISubprogram SP =
2589 DBuilder.createFunction(FDContext, Name, LinkageName, Unit, LineNo,
2590 getOrCreateFunctionType(D, FnType, Unit),
2591 Fn->hasInternalLinkage(), true /*definition*/,
Adrian Prantl42d71b92014-04-10 23:21:53 +00002592 ScopeLine, Flags,
Eric Christopher9e6f5f92013-10-17 01:31:21 +00002593 CGM.getLangOpts().Optimize, Fn, TParamsArray,
2594 getFunctionDeclaration(D));
David Blaikiebd483762013-05-20 04:58:53 +00002595 if (HasDecl)
2596 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(SP)));
Guy Benyei11169dd2012-12-18 14:30:41 +00002597
Adrian Prantlbebb8932014-03-21 21:01:58 +00002598 // Push the function onto the lexical block stack.
Guy Benyei11169dd2012-12-18 14:30:41 +00002599 llvm::MDNode *SPN = SP;
2600 LexicalBlockStack.push_back(SPN);
Adrian Prantlbebb8932014-03-21 21:01:58 +00002601
Guy Benyei11169dd2012-12-18 14:30:41 +00002602 if (HasDecl)
2603 RegionMap[D] = llvm::WeakVH(SP);
2604}
2605
2606/// EmitLocation - Emit metadata to indicate a change in line/column
Adrian Prantl02c0caa2013-07-18 00:27:59 +00002607/// information in the source file. If the location is invalid, the
2608/// previous location will be reused.
Adrian Prantlc7822422013-03-12 20:43:25 +00002609void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc,
Adrian Prantle83b1302014-01-07 22:05:52 +00002610 bool ForceColumnInfo) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002611 // Update our current location
2612 setLocation(Loc);
2613
2614 if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
2615
2616 // Don't bother if things are the same as last time.
2617 SourceManager &SM = CGM.getContext().getSourceManager();
2618 if (CurLoc == PrevLoc ||
2619 SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc))
2620 // New Builder may not be in sync with CGDebugInfo.
David Blaikie357aafb2013-02-01 19:09:49 +00002621 if (!Builder.getCurrentDebugLocation().isUnknown() &&
2622 Builder.getCurrentDebugLocation().getScope(CGM.getLLVMContext()) ==
2623 LexicalBlockStack.back())
Guy Benyei11169dd2012-12-18 14:30:41 +00002624 return;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002625
Guy Benyei11169dd2012-12-18 14:30:41 +00002626 // Update last state.
2627 PrevLoc = CurLoc;
2628
Adrian Prantle83b1302014-01-07 22:05:52 +00002629 llvm::MDNode *Scope = LexicalBlockStack.back();
Adrian Prantlc7822422013-03-12 20:43:25 +00002630 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get
2631 (getLineNumber(CurLoc),
2632 getColumnNumber(CurLoc, ForceColumnInfo),
2633 Scope));
Guy Benyei11169dd2012-12-18 14:30:41 +00002634}
2635
2636/// CreateLexicalBlock - Creates a new lexical block node and pushes it on
2637/// the stack.
2638void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
2639 llvm::DIDescriptor D =
2640 DBuilder.createLexicalBlock(LexicalBlockStack.empty() ?
2641 llvm::DIDescriptor() :
2642 llvm::DIDescriptor(LexicalBlockStack.back()),
2643 getOrCreateFile(CurLoc),
2644 getLineNumber(CurLoc),
Diego Novilloe6d398182014-03-03 18:53:32 +00002645 getColumnNumber(CurLoc),
2646 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00002647 llvm::MDNode *DN = D;
2648 LexicalBlockStack.push_back(DN);
2649}
2650
2651/// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
2652/// region - beginning of a DW_TAG_lexical_block.
Eric Christopher0fdcb312013-05-16 00:52:20 +00002653void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
2654 SourceLocation Loc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002655 // Set our current location.
2656 setLocation(Loc);
2657
2658 // Create a new lexical block and push it on the stack.
2659 CreateLexicalBlock(Loc);
2660
2661 // Emit a line table change for the current location inside the new scope.
2662 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc),
2663 getColumnNumber(Loc),
2664 LexicalBlockStack.back()));
2665}
2666
2667/// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative
2668/// region - end of a DW_TAG_lexical_block.
Eric Christopher0fdcb312013-05-16 00:52:20 +00002669void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
2670 SourceLocation Loc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002671 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2672
2673 // Provide an entry in the line table for the end of the block.
2674 EmitLocation(Builder, Loc);
2675
2676 LexicalBlockStack.pop_back();
2677}
2678
2679/// EmitFunctionEnd - Constructs the debug code for exiting a function.
2680void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
2681 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2682 unsigned RCount = FnBeginRegionCount.back();
2683 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
2684
2685 // Pop all regions for this function.
2686 while (LexicalBlockStack.size() != RCount)
2687 EmitLexicalBlockEnd(Builder, CurLoc);
2688 FnBeginRegionCount.pop_back();
2689}
2690
Eric Christopherb2a008c2013-05-16 00:45:12 +00002691// EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
Guy Benyei11169dd2012-12-18 14:30:41 +00002692// See BuildByRefType.
2693llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
2694 uint64_t *XOffset) {
2695
2696 SmallVector<llvm::Value *, 5> EltTys;
2697 QualType FType;
2698 uint64_t FieldSize, FieldOffset;
2699 unsigned FieldAlign;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002700
Guy Benyei11169dd2012-12-18 14:30:41 +00002701 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
Eric Christopherb2a008c2013-05-16 00:45:12 +00002702 QualType Type = VD->getType();
Guy Benyei11169dd2012-12-18 14:30:41 +00002703
2704 FieldOffset = 0;
2705 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2706 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
2707 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
2708 FType = CGM.getContext().IntTy;
2709 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
2710 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
2711
2712 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
2713 if (HasCopyAndDispose) {
2714 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2715 EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
2716 &FieldOffset));
2717 EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
2718 &FieldOffset));
2719 }
2720 bool HasByrefExtendedLayout;
2721 Qualifiers::ObjCLifetime Lifetime;
2722 if (CGM.getContext().getByrefLifetime(Type,
2723 Lifetime, HasByrefExtendedLayout)
Adrian Prantlead2ba42013-07-23 00:12:14 +00002724 && HasByrefExtendedLayout) {
2725 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
Guy Benyei11169dd2012-12-18 14:30:41 +00002726 EltTys.push_back(CreateMemberType(Unit, FType,
2727 "__byref_variable_layout",
2728 &FieldOffset));
Adrian Prantlead2ba42013-07-23 00:12:14 +00002729 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00002730
Guy Benyei11169dd2012-12-18 14:30:41 +00002731 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2732 if (Align > CGM.getContext().toCharUnitsFromBits(
John McCallc8e01702013-04-16 22:48:15 +00002733 CGM.getTarget().getPointerAlign(0))) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00002734 CharUnits FieldOffsetInBytes
Guy Benyei11169dd2012-12-18 14:30:41 +00002735 = CGM.getContext().toCharUnitsFromBits(FieldOffset);
2736 CharUnits AlignedOffsetInBytes
2737 = FieldOffsetInBytes.RoundUpToAlignment(Align);
2738 CharUnits NumPaddingBytes
2739 = AlignedOffsetInBytes - FieldOffsetInBytes;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002740
Guy Benyei11169dd2012-12-18 14:30:41 +00002741 if (NumPaddingBytes.isPositive()) {
2742 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
2743 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
2744 pad, ArrayType::Normal, 0);
2745 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
2746 }
2747 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00002748
Guy Benyei11169dd2012-12-18 14:30:41 +00002749 FType = Type;
2750 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2751 FieldSize = CGM.getContext().getTypeSize(FType);
2752 FieldAlign = CGM.getContext().toBits(Align);
2753
Eric Christopherb2a008c2013-05-16 00:45:12 +00002754 *XOffset = FieldOffset;
Guy Benyei11169dd2012-12-18 14:30:41 +00002755 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit,
2756 0, FieldSize, FieldAlign,
2757 FieldOffset, 0, FieldTy);
2758 EltTys.push_back(FieldTy);
2759 FieldOffset += FieldSize;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002760
Guy Benyei11169dd2012-12-18 14:30:41 +00002761 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002762
Guy Benyei11169dd2012-12-18 14:30:41 +00002763 unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002764
Guy Benyei11169dd2012-12-18 14:30:41 +00002765 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
David Blaikie6d4fe152013-02-25 01:07:08 +00002766 llvm::DIType(), Elements);
Guy Benyei11169dd2012-12-18 14:30:41 +00002767}
2768
2769/// EmitDeclare - Emit local variable declaration debug info.
2770void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
Eric Christopherb2a008c2013-05-16 00:45:12 +00002771 llvm::Value *Storage,
Guy Benyei11169dd2012-12-18 14:30:41 +00002772 unsigned ArgNo, CGBuilderTy &Builder) {
Eric Christopher75e17682013-05-16 00:45:23 +00002773 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002774 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2775
David Blaikie7fceebf2013-08-19 03:37:48 +00002776 bool Unwritten =
2777 VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) &&
2778 cast<Decl>(VD->getDeclContext())->isImplicit());
2779 llvm::DIFile Unit;
2780 if (!Unwritten)
2781 Unit = getOrCreateFile(VD->getLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00002782 llvm::DIType Ty;
2783 uint64_t XOffset = 0;
2784 if (VD->hasAttr<BlocksAttr>())
2785 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002786 else
Guy Benyei11169dd2012-12-18 14:30:41 +00002787 Ty = getOrCreateType(VD->getType(), Unit);
2788
2789 // If there is no debug info for this type then do not emit debug info
2790 // for this variable.
2791 if (!Ty)
2792 return;
2793
Guy Benyei11169dd2012-12-18 14:30:41 +00002794 // Get location information.
David Blaikie7fceebf2013-08-19 03:37:48 +00002795 unsigned Line = 0;
2796 unsigned Column = 0;
2797 if (!Unwritten) {
2798 Line = getLineNumber(VD->getLocation());
2799 Column = getColumnNumber(VD->getLocation());
2800 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002801 unsigned Flags = 0;
2802 if (VD->isImplicit())
2803 Flags |= llvm::DIDescriptor::FlagArtificial;
2804 // If this is the first argument and it is implicit then
2805 // give it an object pointer flag.
2806 // FIXME: There has to be a better way to do this, but for static
2807 // functions there won't be an implicit param at arg1 and
2808 // otherwise it is 'self' or 'this'.
2809 if (isa<ImplicitParamDecl>(VD) && ArgNo == 1)
2810 Flags |= llvm::DIDescriptor::FlagObjectPointer;
David Blaikieb9c667d2013-06-19 21:53:53 +00002811 if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage))
Eric Christopherffdeb1e2013-07-17 22:52:53 +00002812 if (Arg->getType()->isPointerTy() && !Arg->hasByValAttr() &&
2813 !VD->getType()->isPointerType())
David Blaikieb9c667d2013-06-19 21:53:53 +00002814 Flags |= llvm::DIDescriptor::FlagIndirectVariable;
Guy Benyei11169dd2012-12-18 14:30:41 +00002815
2816 llvm::MDNode *Scope = LexicalBlockStack.back();
2817
2818 StringRef Name = VD->getName();
2819 if (!Name.empty()) {
2820 if (VD->hasAttr<BlocksAttr>()) {
2821 CharUnits offset = CharUnits::fromQuantity(32);
2822 SmallVector<llvm::Value *, 9> addr;
2823 llvm::Type *Int64Ty = CGM.Int64Ty;
2824 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2825 // offset of __forwarding field
2826 offset = CGM.getContext().toCharUnitsFromBits(
John McCallc8e01702013-04-16 22:48:15 +00002827 CGM.getTarget().getPointerWidth(0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002828 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2829 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2830 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2831 // offset of x field
2832 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2833 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2834
2835 // Create the descriptor for the variable.
2836 llvm::DIVariable D =
Eric Christopherb2a008c2013-05-16 00:45:12 +00002837 DBuilder.createComplexVariable(Tag,
Guy Benyei11169dd2012-12-18 14:30:41 +00002838 llvm::DIDescriptor(Scope),
2839 VD->getName(), Unit, Line, Ty,
2840 addr, ArgNo);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002841
Guy Benyei11169dd2012-12-18 14:30:41 +00002842 // Insert an llvm.dbg.declare into the current block.
2843 llvm::Instruction *Call =
2844 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2845 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2846 return;
Adrian Prantl7f2ef222013-09-18 22:18:17 +00002847 } else if (isa<VariableArrayType>(VD->getType()))
Adrian Prantl0315f382013-09-18 22:08:57 +00002848 Flags |= llvm::DIDescriptor::FlagIndirectVariable;
David Blaikiea76a7c92013-01-05 05:58:35 +00002849 } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2850 // If VD is an anonymous union then Storage represents value for
2851 // all union fields.
Guy Benyei11169dd2012-12-18 14:30:41 +00002852 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
David Blaikie219c7d92013-01-05 20:03:07 +00002853 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00002854 for (const auto *Field : RD->fields()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002855 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2856 StringRef FieldName = Field->getName();
Eric Christopherb2a008c2013-05-16 00:45:12 +00002857
Guy Benyei11169dd2012-12-18 14:30:41 +00002858 // Ignore unnamed fields. Do not ignore unnamed records.
2859 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2860 continue;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002861
Guy Benyei11169dd2012-12-18 14:30:41 +00002862 // Use VarDecl's Tag, Scope and Line number.
2863 llvm::DIVariable D =
2864 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
Eric Christopherb2a008c2013-05-16 00:45:12 +00002865 FieldName, Unit, Line, FieldTy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002866 CGM.getLangOpts().Optimize, Flags,
2867 ArgNo);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002868
Guy Benyei11169dd2012-12-18 14:30:41 +00002869 // Insert an llvm.dbg.declare into the current block.
2870 llvm::Instruction *Call =
2871 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2872 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2873 }
David Blaikie219c7d92013-01-05 20:03:07 +00002874 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00002875 }
2876 }
David Blaikiea76a7c92013-01-05 05:58:35 +00002877
2878 // Create the descriptor for the variable.
2879 llvm::DIVariable D =
2880 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2881 Name, Unit, Line, Ty,
2882 CGM.getLangOpts().Optimize, Flags, ArgNo);
2883
2884 // Insert an llvm.dbg.declare into the current block.
2885 llvm::Instruction *Call =
2886 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2887 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
Guy Benyei11169dd2012-12-18 14:30:41 +00002888}
2889
2890void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2891 llvm::Value *Storage,
2892 CGBuilderTy &Builder) {
Eric Christopher75e17682013-05-16 00:45:23 +00002893 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002894 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2895}
2896
Adrian Prantlde17db32013-03-29 19:20:29 +00002897/// Look up the completed type for a self pointer in the TypeCache and
2898/// create a copy of it with the ObjectPointer and Artificial flags
2899/// set. If the type is not cached, a new one is created. This should
2900/// never happen though, since creating a type for the implicit self
2901/// argument implies that we already parsed the interface definition
2902/// and the ivar declarations in the implementation.
Eric Christopher0fdcb312013-05-16 00:52:20 +00002903llvm::DIType CGDebugInfo::CreateSelfType(const QualType &QualTy,
2904 llvm::DIType Ty) {
Adrian Prantlde17db32013-03-29 19:20:29 +00002905 llvm::DIType CachedTy = getTypeOrNull(QualTy);
Eric Christopherf8bc4d82013-07-18 00:52:50 +00002906 if (CachedTy) Ty = CachedTy;
Adrian Prantlde17db32013-03-29 19:20:29 +00002907 return DBuilder.createObjectPointerType(Ty);
2908}
2909
Guy Benyei11169dd2012-12-18 14:30:41 +00002910void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(const VarDecl *VD,
2911 llvm::Value *Storage,
2912 CGBuilderTy &Builder,
2913 const CGBlockInfo &blockInfo) {
Eric Christopher75e17682013-05-16 00:45:23 +00002914 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002915 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
Eric Christopherb2a008c2013-05-16 00:45:12 +00002916
Guy Benyei11169dd2012-12-18 14:30:41 +00002917 if (Builder.GetInsertBlock() == 0)
2918 return;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002919
Guy Benyei11169dd2012-12-18 14:30:41 +00002920 bool isByRef = VD->hasAttr<BlocksAttr>();
Eric Christopherb2a008c2013-05-16 00:45:12 +00002921
Guy Benyei11169dd2012-12-18 14:30:41 +00002922 uint64_t XOffset = 0;
2923 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2924 llvm::DIType Ty;
2925 if (isByRef)
2926 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002927 else
Guy Benyei11169dd2012-12-18 14:30:41 +00002928 Ty = getOrCreateType(VD->getType(), Unit);
2929
2930 // Self is passed along as an implicit non-arg variable in a
2931 // block. Mark it as the object pointer.
2932 if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self")
Adrian Prantlde17db32013-03-29 19:20:29 +00002933 Ty = CreateSelfType(VD->getType(), Ty);
Guy Benyei11169dd2012-12-18 14:30:41 +00002934
2935 // Get location information.
2936 unsigned Line = getLineNumber(VD->getLocation());
2937 unsigned Column = getColumnNumber(VD->getLocation());
2938
2939 const llvm::DataLayout &target = CGM.getDataLayout();
2940
2941 CharUnits offset = CharUnits::fromQuantity(
2942 target.getStructLayout(blockInfo.StructureType)
2943 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2944
2945 SmallVector<llvm::Value *, 9> addr;
2946 llvm::Type *Int64Ty = CGM.Int64Ty;
Adrian Prantl0f6df002013-03-29 19:20:35 +00002947 if (isa<llvm::AllocaInst>(Storage))
2948 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
Guy Benyei11169dd2012-12-18 14:30:41 +00002949 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2950 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2951 if (isByRef) {
2952 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2953 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2954 // offset of __forwarding field
2955 offset = CGM.getContext()
2956 .toCharUnitsFromBits(target.getPointerSizeInBits(0));
2957 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2958 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2959 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2960 // offset of x field
2961 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2962 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2963 }
2964
2965 // Create the descriptor for the variable.
2966 llvm::DIVariable D =
Eric Christopherb2a008c2013-05-16 00:45:12 +00002967 DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable,
Guy Benyei11169dd2012-12-18 14:30:41 +00002968 llvm::DIDescriptor(LexicalBlockStack.back()),
2969 VD->getName(), Unit, Line, Ty, addr);
Adrian Prantl0f6df002013-03-29 19:20:35 +00002970
Guy Benyei11169dd2012-12-18 14:30:41 +00002971 // Insert an llvm.dbg.declare into the current block.
2972 llvm::Instruction *Call =
2973 DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
2974 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column,
2975 LexicalBlockStack.back()));
2976}
2977
2978/// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2979/// variable declaration.
2980void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2981 unsigned ArgNo,
2982 CGBuilderTy &Builder) {
Eric Christopher75e17682013-05-16 00:45:23 +00002983 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002984 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2985}
2986
2987namespace {
2988 struct BlockLayoutChunk {
2989 uint64_t OffsetInBits;
2990 const BlockDecl::Capture *Capture;
2991 };
2992 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2993 return l.OffsetInBits < r.OffsetInBits;
2994 }
2995}
2996
2997void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
Adrian Prantl51936dd2013-03-14 17:53:33 +00002998 llvm::Value *Arg,
2999 llvm::Value *LocalAddr,
Guy Benyei11169dd2012-12-18 14:30:41 +00003000 CGBuilderTy &Builder) {
Eric Christopher75e17682013-05-16 00:45:23 +00003001 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00003002 ASTContext &C = CGM.getContext();
3003 const BlockDecl *blockDecl = block.getBlockDecl();
3004
3005 // Collect some general information about the block's location.
3006 SourceLocation loc = blockDecl->getCaretLocation();
3007 llvm::DIFile tunit = getOrCreateFile(loc);
3008 unsigned line = getLineNumber(loc);
3009 unsigned column = getColumnNumber(loc);
Eric Christopherb2a008c2013-05-16 00:45:12 +00003010
Guy Benyei11169dd2012-12-18 14:30:41 +00003011 // Build the debug-info type for the block literal.
3012 getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
3013
3014 const llvm::StructLayout *blockLayout =
3015 CGM.getDataLayout().getStructLayout(block.StructureType);
3016
3017 SmallVector<llvm::Value*, 16> fields;
3018 fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
3019 blockLayout->getElementOffsetInBits(0),
3020 tunit, tunit));
3021 fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
3022 blockLayout->getElementOffsetInBits(1),
3023 tunit, tunit));
3024 fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
3025 blockLayout->getElementOffsetInBits(2),
3026 tunit, tunit));
3027 fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
3028 blockLayout->getElementOffsetInBits(3),
3029 tunit, tunit));
3030 fields.push_back(createFieldType("__descriptor",
3031 C.getPointerType(block.NeedsCopyDispose ?
3032 C.getBlockDescriptorExtendedType() :
3033 C.getBlockDescriptorType()),
3034 0, loc, AS_public,
3035 blockLayout->getElementOffsetInBits(4),
3036 tunit, tunit));
3037
3038 // We want to sort the captures by offset, not because DWARF
3039 // requires this, but because we're paranoid about debuggers.
3040 SmallVector<BlockLayoutChunk, 8> chunks;
3041
3042 // 'this' capture.
3043 if (blockDecl->capturesCXXThis()) {
3044 BlockLayoutChunk chunk;
3045 chunk.OffsetInBits =
3046 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
3047 chunk.Capture = 0;
3048 chunks.push_back(chunk);
3049 }
3050
3051 // Variable captures.
Aaron Ballman9371dd22014-03-14 18:34:04 +00003052 for (const auto &capture : blockDecl->captures()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003053 const VarDecl *variable = capture.getVariable();
3054 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
3055
3056 // Ignore constant captures.
3057 if (captureInfo.isConstant())
3058 continue;
3059
3060 BlockLayoutChunk chunk;
3061 chunk.OffsetInBits =
3062 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
3063 chunk.Capture = &capture;
3064 chunks.push_back(chunk);
3065 }
3066
3067 // Sort by offset.
3068 llvm::array_pod_sort(chunks.begin(), chunks.end());
3069
3070 for (SmallVectorImpl<BlockLayoutChunk>::iterator
3071 i = chunks.begin(), e = chunks.end(); i != e; ++i) {
3072 uint64_t offsetInBits = i->OffsetInBits;
3073 const BlockDecl::Capture *capture = i->Capture;
3074
3075 // If we have a null capture, this must be the C++ 'this' capture.
3076 if (!capture) {
3077 const CXXMethodDecl *method =
3078 cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
3079 QualType type = method->getThisType(C);
3080
3081 fields.push_back(createFieldType("this", type, 0, loc, AS_public,
3082 offsetInBits, tunit, tunit));
3083 continue;
3084 }
3085
3086 const VarDecl *variable = capture->getVariable();
3087 StringRef name = variable->getName();
3088
3089 llvm::DIType fieldType;
3090 if (capture->isByRef()) {
3091 std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
3092
3093 // FIXME: this creates a second copy of this type!
3094 uint64_t xoffset;
3095 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
3096 fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
3097 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
3098 ptrInfo.first, ptrInfo.second,
3099 offsetInBits, 0, fieldType);
3100 } else {
3101 fieldType = createFieldType(name, variable->getType(), 0,
3102 loc, AS_public, offsetInBits, tunit, tunit);
3103 }
3104 fields.push_back(fieldType);
3105 }
3106
3107 SmallString<36> typeName;
3108 llvm::raw_svector_ostream(typeName)
3109 << "__block_literal_" << CGM.getUniqueBlockCount();
3110
3111 llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
3112
3113 llvm::DIType type =
3114 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
3115 CGM.getContext().toBits(block.BlockSize),
3116 CGM.getContext().toBits(block.BlockAlign),
David Blaikie6d4fe152013-02-25 01:07:08 +00003117 0, llvm::DIType(), fieldsArray);
Guy Benyei11169dd2012-12-18 14:30:41 +00003118 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
3119
3120 // Get overall information about the block.
3121 unsigned flags = llvm::DIDescriptor::FlagArtificial;
3122 llvm::MDNode *scope = LexicalBlockStack.back();
Guy Benyei11169dd2012-12-18 14:30:41 +00003123
3124 // Create the descriptor for the parameter.
3125 llvm::DIVariable debugVar =
3126 DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
Eric Christopherb2a008c2013-05-16 00:45:12 +00003127 llvm::DIDescriptor(scope),
Adrian Prantl51936dd2013-03-14 17:53:33 +00003128 Arg->getName(), tunit, line, type,
Guy Benyei11169dd2012-12-18 14:30:41 +00003129 CGM.getLangOpts().Optimize, flags,
Adrian Prantl51936dd2013-03-14 17:53:33 +00003130 cast<llvm::Argument>(Arg)->getArgNo() + 1);
3131
Adrian Prantl616bef42013-03-14 21:52:59 +00003132 if (LocalAddr) {
Adrian Prantl51936dd2013-03-14 17:53:33 +00003133 // Insert an llvm.dbg.value into the current block.
Adrian Prantl616bef42013-03-14 21:52:59 +00003134 llvm::Instruction *DbgVal =
3135 DBuilder.insertDbgValueIntrinsic(LocalAddr, 0, debugVar,
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00003136 Builder.GetInsertBlock());
Adrian Prantl616bef42013-03-14 21:52:59 +00003137 DbgVal->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
3138 }
Adrian Prantl51936dd2013-03-14 17:53:33 +00003139
Adrian Prantl616bef42013-03-14 21:52:59 +00003140 // Insert an llvm.dbg.declare into the current block.
3141 llvm::Instruction *DbgDecl =
3142 DBuilder.insertDeclare(Arg, debugVar, Builder.GetInsertBlock());
3143 DbgDecl->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
Guy Benyei11169dd2012-12-18 14:30:41 +00003144}
3145
David Blaikie6943dea2013-08-20 01:28:15 +00003146/// If D is an out-of-class definition of a static data member of a class, find
3147/// its corresponding in-class declaration.
3148llvm::DIDerivedType
3149CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {
3150 if (!D->isStaticDataMember())
3151 return llvm::DIDerivedType();
3152 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator MI =
3153 StaticDataMemberCache.find(D->getCanonicalDecl());
3154 if (MI != StaticDataMemberCache.end()) {
3155 assert(MI->second && "Static data member declaration should still exist");
3156 return llvm::DIDerivedType(cast<llvm::MDNode>(MI->second));
Evgeniy Stepanov37b3f732013-08-16 10:35:31 +00003157 }
David Blaikiece763042013-08-20 21:49:21 +00003158
3159 // If the member wasn't found in the cache, lazily construct and add it to the
3160 // type (used when a limited form of the type is emitted).
David Blaikie6943dea2013-08-20 01:28:15 +00003161 llvm::DICompositeType Ctxt(
3162 getContextDescriptor(cast<Decl>(D->getDeclContext())));
3163 llvm::DIDerivedType T = CreateRecordStaticField(D, Ctxt);
David Blaikie6943dea2013-08-20 01:28:15 +00003164 return T;
3165}
3166
Eric Christophercab9fae2014-04-10 05:20:00 +00003167/// Recursively collect all of the member fields of a global anonymous decl and
3168/// create static variables for them. The first time this is called it needs
3169/// to be on a union and then from there we can have additional unnamed fields.
3170llvm::DIGlobalVariable
3171CGDebugInfo::CollectAnonRecordDecls(const RecordDecl *RD, llvm::DIFile Unit,
3172 unsigned LineNo, StringRef LinkageName,
3173 llvm::GlobalVariable *Var,
3174 llvm::DIDescriptor DContext) {
3175 llvm::DIGlobalVariable GV;
3176
3177 for (const auto *Field : RD->fields()) {
3178 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
3179 StringRef FieldName = Field->getName();
3180
3181 // Ignore unnamed fields, but recurse into anonymous records.
3182 if (FieldName.empty()) {
3183 const RecordType *RT = dyn_cast<RecordType>(Field->getType());
3184 if (RT)
3185 GV = CollectAnonRecordDecls(RT->getDecl(), Unit, LineNo, LinkageName,
3186 Var, DContext);
3187 continue;
3188 }
3189 // Use VarDecl's Tag, Scope and Line number.
3190 GV = DBuilder.createStaticVariable(DContext, FieldName, LinkageName, Unit,
3191 LineNo, FieldTy,
3192 Var->hasInternalLinkage(), Var,
3193 llvm::DIDerivedType());
3194 }
3195 return GV;
3196}
3197
Guy Benyei11169dd2012-12-18 14:30:41 +00003198/// EmitGlobalVariable - Emit information about a global variable.
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003199void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
Guy Benyei11169dd2012-12-18 14:30:41 +00003200 const VarDecl *D) {
Eric Christopher75e17682013-05-16 00:45:23 +00003201 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00003202 // Create global variable debug descriptor.
3203 llvm::DIFile Unit = getOrCreateFile(D->getLocation());
3204 unsigned LineNo = getLineNumber(D->getLocation());
3205
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003206 setLocation(D->getLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00003207
3208 QualType T = D->getType();
3209 if (T->isIncompleteArrayType()) {
3210
3211 // CodeGen turns int[] into int[1] so we'll do the same here.
3212 llvm::APInt ConstVal(32, 1);
3213 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3214
3215 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3216 ArrayType::Normal, 0);
3217 }
Eric Christophercab9fae2014-04-10 05:20:00 +00003218
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003219 StringRef DeclName = D->getName();
3220 StringRef LinkageName;
Eric Christophercab9fae2014-04-10 05:20:00 +00003221 if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext()) &&
3222 !isa<ObjCMethodDecl>(D->getDeclContext()))
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003223 LinkageName = Var->getName();
3224 if (LinkageName == DeclName)
3225 LinkageName = StringRef();
Eric Christophercab9fae2014-04-10 05:20:00 +00003226
Eric Christopherb2a008c2013-05-16 00:45:12 +00003227 llvm::DIDescriptor DContext =
Guy Benyei11169dd2012-12-18 14:30:41 +00003228 getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
Eric Christophercab9fae2014-04-10 05:20:00 +00003229
3230 // Attempt to store one global variable for the declaration - even if we
3231 // emit a lot of fields.
3232 llvm::DIGlobalVariable GV;
3233
3234 // If this is an anonymous union then we'll want to emit a global
3235 // variable for each member of the anonymous union so that it's possible
3236 // to find the name of any field in the union.
3237 if (T->isUnionType() && DeclName.empty()) {
3238 const RecordDecl *RD = cast<RecordType>(T)->getDecl();
3239 assert(RD->isAnonymousStructOrUnion() && "unnamed non-anonymous struct or union?");
3240 GV = CollectAnonRecordDecls(RD, Unit, LineNo, LinkageName, Var, DContext);
3241 } else {
3242 GV = DBuilder.createStaticVariable(
3243 DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
3244 Var->hasInternalLinkage(), Var,
3245 getOrCreateStaticDataMemberDeclarationOrNull(D));
3246 }
David Blaikiebd483762013-05-20 04:58:53 +00003247 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(GV)));
Guy Benyei11169dd2012-12-18 14:30:41 +00003248}
3249
3250/// EmitGlobalVariable - Emit information about an objective-c interface.
3251void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
3252 ObjCInterfaceDecl *ID) {
Eric Christopher75e17682013-05-16 00:45:23 +00003253 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00003254 // Create global variable debug descriptor.
3255 llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
3256 unsigned LineNo = getLineNumber(ID->getLocation());
3257
3258 StringRef Name = ID->getName();
3259
3260 QualType T = CGM.getContext().getObjCInterfaceType(ID);
3261 if (T->isIncompleteArrayType()) {
3262
3263 // CodeGen turns int[] into int[1] so we'll do the same here.
3264 llvm::APInt ConstVal(32, 1);
3265 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3266
3267 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3268 ArrayType::Normal, 0);
3269 }
3270
3271 DBuilder.createGlobalVariable(Name, Unit, LineNo,
3272 getOrCreateType(T, Unit),
3273 Var->hasInternalLinkage(), Var);
3274}
3275
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003276/// EmitGlobalVariable - Emit global variable's debug info.
3277void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
3278 llvm::Constant *Init) {
Eric Christopher75e17682013-05-16 00:45:23 +00003279 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003280 // Create the descriptor for the variable.
3281 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
3282 StringRef Name = VD->getName();
3283 llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
3284 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
3285 const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext());
3286 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
3287 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
3288 }
3289 // Do not use DIGlobalVariable for enums.
3290 if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
3291 return;
David Blaikiea15565562014-04-04 20:56:17 +00003292 // Do not emit separate definitions for function local const/statics.
3293 if (isa<FunctionDecl>(VD->getDeclContext()))
3294 return;
David Blaikiebb113912014-04-05 07:23:17 +00003295 VD = cast<ValueDecl>(VD->getCanonicalDecl());
3296 auto pair = DeclCache.insert(std::make_pair(VD, llvm::WeakVH()));
3297 if (!pair.second)
3298 return;
David Blaikie506a7452014-04-05 07:46:57 +00003299 llvm::DIDescriptor DContext =
3300 getContextDescriptor(dyn_cast<Decl>(VD->getDeclContext()));
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003301 llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(
David Blaikie506a7452014-04-05 07:46:57 +00003302 DContext, Name, StringRef(), Unit, getLineNumber(VD->getLocation()), Ty,
3303 true, Init,
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003304 getOrCreateStaticDataMemberDeclarationOrNull(cast<VarDecl>(VD)));
David Blaikiebb113912014-04-05 07:23:17 +00003305 pair.first->second = llvm::WeakVH(GV);
David Blaikiebd483762013-05-20 04:58:53 +00003306}
3307
3308llvm::DIScope CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
3309 if (!LexicalBlockStack.empty())
3310 return llvm::DIScope(LexicalBlockStack.back());
3311 return getContextDescriptor(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00003312}
3313
David Blaikie9f88fe82013-04-22 06:13:21 +00003314void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
David Blaikiebd483762013-05-20 04:58:53 +00003315 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3316 return;
David Blaikie9f88fe82013-04-22 06:13:21 +00003317 DBuilder.createImportedModule(
David Blaikiebd483762013-05-20 04:58:53 +00003318 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
3319 getOrCreateNameSpace(UD.getNominatedNamespace()),
David Blaikie9f88fe82013-04-22 06:13:21 +00003320 getLineNumber(UD.getLocation()));
3321}
3322
David Blaikiebd483762013-05-20 04:58:53 +00003323void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
3324 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3325 return;
3326 assert(UD.shadow_size() &&
3327 "We shouldn't be codegening an invalid UsingDecl containing no decls");
3328 // Emitting one decl is sufficient - debuggers can detect that this is an
3329 // overloaded name & provide lookup for all the overloads.
3330 const UsingShadowDecl &USD = **UD.shadow_begin();
Adrian Prantl6cdce9e2014-04-01 03:41:01 +00003331 if (llvm::DIScope Target =
Eric Christopher1ecc5632013-06-07 22:54:39 +00003332 getDeclarationOrDefinition(USD.getUnderlyingDecl()))
David Blaikiebd483762013-05-20 04:58:53 +00003333 DBuilder.createImportedDeclaration(
3334 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
3335 getLineNumber(USD.getLocation()));
3336}
3337
David Blaikief121b932013-05-20 22:50:41 +00003338llvm::DIImportedEntity
3339CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
3340 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3341 return llvm::DIImportedEntity(0);
3342 llvm::WeakVH &VH = NamespaceAliasCache[&NA];
3343 if (VH)
3344 return llvm::DIImportedEntity(cast<llvm::MDNode>(VH));
3345 llvm::DIImportedEntity R(0);
3346 if (const NamespaceAliasDecl *Underlying =
3347 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
3348 // This could cache & dedup here rather than relying on metadata deduping.
David Blaikie551fb0a2014-04-06 06:30:03 +00003349 R = DBuilder.createImportedDeclaration(
David Blaikief121b932013-05-20 22:50:41 +00003350 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3351 EmitNamespaceAlias(*Underlying), getLineNumber(NA.getLocation()),
3352 NA.getName());
3353 else
David Blaikie551fb0a2014-04-06 06:30:03 +00003354 R = DBuilder.createImportedDeclaration(
David Blaikief121b932013-05-20 22:50:41 +00003355 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3356 getOrCreateNameSpace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
3357 getLineNumber(NA.getLocation()), NA.getName());
3358 VH = R;
3359 return R;
3360}
3361
Guy Benyei11169dd2012-12-18 14:30:41 +00003362/// getOrCreateNamesSpace - Return namespace descriptor for the given
3363/// namespace decl.
Eric Christopherb2a008c2013-05-16 00:45:12 +00003364llvm::DINameSpace
Guy Benyei11169dd2012-12-18 14:30:41 +00003365CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
David Blaikie9fdedec2013-08-16 22:52:07 +00003366 NSDecl = NSDecl->getCanonicalDecl();
Eric Christopherb2a008c2013-05-16 00:45:12 +00003367 llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
Guy Benyei11169dd2012-12-18 14:30:41 +00003368 NameSpaceCache.find(NSDecl);
3369 if (I != NameSpaceCache.end())
3370 return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
Eric Christopherb2a008c2013-05-16 00:45:12 +00003371
Guy Benyei11169dd2012-12-18 14:30:41 +00003372 unsigned LineNo = getLineNumber(NSDecl->getLocation());
3373 llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
Eric Christopherb2a008c2013-05-16 00:45:12 +00003374 llvm::DIDescriptor Context =
Guy Benyei11169dd2012-12-18 14:30:41 +00003375 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
3376 llvm::DINameSpace NS =
3377 DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
3378 NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
3379 return NS;
3380}
3381
3382void CGDebugInfo::finalize() {
3383 for (std::vector<std::pair<void *, llvm::WeakVH> >::const_iterator VI
3384 = ReplaceMap.begin(), VE = ReplaceMap.end(); VI != VE; ++VI) {
3385 llvm::DIType Ty, RepTy;
3386 // Verify that the debug info still exists.
3387 if (llvm::Value *V = VI->second)
3388 Ty = llvm::DIType(cast<llvm::MDNode>(V));
Eric Christopherb2a008c2013-05-16 00:45:12 +00003389
Guy Benyei11169dd2012-12-18 14:30:41 +00003390 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
3391 TypeCache.find(VI->first);
3392 if (it != TypeCache.end()) {
3393 // Verify that the debug info still exists.
3394 if (llvm::Value *V = it->second)
3395 RepTy = llvm::DIType(cast<llvm::MDNode>(V));
3396 }
Adrian Prantl73409ce2013-03-11 18:33:46 +00003397
Eric Christopherf8bc4d82013-07-18 00:52:50 +00003398 if (Ty && Ty.isForwardDecl() && RepTy)
Guy Benyei11169dd2012-12-18 14:30:41 +00003399 Ty.replaceAllUsesWith(RepTy);
Guy Benyei11169dd2012-12-18 14:30:41 +00003400 }
Adrian Prantl73409ce2013-03-11 18:33:46 +00003401
3402 // We keep our own list of retained types, because we need to look
3403 // up the final type in the type cache.
3404 for (std::vector<void *>::const_iterator RI = RetainedTypes.begin(),
3405 RE = RetainedTypes.end(); RI != RE; ++RI)
David Blaikie0856f662014-03-04 22:01:08 +00003406 DBuilder.retainType(llvm::DIType(cast<llvm::MDNode>(TypeCache[*RI])));
Adrian Prantl73409ce2013-03-11 18:33:46 +00003407
Guy Benyei11169dd2012-12-18 14:30:41 +00003408 DBuilder.finalize();
3409}