blob: 0e94b51817ef3c52134305d9909ef030de06bcc5 [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 Blaikie99dab3b2013-09-04 22:03:57 +0000722llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty, llvm::DIFile Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000723 // Typedefs are derived from some other type. If we have a typedef of a
724 // typedef, make sure to emit the whole chain.
David Blaikie99dab3b2013-09-04 22:03:57 +0000725 llvm::DIType Src = getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000726 if (!Src)
Guy Benyei11169dd2012-12-18 14:30:41 +0000727 return llvm::DIType();
728 // We don't set size information, but do specify where the typedef was
729 // declared.
Adrian Prantl3eff2252014-01-21 18:42:27 +0000730 SourceLocation Loc = Ty->getDecl()->getLocation();
731 llvm::DIFile File = getOrCreateFile(Loc);
732 unsigned Line = getLineNumber(Loc);
Guy Benyei11169dd2012-12-18 14:30:41 +0000733 const TypedefNameDecl *TyDecl = Ty->getDecl();
Eric Christopherb2a008c2013-05-16 00:45:12 +0000734
Guy Benyei11169dd2012-12-18 14:30:41 +0000735 llvm::DIDescriptor TypedefContext =
736 getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext()));
Eric Christopherb2a008c2013-05-16 00:45:12 +0000737
Guy Benyei11169dd2012-12-18 14:30:41 +0000738 return
Adrian Prantl3eff2252014-01-21 18:42:27 +0000739 DBuilder.createTypedef(Src, TyDecl->getName(), File, Line, TypedefContext);
Guy Benyei11169dd2012-12-18 14:30:41 +0000740}
741
742llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
743 llvm::DIFile Unit) {
744 SmallVector<llvm::Value *, 16> EltTys;
745
746 // Add the result type at least.
Alp Toker314cc812014-01-25 16:55:45 +0000747 EltTys.push_back(getOrCreateType(Ty->getReturnType(), Unit));
Guy Benyei11169dd2012-12-18 14:30:41 +0000748
749 // Set up remainder of arguments if there is a prototype.
Adrian Prantl800faef2014-02-25 23:42:18 +0000750 // otherwise emit it as a variadic function.
Guy Benyei11169dd2012-12-18 14:30:41 +0000751 if (isa<FunctionNoProtoType>(Ty))
752 EltTys.push_back(DBuilder.createUnspecifiedParameter());
753 else if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Ty)) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000754 for (unsigned i = 0, e = FPT->getNumParams(); i != e; ++i)
755 EltTys.push_back(getOrCreateType(FPT->getParamType(i), Unit));
Adrian Prantld45ba252014-02-25 19:38:11 +0000756 if (FPT->isVariadic())
757 EltTys.push_back(DBuilder.createUnspecifiedParameter());
Guy Benyei11169dd2012-12-18 14:30:41 +0000758 }
759
760 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
761 return DBuilder.createSubroutineType(Unit, EltTypeArray);
762}
763
764
Guy Benyei11169dd2012-12-18 14:30:41 +0000765llvm::DIType CGDebugInfo::createFieldType(StringRef name,
766 QualType type,
767 uint64_t sizeInBitsOverride,
768 SourceLocation loc,
769 AccessSpecifier AS,
770 uint64_t offsetInBits,
771 llvm::DIFile tunit,
Manman Ren2c826dc2013-09-08 03:45:05 +0000772 llvm::DIScope scope) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000773 llvm::DIType debugType = getOrCreateType(type, tunit);
774
775 // Get the location for the field.
776 llvm::DIFile file = getOrCreateFile(loc);
777 unsigned line = getLineNumber(loc);
778
779 uint64_t sizeInBits = 0;
780 unsigned alignInBits = 0;
781 if (!type->isIncompleteArrayType()) {
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000782 std::tie(sizeInBits, alignInBits) = CGM.getContext().getTypeInfo(type);
Guy Benyei11169dd2012-12-18 14:30:41 +0000783
784 if (sizeInBitsOverride)
785 sizeInBits = sizeInBitsOverride;
786 }
787
788 unsigned flags = 0;
789 if (AS == clang::AS_private)
790 flags |= llvm::DIDescriptor::FlagPrivate;
791 else if (AS == clang::AS_protected)
792 flags |= llvm::DIDescriptor::FlagProtected;
793
794 return DBuilder.createMemberType(scope, name, file, line, sizeInBits,
795 alignInBits, offsetInBits, flags, debugType);
796}
797
Eric Christopher91a31902013-01-16 01:22:32 +0000798/// CollectRecordLambdaFields - Helper for CollectRecordFields.
799void CGDebugInfo::
800CollectRecordLambdaFields(const CXXRecordDecl *CXXDecl,
801 SmallVectorImpl<llvm::Value *> &elements,
802 llvm::DIType RecordTy) {
803 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
804 // has the name and the location of the variable so we should iterate over
805 // both concurrently.
806 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
807 RecordDecl::field_iterator Field = CXXDecl->field_begin();
808 unsigned fieldno = 0;
809 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
810 E = CXXDecl->captures_end(); I != E; ++I, ++Field, ++fieldno) {
811 const LambdaExpr::Capture C = *I;
812 if (C.capturesVariable()) {
813 VarDecl *V = C.getCapturedVar();
814 llvm::DIFile VUnit = getOrCreateFile(C.getLocation());
815 StringRef VName = V->getName();
816 uint64_t SizeInBitsOverride = 0;
817 if (Field->isBitField()) {
818 SizeInBitsOverride = Field->getBitWidthValue(CGM.getContext());
819 assert(SizeInBitsOverride && "found named 0-width bitfield");
820 }
821 llvm::DIType fieldType
822 = createFieldType(VName, Field->getType(), SizeInBitsOverride,
823 C.getLocation(), Field->getAccess(),
824 layout.getFieldOffset(fieldno), VUnit, RecordTy);
825 elements.push_back(fieldType);
826 } else {
827 // TODO: Need to handle 'this' in some way by probably renaming the
828 // this of the lambda class and having a field member of 'this' or
829 // by using AT_object_pointer for the function and having that be
830 // used as 'this' for semantic references.
831 assert(C.capturesThis() && "Field that isn't captured and isn't this?");
832 FieldDecl *f = *Field;
833 llvm::DIFile VUnit = getOrCreateFile(f->getLocation());
834 QualType type = f->getType();
835 llvm::DIType fieldType
836 = createFieldType("this", type, 0, f->getLocation(), f->getAccess(),
837 layout.getFieldOffset(fieldno), VUnit, RecordTy);
838
839 elements.push_back(fieldType);
840 }
841 }
842}
843
David Blaikie6943dea2013-08-20 01:28:15 +0000844/// Helper for CollectRecordFields.
David Blaikieae019462013-08-15 22:50:29 +0000845llvm::DIDerivedType
846CGDebugInfo::CreateRecordStaticField(const VarDecl *Var,
847 llvm::DIType RecordTy) {
Eric Christopher91a31902013-01-16 01:22:32 +0000848 // Create the descriptor for the static variable, with or without
849 // constant initializers.
850 llvm::DIFile VUnit = getOrCreateFile(Var->getLocation());
851 llvm::DIType VTy = getOrCreateType(Var->getType(), VUnit);
852
Eric Christopher91a31902013-01-16 01:22:32 +0000853 unsigned LineNumber = getLineNumber(Var->getLocation());
854 StringRef VName = Var->getName();
David Blaikied42917f2013-01-20 01:19:17 +0000855 llvm::Constant *C = NULL;
Eric Christopher91a31902013-01-16 01:22:32 +0000856 if (Var->getInit()) {
857 const APValue *Value = Var->evaluateValue();
David Blaikied42917f2013-01-20 01:19:17 +0000858 if (Value) {
859 if (Value->isInt())
860 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
861 if (Value->isFloat())
862 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
863 }
Eric Christopher91a31902013-01-16 01:22:32 +0000864 }
865
866 unsigned Flags = 0;
867 AccessSpecifier Access = Var->getAccess();
868 if (Access == clang::AS_private)
869 Flags |= llvm::DIDescriptor::FlagPrivate;
870 else if (Access == clang::AS_protected)
871 Flags |= llvm::DIDescriptor::FlagProtected;
872
David Blaikieae019462013-08-15 22:50:29 +0000873 llvm::DIDerivedType GV = DBuilder.createStaticMemberType(
874 RecordTy, VName, VUnit, LineNumber, VTy, Flags, C);
Eric Christopher91a31902013-01-16 01:22:32 +0000875 StaticDataMemberCache[Var->getCanonicalDecl()] = llvm::WeakVH(GV);
David Blaikieae019462013-08-15 22:50:29 +0000876 return GV;
Eric Christopher91a31902013-01-16 01:22:32 +0000877}
878
879/// CollectRecordNormalField - Helper for CollectRecordFields.
880void CGDebugInfo::
881CollectRecordNormalField(const FieldDecl *field, uint64_t OffsetInBits,
882 llvm::DIFile tunit,
883 SmallVectorImpl<llvm::Value *> &elements,
884 llvm::DIType RecordTy) {
885 StringRef name = field->getName();
886 QualType type = field->getType();
887
888 // Ignore unnamed fields unless they're anonymous structs/unions.
889 if (name.empty() && !type->isRecordType())
890 return;
891
892 uint64_t SizeInBitsOverride = 0;
893 if (field->isBitField()) {
894 SizeInBitsOverride = field->getBitWidthValue(CGM.getContext());
895 assert(SizeInBitsOverride && "found named 0-width bitfield");
896 }
897
898 llvm::DIType fieldType
899 = createFieldType(name, type, SizeInBitsOverride,
900 field->getLocation(), field->getAccess(),
901 OffsetInBits, tunit, RecordTy);
902
903 elements.push_back(fieldType);
904}
905
Guy Benyei11169dd2012-12-18 14:30:41 +0000906/// CollectRecordFields - A helper function to collect debug info for
907/// record fields. This is used while creating debug info entry for a Record.
David Blaikieab255bb2013-08-16 20:40:25 +0000908void CGDebugInfo::CollectRecordFields(const RecordDecl *record,
909 llvm::DIFile tunit,
910 SmallVectorImpl<llvm::Value *> &elements,
911 llvm::DICompositeType RecordTy) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000912 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(record);
913
Eric Christopher91a31902013-01-16 01:22:32 +0000914 if (CXXDecl && CXXDecl->isLambda())
915 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
916 else {
917 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
Guy Benyei11169dd2012-12-18 14:30:41 +0000918
Eric Christopher91a31902013-01-16 01:22:32 +0000919 // Field number for non-static fields.
Eric Christopher0f7594372013-01-04 17:59:07 +0000920 unsigned fieldNo = 0;
Eric Christopher91a31902013-01-16 01:22:32 +0000921
Eric Christopher91a31902013-01-16 01:22:32 +0000922 // Static and non-static members should appear in the same order as
923 // the corresponding declarations in the source program.
Aaron Ballman629afae2014-03-07 19:56:05 +0000924 for (const auto *I : record->decls())
925 if (const auto *V = dyn_cast<VarDecl>(I)) {
David Blaikiece763042013-08-20 21:49:21 +0000926 // Reuse the existing static member declaration if one exists
927 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator MI =
928 StaticDataMemberCache.find(V->getCanonicalDecl());
929 if (MI != StaticDataMemberCache.end()) {
930 assert(MI->second &&
931 "Static data member declaration should still exist");
932 elements.push_back(
933 llvm::DIDerivedType(cast<llvm::MDNode>(MI->second)));
934 } else
935 elements.push_back(CreateRecordStaticField(V, RecordTy));
Aaron Ballman629afae2014-03-07 19:56:05 +0000936 } else if (const auto *field = dyn_cast<FieldDecl>(I)) {
Eric Christopher91a31902013-01-16 01:22:32 +0000937 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo),
938 tunit, elements, RecordTy);
939
940 // Bump field number for next field.
941 ++fieldNo;
Guy Benyei11169dd2012-12-18 14:30:41 +0000942 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000943 }
944}
945
946/// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
947/// function type is not updated to include implicit "this" pointer. Use this
948/// routine to get a method type which includes "this" pointer.
David Blaikie469f0792013-05-22 23:22:42 +0000949llvm::DICompositeType
Guy Benyei11169dd2012-12-18 14:30:41 +0000950CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
951 llvm::DIFile Unit) {
David Blaikie7eb06852013-01-07 23:06:35 +0000952 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
David Blaikie2aaf0652013-01-07 22:24:59 +0000953 if (Method->isStatic())
David Blaikie469f0792013-05-22 23:22:42 +0000954 return llvm::DICompositeType(getOrCreateType(QualType(Func, 0), Unit));
David Blaikie7eb06852013-01-07 23:06:35 +0000955 return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()),
956 Func, Unit);
957}
David Blaikie2aaf0652013-01-07 22:24:59 +0000958
David Blaikie469f0792013-05-22 23:22:42 +0000959llvm::DICompositeType CGDebugInfo::getOrCreateInstanceMethodType(
David Blaikie7eb06852013-01-07 23:06:35 +0000960 QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000961 // Add "this" pointer.
David Blaikie7eb06852013-01-07 23:06:35 +0000962 llvm::DIArray Args = llvm::DICompositeType(
963 getOrCreateType(QualType(Func, 0), Unit)).getTypeArray();
Guy Benyei11169dd2012-12-18 14:30:41 +0000964 assert (Args.getNumElements() && "Invalid number of arguments!");
965
966 SmallVector<llvm::Value *, 16> Elts;
967
968 // First element is always return type. For 'void' functions it is NULL.
969 Elts.push_back(Args.getElement(0));
970
David Blaikie2aaf0652013-01-07 22:24:59 +0000971 // "this" pointer is always first argument.
David Blaikie7eb06852013-01-07 23:06:35 +0000972 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
David Blaikie2aaf0652013-01-07 22:24:59 +0000973 if (isa<ClassTemplateSpecializationDecl>(RD)) {
974 // Create pointer type directly in this case.
975 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
976 QualType PointeeTy = ThisPtrTy->getPointeeType();
977 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCallc8e01702013-04-16 22:48:15 +0000978 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
David Blaikie2aaf0652013-01-07 22:24:59 +0000979 uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy);
980 llvm::DIType PointeeType = getOrCreateType(PointeeTy, Unit);
Eric Christopher0fdcb312013-05-16 00:52:20 +0000981 llvm::DIType ThisPtrType =
982 DBuilder.createPointerType(PointeeType, Size, Align);
David Blaikie2aaf0652013-01-07 22:24:59 +0000983 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
984 // TODO: This and the artificial type below are misleading, the
985 // types aren't artificial the argument is, but the current
986 // metadata doesn't represent that.
987 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
988 Elts.push_back(ThisPtrType);
989 } else {
990 llvm::DIType ThisPtrType = getOrCreateType(ThisPtr, Unit);
991 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
992 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
993 Elts.push_back(ThisPtrType);
Guy Benyei11169dd2012-12-18 14:30:41 +0000994 }
995
996 // Copy rest of the arguments.
997 for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
998 Elts.push_back(Args.getElement(i));
999
1000 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
1001
Adrian Prantl0630eb72013-12-18 21:48:18 +00001002 unsigned Flags = 0;
1003 if (Func->getExtProtoInfo().RefQualifier == RQ_LValue)
1004 Flags |= llvm::DIDescriptor::FlagLValueReference;
1005 if (Func->getExtProtoInfo().RefQualifier == RQ_RValue)
1006 Flags |= llvm::DIDescriptor::FlagRValueReference;
1007
1008 return DBuilder.createSubroutineType(Unit, EltTypeArray, Flags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001009}
1010
Eric Christopherb2a008c2013-05-16 00:45:12 +00001011/// isFunctionLocalClass - Return true if CXXRecordDecl is defined
Guy Benyei11169dd2012-12-18 14:30:41 +00001012/// inside a function.
1013static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
1014 if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
1015 return isFunctionLocalClass(NRD);
1016 if (isa<FunctionDecl>(RD->getDeclContext()))
1017 return true;
1018 return false;
1019}
1020
1021/// CreateCXXMemberFunction - A helper function to create a DISubprogram for
1022/// a single member function GlobalDecl.
1023llvm::DISubprogram
1024CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
1025 llvm::DIFile Unit,
1026 llvm::DIType RecordTy) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001027 bool IsCtorOrDtor =
Guy Benyei11169dd2012-12-18 14:30:41 +00001028 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
Eric Christopherb2a008c2013-05-16 00:45:12 +00001029
Guy Benyei11169dd2012-12-18 14:30:41 +00001030 StringRef MethodName = getFunctionName(Method);
David Blaikie469f0792013-05-22 23:22:42 +00001031 llvm::DICompositeType MethodTy = getOrCreateMethodType(Method, Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00001032
1033 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1034 // make sense to give a single ctor/dtor a linkage name.
1035 StringRef MethodLinkageName;
1036 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1037 MethodLinkageName = CGM.getMangledName(Method);
1038
1039 // Get the location for the method.
David Blaikie7fceebf2013-08-19 03:37:48 +00001040 llvm::DIFile MethodDefUnit;
1041 unsigned MethodLine = 0;
1042 if (!Method->isImplicit()) {
1043 MethodDefUnit = getOrCreateFile(Method->getLocation());
1044 MethodLine = getLineNumber(Method->getLocation());
1045 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001046
1047 // Collect virtual method info.
1048 llvm::DIType ContainingType;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001049 unsigned Virtuality = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00001050 unsigned VIndex = 0;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001051
Guy Benyei11169dd2012-12-18 14:30:41 +00001052 if (Method->isVirtual()) {
1053 if (Method->isPure())
1054 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
1055 else
1056 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001057
Guy Benyei11169dd2012-12-18 14:30:41 +00001058 // It doesn't make sense to give a virtual destructor a vtable index,
1059 // since a single destructor has two entries in the vtable.
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001060 // FIXME: Add proper support for debug info for virtual calls in
1061 // the Microsoft ABI, where we may use multiple vptrs to make a vftable
1062 // lookup if we have multiple or virtual inheritance.
1063 if (!isa<CXXDestructorDecl>(Method) &&
1064 !CGM.getTarget().getCXXABI().isMicrosoft())
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001065 VIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(Method);
Guy Benyei11169dd2012-12-18 14:30:41 +00001066 ContainingType = RecordTy;
1067 }
1068
1069 unsigned Flags = 0;
1070 if (Method->isImplicit())
1071 Flags |= llvm::DIDescriptor::FlagArtificial;
1072 AccessSpecifier Access = Method->getAccess();
1073 if (Access == clang::AS_private)
1074 Flags |= llvm::DIDescriptor::FlagPrivate;
1075 else if (Access == clang::AS_protected)
1076 Flags |= llvm::DIDescriptor::FlagProtected;
1077 if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1078 if (CXXC->isExplicit())
1079 Flags |= llvm::DIDescriptor::FlagExplicit;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001080 } else if (const CXXConversionDecl *CXXC =
Guy Benyei11169dd2012-12-18 14:30:41 +00001081 dyn_cast<CXXConversionDecl>(Method)) {
1082 if (CXXC->isExplicit())
1083 Flags |= llvm::DIDescriptor::FlagExplicit;
1084 }
1085 if (Method->hasPrototype())
1086 Flags |= llvm::DIDescriptor::FlagPrototyped;
Adrian Prantl0630eb72013-12-18 21:48:18 +00001087 if (Method->getRefQualifier() == RQ_LValue)
1088 Flags |= llvm::DIDescriptor::FlagLValueReference;
1089 if (Method->getRefQualifier() == RQ_RValue)
1090 Flags |= llvm::DIDescriptor::FlagRValueReference;
Guy Benyei11169dd2012-12-18 14:30:41 +00001091
1092 llvm::DIArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1093 llvm::DISubprogram SP =
Eric Christopherb2a008c2013-05-16 00:45:12 +00001094 DBuilder.createMethod(RecordTy, MethodName, MethodLinkageName,
Guy Benyei11169dd2012-12-18 14:30:41 +00001095 MethodDefUnit, MethodLine,
Eric Christopherb2a008c2013-05-16 00:45:12 +00001096 MethodTy, /*isLocalToUnit=*/false,
Guy Benyei11169dd2012-12-18 14:30:41 +00001097 /* isDefinition=*/ false,
1098 Virtuality, VIndex, ContainingType,
1099 Flags, CGM.getLangOpts().Optimize, NULL,
1100 TParamsArray);
Eric Christopherb2a008c2013-05-16 00:45:12 +00001101
Guy Benyei11169dd2012-12-18 14:30:41 +00001102 SPCache[Method->getCanonicalDecl()] = llvm::WeakVH(SP);
1103
1104 return SP;
1105}
1106
1107/// CollectCXXMemberFunctions - A helper function to collect debug info for
Eric Christopherb2a008c2013-05-16 00:45:12 +00001108/// C++ member functions. This is used while creating debug info entry for
Guy Benyei11169dd2012-12-18 14:30:41 +00001109/// a Record.
1110void CGDebugInfo::
1111CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
1112 SmallVectorImpl<llvm::Value *> &EltTys,
1113 llvm::DIType RecordTy) {
1114
1115 // Since we want more than just the individual member decls if we
1116 // have templated functions iterate over every declaration to gather
1117 // the functions.
Aaron Ballman629afae2014-03-07 19:56:05 +00001118 for(const auto *I : RD->decls()) {
1119 if (const auto *Method = dyn_cast<CXXMethodDecl>(I)) {
David Blaikiea6cc8212013-08-28 20:58:00 +00001120 // Reuse the existing member function declaration if it exists.
David Blaikie8c8e8e22013-08-28 20:24:55 +00001121 // It may be associated with the declaration of the type & should be
1122 // reused as we're building the definition.
David Blaikiea6cc8212013-08-28 20:58:00 +00001123 //
1124 // This situation can arise in the vtable-based debug info reduction where
1125 // implicit members are emitted in a non-vtable TU.
David Blaikie6943dea2013-08-20 01:28:15 +00001126 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator MI =
1127 SPCache.find(Method->getCanonicalDecl());
David Blaikiefae219a2013-08-28 17:27:13 +00001128 if (MI == SPCache.end()) {
David Blaikie8c8e8e22013-08-28 20:24:55 +00001129 // If the member is implicit, lazily create it when we see the
1130 // definition, not before. (an ODR-used implicit default ctor that's
1131 // never actually code generated should not produce debug info)
David Blaikiefae219a2013-08-28 17:27:13 +00001132 if (!Method->isImplicit())
1133 EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
1134 } else
David Blaikie6943dea2013-08-20 01:28:15 +00001135 EltTys.push_back(MI->second);
Aaron Ballman629afae2014-03-07 19:56:05 +00001136 } else if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(I)) {
David Blaikief2053af2013-08-28 23:06:52 +00001137 // Add any template specializations that have already been seen. Like
1138 // implicit member functions, these may have been added to a declaration
1139 // in the case of vtable-based debug info reduction.
Aaron Ballmanb8733c52014-03-14 16:05:56 +00001140 for (const auto *SI : FTD->specializations()) {
David Blaikief2053af2013-08-28 23:06:52 +00001141 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator MI =
Aaron Ballmanb8733c52014-03-14 16:05:56 +00001142 SPCache.find(cast<CXXMethodDecl>(SI)->getCanonicalDecl());
David Blaikief2053af2013-08-28 23:06:52 +00001143 if (MI != SPCache.end())
1144 EltTys.push_back(MI->second);
1145 }
David Blaikie6943dea2013-08-20 01:28:15 +00001146 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001147 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00001148}
Guy Benyei11169dd2012-12-18 14:30:41 +00001149
Guy Benyei11169dd2012-12-18 14:30:41 +00001150/// CollectCXXBases - A helper function to collect debug info for
Eric Christopherb2a008c2013-05-16 00:45:12 +00001151/// C++ base classes. This is used while creating debug info entry for
Guy Benyei11169dd2012-12-18 14:30:41 +00001152/// a Record.
1153void CGDebugInfo::
1154CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
1155 SmallVectorImpl<llvm::Value *> &EltTys,
1156 llvm::DIType RecordTy) {
1157
1158 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
Aaron Ballman574705e2014-03-13 15:41:46 +00001159 for (const auto &BI : RD->bases()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001160 unsigned BFlags = 0;
1161 uint64_t BaseOffset;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001162
Guy Benyei11169dd2012-12-18 14:30:41 +00001163 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00001164 cast<CXXRecordDecl>(BI.getType()->getAs<RecordType>()->getDecl());
Eric Christopherb2a008c2013-05-16 00:45:12 +00001165
Aaron Ballman574705e2014-03-13 15:41:46 +00001166 if (BI.isVirtual()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001167 // virtual base offset offset is -ve. The code generator emits dwarf
1168 // expression where it expects +ve number.
Eric Christopherb2a008c2013-05-16 00:45:12 +00001169 BaseOffset =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001170 0 - CGM.getItaniumVTableContext()
Guy Benyei11169dd2012-12-18 14:30:41 +00001171 .getVirtualBaseOffsetOffset(RD, Base).getQuantity();
1172 BFlags = llvm::DIDescriptor::FlagVirtual;
1173 } else
1174 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1175 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1176 // BI->isVirtual() and bits when not.
Eric Christopherb2a008c2013-05-16 00:45:12 +00001177
Aaron Ballman574705e2014-03-13 15:41:46 +00001178 AccessSpecifier Access = BI.getAccessSpecifier();
Guy Benyei11169dd2012-12-18 14:30:41 +00001179 if (Access == clang::AS_private)
1180 BFlags |= llvm::DIDescriptor::FlagPrivate;
1181 else if (Access == clang::AS_protected)
1182 BFlags |= llvm::DIDescriptor::FlagProtected;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001183
1184 llvm::DIType DTy =
1185 DBuilder.createInheritance(RecordTy,
Aaron Ballman574705e2014-03-13 15:41:46 +00001186 getOrCreateType(BI.getType(), Unit),
Guy Benyei11169dd2012-12-18 14:30:41 +00001187 BaseOffset, BFlags);
1188 EltTys.push_back(DTy);
1189 }
1190}
1191
1192/// CollectTemplateParams - A helper function to collect template parameters.
1193llvm::DIArray CGDebugInfo::
1194CollectTemplateParams(const TemplateParameterList *TPList,
David Blaikie47c11502013-06-22 18:59:18 +00001195 ArrayRef<TemplateArgument> TAList,
Guy Benyei11169dd2012-12-18 14:30:41 +00001196 llvm::DIFile Unit) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001197 SmallVector<llvm::Value *, 16> TemplateParams;
Guy Benyei11169dd2012-12-18 14:30:41 +00001198 for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1199 const TemplateArgument &TA = TAList[i];
David Blaikie47c11502013-06-22 18:59:18 +00001200 StringRef Name;
1201 if (TPList)
1202 Name = TPList->getParam(i)->getName();
David Blaikie38079fd2013-05-10 21:53:14 +00001203 switch (TA.getKind()) {
1204 case TemplateArgument::Type: {
Guy Benyei11169dd2012-12-18 14:30:41 +00001205 llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit);
1206 llvm::DITemplateTypeParameter TTP =
David Blaikie47c11502013-06-22 18:59:18 +00001207 DBuilder.createTemplateTypeParameter(TheCU, Name, TTy);
Guy Benyei11169dd2012-12-18 14:30:41 +00001208 TemplateParams.push_back(TTP);
David Blaikie38079fd2013-05-10 21:53:14 +00001209 } break;
1210 case TemplateArgument::Integral: {
Guy Benyei11169dd2012-12-18 14:30:41 +00001211 llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit);
1212 llvm::DITemplateValueParameter TVP =
David Blaikie38079fd2013-05-10 21:53:14 +00001213 DBuilder.createTemplateValueParameter(
David Blaikie47c11502013-06-22 18:59:18 +00001214 TheCU, Name, TTy,
David Blaikie38079fd2013-05-10 21:53:14 +00001215 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral()));
1216 TemplateParams.push_back(TVP);
1217 } break;
1218 case TemplateArgument::Declaration: {
1219 const ValueDecl *D = TA.getAsDecl();
1220 bool InstanceMember = D->isCXXInstanceMember();
1221 QualType T = InstanceMember
1222 ? CGM.getContext().getMemberPointerType(
1223 D->getType(), cast<RecordDecl>(D->getDeclContext())
1224 ->getTypeForDecl())
1225 : CGM.getContext().getPointerType(D->getType());
1226 llvm::DIType TTy = getOrCreateType(T, Unit);
1227 llvm::Value *V = 0;
1228 // Variable pointer template parameters have a value that is the address
1229 // of the variable.
1230 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1231 V = CGM.GetAddrOfGlobalVar(VD);
1232 // Member function pointers have special support for building them, though
1233 // this is currently unsupported in LLVM CodeGen.
David Blaikied900f982013-05-13 06:57:50 +00001234 if (InstanceMember) {
David Blaikie38079fd2013-05-10 21:53:14 +00001235 if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(D))
1236 V = CGM.getCXXABI().EmitMemberPointer(method);
David Blaikied900f982013-05-13 06:57:50 +00001237 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1238 V = CGM.GetAddrOfFunction(FD);
David Blaikie38079fd2013-05-10 21:53:14 +00001239 // Member data pointers have special handling too to compute the fixed
1240 // offset within the object.
Adrian Prantlefb88052014-04-01 17:52:06 +00001241 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) {
David Blaikie38079fd2013-05-10 21:53:14 +00001242 // These five lines (& possibly the above member function pointer
1243 // handling) might be able to be refactored to use similar code in
1244 // CodeGenModule::getMemberPointerConstant
1245 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
1246 CharUnits chars =
1247 CGM.getContext().toCharUnitsFromBits((int64_t) fieldOffset);
1248 V = CGM.getCXXABI().EmitMemberDataPointer(
1249 cast<MemberPointerType>(T.getTypePtr()), chars);
1250 }
1251 llvm::DITemplateValueParameter TVP =
David Majnemera3644d62013-08-25 22:13:27 +00001252 DBuilder.createTemplateValueParameter(TheCU, Name, TTy,
1253 V->stripPointerCasts());
David Blaikie38079fd2013-05-10 21:53:14 +00001254 TemplateParams.push_back(TVP);
1255 } break;
1256 case TemplateArgument::NullPtr: {
1257 QualType T = TA.getNullPtrType();
1258 llvm::DIType TTy = getOrCreateType(T, Unit);
1259 llvm::Value *V = 0;
1260 // Special case member data pointer null values since they're actually -1
1261 // instead of zero.
1262 if (const MemberPointerType *MPT =
1263 dyn_cast<MemberPointerType>(T.getTypePtr()))
1264 // But treat member function pointers as simple zero integers because
1265 // it's easier than having a special case in LLVM's CodeGen. If LLVM
1266 // CodeGen grows handling for values of non-null member function
1267 // pointers then perhaps we could remove this special case and rely on
1268 // EmitNullMemberPointer for member function pointers.
1269 if (MPT->isMemberDataPointer())
1270 V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1271 if (!V)
1272 V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
1273 llvm::DITemplateValueParameter TVP =
David Blaikie47c11502013-06-22 18:59:18 +00001274 DBuilder.createTemplateValueParameter(TheCU, Name, TTy, V);
David Blaikie38079fd2013-05-10 21:53:14 +00001275 TemplateParams.push_back(TVP);
1276 } break;
David Blaikie47c11502013-06-22 18:59:18 +00001277 case TemplateArgument::Template: {
1278 llvm::DITemplateValueParameter TVP =
1279 DBuilder.createTemplateTemplateParameter(
1280 TheCU, Name, llvm::DIType(),
1281 TA.getAsTemplate().getAsTemplateDecl()
1282 ->getQualifiedNameAsString());
1283 TemplateParams.push_back(TVP);
1284 } break;
1285 case TemplateArgument::Pack: {
1286 llvm::DITemplateValueParameter TVP =
1287 DBuilder.createTemplateParameterPack(
1288 TheCU, Name, llvm::DIType(),
1289 CollectTemplateParams(NULL, TA.getPackAsArray(), Unit));
1290 TemplateParams.push_back(TVP);
1291 } break;
David Majnemer5559d472013-08-24 08:21:10 +00001292 case TemplateArgument::Expression: {
1293 const Expr *E = TA.getAsExpr();
1294 QualType T = E->getType();
1295 llvm::Value *V = CGM.EmitConstantExpr(E, T);
1296 assert(V && "Expression in template argument isn't constant");
1297 llvm::DIType TTy = getOrCreateType(T, Unit);
1298 llvm::DITemplateValueParameter TVP =
1299 DBuilder.createTemplateValueParameter(TheCU, Name, TTy,
1300 V->stripPointerCasts());
1301 TemplateParams.push_back(TVP);
1302 } break;
David Blaikie2b93c542013-05-10 23:36:06 +00001303 // And the following should never occur:
David Blaikie38079fd2013-05-10 21:53:14 +00001304 case TemplateArgument::TemplateExpansion:
David Blaikie38079fd2013-05-10 21:53:14 +00001305 case TemplateArgument::Null:
1306 llvm_unreachable(
1307 "These argument types shouldn't exist in concrete types");
Guy Benyei11169dd2012-12-18 14:30:41 +00001308 }
1309 }
1310 return DBuilder.getOrCreateArray(TemplateParams);
1311}
1312
1313/// CollectFunctionTemplateParams - A helper function to collect debug
1314/// info for function template parameters.
1315llvm::DIArray CGDebugInfo::
1316CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) {
1317 if (FD->getTemplatedKind() ==
1318 FunctionDecl::TK_FunctionTemplateSpecialization) {
1319 const TemplateParameterList *TList =
1320 FD->getTemplateSpecializationInfo()->getTemplate()
1321 ->getTemplateParameters();
David Blaikie47c11502013-06-22 18:59:18 +00001322 return CollectTemplateParams(
1323 TList, FD->getTemplateSpecializationArgs()->asArray(), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00001324 }
1325 return llvm::DIArray();
1326}
1327
1328/// CollectCXXTemplateParams - A helper function to collect debug info for
1329/// template parameters.
1330llvm::DIArray CGDebugInfo::
1331CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial,
1332 llvm::DIFile Unit) {
1333 llvm::PointerUnion<ClassTemplateDecl *,
1334 ClassTemplatePartialSpecializationDecl *>
1335 PU = TSpecial->getSpecializedTemplateOrPartial();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001336
Guy Benyei11169dd2012-12-18 14:30:41 +00001337 TemplateParameterList *TPList = PU.is<ClassTemplateDecl *>() ?
1338 PU.get<ClassTemplateDecl *>()->getTemplateParameters() :
1339 PU.get<ClassTemplatePartialSpecializationDecl *>()->getTemplateParameters();
1340 const TemplateArgumentList &TAList = TSpecial->getTemplateInstantiationArgs();
David Blaikie47c11502013-06-22 18:59:18 +00001341 return CollectTemplateParams(TPList, TAList.asArray(), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00001342}
1343
1344/// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
1345llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
1346 if (VTablePtrType.isValid())
1347 return VTablePtrType;
1348
1349 ASTContext &Context = CGM.getContext();
1350
1351 /* Function type */
1352 llvm::Value *STy = getOrCreateType(Context.IntTy, Unit);
1353 llvm::DIArray SElements = DBuilder.getOrCreateArray(STy);
1354 llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements);
1355 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1356 llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0,
1357 "__vtbl_ptr_type");
1358 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1359 return VTablePtrType;
1360}
1361
1362/// getVTableName - Get vtable name for the given Class.
1363StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +00001364 // Copy the gdb compatible name on the side and use its reference.
1365 return internString("_vptr$", RD->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00001366}
1367
1368
1369/// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
1370/// debug info entry in EltTys vector.
1371void CGDebugInfo::
1372CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
1373 SmallVectorImpl<llvm::Value *> &EltTys) {
1374 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1375
1376 // If there is a primary base then it will hold vtable info.
1377 if (RL.getPrimaryBase())
1378 return;
1379
1380 // If this class is not dynamic then there is not any vtable info to collect.
1381 if (!RD->isDynamicClass())
1382 return;
1383
1384 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1385 llvm::DIType VPTR
1386 = DBuilder.createMemberType(Unit, getVTableName(RD), Unit,
Eric Christopher0fdcb312013-05-16 00:52:20 +00001387 0, Size, 0, 0,
1388 llvm::DIDescriptor::FlagArtificial,
Guy Benyei11169dd2012-12-18 14:30:41 +00001389 getOrCreateVTablePtrType(Unit));
1390 EltTys.push_back(VPTR);
1391}
1392
Eric Christopherb2a008c2013-05-16 00:45:12 +00001393/// getOrCreateRecordType - Emit record type's standalone debug info.
1394llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy,
Guy Benyei11169dd2012-12-18 14:30:41 +00001395 SourceLocation Loc) {
Eric Christopher75e17682013-05-16 00:45:23 +00001396 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00001397 llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc));
1398 return T;
1399}
1400
1401/// getOrCreateInterfaceType - Emit an objective c interface type standalone
1402/// debug info.
1403llvm::DIType CGDebugInfo::getOrCreateInterfaceType(QualType D,
Eric Christopherc0c5d462013-02-21 22:35:08 +00001404 SourceLocation Loc) {
Eric Christopher75e17682013-05-16 00:45:23 +00001405 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00001406 llvm::DIType T = getOrCreateType(D, getOrCreateFile(Loc));
Adrian Prantl73409ce2013-03-11 18:33:46 +00001407 RetainedTypes.push_back(D.getAsOpaquePtr());
Guy Benyei11169dd2012-12-18 14:30:41 +00001408 return T;
1409}
1410
David Blaikieb2e86eb2013-08-15 20:49:17 +00001411void CGDebugInfo::completeType(const RecordDecl *RD) {
1412 if (DebugKind > CodeGenOptions::LimitedDebugInfo ||
1413 !CGM.getLangOpts().CPlusPlus)
1414 completeRequiredType(RD);
1415}
1416
1417void CGDebugInfo::completeRequiredType(const RecordDecl *RD) {
David Blaikie0856f662014-03-04 22:01:08 +00001418 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
1419 return;
1420
David Blaikie6943dea2013-08-20 01:28:15 +00001421 if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
1422 if (CXXDecl->isDynamicClass())
1423 return;
1424
David Blaikieb2e86eb2013-08-15 20:49:17 +00001425 QualType Ty = CGM.getContext().getRecordType(RD);
1426 llvm::DIType T = getTypeOrNull(Ty);
David Blaikie6943dea2013-08-20 01:28:15 +00001427 if (T && T.isForwardDecl())
1428 completeClassData(RD);
1429}
1430
1431void CGDebugInfo::completeClassData(const RecordDecl *RD) {
1432 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
Michael Gottesman349542b2013-08-19 18:46:16 +00001433 return;
David Blaikie6943dea2013-08-20 01:28:15 +00001434 QualType Ty = CGM.getContext().getRecordType(RD);
David Blaikieb2e86eb2013-08-15 20:49:17 +00001435 void* TyPtr = Ty.getAsOpaquePtr();
1436 if (CompletedTypeCache.count(TyPtr))
1437 return;
1438 llvm::DIType Res = CreateTypeDefinition(Ty->castAs<RecordType>());
1439 assert(!Res.isForwardDecl());
1440 CompletedTypeCache[TyPtr] = Res;
1441 TypeCache[TyPtr] = Res;
1442}
1443
David Blaikie0e716b42014-03-03 23:48:23 +00001444static bool hasExplicitMemberDefinition(CXXRecordDecl::method_iterator I,
1445 CXXRecordDecl::method_iterator End) {
1446 for (; I != End; ++I)
1447 if (FunctionDecl *Tmpl = I->getInstantiatedFromMemberFunction())
David Blaikief7f21852014-03-04 03:08:14 +00001448 if (!Tmpl->isImplicit() && Tmpl->isThisDeclarationADefinition() &&
1449 !I->getMemberSpecializationInfo()->isExplicitSpecialization())
David Blaikie0e716b42014-03-03 23:48:23 +00001450 return true;
1451 return false;
1452}
1453
1454static bool shouldOmitDefinition(CodeGenOptions::DebugInfoKind DebugKind,
1455 const RecordDecl *RD,
1456 const LangOptions &LangOpts) {
1457 if (DebugKind > CodeGenOptions::LimitedDebugInfo)
1458 return false;
1459
1460 if (!LangOpts.CPlusPlus)
1461 return false;
1462
1463 if (!RD->isCompleteDefinitionRequired())
1464 return true;
1465
1466 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1467
1468 if (!CXXDecl)
1469 return false;
1470
1471 if (CXXDecl->hasDefinition() && CXXDecl->isDynamicClass())
1472 return true;
1473
1474 TemplateSpecializationKind Spec = TSK_Undeclared;
1475 if (const ClassTemplateSpecializationDecl *SD =
1476 dyn_cast<ClassTemplateSpecializationDecl>(RD))
1477 Spec = SD->getSpecializationKind();
1478
1479 if (Spec == TSK_ExplicitInstantiationDeclaration &&
1480 hasExplicitMemberDefinition(CXXDecl->method_begin(),
1481 CXXDecl->method_end()))
1482 return true;
1483
1484 return false;
1485}
1486
Guy Benyei11169dd2012-12-18 14:30:41 +00001487/// CreateType - get structure or union type.
David Blaikie99dab3b2013-09-04 22:03:57 +00001488llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001489 RecordDecl *RD = Ty->getDecl();
David Blaikie3b1cc9b2013-09-06 06:45:04 +00001490 llvm::DICompositeType T(getTypeOrNull(QualType(Ty, 0)));
David Blaikie0e716b42014-03-03 23:48:23 +00001491 if (T || shouldOmitDefinition(DebugKind, RD, CGM.getLangOpts())) {
David Blaikie3b1cc9b2013-09-06 06:45:04 +00001492 if (!T)
David Blaikie65ec94e2014-02-18 20:52:05 +00001493 T = getOrCreateRecordFwdDecl(
1494 Ty, getContextDescriptor(cast<Decl>(RD->getDeclContext())));
David Blaikie3b1cc9b2013-09-06 06:45:04 +00001495 return T;
David Blaikiee36464c2013-06-05 05:32:23 +00001496 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001497
David Blaikieb2e86eb2013-08-15 20:49:17 +00001498 return CreateTypeDefinition(Ty);
1499}
1500
1501llvm::DIType CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {
1502 RecordDecl *RD = Ty->getDecl();
1503
Guy Benyei11169dd2012-12-18 14:30:41 +00001504 // Get overall information about the record type for the debug info.
1505 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1506
1507 // Records and classes and unions can all be recursive. To handle them, we
1508 // first generate a debug descriptor for the struct as a forward declaration.
1509 // Then (if it is a definition) we go through and get debug info for all of
1510 // its members. Finally, we create a descriptor for the complete type (which
1511 // may refer to the forward decl if the struct is recursive) and replace all
1512 // uses of the forward declaration with the final definition.
1513
David Blaikie4a2b5ef2013-08-12 22:24:20 +00001514 llvm::DICompositeType FwdDecl(getOrCreateLimitedType(Ty, DefUnit));
Manman Ren0d441f12013-07-02 19:01:53 +00001515 assert(FwdDecl.isCompositeType() &&
David Blaikie469f0792013-05-22 23:22:42 +00001516 "The debug type of a RecordType should be a llvm::DICompositeType");
Guy Benyei11169dd2012-12-18 14:30:41 +00001517
1518 if (FwdDecl.isForwardDecl())
1519 return FwdDecl;
1520
David Blaikieadfbf992013-08-18 16:55:33 +00001521 if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
1522 CollectContainingType(CXXDecl, FwdDecl);
1523
Guy Benyei11169dd2012-12-18 14:30:41 +00001524 // Push the struct on region stack.
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001525 LexicalBlockStack.push_back(&*FwdDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00001526 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1527
Adrian Prantla03a85a2013-03-06 22:03:30 +00001528 // Add this to the completed-type cache while we're completing it recursively.
Guy Benyei11169dd2012-12-18 14:30:41 +00001529 CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1530
1531 // Convert all the elements.
1532 SmallVector<llvm::Value *, 16> EltTys;
David Blaikie6943dea2013-08-20 01:28:15 +00001533 // what about nested types?
Guy Benyei11169dd2012-12-18 14:30:41 +00001534
1535 // Note: The split of CXXDecl information here is intentional, the
1536 // gdb tests will depend on a certain ordering at printout. The debug
1537 // information offsets are still correct if we merge them all together
1538 // though.
1539 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1540 if (CXXDecl) {
1541 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1542 CollectVTableInfo(CXXDecl, DefUnit, EltTys);
1543 }
1544
Eric Christopher91a31902013-01-16 01:22:32 +00001545 // Collect data fields (including static variables and any initializers).
Guy Benyei11169dd2012-12-18 14:30:41 +00001546 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
Eric Christopher2df080e2013-10-11 18:16:51 +00001547 if (CXXDecl)
Guy Benyei11169dd2012-12-18 14:30:41 +00001548 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00001549
1550 LexicalBlockStack.pop_back();
1551 RegionMap.erase(Ty->getDecl());
1552
1553 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
David Blaikie4a5b8952013-08-01 20:31:40 +00001554 FwdDecl.setTypeArray(Elements);
Guy Benyei11169dd2012-12-18 14:30:41 +00001555
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001556 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1557 return FwdDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00001558}
1559
1560/// CreateType - get objective-c object type.
1561llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1562 llvm::DIFile Unit) {
1563 // Ignore protocols.
1564 return getOrCreateType(Ty->getBaseType(), Unit);
1565}
1566
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001567
1568/// \return true if Getter has the default name for the property PD.
1569static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
1570 const ObjCMethodDecl *Getter) {
1571 assert(PD);
1572 if (!Getter)
1573 return true;
1574
1575 assert(Getter->getDeclName().isObjCZeroArgSelector());
1576 return PD->getName() ==
1577 Getter->getDeclName().getObjCSelector().getNameForSlot(0);
1578}
1579
1580/// \return true if Setter has the default name for the property PD.
1581static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
1582 const ObjCMethodDecl *Setter) {
1583 assert(PD);
1584 if (!Setter)
1585 return true;
1586
1587 assert(Setter->getDeclName().isObjCOneArgSelector());
Adrian Prantla4ce9062013-06-07 22:29:12 +00001588 return SelectorTable::constructSetterName(PD->getName()) ==
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001589 Setter->getDeclName().getObjCSelector().getNameForSlot(0);
1590}
1591
Guy Benyei11169dd2012-12-18 14:30:41 +00001592/// CreateType - get objective-c interface type.
1593llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1594 llvm::DIFile Unit) {
1595 ObjCInterfaceDecl *ID = Ty->getDecl();
1596 if (!ID)
1597 return llvm::DIType();
1598
1599 // Get overall information about the record type for the debug info.
1600 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1601 unsigned Line = getLineNumber(ID->getLocation());
1602 unsigned RuntimeLang = TheCU.getLanguage();
1603
1604 // If this is just a forward declaration return a special forward-declaration
1605 // debug type since we won't be able to lay out the entire type.
1606 ObjCInterfaceDecl *Def = ID->getDefinition();
1607 if (!Def) {
1608 llvm::DIType FwdDecl =
1609 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
Eric Christopherc0c5d462013-02-21 22:35:08 +00001610 ID->getName(), TheCU, DefUnit, Line,
1611 RuntimeLang);
Guy Benyei11169dd2012-12-18 14:30:41 +00001612 return FwdDecl;
1613 }
1614
1615 ID = Def;
1616
1617 // Bit size, align and offset of the type.
1618 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1619 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1620
1621 unsigned Flags = 0;
1622 if (ID->getImplementation())
1623 Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
1624
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001625 llvm::DICompositeType RealDecl =
Guy Benyei11169dd2012-12-18 14:30:41 +00001626 DBuilder.createStructType(Unit, ID->getName(), DefUnit,
1627 Line, Size, Align, Flags,
David Blaikie6d4fe152013-02-25 01:07:08 +00001628 llvm::DIType(), llvm::DIArray(), RuntimeLang);
Guy Benyei11169dd2012-12-18 14:30:41 +00001629
1630 // Otherwise, insert it into the CompletedTypeCache so that recursive uses
1631 // will find it and we're emitting the complete type.
Adrian Prantla03a85a2013-03-06 22:03:30 +00001632 QualType QualTy = QualType(Ty, 0);
1633 CompletedTypeCache[QualTy.getAsOpaquePtr()] = RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00001634
Eric Christopher35f1f9f2013-07-14 21:00:07 +00001635 // Push the struct on region stack.
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001636 LexicalBlockStack.push_back(static_cast<llvm::MDNode*>(RealDecl));
Guy Benyei11169dd2012-12-18 14:30:41 +00001637 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1638
1639 // Convert all the elements.
1640 SmallVector<llvm::Value *, 16> EltTys;
1641
1642 ObjCInterfaceDecl *SClass = ID->getSuperClass();
1643 if (SClass) {
1644 llvm::DIType SClassTy =
1645 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1646 if (!SClassTy.isValid())
1647 return llvm::DIType();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001648
Guy Benyei11169dd2012-12-18 14:30:41 +00001649 llvm::DIType InhTag =
1650 DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
1651 EltTys.push_back(InhTag);
1652 }
1653
Eric Christopher35f1f9f2013-07-14 21:00:07 +00001654 // Create entries for all of the properties.
Aaron Ballmand174edf2014-03-13 19:11:50 +00001655 for (const auto *PD : ID->properties()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001656 SourceLocation Loc = PD->getLocation();
1657 llvm::DIFile PUnit = getOrCreateFile(Loc);
1658 unsigned PLine = getLineNumber(Loc);
1659 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1660 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1661 llvm::MDNode *PropertyNode =
1662 DBuilder.createObjCProperty(PD->getName(),
Eric Christopherc0c5d462013-02-21 22:35:08 +00001663 PUnit, PLine,
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001664 hasDefaultGetterName(PD, Getter) ? "" :
Guy Benyei11169dd2012-12-18 14:30:41 +00001665 getSelectorName(PD->getGetterName()),
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001666 hasDefaultSetterName(PD, Setter) ? "" :
Guy Benyei11169dd2012-12-18 14:30:41 +00001667 getSelectorName(PD->getSetterName()),
1668 PD->getPropertyAttributes(),
Eric Christopherc0c5d462013-02-21 22:35:08 +00001669 getOrCreateType(PD->getType(), PUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00001670 EltTys.push_back(PropertyNode);
1671 }
1672
1673 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1674 unsigned FieldNo = 0;
1675 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1676 Field = Field->getNextIvar(), ++FieldNo) {
1677 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1678 if (!FieldTy.isValid())
1679 return llvm::DIType();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001680
Guy Benyei11169dd2012-12-18 14:30:41 +00001681 StringRef FieldName = Field->getName();
1682
1683 // Ignore unnamed fields.
1684 if (FieldName.empty())
1685 continue;
1686
1687 // Get the location for the field.
1688 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1689 unsigned FieldLine = getLineNumber(Field->getLocation());
1690 QualType FType = Field->getType();
1691 uint64_t FieldSize = 0;
1692 unsigned FieldAlign = 0;
1693
1694 if (!FType->isIncompleteArrayType()) {
1695
1696 // Bit size, align and offset of the type.
1697 FieldSize = Field->isBitField()
Eric Christopher35f1f9f2013-07-14 21:00:07 +00001698 ? Field->getBitWidthValue(CGM.getContext())
1699 : CGM.getContext().getTypeSize(FType);
Guy Benyei11169dd2012-12-18 14:30:41 +00001700 FieldAlign = CGM.getContext().getTypeAlign(FType);
1701 }
1702
1703 uint64_t FieldOffset;
1704 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1705 // We don't know the runtime offset of an ivar if we're using the
1706 // non-fragile ABI. For bitfields, use the bit offset into the first
1707 // byte of storage of the bitfield. For other fields, use zero.
1708 if (Field->isBitField()) {
1709 FieldOffset = CGM.getObjCRuntime().ComputeBitfieldBitOffset(
1710 CGM, ID, Field);
1711 FieldOffset %= CGM.getContext().getCharWidth();
1712 } else {
1713 FieldOffset = 0;
1714 }
1715 } else {
1716 FieldOffset = RL.getFieldOffset(FieldNo);
1717 }
1718
1719 unsigned Flags = 0;
1720 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1721 Flags = llvm::DIDescriptor::FlagProtected;
1722 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1723 Flags = llvm::DIDescriptor::FlagPrivate;
1724
1725 llvm::MDNode *PropertyNode = NULL;
1726 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001727 if (ObjCPropertyImplDecl *PImpD =
Guy Benyei11169dd2012-12-18 14:30:41 +00001728 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
1729 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
Eric Christopherc0c5d462013-02-21 22:35:08 +00001730 SourceLocation Loc = PD->getLocation();
1731 llvm::DIFile PUnit = getOrCreateFile(Loc);
1732 unsigned PLine = getLineNumber(Loc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001733 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1734 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1735 PropertyNode =
1736 DBuilder.createObjCProperty(PD->getName(),
1737 PUnit, PLine,
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001738 hasDefaultGetterName(PD, Getter) ? "" :
Guy Benyei11169dd2012-12-18 14:30:41 +00001739 getSelectorName(PD->getGetterName()),
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001740 hasDefaultSetterName(PD, Setter) ? "" :
Guy Benyei11169dd2012-12-18 14:30:41 +00001741 getSelectorName(PD->getSetterName()),
1742 PD->getPropertyAttributes(),
1743 getOrCreateType(PD->getType(), PUnit));
1744 }
1745 }
1746 }
1747 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
1748 FieldLine, FieldSize, FieldAlign,
1749 FieldOffset, Flags, FieldTy,
1750 PropertyNode);
1751 EltTys.push_back(FieldTy);
1752 }
1753
1754 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001755 RealDecl.setTypeArray(Elements);
Adrian Prantla03a85a2013-03-06 22:03:30 +00001756
1757 // If the implementation is not yet set, we do not want to mark it
1758 // as complete. An implementation may declare additional
1759 // private ivars that we would miss otherwise.
1760 if (ID->getImplementation() == 0)
1761 CompletedTypeCache.erase(QualTy.getAsOpaquePtr());
Eric Christopherb2a008c2013-05-16 00:45:12 +00001762
Guy Benyei11169dd2012-12-18 14:30:41 +00001763 LexicalBlockStack.pop_back();
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001764 return RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00001765}
1766
1767llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) {
1768 llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1769 int64_t Count = Ty->getNumElements();
1770 if (Count == 0)
1771 // If number of elements are not known then this is an unbounded array.
1772 // Use Count == -1 to express such arrays.
1773 Count = -1;
1774
1775 llvm::Value *Subscript = DBuilder.getOrCreateSubrange(0, Count);
1776 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1777
1778 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1779 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1780
1781 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1782}
1783
1784llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1785 llvm::DIFile Unit) {
1786 uint64_t Size;
1787 uint64_t Align;
1788
1789 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1790 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1791 Size = 0;
1792 Align =
1793 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1794 } else if (Ty->isIncompleteArrayType()) {
1795 Size = 0;
1796 if (Ty->getElementType()->isIncompleteType())
1797 Align = 0;
1798 else
1799 Align = CGM.getContext().getTypeAlign(Ty->getElementType());
David Blaikief03b2e82013-05-09 20:48:12 +00001800 } else if (Ty->isIncompleteType()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001801 Size = 0;
1802 Align = 0;
1803 } else {
1804 // Size and align of the whole array, not the element type.
1805 Size = CGM.getContext().getTypeSize(Ty);
1806 Align = CGM.getContext().getTypeAlign(Ty);
1807 }
1808
1809 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
1810 // interior arrays, do we care? Why aren't nested arrays represented the
1811 // obvious/recursive way?
1812 SmallVector<llvm::Value *, 8> Subscripts;
1813 QualType EltTy(Ty, 0);
1814 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1815 // If the number of elements is known, then count is that number. Otherwise,
1816 // it's -1. This allows us to represent a subrange with an array of 0
1817 // elements, like this:
1818 //
1819 // struct foo {
1820 // int x[0];
1821 // };
1822 int64_t Count = -1; // Count == -1 is an unbounded array.
1823 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1824 Count = CAT->getSize().getZExtValue();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001825
Guy Benyei11169dd2012-12-18 14:30:41 +00001826 // FIXME: Verify this is right for VLAs.
1827 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
1828 EltTy = Ty->getElementType();
1829 }
1830
1831 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1832
Eric Christopherb2a008c2013-05-16 00:45:12 +00001833 llvm::DIType DbgTy =
Guy Benyei11169dd2012-12-18 14:30:41 +00001834 DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1835 SubscriptArray);
1836 return DbgTy;
1837}
1838
Eric Christopherb2a008c2013-05-16 00:45:12 +00001839llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +00001840 llvm::DIFile Unit) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001841 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
Guy Benyei11169dd2012-12-18 14:30:41 +00001842 Ty, Ty->getPointeeType(), Unit);
1843}
1844
Eric Christopherb2a008c2013-05-16 00:45:12 +00001845llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +00001846 llvm::DIFile Unit) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001847 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
Guy Benyei11169dd2012-12-18 14:30:41 +00001848 Ty, Ty->getPointeeType(), Unit);
1849}
1850
Eric Christopherb2a008c2013-05-16 00:45:12 +00001851llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +00001852 llvm::DIFile U) {
David Blaikie2c705ca2013-01-19 19:20:56 +00001853 llvm::DIType ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
1854 if (!Ty->getPointeeType()->isFunctionType())
1855 return DBuilder.createMemberPointerType(
David Blaikie99dab3b2013-09-04 22:03:57 +00001856 getOrCreateType(Ty->getPointeeType(), U), ClassType);
Adrian Prantl0866acd2013-12-19 01:38:47 +00001857
1858 const FunctionProtoType *FPT =
1859 Ty->getPointeeType()->getAs<FunctionProtoType>();
David Blaikie2c705ca2013-01-19 19:20:56 +00001860 return DBuilder.createMemberPointerType(getOrCreateInstanceMethodType(
Adrian Prantl0866acd2013-12-19 01:38:47 +00001861 CGM.getContext().getPointerType(QualType(Ty->getClass(),
1862 FPT->getTypeQuals())),
1863 FPT, U), ClassType);
Guy Benyei11169dd2012-12-18 14:30:41 +00001864}
1865
Eric Christopherb2a008c2013-05-16 00:45:12 +00001866llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +00001867 llvm::DIFile U) {
1868 // Ignore the atomic wrapping
1869 // FIXME: What is the correct representation?
1870 return getOrCreateType(Ty->getValueType(), U);
1871}
1872
1873/// CreateEnumType - get enumeration type.
Manman Ren501ecf92013-08-28 21:46:36 +00001874llvm::DIType CGDebugInfo::CreateEnumType(const EnumType *Ty) {
Manman Ren1b457022013-08-28 21:20:28 +00001875 const EnumDecl *ED = Ty->getDecl();
Guy Benyei11169dd2012-12-18 14:30:41 +00001876 uint64_t Size = 0;
1877 uint64_t Align = 0;
1878 if (!ED->getTypeForDecl()->isIncompleteType()) {
1879 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1880 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1881 }
1882
Manman Rene0064d82013-08-29 23:19:58 +00001883 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
1884
Guy Benyei11169dd2012-12-18 14:30:41 +00001885 // If this is just a forward declaration, construct an appropriately
1886 // marked node and just return it.
1887 if (!ED->getDefinition()) {
1888 llvm::DIDescriptor EDContext;
1889 EDContext = getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1890 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1891 unsigned Line = getLineNumber(ED->getLocation());
1892 StringRef EDName = ED->getName();
1893 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_enumeration_type,
1894 EDName, EDContext, DefUnit, Line, 0,
Manman Rene0064d82013-08-29 23:19:58 +00001895 Size, Align, FullName);
Guy Benyei11169dd2012-12-18 14:30:41 +00001896 }
1897
1898 // Create DIEnumerator elements for each enumerator.
1899 SmallVector<llvm::Value *, 16> Enumerators;
1900 ED = ED->getDefinition();
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001901 for (const auto *Enum : ED->enumerators()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001902 Enumerators.push_back(
1903 DBuilder.createEnumerator(Enum->getName(),
David Blaikiece1ae382013-06-24 07:13:13 +00001904 Enum->getInitVal().getSExtValue()));
Guy Benyei11169dd2012-12-18 14:30:41 +00001905 }
1906
1907 // Return a CompositeType for the enum itself.
1908 llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1909
1910 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1911 unsigned Line = getLineNumber(ED->getLocation());
Eric Christopherb2a008c2013-05-16 00:45:12 +00001912 llvm::DIDescriptor EnumContext =
Guy Benyei11169dd2012-12-18 14:30:41 +00001913 getContextDescriptor(cast<Decl>(ED->getDeclContext()));
Adrian Prantlc60dc712013-04-19 19:56:39 +00001914 llvm::DIType ClassTy = ED->isFixed() ?
Guy Benyei11169dd2012-12-18 14:30:41 +00001915 getOrCreateType(ED->getIntegerType(), DefUnit) : llvm::DIType();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001916 llvm::DIType DbgTy =
Guy Benyei11169dd2012-12-18 14:30:41 +00001917 DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1918 Size, Align, EltArray,
Manman Rene0064d82013-08-29 23:19:58 +00001919 ClassTy, FullName);
Guy Benyei11169dd2012-12-18 14:30:41 +00001920 return DbgTy;
1921}
1922
David Blaikie05491062013-01-21 04:37:12 +00001923static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
1924 Qualifiers Quals;
Guy Benyei11169dd2012-12-18 14:30:41 +00001925 do {
Adrian Prantl179af902013-09-26 21:35:50 +00001926 Qualifiers InnerQuals = T.getLocalQualifiers();
1927 // Qualifiers::operator+() doesn't like it if you add a Qualifier
1928 // that is already there.
1929 Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals);
1930 Quals += InnerQuals;
Guy Benyei11169dd2012-12-18 14:30:41 +00001931 QualType LastT = T;
1932 switch (T->getTypeClass()) {
1933 default:
David Blaikie05491062013-01-21 04:37:12 +00001934 return C.getQualifiedType(T.getTypePtr(), Quals);
Guy Benyei11169dd2012-12-18 14:30:41 +00001935 case Type::TemplateSpecialization:
1936 T = cast<TemplateSpecializationType>(T)->desugar();
1937 break;
1938 case Type::TypeOfExpr:
1939 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1940 break;
1941 case Type::TypeOf:
1942 T = cast<TypeOfType>(T)->getUnderlyingType();
1943 break;
1944 case Type::Decltype:
1945 T = cast<DecltypeType>(T)->getUnderlyingType();
1946 break;
1947 case Type::UnaryTransform:
1948 T = cast<UnaryTransformType>(T)->getUnderlyingType();
1949 break;
1950 case Type::Attributed:
1951 T = cast<AttributedType>(T)->getEquivalentType();
1952 break;
1953 case Type::Elaborated:
1954 T = cast<ElaboratedType>(T)->getNamedType();
1955 break;
1956 case Type::Paren:
1957 T = cast<ParenType>(T)->getInnerType();
1958 break;
David Blaikie05491062013-01-21 04:37:12 +00001959 case Type::SubstTemplateTypeParm:
Guy Benyei11169dd2012-12-18 14:30:41 +00001960 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
Guy Benyei11169dd2012-12-18 14:30:41 +00001961 break;
1962 case Type::Auto:
David Blaikie22c460a02013-05-24 21:24:35 +00001963 QualType DT = cast<AutoType>(T)->getDeducedType();
1964 if (DT.isNull())
1965 return T;
1966 T = DT;
Guy Benyei11169dd2012-12-18 14:30:41 +00001967 break;
1968 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00001969
Guy Benyei11169dd2012-12-18 14:30:41 +00001970 assert(T != LastT && "Type unwrapping failed to unwrap!");
NAKAMURA Takumi3e0a3632013-01-21 10:51:28 +00001971 (void)LastT;
Guy Benyei11169dd2012-12-18 14:30:41 +00001972 } while (true);
1973}
1974
Eric Christopher0fdcb312013-05-16 00:52:20 +00001975/// getType - Get the type from the cache or return null type if it doesn't
1976/// exist.
Guy Benyei11169dd2012-12-18 14:30:41 +00001977llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) {
1978
1979 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00001980 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Eric Christopherb2a008c2013-05-16 00:45:12 +00001981
Guy Benyei11169dd2012-12-18 14:30:41 +00001982 // Check for existing entry.
Adrian Prantl73409ce2013-03-11 18:33:46 +00001983 if (Ty->getTypeClass() == Type::ObjCInterface) {
1984 llvm::Value *V = getCachedInterfaceTypeOrNull(Ty);
1985 if (V)
1986 return llvm::DIType(cast<llvm::MDNode>(V));
1987 else return llvm::DIType();
1988 }
1989
Guy Benyei11169dd2012-12-18 14:30:41 +00001990 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1991 TypeCache.find(Ty.getAsOpaquePtr());
1992 if (it != TypeCache.end()) {
1993 // Verify that the debug info still exists.
1994 if (llvm::Value *V = it->second)
1995 return llvm::DIType(cast<llvm::MDNode>(V));
1996 }
1997
1998 return llvm::DIType();
1999}
2000
2001/// getCompletedTypeOrNull - Get the type from the cache or return null if it
2002/// doesn't exist.
2003llvm::DIType CGDebugInfo::getCompletedTypeOrNull(QualType Ty) {
2004
2005 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00002006 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00002007
2008 // Check for existing entry.
Adrian Prantla03a85a2013-03-06 22:03:30 +00002009 llvm::Value *V = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00002010 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
2011 CompletedTypeCache.find(Ty.getAsOpaquePtr());
Adrian Prantla03a85a2013-03-06 22:03:30 +00002012 if (it != CompletedTypeCache.end())
2013 V = it->second;
2014 else {
Adrian Prantl73409ce2013-03-11 18:33:46 +00002015 V = getCachedInterfaceTypeOrNull(Ty);
Guy Benyei11169dd2012-12-18 14:30:41 +00002016 }
2017
Adrian Prantla03a85a2013-03-06 22:03:30 +00002018 // Verify that any cached debug info still exists.
David Blaikie80d28de2013-08-13 04:21:38 +00002019 return llvm::DIType(cast_or_null<llvm::MDNode>(V));
Guy Benyei11169dd2012-12-18 14:30:41 +00002020}
2021
David Blaikie0e716b42014-03-03 23:48:23 +00002022void CGDebugInfo::completeTemplateDefinition(
2023 const ClassTemplateSpecializationDecl &SD) {
David Blaikie0856f662014-03-04 22:01:08 +00002024 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
2025 return;
2026
David Blaikie0e716b42014-03-03 23:48:23 +00002027 completeClassData(&SD);
2028 // In case this type has no member function definitions being emitted, ensure
2029 // it is retained
2030 RetainedTypes.push_back(CGM.getContext().getRecordType(&SD).getAsOpaquePtr());
2031}
2032
Adrian Prantl73409ce2013-03-11 18:33:46 +00002033/// getCachedInterfaceTypeOrNull - Get the type from the interface
2034/// cache, unless it needs to regenerated. Otherwise return null.
2035llvm::Value *CGDebugInfo::getCachedInterfaceTypeOrNull(QualType Ty) {
2036 // Is there a cached interface that hasn't changed?
2037 llvm::DenseMap<void *, std::pair<llvm::WeakVH, unsigned > >
2038 ::iterator it1 = ObjCInterfaceCache.find(Ty.getAsOpaquePtr());
2039
2040 if (it1 != ObjCInterfaceCache.end())
2041 if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty))
2042 if (Checksum(Decl) == it1->second.second)
2043 // Return cached forward declaration.
2044 return it1->second.first;
2045
2046 return 0;
2047}
Guy Benyei11169dd2012-12-18 14:30:41 +00002048
2049/// getOrCreateType - Get the type from the cache or create a new
2050/// one if necessary.
David Blaikie99dab3b2013-09-04 22:03:57 +00002051llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002052 if (Ty.isNull())
2053 return llvm::DIType();
2054
2055 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00002056 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00002057
David Blaikie99dab3b2013-09-04 22:03:57 +00002058 if (llvm::DIType T = getCompletedTypeOrNull(Ty))
Guy Benyei11169dd2012-12-18 14:30:41 +00002059 return T;
2060
2061 // Otherwise create the type.
David Blaikie99dab3b2013-09-04 22:03:57 +00002062 llvm::DIType Res = CreateTypeNode(Ty, Unit);
Adrian Prantl73409ce2013-03-11 18:33:46 +00002063 void* TyPtr = Ty.getAsOpaquePtr();
2064
2065 // And update the type cache.
2066 TypeCache[TyPtr] = Res;
Guy Benyei11169dd2012-12-18 14:30:41 +00002067
David Blaikie6a723442013-08-15 21:21:19 +00002068 // FIXME: this getTypeOrNull call seems silly when we just inserted the type
2069 // into the cache - but getTypeOrNull has a special case for cached interface
2070 // types. We should probably just pull that out as a special case for the
2071 // "else" block below & skip the otherwise needless lookup.
Guy Benyei11169dd2012-12-18 14:30:41 +00002072 llvm::DIType TC = getTypeOrNull(Ty);
Eric Christopherf8bc4d82013-07-18 00:52:50 +00002073 if (TC && TC.isForwardDecl())
Adrian Prantl73409ce2013-03-11 18:33:46 +00002074 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
2075 else if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty)) {
2076 // Interface types may have elements added to them by a
2077 // subsequent implementation or extension, so we keep them in
2078 // the ObjCInterfaceCache together with a checksum. Instead of
Adrian Prantlc20237d2013-05-08 23:37:22 +00002079 // the (possibly) incomplete interface type, we return a forward
Adrian Prantl73409ce2013-03-11 18:33:46 +00002080 // declaration that gets RAUW'd in CGDebugInfo::finalize().
David Blaikie8e5939b2013-05-21 18:29:40 +00002081 std::pair<llvm::WeakVH, unsigned> &V = ObjCInterfaceCache[TyPtr];
2082 if (V.first)
2083 return llvm::DIType(cast<llvm::MDNode>(V.first));
2084 TC = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
2085 Decl->getName(), TheCU, Unit,
2086 getLineNumber(Decl->getLocation()),
2087 TheCU.getLanguage());
2088 // Store the forward declaration in the cache.
2089 V.first = TC;
2090 V.second = Checksum(Decl);
Adrian Prantl73409ce2013-03-11 18:33:46 +00002091
David Blaikie8e5939b2013-05-21 18:29:40 +00002092 // Register the type for replacement in finalize().
2093 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
2094
Adrian Prantl73409ce2013-03-11 18:33:46 +00002095 return TC;
Adrian Prantla03a85a2013-03-06 22:03:30 +00002096 }
2097
Guy Benyei11169dd2012-12-18 14:30:41 +00002098 if (!Res.isForwardDecl())
Adrian Prantl73409ce2013-03-11 18:33:46 +00002099 CompletedTypeCache[TyPtr] = Res;
Guy Benyei11169dd2012-12-18 14:30:41 +00002100
2101 return Res;
2102}
2103
Adrian Prantlc4de1ef2013-06-07 01:10:41 +00002104/// Currently the checksum of an interface includes the number of
2105/// ivars and property accessors.
Eric Christopher1ecc5632013-06-07 22:54:39 +00002106unsigned CGDebugInfo::Checksum(const ObjCInterfaceDecl *ID) {
Adrian Prantl817bbb32013-06-07 01:10:48 +00002107 // The assumption is that the number of ivars can only increase
2108 // monotonically, so it is safe to just use their current number as
2109 // a checksum.
Adrian Prantlc4de1ef2013-06-07 01:10:41 +00002110 unsigned Sum = 0;
2111 for (const ObjCIvarDecl *Ivar = ID->all_declared_ivar_begin();
2112 Ivar != 0; Ivar = Ivar->getNextIvar())
2113 ++Sum;
2114
2115 return Sum;
Adrian Prantla03a85a2013-03-06 22:03:30 +00002116}
2117
2118ObjCInterfaceDecl *CGDebugInfo::getObjCInterfaceDecl(QualType Ty) {
2119 switch (Ty->getTypeClass()) {
2120 case Type::ObjCObjectPointer:
Eric Christopher0fdcb312013-05-16 00:52:20 +00002121 return getObjCInterfaceDecl(cast<ObjCObjectPointerType>(Ty)
2122 ->getPointeeType());
Adrian Prantla03a85a2013-03-06 22:03:30 +00002123 case Type::ObjCInterface:
2124 return cast<ObjCInterfaceType>(Ty)->getDecl();
2125 default:
2126 return 0;
2127 }
2128}
2129
Guy Benyei11169dd2012-12-18 14:30:41 +00002130/// CreateTypeNode - Create a new debug type node.
David Blaikie99dab3b2013-09-04 22:03:57 +00002131llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002132 // Handle qualifiers, which recursively handles what they refer to.
2133 if (Ty.hasLocalQualifiers())
David Blaikie99dab3b2013-09-04 22:03:57 +00002134 return CreateQualifiedType(Ty, Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00002135
2136 const char *Diag = 0;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002137
Guy Benyei11169dd2012-12-18 14:30:41 +00002138 // Work out details of type.
2139 switch (Ty->getTypeClass()) {
2140#define TYPE(Class, Base)
2141#define ABSTRACT_TYPE(Class, Base)
2142#define NON_CANONICAL_TYPE(Class, Base)
2143#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2144#include "clang/AST/TypeNodes.def"
2145 llvm_unreachable("Dependent types cannot show up in debug information");
2146
2147 case Type::ExtVector:
2148 case Type::Vector:
2149 return CreateType(cast<VectorType>(Ty), Unit);
2150 case Type::ObjCObjectPointer:
2151 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
2152 case Type::ObjCObject:
2153 return CreateType(cast<ObjCObjectType>(Ty), Unit);
2154 case Type::ObjCInterface:
2155 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
2156 case Type::Builtin:
2157 return CreateType(cast<BuiltinType>(Ty));
2158 case Type::Complex:
2159 return CreateType(cast<ComplexType>(Ty));
2160 case Type::Pointer:
2161 return CreateType(cast<PointerType>(Ty), Unit);
Reid Kleckner0503a872013-12-05 01:23:43 +00002162 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00002163 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00002164 // Decayed and adjusted types use the adjusted type in LLVM and DWARF.
Reid Kleckner8a365022013-06-24 17:51:48 +00002165 return CreateType(
Reid Kleckner0503a872013-12-05 01:23:43 +00002166 cast<PointerType>(cast<AdjustedType>(Ty)->getAdjustedType()), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00002167 case Type::BlockPointer:
2168 return CreateType(cast<BlockPointerType>(Ty), Unit);
2169 case Type::Typedef:
David Blaikie99dab3b2013-09-04 22:03:57 +00002170 return CreateType(cast<TypedefType>(Ty), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00002171 case Type::Record:
David Blaikie99dab3b2013-09-04 22:03:57 +00002172 return CreateType(cast<RecordType>(Ty));
Guy Benyei11169dd2012-12-18 14:30:41 +00002173 case Type::Enum:
Manman Ren1b457022013-08-28 21:20:28 +00002174 return CreateEnumType(cast<EnumType>(Ty));
Guy Benyei11169dd2012-12-18 14:30:41 +00002175 case Type::FunctionProto:
2176 case Type::FunctionNoProto:
2177 return CreateType(cast<FunctionType>(Ty), Unit);
2178 case Type::ConstantArray:
2179 case Type::VariableArray:
2180 case Type::IncompleteArray:
2181 return CreateType(cast<ArrayType>(Ty), Unit);
2182
2183 case Type::LValueReference:
2184 return CreateType(cast<LValueReferenceType>(Ty), Unit);
2185 case Type::RValueReference:
2186 return CreateType(cast<RValueReferenceType>(Ty), Unit);
2187
2188 case Type::MemberPointer:
2189 return CreateType(cast<MemberPointerType>(Ty), Unit);
2190
2191 case Type::Atomic:
2192 return CreateType(cast<AtomicType>(Ty), Unit);
2193
2194 case Type::Attributed:
2195 case Type::TemplateSpecialization:
2196 case Type::Elaborated:
2197 case Type::Paren:
2198 case Type::SubstTemplateTypeParm:
2199 case Type::TypeOfExpr:
2200 case Type::TypeOf:
2201 case Type::Decltype:
2202 case Type::UnaryTransform:
David Blaikie66ed89d2013-07-13 21:08:08 +00002203 case Type::PackExpansion:
Guy Benyei11169dd2012-12-18 14:30:41 +00002204 llvm_unreachable("type should have been unwrapped!");
David Blaikie22c460a02013-05-24 21:24:35 +00002205 case Type::Auto:
2206 Diag = "auto";
2207 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002208 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00002209
Guy Benyei11169dd2012-12-18 14:30:41 +00002210 assert(Diag && "Fall through without a diagnostic?");
2211 unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error,
2212 "debug information for %0 is not yet supported");
2213 CGM.getDiags().Report(DiagID)
2214 << Diag;
2215 return llvm::DIType();
2216}
2217
2218/// getOrCreateLimitedType - Get the type from the cache or create a new
2219/// limited type if necessary.
David Blaikie4a2b5ef2013-08-12 22:24:20 +00002220llvm::DIType CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty,
Eric Christopherc0c5d462013-02-21 22:35:08 +00002221 llvm::DIFile Unit) {
David Blaikie4a2b5ef2013-08-12 22:24:20 +00002222 QualType QTy(Ty, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00002223
David Blaikie8d5e1282013-08-20 21:03:29 +00002224 llvm::DICompositeType T(getTypeOrNull(QTy));
Guy Benyei11169dd2012-12-18 14:30:41 +00002225
2226 // We may have cached a forward decl when we could have created
2227 // a non-forward decl. Go ahead and create a non-forward decl
2228 // now.
Eric Christopherf8bc4d82013-07-18 00:52:50 +00002229 if (T && !T.isForwardDecl()) return T;
Guy Benyei11169dd2012-12-18 14:30:41 +00002230
2231 // Otherwise create the type.
David Blaikie8d5e1282013-08-20 21:03:29 +00002232 llvm::DICompositeType Res = CreateLimitedType(Ty);
2233
2234 // Propagate members from the declaration to the definition
2235 // CreateType(const RecordType*) will overwrite this with the members in the
2236 // correct order if the full type is needed.
2237 Res.setTypeArray(T.getTypeArray());
Guy Benyei11169dd2012-12-18 14:30:41 +00002238
Eric Christopherf8bc4d82013-07-18 00:52:50 +00002239 if (T && T.isForwardDecl())
David Blaikie4a2b5ef2013-08-12 22:24:20 +00002240 ReplaceMap.push_back(
2241 std::make_pair(QTy.getAsOpaquePtr(), static_cast<llvm::Value *>(T)));
Guy Benyei11169dd2012-12-18 14:30:41 +00002242
2243 // And update the type cache.
David Blaikie4a2b5ef2013-08-12 22:24:20 +00002244 TypeCache[QTy.getAsOpaquePtr()] = Res;
Guy Benyei11169dd2012-12-18 14:30:41 +00002245 return Res;
2246}
2247
2248// TODO: Currently used for context chains when limiting debug info.
David Blaikie8d5e1282013-08-20 21:03:29 +00002249llvm::DICompositeType CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002250 RecordDecl *RD = Ty->getDecl();
Eric Christopherb2a008c2013-05-16 00:45:12 +00002251
Guy Benyei11169dd2012-12-18 14:30:41 +00002252 // Get overall information about the record type for the debug info.
2253 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
2254 unsigned Line = getLineNumber(RD->getLocation());
2255 StringRef RDName = getClassName(RD);
2256
Eric Christopher07429ff2013-10-15 21:22:34 +00002257 llvm::DIDescriptor RDContext =
2258 getContextDescriptor(cast<Decl>(RD->getDeclContext()));
Guy Benyei11169dd2012-12-18 14:30:41 +00002259
David Blaikied2785892013-08-18 17:36:19 +00002260 // If we ended up creating the type during the context chain construction,
2261 // just return that.
2262 // FIXME: this could be dealt with better if the type was recorded as
2263 // completed before we started this (see the CompletedTypeCache usage in
2264 // CGDebugInfo::CreateTypeDefinition(const RecordType*) - that would need to
2265 // be pushed to before context creation, but after it was known to be
2266 // destined for completion (might still have an issue if this caller only
2267 // required a declaration but the context construction ended up creating a
2268 // definition)
David Blaikie8d5e1282013-08-20 21:03:29 +00002269 llvm::DICompositeType T(getTypeOrNull(CGM.getContext().getRecordType(RD)));
2270 if (T && (!T.isForwardDecl() || !RD->getDefinition()))
David Blaikied2785892013-08-18 17:36:19 +00002271 return T;
2272
Adrian Prantl381e7552014-02-04 21:29:50 +00002273 // If this is just a forward or incomplete declaration, construct an
2274 // appropriately marked node and just return it.
2275 const RecordDecl *D = RD->getDefinition();
2276 if (!D || !D->isCompleteDefinition())
Manman Ren1b457022013-08-28 21:20:28 +00002277 return getOrCreateRecordFwdDecl(Ty, RDContext);
Guy Benyei11169dd2012-12-18 14:30:41 +00002278
2279 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2280 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
David Blaikie49ae6a72013-03-26 23:47:35 +00002281 llvm::DICompositeType RealDecl;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002282
Manman Rene0064d82013-08-29 23:19:58 +00002283 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
2284
Guy Benyei11169dd2012-12-18 14:30:41 +00002285 if (RD->isUnion())
2286 RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
Manman Rene0064d82013-08-29 23:19:58 +00002287 Size, Align, 0, llvm::DIArray(), 0,
2288 FullName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002289 else if (RD->isClass()) {
2290 // FIXME: This could be a struct type giving a default visibility different
2291 // than C++ class type, but needs llvm metadata changes first.
2292 RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
Eric Christopherc0c5d462013-02-21 22:35:08 +00002293 Size, Align, 0, 0, llvm::DIType(),
2294 llvm::DIArray(), llvm::DIType(),
Manman Rene0064d82013-08-29 23:19:58 +00002295 llvm::DIArray(), FullName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002296 } else
2297 RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line,
Eric Christopher0fdcb312013-05-16 00:52:20 +00002298 Size, Align, 0, llvm::DIType(),
David Blaikieba477362013-11-18 23:38:26 +00002299 llvm::DIArray(), 0, llvm::DIType(),
2300 FullName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002301
2302 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
David Blaikie49ae6a72013-03-26 23:47:35 +00002303 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00002304
David Blaikieadfbf992013-08-18 16:55:33 +00002305 if (const ClassTemplateSpecializationDecl *TSpecial =
2306 dyn_cast<ClassTemplateSpecializationDecl>(RD))
2307 RealDecl.setTypeArray(llvm::DIArray(),
2308 CollectCXXTemplateParams(TSpecial, DefUnit));
David Blaikie952dac32013-08-15 22:42:12 +00002309 return RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00002310}
2311
David Blaikieadfbf992013-08-18 16:55:33 +00002312void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,
2313 llvm::DICompositeType RealDecl) {
2314 // A class's primary base or the class itself contains the vtable.
2315 llvm::DICompositeType ContainingType;
2316 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2317 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
Alp Tokerd4733632013-12-05 04:47:09 +00002318 // Seek non-virtual primary base root.
David Blaikieadfbf992013-08-18 16:55:33 +00002319 while (1) {
2320 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
2321 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
2322 if (PBT && !BRL.isPrimaryBaseVirtual())
2323 PBase = PBT;
2324 else
2325 break;
2326 }
2327 ContainingType = llvm::DICompositeType(
2328 getOrCreateType(QualType(PBase->getTypeForDecl(), 0),
2329 getOrCreateFile(RD->getLocation())));
2330 } else if (RD->isDynamicClass())
2331 ContainingType = RealDecl;
2332
2333 RealDecl.setContainingType(ContainingType);
2334}
2335
Guy Benyei11169dd2012-12-18 14:30:41 +00002336/// CreateMemberType - Create new member and increase Offset by FType's size.
2337llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
2338 StringRef Name,
2339 uint64_t *Offset) {
2340 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2341 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
2342 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
2343 llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0,
2344 FieldSize, FieldAlign,
2345 *Offset, 0, FieldTy);
2346 *Offset += FieldSize;
2347 return Ty;
2348}
2349
Adrian Prantl6cdce9e2014-04-01 03:41:01 +00002350llvm::DIScope CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
David Blaikiebd483762013-05-20 04:58:53 +00002351 // We only need a declaration (not a definition) of the type - so use whatever
2352 // we would otherwise do to get a type for a pointee. (forward declarations in
2353 // limited debug info, full definitions (if the type definition is available)
2354 // in unlimited debug info)
David Blaikie6b7d060c2013-08-12 23:14:36 +00002355 if (const TypeDecl *TD = dyn_cast<TypeDecl>(D))
2356 return getOrCreateType(CGM.getContext().getTypeDeclType(TD),
David Blaikie99dab3b2013-09-04 22:03:57 +00002357 getOrCreateFile(TD->getLocation()));
David Blaikiebd483762013-05-20 04:58:53 +00002358 // Otherwise fall back to a fairly rudimentary cache of existing declarations.
2359 // This doesn't handle providing declarations (for functions or variables) for
2360 // entities without definitions in this TU, nor when the definition proceeds
2361 // the call to this function.
2362 // FIXME: This should be split out into more specific maps with support for
2363 // emitting forward declarations and merging definitions with declarations,
2364 // the same way as we do for types.
2365 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator I =
2366 DeclCache.find(D->getCanonicalDecl());
2367 if (I == DeclCache.end())
Adrian Prantl6cdce9e2014-04-01 03:41:01 +00002368 return llvm::DIScope();
David Blaikiebd483762013-05-20 04:58:53 +00002369 llvm::Value *V = I->second;
Adrian Prantl6cdce9e2014-04-01 03:41:01 +00002370 return llvm::DIScope(dyn_cast_or_null<llvm::MDNode>(V));
David Blaikiebd483762013-05-20 04:58:53 +00002371}
2372
Guy Benyei11169dd2012-12-18 14:30:41 +00002373/// getFunctionDeclaration - Return debug info descriptor to describe method
2374/// declaration for the given method definition.
2375llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
David Blaikie18cfbc52013-06-22 00:09:36 +00002376 if (!D || DebugKind == CodeGenOptions::DebugLineTablesOnly)
2377 return llvm::DISubprogram();
2378
Guy Benyei11169dd2012-12-18 14:30:41 +00002379 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
2380 if (!FD) return llvm::DISubprogram();
2381
2382 // Setup context.
David Blaikiefd07c602013-08-09 17:20:05 +00002383 llvm::DIScope S = getContextDescriptor(cast<Decl>(D->getDeclContext()));
Guy Benyei11169dd2012-12-18 14:30:41 +00002384
2385 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2386 MI = SPCache.find(FD->getCanonicalDecl());
David Blaikiefd07c602013-08-09 17:20:05 +00002387 if (MI == SPCache.end()) {
Eric Christopherf86c4052013-08-28 23:12:10 +00002388 if (const CXXMethodDecl *MD =
2389 dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
David Blaikiefd07c602013-08-09 17:20:05 +00002390 llvm::DICompositeType T(S);
Eric Christopherf86c4052013-08-28 23:12:10 +00002391 llvm::DISubprogram SP =
2392 CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()), T);
David Blaikiefd07c602013-08-09 17:20:05 +00002393 return SP;
2394 }
2395 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002396 if (MI != SPCache.end()) {
2397 llvm::Value *V = MI->second;
2398 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
David Blaikie18cfbc52013-06-22 00:09:36 +00002399 if (SP.isSubprogram() && !SP.isDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00002400 return SP;
2401 }
2402
Aaron Ballman86c93902014-03-06 23:45:36 +00002403 for (auto NextFD : FD->redecls()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002404 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2405 MI = SPCache.find(NextFD->getCanonicalDecl());
2406 if (MI != SPCache.end()) {
2407 llvm::Value *V = MI->second;
2408 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
David Blaikie18cfbc52013-06-22 00:09:36 +00002409 if (SP.isSubprogram() && !SP.isDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00002410 return SP;
2411 }
2412 }
2413 return llvm::DISubprogram();
2414}
2415
2416// getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
2417// implicit parameter "this".
David Blaikie469f0792013-05-22 23:22:42 +00002418llvm::DICompositeType CGDebugInfo::getOrCreateFunctionType(const Decl *D,
2419 QualType FnType,
2420 llvm::DIFile F) {
David Blaikie18cfbc52013-06-22 00:09:36 +00002421 if (!D || DebugKind == CodeGenOptions::DebugLineTablesOnly)
2422 // Create fake but valid subroutine type. Otherwise
2423 // llvm::DISubprogram::Verify() would return false, and
2424 // subprogram DIE will miss DW_AT_decl_file and
2425 // DW_AT_decl_line fields.
2426 return DBuilder.createSubroutineType(F, DBuilder.getOrCreateArray(None));
Guy Benyei11169dd2012-12-18 14:30:41 +00002427
2428 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
2429 return getOrCreateMethodType(Method, F);
2430 if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
2431 // Add "self" and "_cmd"
2432 SmallVector<llvm::Value *, 16> Elts;
2433
2434 // First element is always return type. For 'void' functions it is NULL.
Alp Toker314cc812014-01-25 16:55:45 +00002435 QualType ResultTy = OMethod->getReturnType();
Adrian Prantl5f360102013-05-22 21:37:49 +00002436
2437 // Replace the instancetype keyword with the actual type.
2438 if (ResultTy == CGM.getContext().getObjCInstanceType())
2439 ResultTy = CGM.getContext().getPointerType(
2440 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
2441
Adrian Prantl7bec9032013-05-10 21:08:31 +00002442 Elts.push_back(getOrCreateType(ResultTy, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002443 // "self" pointer is always first argument.
Adrian Prantlde17db32013-03-29 19:20:29 +00002444 QualType SelfDeclTy = OMethod->getSelfDecl()->getType();
2445 llvm::DIType SelfTy = getOrCreateType(SelfDeclTy, F);
2446 Elts.push_back(CreateSelfType(SelfDeclTy, SelfTy));
Guy Benyei11169dd2012-12-18 14:30:41 +00002447 // "_cmd" pointer is always second argument.
2448 llvm::DIType CmdTy = getOrCreateType(OMethod->getCmdDecl()->getType(), F);
2449 Elts.push_back(DBuilder.createArtificialType(CmdTy));
2450 // Get rest of the arguments.
Aaron Ballman43b68be2014-03-07 17:50:17 +00002451 for (const auto *PI : OMethod->params())
2452 Elts.push_back(getOrCreateType(PI->getType(), F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002453
2454 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2455 return DBuilder.createSubroutineType(F, EltTypeArray);
2456 }
Adrian Prantld45ba252014-02-25 19:38:11 +00002457
Adrian Prantl800faef2014-02-25 23:42:18 +00002458 // Handle variadic function types; they need an additional
2459 // unspecified parameter.
Adrian Prantld45ba252014-02-25 19:38:11 +00002460 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2461 if (FD->isVariadic()) {
2462 SmallVector<llvm::Value *, 16> EltTys;
2463 EltTys.push_back(getOrCreateType(FD->getReturnType(), F));
2464 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FnType))
2465 for (unsigned i = 0, e = FPT->getNumParams(); i != e; ++i)
2466 EltTys.push_back(getOrCreateType(FPT->getParamType(i), F));
2467 EltTys.push_back(DBuilder.createUnspecifiedParameter());
2468 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
2469 return DBuilder.createSubroutineType(F, EltTypeArray);
2470 }
2471
David Blaikie469f0792013-05-22 23:22:42 +00002472 return llvm::DICompositeType(getOrCreateType(FnType, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002473}
2474
2475/// EmitFunctionStart - Constructs the debug code for entering a function.
2476void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
2477 llvm::Function *Fn,
2478 CGBuilderTy &Builder) {
2479
2480 StringRef Name;
2481 StringRef LinkageName;
2482
2483 FnBeginRegionCount.push_back(LexicalBlockStack.size());
2484
2485 const Decl *D = GD.getDecl();
Eric Christopher885c41b2014-04-01 22:25:28 +00002486
2487 // Use the location of the start of the function to determine where
2488 // the function definition is located. By default use the location
2489 // of the declaration as the location for the subprogram. A function
2490 // may lack a declaration in the source code if it is created by code
2491 // gen. (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
Guy Benyei11169dd2012-12-18 14:30:41 +00002492 bool HasDecl = (D != 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00002493 SourceLocation Loc;
Eric Christopher885c41b2014-04-01 22:25:28 +00002494 if (HasDecl) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002495 Loc = D->getLocation();
2496
Eric Christopher885c41b2014-04-01 22:25:28 +00002497 // If this is a function specialization then use the pattern body
2498 // as the location for the function.
2499 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2500 if (const FunctionDecl *SpecDecl = FD->getTemplateInstantiationPattern())
2501 if (SpecDecl->hasBody(SpecDecl))
2502 Loc = SpecDecl->getLocation();
2503 }
2504
Guy Benyei11169dd2012-12-18 14:30:41 +00002505 unsigned Flags = 0;
2506 llvm::DIFile Unit = getOrCreateFile(Loc);
2507 llvm::DIDescriptor FDContext(Unit);
2508 llvm::DIArray TParamsArray;
2509 if (!HasDecl) {
2510 // Use llvm function name.
David Blaikieebe87e12013-08-27 23:57:18 +00002511 LinkageName = Fn->getName();
Guy Benyei11169dd2012-12-18 14:30:41 +00002512 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2513 // If there is a DISubprogram for this function available then use it.
2514 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2515 FI = SPCache.find(FD->getCanonicalDecl());
2516 if (FI != SPCache.end()) {
2517 llvm::Value *V = FI->second;
2518 llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(V));
2519 if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
2520 llvm::MDNode *SPN = SP;
2521 LexicalBlockStack.push_back(SPN);
2522 RegionMap[D] = llvm::WeakVH(SP);
2523 return;
2524 }
2525 }
2526 Name = getFunctionName(FD);
Nick Lewyckyc02bbb62013-03-20 01:38:16 +00002527 // Use mangled name as linkage name for C/C++ functions.
Guy Benyei11169dd2012-12-18 14:30:41 +00002528 if (FD->hasPrototype()) {
2529 LinkageName = CGM.getMangledName(GD);
2530 Flags |= llvm::DIDescriptor::FlagPrototyped;
2531 }
Nick Lewyckyc02bbb62013-03-20 01:38:16 +00002532 // No need to replicate the linkage name if it isn't different from the
2533 // subprogram name, no need to have it at all unless coverage is enabled or
2534 // debug is set to more than just line tables.
Guy Benyei11169dd2012-12-18 14:30:41 +00002535 if (LinkageName == Name ||
Nick Lewyckyc02bbb62013-03-20 01:38:16 +00002536 (!CGM.getCodeGenOpts().EmitGcovArcs &&
2537 !CGM.getCodeGenOpts().EmitGcovNotes &&
Eric Christopher75e17682013-05-16 00:45:23 +00002538 DebugKind <= CodeGenOptions::DebugLineTablesOnly))
Guy Benyei11169dd2012-12-18 14:30:41 +00002539 LinkageName = StringRef();
2540
Eric Christopher75e17682013-05-16 00:45:23 +00002541 if (DebugKind >= CodeGenOptions::LimitedDebugInfo) {
Eric Christopher4cbd0d9d2014-03-27 05:29:34 +00002542 if (const NamespaceDecl *NSDecl =
2543 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
2544 FDContext = getOrCreateNameSpace(NSDecl);
2545 else if (const RecordDecl *RDecl =
2546 dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
2547 FDContext = getContextDescriptor(cast<Decl>(RDecl));
2548
2549 // Collect template parameters.
Guy Benyei11169dd2012-12-18 14:30:41 +00002550 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
2551 }
2552 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
2553 Name = getObjCMethodName(OMD);
2554 Flags |= llvm::DIDescriptor::FlagPrototyped;
2555 } else {
2556 // Use llvm function name.
2557 Name = Fn->getName();
2558 Flags |= llvm::DIDescriptor::FlagPrototyped;
2559 }
2560 if (!Name.empty() && Name[0] == '\01')
2561 Name = Name.substr(1);
2562
2563 unsigned LineNo = getLineNumber(Loc);
2564 if (!HasDecl || D->isImplicit())
2565 Flags |= llvm::DIDescriptor::FlagArtificial;
2566
Eric Christopher8018e412014-03-27 18:50:35 +00002567 // FIXME: The function declaration we're constructing here is mostly reusing
2568 // declarations from CXXMethodDecl and not constructing new ones for arbitrary
2569 // FunctionDecls. When/if we fix this we can have FDContext be TheCU/null for
2570 // all subprograms instead of the actual context since subprogram definitions
2571 // are emitted as CU level entities by the backend.
Eric Christopher9e6f5f92013-10-17 01:31:21 +00002572 llvm::DISubprogram SP =
2573 DBuilder.createFunction(FDContext, Name, LinkageName, Unit, LineNo,
2574 getOrCreateFunctionType(D, FnType, Unit),
2575 Fn->hasInternalLinkage(), true /*definition*/,
2576 getLineNumber(CurLoc), Flags,
2577 CGM.getLangOpts().Optimize, Fn, TParamsArray,
2578 getFunctionDeclaration(D));
David Blaikiebd483762013-05-20 04:58:53 +00002579 if (HasDecl)
2580 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(SP)));
Guy Benyei11169dd2012-12-18 14:30:41 +00002581
Adrian Prantlbebb8932014-03-21 21:01:58 +00002582 // Push the function onto the lexical block stack.
Guy Benyei11169dd2012-12-18 14:30:41 +00002583 llvm::MDNode *SPN = SP;
2584 LexicalBlockStack.push_back(SPN);
Adrian Prantlbebb8932014-03-21 21:01:58 +00002585
Guy Benyei11169dd2012-12-18 14:30:41 +00002586 if (HasDecl)
2587 RegionMap[D] = llvm::WeakVH(SP);
2588}
2589
2590/// EmitLocation - Emit metadata to indicate a change in line/column
Adrian Prantl02c0caa2013-07-18 00:27:59 +00002591/// information in the source file. If the location is invalid, the
2592/// previous location will be reused.
Adrian Prantlc7822422013-03-12 20:43:25 +00002593void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc,
Adrian Prantle83b1302014-01-07 22:05:52 +00002594 bool ForceColumnInfo) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002595 // Update our current location
2596 setLocation(Loc);
2597
2598 if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
2599
2600 // Don't bother if things are the same as last time.
2601 SourceManager &SM = CGM.getContext().getSourceManager();
2602 if (CurLoc == PrevLoc ||
2603 SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc))
2604 // New Builder may not be in sync with CGDebugInfo.
David Blaikie357aafb2013-02-01 19:09:49 +00002605 if (!Builder.getCurrentDebugLocation().isUnknown() &&
2606 Builder.getCurrentDebugLocation().getScope(CGM.getLLVMContext()) ==
2607 LexicalBlockStack.back())
Guy Benyei11169dd2012-12-18 14:30:41 +00002608 return;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002609
Guy Benyei11169dd2012-12-18 14:30:41 +00002610 // Update last state.
2611 PrevLoc = CurLoc;
2612
Adrian Prantle83b1302014-01-07 22:05:52 +00002613 llvm::MDNode *Scope = LexicalBlockStack.back();
Adrian Prantlc7822422013-03-12 20:43:25 +00002614 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get
2615 (getLineNumber(CurLoc),
2616 getColumnNumber(CurLoc, ForceColumnInfo),
2617 Scope));
Guy Benyei11169dd2012-12-18 14:30:41 +00002618}
2619
2620/// CreateLexicalBlock - Creates a new lexical block node and pushes it on
2621/// the stack.
2622void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
2623 llvm::DIDescriptor D =
2624 DBuilder.createLexicalBlock(LexicalBlockStack.empty() ?
2625 llvm::DIDescriptor() :
2626 llvm::DIDescriptor(LexicalBlockStack.back()),
2627 getOrCreateFile(CurLoc),
2628 getLineNumber(CurLoc),
Diego Novilloe6d398182014-03-03 18:53:32 +00002629 getColumnNumber(CurLoc),
2630 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00002631 llvm::MDNode *DN = D;
2632 LexicalBlockStack.push_back(DN);
2633}
2634
2635/// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
2636/// region - beginning of a DW_TAG_lexical_block.
Eric Christopher0fdcb312013-05-16 00:52:20 +00002637void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
2638 SourceLocation Loc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002639 // Set our current location.
2640 setLocation(Loc);
2641
2642 // Create a new lexical block and push it on the stack.
2643 CreateLexicalBlock(Loc);
2644
2645 // Emit a line table change for the current location inside the new scope.
2646 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc),
2647 getColumnNumber(Loc),
2648 LexicalBlockStack.back()));
2649}
2650
2651/// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative
2652/// region - end of a DW_TAG_lexical_block.
Eric Christopher0fdcb312013-05-16 00:52:20 +00002653void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
2654 SourceLocation Loc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002655 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2656
2657 // Provide an entry in the line table for the end of the block.
2658 EmitLocation(Builder, Loc);
2659
2660 LexicalBlockStack.pop_back();
2661}
2662
2663/// EmitFunctionEnd - Constructs the debug code for exiting a function.
2664void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
2665 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2666 unsigned RCount = FnBeginRegionCount.back();
2667 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
2668
2669 // Pop all regions for this function.
2670 while (LexicalBlockStack.size() != RCount)
2671 EmitLexicalBlockEnd(Builder, CurLoc);
2672 FnBeginRegionCount.pop_back();
2673}
2674
Eric Christopherb2a008c2013-05-16 00:45:12 +00002675// EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
Guy Benyei11169dd2012-12-18 14:30:41 +00002676// See BuildByRefType.
2677llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
2678 uint64_t *XOffset) {
2679
2680 SmallVector<llvm::Value *, 5> EltTys;
2681 QualType FType;
2682 uint64_t FieldSize, FieldOffset;
2683 unsigned FieldAlign;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002684
Guy Benyei11169dd2012-12-18 14:30:41 +00002685 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
Eric Christopherb2a008c2013-05-16 00:45:12 +00002686 QualType Type = VD->getType();
Guy Benyei11169dd2012-12-18 14:30:41 +00002687
2688 FieldOffset = 0;
2689 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2690 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
2691 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
2692 FType = CGM.getContext().IntTy;
2693 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
2694 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
2695
2696 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
2697 if (HasCopyAndDispose) {
2698 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2699 EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
2700 &FieldOffset));
2701 EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
2702 &FieldOffset));
2703 }
2704 bool HasByrefExtendedLayout;
2705 Qualifiers::ObjCLifetime Lifetime;
2706 if (CGM.getContext().getByrefLifetime(Type,
2707 Lifetime, HasByrefExtendedLayout)
Adrian Prantlead2ba42013-07-23 00:12:14 +00002708 && HasByrefExtendedLayout) {
2709 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
Guy Benyei11169dd2012-12-18 14:30:41 +00002710 EltTys.push_back(CreateMemberType(Unit, FType,
2711 "__byref_variable_layout",
2712 &FieldOffset));
Adrian Prantlead2ba42013-07-23 00:12:14 +00002713 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00002714
Guy Benyei11169dd2012-12-18 14:30:41 +00002715 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2716 if (Align > CGM.getContext().toCharUnitsFromBits(
John McCallc8e01702013-04-16 22:48:15 +00002717 CGM.getTarget().getPointerAlign(0))) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00002718 CharUnits FieldOffsetInBytes
Guy Benyei11169dd2012-12-18 14:30:41 +00002719 = CGM.getContext().toCharUnitsFromBits(FieldOffset);
2720 CharUnits AlignedOffsetInBytes
2721 = FieldOffsetInBytes.RoundUpToAlignment(Align);
2722 CharUnits NumPaddingBytes
2723 = AlignedOffsetInBytes - FieldOffsetInBytes;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002724
Guy Benyei11169dd2012-12-18 14:30:41 +00002725 if (NumPaddingBytes.isPositive()) {
2726 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
2727 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
2728 pad, ArrayType::Normal, 0);
2729 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
2730 }
2731 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00002732
Guy Benyei11169dd2012-12-18 14:30:41 +00002733 FType = Type;
2734 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2735 FieldSize = CGM.getContext().getTypeSize(FType);
2736 FieldAlign = CGM.getContext().toBits(Align);
2737
Eric Christopherb2a008c2013-05-16 00:45:12 +00002738 *XOffset = FieldOffset;
Guy Benyei11169dd2012-12-18 14:30:41 +00002739 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit,
2740 0, FieldSize, FieldAlign,
2741 FieldOffset, 0, FieldTy);
2742 EltTys.push_back(FieldTy);
2743 FieldOffset += FieldSize;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002744
Guy Benyei11169dd2012-12-18 14:30:41 +00002745 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002746
Guy Benyei11169dd2012-12-18 14:30:41 +00002747 unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002748
Guy Benyei11169dd2012-12-18 14:30:41 +00002749 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
David Blaikie6d4fe152013-02-25 01:07:08 +00002750 llvm::DIType(), Elements);
Guy Benyei11169dd2012-12-18 14:30:41 +00002751}
2752
2753/// EmitDeclare - Emit local variable declaration debug info.
2754void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
Eric Christopherb2a008c2013-05-16 00:45:12 +00002755 llvm::Value *Storage,
Guy Benyei11169dd2012-12-18 14:30:41 +00002756 unsigned ArgNo, CGBuilderTy &Builder) {
Eric Christopher75e17682013-05-16 00:45:23 +00002757 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002758 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2759
David Blaikie7fceebf2013-08-19 03:37:48 +00002760 bool Unwritten =
2761 VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) &&
2762 cast<Decl>(VD->getDeclContext())->isImplicit());
2763 llvm::DIFile Unit;
2764 if (!Unwritten)
2765 Unit = getOrCreateFile(VD->getLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00002766 llvm::DIType Ty;
2767 uint64_t XOffset = 0;
2768 if (VD->hasAttr<BlocksAttr>())
2769 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002770 else
Guy Benyei11169dd2012-12-18 14:30:41 +00002771 Ty = getOrCreateType(VD->getType(), Unit);
2772
2773 // If there is no debug info for this type then do not emit debug info
2774 // for this variable.
2775 if (!Ty)
2776 return;
2777
Guy Benyei11169dd2012-12-18 14:30:41 +00002778 // Get location information.
David Blaikie7fceebf2013-08-19 03:37:48 +00002779 unsigned Line = 0;
2780 unsigned Column = 0;
2781 if (!Unwritten) {
2782 Line = getLineNumber(VD->getLocation());
2783 Column = getColumnNumber(VD->getLocation());
2784 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002785 unsigned Flags = 0;
2786 if (VD->isImplicit())
2787 Flags |= llvm::DIDescriptor::FlagArtificial;
2788 // If this is the first argument and it is implicit then
2789 // give it an object pointer flag.
2790 // FIXME: There has to be a better way to do this, but for static
2791 // functions there won't be an implicit param at arg1 and
2792 // otherwise it is 'self' or 'this'.
2793 if (isa<ImplicitParamDecl>(VD) && ArgNo == 1)
2794 Flags |= llvm::DIDescriptor::FlagObjectPointer;
David Blaikieb9c667d2013-06-19 21:53:53 +00002795 if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage))
Eric Christopherffdeb1e2013-07-17 22:52:53 +00002796 if (Arg->getType()->isPointerTy() && !Arg->hasByValAttr() &&
2797 !VD->getType()->isPointerType())
David Blaikieb9c667d2013-06-19 21:53:53 +00002798 Flags |= llvm::DIDescriptor::FlagIndirectVariable;
Guy Benyei11169dd2012-12-18 14:30:41 +00002799
2800 llvm::MDNode *Scope = LexicalBlockStack.back();
2801
2802 StringRef Name = VD->getName();
2803 if (!Name.empty()) {
2804 if (VD->hasAttr<BlocksAttr>()) {
2805 CharUnits offset = CharUnits::fromQuantity(32);
2806 SmallVector<llvm::Value *, 9> addr;
2807 llvm::Type *Int64Ty = CGM.Int64Ty;
2808 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2809 // offset of __forwarding field
2810 offset = CGM.getContext().toCharUnitsFromBits(
John McCallc8e01702013-04-16 22:48:15 +00002811 CGM.getTarget().getPointerWidth(0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002812 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2813 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2814 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2815 // offset of x field
2816 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2817 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2818
2819 // Create the descriptor for the variable.
2820 llvm::DIVariable D =
Eric Christopherb2a008c2013-05-16 00:45:12 +00002821 DBuilder.createComplexVariable(Tag,
Guy Benyei11169dd2012-12-18 14:30:41 +00002822 llvm::DIDescriptor(Scope),
2823 VD->getName(), Unit, Line, Ty,
2824 addr, ArgNo);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002825
Guy Benyei11169dd2012-12-18 14:30:41 +00002826 // Insert an llvm.dbg.declare into the current block.
2827 llvm::Instruction *Call =
2828 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2829 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2830 return;
Adrian Prantl7f2ef222013-09-18 22:18:17 +00002831 } else if (isa<VariableArrayType>(VD->getType()))
Adrian Prantl0315f382013-09-18 22:08:57 +00002832 Flags |= llvm::DIDescriptor::FlagIndirectVariable;
David Blaikiea76a7c92013-01-05 05:58:35 +00002833 } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2834 // If VD is an anonymous union then Storage represents value for
2835 // all union fields.
Guy Benyei11169dd2012-12-18 14:30:41 +00002836 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
David Blaikie219c7d92013-01-05 20:03:07 +00002837 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00002838 for (const auto *Field : RD->fields()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002839 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2840 StringRef FieldName = Field->getName();
Eric Christopherb2a008c2013-05-16 00:45:12 +00002841
Guy Benyei11169dd2012-12-18 14:30:41 +00002842 // Ignore unnamed fields. Do not ignore unnamed records.
2843 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2844 continue;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002845
Guy Benyei11169dd2012-12-18 14:30:41 +00002846 // Use VarDecl's Tag, Scope and Line number.
2847 llvm::DIVariable D =
2848 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
Eric Christopherb2a008c2013-05-16 00:45:12 +00002849 FieldName, Unit, Line, FieldTy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002850 CGM.getLangOpts().Optimize, Flags,
2851 ArgNo);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002852
Guy Benyei11169dd2012-12-18 14:30:41 +00002853 // Insert an llvm.dbg.declare into the current block.
2854 llvm::Instruction *Call =
2855 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2856 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2857 }
David Blaikie219c7d92013-01-05 20:03:07 +00002858 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00002859 }
2860 }
David Blaikiea76a7c92013-01-05 05:58:35 +00002861
2862 // Create the descriptor for the variable.
2863 llvm::DIVariable D =
2864 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2865 Name, Unit, Line, Ty,
2866 CGM.getLangOpts().Optimize, Flags, ArgNo);
2867
2868 // Insert an llvm.dbg.declare into the current block.
2869 llvm::Instruction *Call =
2870 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2871 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
Guy Benyei11169dd2012-12-18 14:30:41 +00002872}
2873
2874void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2875 llvm::Value *Storage,
2876 CGBuilderTy &Builder) {
Eric Christopher75e17682013-05-16 00:45:23 +00002877 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002878 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2879}
2880
Adrian Prantlde17db32013-03-29 19:20:29 +00002881/// Look up the completed type for a self pointer in the TypeCache and
2882/// create a copy of it with the ObjectPointer and Artificial flags
2883/// set. If the type is not cached, a new one is created. This should
2884/// never happen though, since creating a type for the implicit self
2885/// argument implies that we already parsed the interface definition
2886/// and the ivar declarations in the implementation.
Eric Christopher0fdcb312013-05-16 00:52:20 +00002887llvm::DIType CGDebugInfo::CreateSelfType(const QualType &QualTy,
2888 llvm::DIType Ty) {
Adrian Prantlde17db32013-03-29 19:20:29 +00002889 llvm::DIType CachedTy = getTypeOrNull(QualTy);
Eric Christopherf8bc4d82013-07-18 00:52:50 +00002890 if (CachedTy) Ty = CachedTy;
Adrian Prantlde17db32013-03-29 19:20:29 +00002891 else DEBUG(llvm::dbgs() << "No cached type for self.");
2892 return DBuilder.createObjectPointerType(Ty);
2893}
2894
Guy Benyei11169dd2012-12-18 14:30:41 +00002895void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(const VarDecl *VD,
2896 llvm::Value *Storage,
2897 CGBuilderTy &Builder,
2898 const CGBlockInfo &blockInfo) {
Eric Christopher75e17682013-05-16 00:45:23 +00002899 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002900 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
Eric Christopherb2a008c2013-05-16 00:45:12 +00002901
Guy Benyei11169dd2012-12-18 14:30:41 +00002902 if (Builder.GetInsertBlock() == 0)
2903 return;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002904
Guy Benyei11169dd2012-12-18 14:30:41 +00002905 bool isByRef = VD->hasAttr<BlocksAttr>();
Eric Christopherb2a008c2013-05-16 00:45:12 +00002906
Guy Benyei11169dd2012-12-18 14:30:41 +00002907 uint64_t XOffset = 0;
2908 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2909 llvm::DIType Ty;
2910 if (isByRef)
2911 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002912 else
Guy Benyei11169dd2012-12-18 14:30:41 +00002913 Ty = getOrCreateType(VD->getType(), Unit);
2914
2915 // Self is passed along as an implicit non-arg variable in a
2916 // block. Mark it as the object pointer.
2917 if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self")
Adrian Prantlde17db32013-03-29 19:20:29 +00002918 Ty = CreateSelfType(VD->getType(), Ty);
Guy Benyei11169dd2012-12-18 14:30:41 +00002919
2920 // Get location information.
2921 unsigned Line = getLineNumber(VD->getLocation());
2922 unsigned Column = getColumnNumber(VD->getLocation());
2923
2924 const llvm::DataLayout &target = CGM.getDataLayout();
2925
2926 CharUnits offset = CharUnits::fromQuantity(
2927 target.getStructLayout(blockInfo.StructureType)
2928 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2929
2930 SmallVector<llvm::Value *, 9> addr;
2931 llvm::Type *Int64Ty = CGM.Int64Ty;
Adrian Prantl0f6df002013-03-29 19:20:35 +00002932 if (isa<llvm::AllocaInst>(Storage))
2933 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
Guy Benyei11169dd2012-12-18 14:30:41 +00002934 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2935 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2936 if (isByRef) {
2937 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2938 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2939 // offset of __forwarding field
2940 offset = CGM.getContext()
2941 .toCharUnitsFromBits(target.getPointerSizeInBits(0));
2942 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2943 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2944 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2945 // offset of x field
2946 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2947 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2948 }
2949
2950 // Create the descriptor for the variable.
2951 llvm::DIVariable D =
Eric Christopherb2a008c2013-05-16 00:45:12 +00002952 DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable,
Guy Benyei11169dd2012-12-18 14:30:41 +00002953 llvm::DIDescriptor(LexicalBlockStack.back()),
2954 VD->getName(), Unit, Line, Ty, addr);
Adrian Prantl0f6df002013-03-29 19:20:35 +00002955
Guy Benyei11169dd2012-12-18 14:30:41 +00002956 // Insert an llvm.dbg.declare into the current block.
2957 llvm::Instruction *Call =
2958 DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
2959 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column,
2960 LexicalBlockStack.back()));
2961}
2962
2963/// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2964/// variable declaration.
2965void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2966 unsigned ArgNo,
2967 CGBuilderTy &Builder) {
Eric Christopher75e17682013-05-16 00:45:23 +00002968 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002969 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2970}
2971
2972namespace {
2973 struct BlockLayoutChunk {
2974 uint64_t OffsetInBits;
2975 const BlockDecl::Capture *Capture;
2976 };
2977 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2978 return l.OffsetInBits < r.OffsetInBits;
2979 }
2980}
2981
2982void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
Adrian Prantl51936dd2013-03-14 17:53:33 +00002983 llvm::Value *Arg,
2984 llvm::Value *LocalAddr,
Guy Benyei11169dd2012-12-18 14:30:41 +00002985 CGBuilderTy &Builder) {
Eric Christopher75e17682013-05-16 00:45:23 +00002986 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002987 ASTContext &C = CGM.getContext();
2988 const BlockDecl *blockDecl = block.getBlockDecl();
2989
2990 // Collect some general information about the block's location.
2991 SourceLocation loc = blockDecl->getCaretLocation();
2992 llvm::DIFile tunit = getOrCreateFile(loc);
2993 unsigned line = getLineNumber(loc);
2994 unsigned column = getColumnNumber(loc);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002995
Guy Benyei11169dd2012-12-18 14:30:41 +00002996 // Build the debug-info type for the block literal.
2997 getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
2998
2999 const llvm::StructLayout *blockLayout =
3000 CGM.getDataLayout().getStructLayout(block.StructureType);
3001
3002 SmallVector<llvm::Value*, 16> fields;
3003 fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
3004 blockLayout->getElementOffsetInBits(0),
3005 tunit, tunit));
3006 fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
3007 blockLayout->getElementOffsetInBits(1),
3008 tunit, tunit));
3009 fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
3010 blockLayout->getElementOffsetInBits(2),
3011 tunit, tunit));
3012 fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
3013 blockLayout->getElementOffsetInBits(3),
3014 tunit, tunit));
3015 fields.push_back(createFieldType("__descriptor",
3016 C.getPointerType(block.NeedsCopyDispose ?
3017 C.getBlockDescriptorExtendedType() :
3018 C.getBlockDescriptorType()),
3019 0, loc, AS_public,
3020 blockLayout->getElementOffsetInBits(4),
3021 tunit, tunit));
3022
3023 // We want to sort the captures by offset, not because DWARF
3024 // requires this, but because we're paranoid about debuggers.
3025 SmallVector<BlockLayoutChunk, 8> chunks;
3026
3027 // 'this' capture.
3028 if (blockDecl->capturesCXXThis()) {
3029 BlockLayoutChunk chunk;
3030 chunk.OffsetInBits =
3031 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
3032 chunk.Capture = 0;
3033 chunks.push_back(chunk);
3034 }
3035
3036 // Variable captures.
Aaron Ballman9371dd22014-03-14 18:34:04 +00003037 for (const auto &capture : blockDecl->captures()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003038 const VarDecl *variable = capture.getVariable();
3039 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
3040
3041 // Ignore constant captures.
3042 if (captureInfo.isConstant())
3043 continue;
3044
3045 BlockLayoutChunk chunk;
3046 chunk.OffsetInBits =
3047 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
3048 chunk.Capture = &capture;
3049 chunks.push_back(chunk);
3050 }
3051
3052 // Sort by offset.
3053 llvm::array_pod_sort(chunks.begin(), chunks.end());
3054
3055 for (SmallVectorImpl<BlockLayoutChunk>::iterator
3056 i = chunks.begin(), e = chunks.end(); i != e; ++i) {
3057 uint64_t offsetInBits = i->OffsetInBits;
3058 const BlockDecl::Capture *capture = i->Capture;
3059
3060 // If we have a null capture, this must be the C++ 'this' capture.
3061 if (!capture) {
3062 const CXXMethodDecl *method =
3063 cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
3064 QualType type = method->getThisType(C);
3065
3066 fields.push_back(createFieldType("this", type, 0, loc, AS_public,
3067 offsetInBits, tunit, tunit));
3068 continue;
3069 }
3070
3071 const VarDecl *variable = capture->getVariable();
3072 StringRef name = variable->getName();
3073
3074 llvm::DIType fieldType;
3075 if (capture->isByRef()) {
3076 std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
3077
3078 // FIXME: this creates a second copy of this type!
3079 uint64_t xoffset;
3080 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
3081 fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
3082 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
3083 ptrInfo.first, ptrInfo.second,
3084 offsetInBits, 0, fieldType);
3085 } else {
3086 fieldType = createFieldType(name, variable->getType(), 0,
3087 loc, AS_public, offsetInBits, tunit, tunit);
3088 }
3089 fields.push_back(fieldType);
3090 }
3091
3092 SmallString<36> typeName;
3093 llvm::raw_svector_ostream(typeName)
3094 << "__block_literal_" << CGM.getUniqueBlockCount();
3095
3096 llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
3097
3098 llvm::DIType type =
3099 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
3100 CGM.getContext().toBits(block.BlockSize),
3101 CGM.getContext().toBits(block.BlockAlign),
David Blaikie6d4fe152013-02-25 01:07:08 +00003102 0, llvm::DIType(), fieldsArray);
Guy Benyei11169dd2012-12-18 14:30:41 +00003103 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
3104
3105 // Get overall information about the block.
3106 unsigned flags = llvm::DIDescriptor::FlagArtificial;
3107 llvm::MDNode *scope = LexicalBlockStack.back();
Guy Benyei11169dd2012-12-18 14:30:41 +00003108
3109 // Create the descriptor for the parameter.
3110 llvm::DIVariable debugVar =
3111 DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
Eric Christopherb2a008c2013-05-16 00:45:12 +00003112 llvm::DIDescriptor(scope),
Adrian Prantl51936dd2013-03-14 17:53:33 +00003113 Arg->getName(), tunit, line, type,
Guy Benyei11169dd2012-12-18 14:30:41 +00003114 CGM.getLangOpts().Optimize, flags,
Adrian Prantl51936dd2013-03-14 17:53:33 +00003115 cast<llvm::Argument>(Arg)->getArgNo() + 1);
3116
Adrian Prantl616bef42013-03-14 21:52:59 +00003117 if (LocalAddr) {
Adrian Prantl51936dd2013-03-14 17:53:33 +00003118 // Insert an llvm.dbg.value into the current block.
Adrian Prantl616bef42013-03-14 21:52:59 +00003119 llvm::Instruction *DbgVal =
3120 DBuilder.insertDbgValueIntrinsic(LocalAddr, 0, debugVar,
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00003121 Builder.GetInsertBlock());
Adrian Prantl616bef42013-03-14 21:52:59 +00003122 DbgVal->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
3123 }
Adrian Prantl51936dd2013-03-14 17:53:33 +00003124
Adrian Prantl616bef42013-03-14 21:52:59 +00003125 // Insert an llvm.dbg.declare into the current block.
3126 llvm::Instruction *DbgDecl =
3127 DBuilder.insertDeclare(Arg, debugVar, Builder.GetInsertBlock());
3128 DbgDecl->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
Guy Benyei11169dd2012-12-18 14:30:41 +00003129}
3130
David Blaikie6943dea2013-08-20 01:28:15 +00003131/// If D is an out-of-class definition of a static data member of a class, find
3132/// its corresponding in-class declaration.
3133llvm::DIDerivedType
3134CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {
3135 if (!D->isStaticDataMember())
3136 return llvm::DIDerivedType();
3137 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator MI =
3138 StaticDataMemberCache.find(D->getCanonicalDecl());
3139 if (MI != StaticDataMemberCache.end()) {
3140 assert(MI->second && "Static data member declaration should still exist");
3141 return llvm::DIDerivedType(cast<llvm::MDNode>(MI->second));
Evgeniy Stepanov37b3f732013-08-16 10:35:31 +00003142 }
David Blaikiece763042013-08-20 21:49:21 +00003143
3144 // If the member wasn't found in the cache, lazily construct and add it to the
3145 // type (used when a limited form of the type is emitted).
David Blaikie6943dea2013-08-20 01:28:15 +00003146 llvm::DICompositeType Ctxt(
3147 getContextDescriptor(cast<Decl>(D->getDeclContext())));
3148 llvm::DIDerivedType T = CreateRecordStaticField(D, Ctxt);
David Blaikie6943dea2013-08-20 01:28:15 +00003149 return T;
3150}
3151
Guy Benyei11169dd2012-12-18 14:30:41 +00003152/// EmitGlobalVariable - Emit information about a global variable.
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003153void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
Guy Benyei11169dd2012-12-18 14:30:41 +00003154 const VarDecl *D) {
Eric Christopher75e17682013-05-16 00:45:23 +00003155 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00003156 // Create global variable debug descriptor.
3157 llvm::DIFile Unit = getOrCreateFile(D->getLocation());
3158 unsigned LineNo = getLineNumber(D->getLocation());
3159
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003160 setLocation(D->getLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00003161
3162 QualType T = D->getType();
3163 if (T->isIncompleteArrayType()) {
3164
3165 // CodeGen turns int[] into int[1] so we'll do the same here.
3166 llvm::APInt ConstVal(32, 1);
3167 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3168
3169 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3170 ArrayType::Normal, 0);
3171 }
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003172 StringRef DeclName = D->getName();
3173 StringRef LinkageName;
3174 if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext())
3175 && !isa<ObjCMethodDecl>(D->getDeclContext()))
3176 LinkageName = Var->getName();
3177 if (LinkageName == DeclName)
3178 LinkageName = StringRef();
Eric Christopherb2a008c2013-05-16 00:45:12 +00003179 llvm::DIDescriptor DContext =
Guy Benyei11169dd2012-12-18 14:30:41 +00003180 getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
David Blaikie6943dea2013-08-20 01:28:15 +00003181 llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(
3182 DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003183 Var->hasInternalLinkage(), Var,
David Blaikie6943dea2013-08-20 01:28:15 +00003184 getOrCreateStaticDataMemberDeclarationOrNull(D));
David Blaikiebd483762013-05-20 04:58:53 +00003185 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(GV)));
Guy Benyei11169dd2012-12-18 14:30:41 +00003186}
3187
3188/// EmitGlobalVariable - Emit information about an objective-c interface.
3189void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
3190 ObjCInterfaceDecl *ID) {
Eric Christopher75e17682013-05-16 00:45:23 +00003191 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00003192 // Create global variable debug descriptor.
3193 llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
3194 unsigned LineNo = getLineNumber(ID->getLocation());
3195
3196 StringRef Name = ID->getName();
3197
3198 QualType T = CGM.getContext().getObjCInterfaceType(ID);
3199 if (T->isIncompleteArrayType()) {
3200
3201 // CodeGen turns int[] into int[1] so we'll do the same here.
3202 llvm::APInt ConstVal(32, 1);
3203 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3204
3205 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3206 ArrayType::Normal, 0);
3207 }
3208
3209 DBuilder.createGlobalVariable(Name, Unit, LineNo,
3210 getOrCreateType(T, Unit),
3211 Var->hasInternalLinkage(), Var);
3212}
3213
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003214/// EmitGlobalVariable - Emit global variable's debug info.
3215void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
3216 llvm::Constant *Init) {
Eric Christopher75e17682013-05-16 00:45:23 +00003217 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003218 // Create the descriptor for the variable.
3219 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
3220 StringRef Name = VD->getName();
3221 llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
3222 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
3223 const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext());
3224 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
3225 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
3226 }
3227 // Do not use DIGlobalVariable for enums.
3228 if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
3229 return;
3230 llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(
3231 Unit, Name, Name, Unit, getLineNumber(VD->getLocation()), Ty, true, Init,
3232 getOrCreateStaticDataMemberDeclarationOrNull(cast<VarDecl>(VD)));
3233 DeclCache.insert(std::make_pair(VD->getCanonicalDecl(), llvm::WeakVH(GV)));
David Blaikiebd483762013-05-20 04:58:53 +00003234}
3235
3236llvm::DIScope CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
3237 if (!LexicalBlockStack.empty())
3238 return llvm::DIScope(LexicalBlockStack.back());
3239 return getContextDescriptor(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00003240}
3241
David Blaikie9f88fe82013-04-22 06:13:21 +00003242void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
David Blaikiebd483762013-05-20 04:58:53 +00003243 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3244 return;
David Blaikie9f88fe82013-04-22 06:13:21 +00003245 DBuilder.createImportedModule(
David Blaikiebd483762013-05-20 04:58:53 +00003246 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
3247 getOrCreateNameSpace(UD.getNominatedNamespace()),
David Blaikie9f88fe82013-04-22 06:13:21 +00003248 getLineNumber(UD.getLocation()));
3249}
3250
David Blaikiebd483762013-05-20 04:58:53 +00003251void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
3252 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3253 return;
3254 assert(UD.shadow_size() &&
3255 "We shouldn't be codegening an invalid UsingDecl containing no decls");
3256 // Emitting one decl is sufficient - debuggers can detect that this is an
3257 // overloaded name & provide lookup for all the overloads.
3258 const UsingShadowDecl &USD = **UD.shadow_begin();
Adrian Prantl6cdce9e2014-04-01 03:41:01 +00003259 if (llvm::DIScope Target =
Eric Christopher1ecc5632013-06-07 22:54:39 +00003260 getDeclarationOrDefinition(USD.getUnderlyingDecl()))
David Blaikiebd483762013-05-20 04:58:53 +00003261 DBuilder.createImportedDeclaration(
3262 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
3263 getLineNumber(USD.getLocation()));
3264}
3265
David Blaikief121b932013-05-20 22:50:41 +00003266llvm::DIImportedEntity
3267CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
3268 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3269 return llvm::DIImportedEntity(0);
3270 llvm::WeakVH &VH = NamespaceAliasCache[&NA];
3271 if (VH)
3272 return llvm::DIImportedEntity(cast<llvm::MDNode>(VH));
3273 llvm::DIImportedEntity R(0);
3274 if (const NamespaceAliasDecl *Underlying =
3275 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
3276 // This could cache & dedup here rather than relying on metadata deduping.
3277 R = DBuilder.createImportedModule(
3278 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3279 EmitNamespaceAlias(*Underlying), getLineNumber(NA.getLocation()),
3280 NA.getName());
3281 else
3282 R = DBuilder.createImportedModule(
3283 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3284 getOrCreateNameSpace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
3285 getLineNumber(NA.getLocation()), NA.getName());
3286 VH = R;
3287 return R;
3288}
3289
Guy Benyei11169dd2012-12-18 14:30:41 +00003290/// getOrCreateNamesSpace - Return namespace descriptor for the given
3291/// namespace decl.
Eric Christopherb2a008c2013-05-16 00:45:12 +00003292llvm::DINameSpace
Guy Benyei11169dd2012-12-18 14:30:41 +00003293CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
David Blaikie9fdedec2013-08-16 22:52:07 +00003294 NSDecl = NSDecl->getCanonicalDecl();
Eric Christopherb2a008c2013-05-16 00:45:12 +00003295 llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
Guy Benyei11169dd2012-12-18 14:30:41 +00003296 NameSpaceCache.find(NSDecl);
3297 if (I != NameSpaceCache.end())
3298 return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
Eric Christopherb2a008c2013-05-16 00:45:12 +00003299
Guy Benyei11169dd2012-12-18 14:30:41 +00003300 unsigned LineNo = getLineNumber(NSDecl->getLocation());
3301 llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
Eric Christopherb2a008c2013-05-16 00:45:12 +00003302 llvm::DIDescriptor Context =
Guy Benyei11169dd2012-12-18 14:30:41 +00003303 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
3304 llvm::DINameSpace NS =
3305 DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
3306 NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
3307 return NS;
3308}
3309
3310void CGDebugInfo::finalize() {
3311 for (std::vector<std::pair<void *, llvm::WeakVH> >::const_iterator VI
3312 = ReplaceMap.begin(), VE = ReplaceMap.end(); VI != VE; ++VI) {
3313 llvm::DIType Ty, RepTy;
3314 // Verify that the debug info still exists.
3315 if (llvm::Value *V = VI->second)
3316 Ty = llvm::DIType(cast<llvm::MDNode>(V));
Eric Christopherb2a008c2013-05-16 00:45:12 +00003317
Guy Benyei11169dd2012-12-18 14:30:41 +00003318 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
3319 TypeCache.find(VI->first);
3320 if (it != TypeCache.end()) {
3321 // Verify that the debug info still exists.
3322 if (llvm::Value *V = it->second)
3323 RepTy = llvm::DIType(cast<llvm::MDNode>(V));
3324 }
Adrian Prantl73409ce2013-03-11 18:33:46 +00003325
Eric Christopherf8bc4d82013-07-18 00:52:50 +00003326 if (Ty && Ty.isForwardDecl() && RepTy)
Guy Benyei11169dd2012-12-18 14:30:41 +00003327 Ty.replaceAllUsesWith(RepTy);
Guy Benyei11169dd2012-12-18 14:30:41 +00003328 }
Adrian Prantl73409ce2013-03-11 18:33:46 +00003329
3330 // We keep our own list of retained types, because we need to look
3331 // up the final type in the type cache.
3332 for (std::vector<void *>::const_iterator RI = RetainedTypes.begin(),
3333 RE = RetainedTypes.end(); RI != RE; ++RI)
David Blaikie0856f662014-03-04 22:01:08 +00003334 DBuilder.retainType(llvm::DIType(cast<llvm::MDNode>(TypeCache[*RI])));
Adrian Prantl73409ce2013-03-11 18:33:46 +00003335
Guy Benyei11169dd2012-12-18 14:30:41 +00003336 DBuilder.finalize();
3337}