blob: c12e2949bf135f88df86e05cb8a567a4eacf670c [file] [log] [blame]
Guy Benyei11169dd2012-12-18 14:30:41 +00001//===--- CGDebugInfo.cpp - Emit Debug Information for a Module ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the debug information generation while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGDebugInfo.h"
15#include "CGBlocks.h"
David Blaikie38079fd2013-05-10 21:53:14 +000016#include "CGCXXABI.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000017#include "CGObjCRuntime.h"
18#include "CodeGenFunction.h"
19#include "CodeGenModule.h"
20#include "clang/AST/ASTContext.h"
21#include "clang/AST/DeclFriend.h"
22#include "clang/AST/DeclObjC.h"
23#include "clang/AST/DeclTemplate.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/RecordLayout.h"
26#include "clang/Basic/FileManager.h"
27#include "clang/Basic/SourceManager.h"
28#include "clang/Basic/Version.h"
29#include "clang/Frontend/CodeGenOptions.h"
30#include "llvm/ADT/SmallVector.h"
31#include "llvm/ADT/StringExtras.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000032#include "llvm/IR/Constants.h"
33#include "llvm/IR/DataLayout.h"
34#include "llvm/IR/DerivedTypes.h"
35#include "llvm/IR/Instructions.h"
36#include "llvm/IR/Intrinsics.h"
37#include "llvm/IR/Module.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000038#include "llvm/Support/Dwarf.h"
39#include "llvm/Support/FileSystem.h"
Adrian Prantl0630eb72013-12-18 21:48:18 +000040#include "llvm/Support/Path.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000041using namespace clang;
42using namespace clang::CodeGen;
43
44CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
Eric Christopher324bbbd2013-07-14 21:12:44 +000045 : CGM(CGM), DebugKind(CGM.getCodeGenOpts().getDebugInfo()),
46 DBuilder(CGM.getModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +000047 CreateCompileUnit();
48}
49
50CGDebugInfo::~CGDebugInfo() {
51 assert(LexicalBlockStack.empty() &&
52 "Region stack mismatch, stack not empty!");
53}
54
Adrian Prantl2e0637f2013-07-18 00:28:02 +000055
56NoLocation::NoLocation(CodeGenFunction &CGF, CGBuilderTy &B)
57 : DI(CGF.getDebugInfo()), Builder(B) {
58 if (DI) {
59 SavedLoc = DI->getLocation();
60 DI->CurLoc = SourceLocation();
61 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
62 }
63}
64
65NoLocation::~NoLocation() {
66 if (DI) {
67 assert(Builder.getCurrentDebugLocation().isUnknown());
68 DI->CurLoc = SavedLoc;
69 }
70}
71
Adrian Prantlb75016d2013-07-18 01:36:04 +000072ArtificialLocation::ArtificialLocation(CodeGenFunction &CGF, CGBuilderTy &B)
Adrian Prantl2e0637f2013-07-18 00:28:02 +000073 : DI(CGF.getDebugInfo()), Builder(B) {
74 if (DI) {
75 SavedLoc = DI->getLocation();
Adrian Prantl49a78562013-07-24 20:34:39 +000076 DI->CurLoc = SourceLocation();
77 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
78 }
79}
80
81void ArtificialLocation::Emit() {
82 if (DI) {
Adrian Prantl2e0637f2013-07-18 00:28:02 +000083 // Sync the Builder.
84 DI->EmitLocation(Builder, SavedLoc);
85 DI->CurLoc = SourceLocation();
86 // Construct a location that has a valid scope, but no line info.
Adrian Prantl49a78562013-07-24 20:34:39 +000087 assert(!DI->LexicalBlockStack.empty());
88 llvm::DIDescriptor Scope(DI->LexicalBlockStack.back());
Adrian Prantl2e0637f2013-07-18 00:28:02 +000089 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(0, 0, Scope));
90 }
91}
92
Adrian Prantlb75016d2013-07-18 01:36:04 +000093ArtificialLocation::~ArtificialLocation() {
Adrian Prantl2e0637f2013-07-18 00:28:02 +000094 if (DI) {
95 assert(Builder.getCurrentDebugLocation().getLine() == 0);
96 DI->CurLoc = SavedLoc;
97 }
98}
99
Guy Benyei11169dd2012-12-18 14:30:41 +0000100void CGDebugInfo::setLocation(SourceLocation Loc) {
101 // If the new location isn't valid return.
Adrian Prantlb1b3bfc2013-07-18 00:27:56 +0000102 if (Loc.isInvalid()) return;
Guy Benyei11169dd2012-12-18 14:30:41 +0000103
104 CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc);
105
106 // If we've changed files in the middle of a lexical scope go ahead
107 // and create a new lexical scope with file node if it's different
108 // from the one in the scope.
109 if (LexicalBlockStack.empty()) return;
110
111 SourceManager &SM = CGM.getContext().getSourceManager();
112 PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
113 PresumedLoc PPLoc = SM.getPresumedLoc(PrevLoc);
114
115 if (PCLoc.isInvalid() || PPLoc.isInvalid() ||
116 !strcmp(PPLoc.getFilename(), PCLoc.getFilename()))
117 return;
118
119 llvm::MDNode *LB = LexicalBlockStack.back();
120 llvm::DIScope Scope = llvm::DIScope(LB);
121 if (Scope.isLexicalBlockFile()) {
122 llvm::DILexicalBlockFile LBF = llvm::DILexicalBlockFile(LB);
123 llvm::DIDescriptor D
124 = DBuilder.createLexicalBlockFile(LBF.getScope(),
125 getOrCreateFile(CurLoc));
126 llvm::MDNode *N = D;
127 LexicalBlockStack.pop_back();
128 LexicalBlockStack.push_back(N);
David Blaikie0a21d0d2013-01-26 22:16:26 +0000129 } else if (Scope.isLexicalBlock() || Scope.isSubprogram()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000130 llvm::DIDescriptor D
131 = DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc));
132 llvm::MDNode *N = D;
133 LexicalBlockStack.pop_back();
134 LexicalBlockStack.push_back(N);
135 }
136}
137
138/// getContextDescriptor - Get context info for the decl.
David Blaikiebfa52742013-04-19 06:56:38 +0000139llvm::DIScope CGDebugInfo::getContextDescriptor(const Decl *Context) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000140 if (!Context)
141 return TheCU;
142
143 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
144 I = RegionMap.find(Context);
145 if (I != RegionMap.end()) {
146 llvm::Value *V = I->second;
David Blaikiebfa52742013-04-19 06:56:38 +0000147 return llvm::DIScope(dyn_cast_or_null<llvm::MDNode>(V));
Guy Benyei11169dd2012-12-18 14:30:41 +0000148 }
149
150 // Check namespace.
151 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
David Blaikiebfa52742013-04-19 06:56:38 +0000152 return getOrCreateNameSpace(NSDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +0000153
David Blaikiebfa52742013-04-19 06:56:38 +0000154 if (const RecordDecl *RDecl = dyn_cast<RecordDecl>(Context))
155 if (!RDecl->isDependentType())
156 return getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
Guy Benyei11169dd2012-12-18 14:30:41 +0000157 getOrCreateMainFile());
Guy Benyei11169dd2012-12-18 14:30:41 +0000158 return TheCU;
159}
160
161/// getFunctionName - Get function name for the given FunctionDecl. If the
Benjamin Kramer60509af2013-09-09 14:48:42 +0000162/// name is constructed on demand (e.g. C++ destructor) then the name
Guy Benyei11169dd2012-12-18 14:30:41 +0000163/// is stored on the side.
164StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
165 assert (FD && "Invalid FunctionDecl!");
166 IdentifierInfo *FII = FD->getIdentifier();
167 FunctionTemplateSpecializationInfo *Info
168 = FD->getTemplateSpecializationInfo();
169 if (!Info && FII)
170 return FII->getName();
171
172 // Otherwise construct human readable name for debug info.
Benjamin Kramer9170e912013-02-22 15:46:01 +0000173 SmallString<128> NS;
174 llvm::raw_svector_ostream OS(NS);
175 FD->printName(OS);
Guy Benyei11169dd2012-12-18 14:30:41 +0000176
177 // Add any template specialization args.
178 if (Info) {
179 const TemplateArgumentList *TArgs = Info->TemplateArguments;
180 const TemplateArgument *Args = TArgs->data();
181 unsigned NumArgs = TArgs->size();
182 PrintingPolicy Policy(CGM.getLangOpts());
Benjamin Kramer9170e912013-02-22 15:46:01 +0000183 TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs,
184 Policy);
Guy Benyei11169dd2012-12-18 14:30:41 +0000185 }
186
187 // Copy this name on the side and use its reference.
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +0000188 return internString(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +0000189}
190
191StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
192 SmallString<256> MethodName;
193 llvm::raw_svector_ostream OS(MethodName);
194 OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
195 const DeclContext *DC = OMD->getDeclContext();
Eric Christopherb2a008c2013-05-16 00:45:12 +0000196 if (const ObjCImplementationDecl *OID =
Guy Benyei11169dd2012-12-18 14:30:41 +0000197 dyn_cast<const ObjCImplementationDecl>(DC)) {
198 OS << OID->getName();
Eric Christopherb2a008c2013-05-16 00:45:12 +0000199 } else if (const ObjCInterfaceDecl *OID =
Guy Benyei11169dd2012-12-18 14:30:41 +0000200 dyn_cast<const ObjCInterfaceDecl>(DC)) {
201 OS << OID->getName();
Eric Christopherb2a008c2013-05-16 00:45:12 +0000202 } else if (const ObjCCategoryImplDecl *OCD =
Guy Benyei11169dd2012-12-18 14:30:41 +0000203 dyn_cast<const ObjCCategoryImplDecl>(DC)){
204 OS << ((const NamedDecl *)OCD)->getIdentifier()->getNameStart() << '(' <<
205 OCD->getIdentifier()->getNameStart() << ')';
Adrian Prantlb39fc142013-05-17 23:58:45 +0000206 } else if (isa<ObjCProtocolDecl>(DC)) {
Adrian Prantl6e785ec2013-05-17 23:49:10 +0000207 // We can extract the type of the class from the self pointer.
208 if (ImplicitParamDecl* SelfDecl = OMD->getSelfDecl()) {
209 QualType ClassTy =
210 cast<ObjCObjectPointerType>(SelfDecl->getType())->getPointeeType();
211 ClassTy.print(OS, PrintingPolicy(LangOptions()));
212 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000213 }
214 OS << ' ' << OMD->getSelector().getAsString() << ']';
215
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +0000216 return internString(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +0000217}
218
219/// getSelectorName - Return selector name. This is used for debugging
220/// info.
221StringRef CGDebugInfo::getSelectorName(Selector S) {
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +0000222 return internString(S.getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +0000223}
224
225/// getClassName - Get class name including template argument list.
Eric Christopherb2a008c2013-05-16 00:45:12 +0000226StringRef
Guy Benyei11169dd2012-12-18 14:30:41 +0000227CGDebugInfo::getClassName(const RecordDecl *RD) {
228 const ClassTemplateSpecializationDecl *Spec
229 = dyn_cast<ClassTemplateSpecializationDecl>(RD);
230 if (!Spec)
231 return RD->getName();
232
233 const TemplateArgument *Args;
234 unsigned NumArgs;
235 if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) {
236 const TemplateSpecializationType *TST =
237 cast<TemplateSpecializationType>(TAW->getType());
238 Args = TST->getArgs();
239 NumArgs = TST->getNumArgs();
240 } else {
241 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
242 Args = TemplateArgs.data();
243 NumArgs = TemplateArgs.size();
244 }
245 StringRef Name = RD->getIdentifier()->getName();
246 PrintingPolicy Policy(CGM.getLangOpts());
Benjamin Kramer9170e912013-02-22 15:46:01 +0000247 SmallString<128> TemplateArgList;
248 {
249 llvm::raw_svector_ostream OS(TemplateArgList);
250 TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs,
251 Policy);
252 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000253
254 // Copy this name on the side and use its reference.
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +0000255 return internString(Name, TemplateArgList);
Guy Benyei11169dd2012-12-18 14:30:41 +0000256}
257
258/// getOrCreateFile - Get the file debug info descriptor for the input location.
259llvm::DIFile CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
260 if (!Loc.isValid())
261 // If Location is not valid then use main input file.
262 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
263
264 SourceManager &SM = CGM.getContext().getSourceManager();
265 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
266
267 if (PLoc.isInvalid() || StringRef(PLoc.getFilename()).empty())
268 // If the location is not valid then use main input file.
269 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
270
271 // Cache the results.
272 const char *fname = PLoc.getFilename();
273 llvm::DenseMap<const char *, llvm::WeakVH>::iterator it =
274 DIFileCache.find(fname);
275
276 if (it != DIFileCache.end()) {
277 // Verify that the information still exists.
278 if (llvm::Value *V = it->second)
279 return llvm::DIFile(cast<llvm::MDNode>(V));
280 }
281
282 llvm::DIFile F = DBuilder.createFile(PLoc.getFilename(), getCurrentDirname());
283
284 DIFileCache[fname] = F;
285 return F;
286}
287
288/// getOrCreateMainFile - Get the file info for main compile unit.
289llvm::DIFile CGDebugInfo::getOrCreateMainFile() {
290 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
291}
292
293/// getLineNumber - Get line number for the location. If location is invalid
294/// then use current location.
295unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
296 if (Loc.isInvalid() && CurLoc.isInvalid())
297 return 0;
298 SourceManager &SM = CGM.getContext().getSourceManager();
299 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
300 return PLoc.isValid()? PLoc.getLine() : 0;
301}
302
303/// getColumnNumber - Get column number for the location.
Adrian Prantlc7822422013-03-12 20:43:25 +0000304unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000305 // We may not want column information at all.
Adrian Prantlc7822422013-03-12 20:43:25 +0000306 if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo)
Guy Benyei11169dd2012-12-18 14:30:41 +0000307 return 0;
308
309 // If the location is invalid then use the current column.
310 if (Loc.isInvalid() && CurLoc.isInvalid())
311 return 0;
312 SourceManager &SM = CGM.getContext().getSourceManager();
313 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
314 return PLoc.isValid()? PLoc.getColumn() : 0;
315}
316
317StringRef CGDebugInfo::getCurrentDirname() {
318 if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
319 return CGM.getCodeGenOpts().DebugCompilationDir;
320
321 if (!CWDName.empty())
322 return CWDName;
323 SmallString<256> CWD;
324 llvm::sys::fs::current_path(CWD);
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +0000325 return CWDName = internString(CWD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000326}
327
328/// CreateCompileUnit - Create new compile unit.
329void CGDebugInfo::CreateCompileUnit() {
330
331 // Get absolute path name.
332 SourceManager &SM = CGM.getContext().getSourceManager();
333 std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
334 if (MainFileName.empty())
335 MainFileName = "<unknown>";
336
337 // The main file name provided via the "-main-file-name" option contains just
338 // the file name itself with no path information. This file name may have had
339 // a relative path, so we look into the actual file entry for the main
340 // file to determine the real absolute path for the file.
341 std::string MainFileDir;
342 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
343 MainFileDir = MainFile->getDir()->getName();
Yaron Keren9fb7e902013-10-21 20:07:37 +0000344 if (MainFileDir != ".") {
345 llvm::SmallString<1024> MainFileDirSS(MainFileDir);
346 llvm::sys::path::append(MainFileDirSS, MainFileName);
347 MainFileName = MainFileDirSS.str();
348 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000349 }
350
351 // Save filename string.
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +0000352 StringRef Filename = internString(MainFileName);
Eric Christopherf1545832013-02-22 23:50:16 +0000353
354 // Save split dwarf file string.
355 std::string SplitDwarfFile = CGM.getCodeGenOpts().SplitDwarfFile;
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +0000356 StringRef SplitDwarfFilename = internString(SplitDwarfFile);
Eric Christopherb2a008c2013-05-16 00:45:12 +0000357
Guy Benyei11169dd2012-12-18 14:30:41 +0000358 unsigned LangTag;
359 const LangOptions &LO = CGM.getLangOpts();
360 if (LO.CPlusPlus) {
361 if (LO.ObjC1)
362 LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
363 else
364 LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
365 } else if (LO.ObjC1) {
366 LangTag = llvm::dwarf::DW_LANG_ObjC;
367 } else if (LO.C99) {
368 LangTag = llvm::dwarf::DW_LANG_C99;
369 } else {
370 LangTag = llvm::dwarf::DW_LANG_C89;
371 }
372
373 std::string Producer = getClangFullVersion();
374
375 // Figure out which version of the ObjC runtime we have.
376 unsigned RuntimeVers = 0;
377 if (LO.ObjC1)
378 RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
379
380 // Create new compile unit.
Guy Benyei11169dd2012-12-18 14:30:41 +0000381 // FIXME - Eliminate TheCU.
Eric Christopher978c8392013-07-19 00:51:58 +0000382 TheCU = DBuilder.createCompileUnit(LangTag, Filename, getCurrentDirname(),
383 Producer, LO.Optimize,
384 CGM.getCodeGenOpts().DwarfDebugFlags,
385 RuntimeVers, SplitDwarfFilename);
Guy Benyei11169dd2012-12-18 14:30:41 +0000386}
387
388/// CreateType - Get the Basic type from the cache or create a new
389/// one if necessary.
390llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT) {
391 unsigned Encoding = 0;
392 StringRef BTName;
393 switch (BT->getKind()) {
394#define BUILTIN_TYPE(Id, SingletonId)
395#define PLACEHOLDER_TYPE(Id, SingletonId) \
396 case BuiltinType::Id:
397#include "clang/AST/BuiltinTypes.def"
398 case BuiltinType::Dependent:
399 llvm_unreachable("Unexpected builtin type");
400 case BuiltinType::NullPtr:
Peter Collingbourne5c5e6172013-06-27 22:51:01 +0000401 return DBuilder.createNullPtrType();
Guy Benyei11169dd2012-12-18 14:30:41 +0000402 case BuiltinType::Void:
403 return llvm::DIType();
404 case BuiltinType::ObjCClass:
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000405 if (ClassTy)
Guy Benyei11169dd2012-12-18 14:30:41 +0000406 return ClassTy;
407 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
408 "objc_class", TheCU,
409 getOrCreateMainFile(), 0);
410 return ClassTy;
411 case BuiltinType::ObjCId: {
412 // typedef struct objc_class *Class;
413 // typedef struct objc_object {
414 // Class isa;
415 // } *id;
416
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000417 if (ObjTy)
Guy Benyei11169dd2012-12-18 14:30:41 +0000418 return ObjTy;
419
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000420 if (!ClassTy)
Guy Benyei11169dd2012-12-18 14:30:41 +0000421 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
422 "objc_class", TheCU,
423 getOrCreateMainFile(), 0);
424
425 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
Eric Christopherb2a008c2013-05-16 00:45:12 +0000426
Guy Benyei11169dd2012-12-18 14:30:41 +0000427 llvm::DIType ISATy = DBuilder.createPointerType(ClassTy, Size);
428
Eric Christopher5c7ee8b2013-04-02 22:59:11 +0000429 ObjTy =
David Blaikie6d4fe152013-02-25 01:07:08 +0000430 DBuilder.createStructType(TheCU, "objc_object", getOrCreateMainFile(),
431 0, 0, 0, 0, llvm::DIType(), llvm::DIArray());
Guy Benyei11169dd2012-12-18 14:30:41 +0000432
Eric Christopher5c7ee8b2013-04-02 22:59:11 +0000433 ObjTy.setTypeArray(DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
434 ObjTy, "isa", getOrCreateMainFile(), 0, Size, 0, 0, 0, ISATy)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000435 return ObjTy;
436 }
437 case BuiltinType::ObjCSel: {
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000438 if (SelTy)
Guy Benyei11169dd2012-12-18 14:30:41 +0000439 return SelTy;
440 SelTy =
441 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
442 "objc_selector", TheCU, getOrCreateMainFile(),
443 0);
444 return SelTy;
445 }
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000446
447 case BuiltinType::OCLImage1d:
448 return getOrCreateStructPtrType("opencl_image1d_t",
449 OCLImage1dDITy);
450 case BuiltinType::OCLImage1dArray:
Eric Christopherb2a008c2013-05-16 00:45:12 +0000451 return getOrCreateStructPtrType("opencl_image1d_array_t",
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000452 OCLImage1dArrayDITy);
453 case BuiltinType::OCLImage1dBuffer:
454 return getOrCreateStructPtrType("opencl_image1d_buffer_t",
455 OCLImage1dBufferDITy);
456 case BuiltinType::OCLImage2d:
457 return getOrCreateStructPtrType("opencl_image2d_t",
458 OCLImage2dDITy);
459 case BuiltinType::OCLImage2dArray:
460 return getOrCreateStructPtrType("opencl_image2d_array_t",
461 OCLImage2dArrayDITy);
462 case BuiltinType::OCLImage3d:
463 return getOrCreateStructPtrType("opencl_image3d_t",
464 OCLImage3dDITy);
Guy Benyei61054192013-02-07 10:55:47 +0000465 case BuiltinType::OCLSampler:
466 return DBuilder.createBasicType("opencl_sampler_t",
467 CGM.getContext().getTypeSize(BT),
468 CGM.getContext().getTypeAlign(BT),
469 llvm::dwarf::DW_ATE_unsigned);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +0000470 case BuiltinType::OCLEvent:
471 return getOrCreateStructPtrType("opencl_event_t",
472 OCLEventDITy);
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000473
Guy Benyei11169dd2012-12-18 14:30:41 +0000474 case BuiltinType::UChar:
475 case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
476 case BuiltinType::Char_S:
477 case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
478 case BuiltinType::Char16:
479 case BuiltinType::Char32: Encoding = llvm::dwarf::DW_ATE_UTF; break;
480 case BuiltinType::UShort:
481 case BuiltinType::UInt:
482 case BuiltinType::UInt128:
483 case BuiltinType::ULong:
484 case BuiltinType::WChar_U:
485 case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
486 case BuiltinType::Short:
487 case BuiltinType::Int:
488 case BuiltinType::Int128:
489 case BuiltinType::Long:
490 case BuiltinType::WChar_S:
491 case BuiltinType::LongLong: Encoding = llvm::dwarf::DW_ATE_signed; break;
492 case BuiltinType::Bool: Encoding = llvm::dwarf::DW_ATE_boolean; break;
493 case BuiltinType::Half:
494 case BuiltinType::Float:
495 case BuiltinType::LongDouble:
496 case BuiltinType::Double: Encoding = llvm::dwarf::DW_ATE_float; break;
497 }
498
499 switch (BT->getKind()) {
500 case BuiltinType::Long: BTName = "long int"; break;
501 case BuiltinType::LongLong: BTName = "long long int"; break;
502 case BuiltinType::ULong: BTName = "long unsigned int"; break;
503 case BuiltinType::ULongLong: BTName = "long long unsigned int"; break;
504 default:
505 BTName = BT->getName(CGM.getLangOpts());
506 break;
507 }
508 // Bit size, align and offset of the type.
509 uint64_t Size = CGM.getContext().getTypeSize(BT);
510 uint64_t Align = CGM.getContext().getTypeAlign(BT);
Eric Christopherb2a008c2013-05-16 00:45:12 +0000511 llvm::DIType DbgTy =
Guy Benyei11169dd2012-12-18 14:30:41 +0000512 DBuilder.createBasicType(BTName, Size, Align, Encoding);
513 return DbgTy;
514}
515
516llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty) {
517 // Bit size, align and offset of the type.
518 unsigned Encoding = llvm::dwarf::DW_ATE_complex_float;
519 if (Ty->isComplexIntegerType())
520 Encoding = llvm::dwarf::DW_ATE_lo_user;
521
522 uint64_t Size = CGM.getContext().getTypeSize(Ty);
523 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
Eric Christopherb2a008c2013-05-16 00:45:12 +0000524 llvm::DIType DbgTy =
Guy Benyei11169dd2012-12-18 14:30:41 +0000525 DBuilder.createBasicType("complex", Size, Align, Encoding);
526
527 return DbgTy;
528}
529
530/// CreateCVRType - Get the qualified type from the cache or create
531/// a new one if necessary.
David Blaikie99dab3b2013-09-04 22:03:57 +0000532llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000533 QualifierCollector Qc;
534 const Type *T = Qc.strip(Ty);
535
536 // Ignore these qualifiers for now.
537 Qc.removeObjCGCAttr();
538 Qc.removeAddressSpace();
539 Qc.removeObjCLifetime();
540
541 // We will create one Derived type for one qualifier and recurse to handle any
542 // additional ones.
543 unsigned Tag;
544 if (Qc.hasConst()) {
545 Tag = llvm::dwarf::DW_TAG_const_type;
546 Qc.removeConst();
547 } else if (Qc.hasVolatile()) {
548 Tag = llvm::dwarf::DW_TAG_volatile_type;
549 Qc.removeVolatile();
550 } else if (Qc.hasRestrict()) {
551 Tag = llvm::dwarf::DW_TAG_restrict_type;
552 Qc.removeRestrict();
553 } else {
554 assert(Qc.empty() && "Unknown type qualifier for debug info");
555 return getOrCreateType(QualType(T, 0), Unit);
556 }
557
David Blaikie99dab3b2013-09-04 22:03:57 +0000558 llvm::DIType FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +0000559
560 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
561 // CVR derived types.
562 llvm::DIType DbgTy = DBuilder.createQualifiedType(Tag, FromTy);
Eric Christopherb2a008c2013-05-16 00:45:12 +0000563
Guy Benyei11169dd2012-12-18 14:30:41 +0000564 return DbgTy;
565}
566
567llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
568 llvm::DIFile Unit) {
Fariborz Jahanian65f1fa12013-02-21 20:42:11 +0000569
570 // The frontend treats 'id' as a typedef to an ObjCObjectType,
571 // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
572 // debug info, we want to emit 'id' in both cases.
573 if (Ty->isObjCQualifiedIdType())
574 return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
575
Guy Benyei11169dd2012-12-18 14:30:41 +0000576 llvm::DIType DbgTy =
Eric Christopherb2a008c2013-05-16 00:45:12 +0000577 CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +0000578 Ty->getPointeeType(), Unit);
579 return DbgTy;
580}
581
582llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
583 llvm::DIFile Unit) {
Eric Christopherb2a008c2013-05-16 00:45:12 +0000584 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +0000585 Ty->getPointeeType(), Unit);
586}
587
Manman Rene0064d82013-08-29 23:19:58 +0000588/// In C++ mode, types have linkage, so we can rely on the ODR and
589/// on their mangled names, if they're external.
590static SmallString<256>
591getUniqueTagTypeName(const TagType *Ty, CodeGenModule &CGM,
592 llvm::DICompileUnit TheCU) {
593 SmallString<256> FullName;
594 // FIXME: ODR should apply to ObjC++ exactly the same wasy it does to C++.
595 // For now, only apply ODR with C++.
596 const TagDecl *TD = Ty->getDecl();
597 if (TheCU.getLanguage() != llvm::dwarf::DW_LANG_C_plus_plus ||
598 !TD->isExternallyVisible())
599 return FullName;
600 // Microsoft Mangler does not have support for mangleCXXRTTIName yet.
601 if (CGM.getTarget().getCXXABI().isMicrosoft())
602 return FullName;
603
604 // TODO: This is using the RTTI name. Is there a better way to get
605 // a unique string for a type?
606 llvm::raw_svector_ostream Out(FullName);
607 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(QualType(Ty, 0), Out);
608 Out.flush();
609 return FullName;
610}
611
Guy Benyei11169dd2012-12-18 14:30:41 +0000612// Creates a forward declaration for a RecordDecl in the given context.
David Blaikie8d5e1282013-08-20 21:03:29 +0000613llvm::DICompositeType
Manman Ren1b457022013-08-28 21:20:28 +0000614CGDebugInfo::getOrCreateRecordFwdDecl(const RecordType *Ty,
David Blaikie8d5e1282013-08-20 21:03:29 +0000615 llvm::DIDescriptor Ctx) {
Manman Ren1b457022013-08-28 21:20:28 +0000616 const RecordDecl *RD = Ty->getDecl();
David Blaikie4e7ef802013-08-15 20:17:25 +0000617 if (llvm::DIType T = getTypeOrNull(CGM.getContext().getRecordType(RD)))
David Blaikie8d5e1282013-08-20 21:03:29 +0000618 return llvm::DICompositeType(T);
Guy Benyei11169dd2012-12-18 14:30:41 +0000619 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
620 unsigned Line = getLineNumber(RD->getLocation());
621 StringRef RDName = getClassName(RD);
622
623 unsigned Tag = 0;
624 if (RD->isStruct() || RD->isInterface())
625 Tag = llvm::dwarf::DW_TAG_structure_type;
626 else if (RD->isUnion())
627 Tag = llvm::dwarf::DW_TAG_union_type;
628 else {
629 assert(RD->isClass());
630 Tag = llvm::dwarf::DW_TAG_class_type;
631 }
632
633 // Create the type.
Manman Rene0064d82013-08-29 23:19:58 +0000634 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
635 return DBuilder.createForwardDecl(Tag, RDName, Ctx, DefUnit, Line, 0, 0, 0,
636 FullName);
Guy Benyei11169dd2012-12-18 14:30:41 +0000637}
638
Guy Benyei11169dd2012-12-18 14:30:41 +0000639llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag,
Eric Christopherb2a008c2013-05-16 00:45:12 +0000640 const Type *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +0000641 QualType PointeeTy,
642 llvm::DIFile Unit) {
643 if (Tag == llvm::dwarf::DW_TAG_reference_type ||
644 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
David Blaikie99dab3b2013-09-04 22:03:57 +0000645 return DBuilder.createReferenceType(Tag, getOrCreateType(PointeeTy, Unit));
Fariborz Jahanian65f1fa12013-02-21 20:42:11 +0000646
Guy Benyei11169dd2012-12-18 14:30:41 +0000647 // Bit size, align and offset of the type.
648 // Size is always the size of a pointer. We can't use getTypeSize here
649 // because that does not return the correct value for references.
650 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCallc8e01702013-04-16 22:48:15 +0000651 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
Guy Benyei11169dd2012-12-18 14:30:41 +0000652 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
653
David Blaikie99dab3b2013-09-04 22:03:57 +0000654 return DBuilder.createPointerType(getOrCreateType(PointeeTy, Unit), Size,
655 Align);
Guy Benyei11169dd2012-12-18 14:30:41 +0000656}
657
Eric Christopher0fdcb312013-05-16 00:52:20 +0000658llvm::DIType CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
659 llvm::DIType &Cache) {
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000660 if (Cache)
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000661 return Cache;
David Blaikiefefc7f72013-05-21 17:58:54 +0000662 Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
663 TheCU, getOrCreateMainFile(), 0);
664 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
665 Cache = DBuilder.createPointerType(Cache, Size);
666 return Cache;
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000667}
668
Guy Benyei11169dd2012-12-18 14:30:41 +0000669llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
670 llvm::DIFile Unit) {
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000671 if (BlockLiteralGeneric)
Guy Benyei11169dd2012-12-18 14:30:41 +0000672 return BlockLiteralGeneric;
673
674 SmallVector<llvm::Value *, 8> EltTys;
675 llvm::DIType FieldTy;
676 QualType FType;
677 uint64_t FieldSize, FieldOffset;
678 unsigned FieldAlign;
679 llvm::DIArray Elements;
680 llvm::DIType EltTy, DescTy;
681
682 FieldOffset = 0;
683 FType = CGM.getContext().UnsignedLongTy;
684 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
685 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
686
687 Elements = DBuilder.getOrCreateArray(EltTys);
688 EltTys.clear();
689
690 unsigned Flags = llvm::DIDescriptor::FlagAppleBlock;
691 unsigned LineNo = getLineNumber(CurLoc);
692
693 EltTy = DBuilder.createStructType(Unit, "__block_descriptor",
694 Unit, LineNo, FieldOffset, 0,
David Blaikie6d4fe152013-02-25 01:07:08 +0000695 Flags, llvm::DIType(), Elements);
Guy Benyei11169dd2012-12-18 14:30:41 +0000696
697 // Bit size, align and offset of the type.
698 uint64_t Size = CGM.getContext().getTypeSize(Ty);
699
700 DescTy = DBuilder.createPointerType(EltTy, Size);
701
702 FieldOffset = 0;
703 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
704 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
705 FType = CGM.getContext().IntTy;
706 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
707 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
708 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
709 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
710
711 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
712 FieldTy = DescTy;
713 FieldSize = CGM.getContext().getTypeSize(Ty);
714 FieldAlign = CGM.getContext().getTypeAlign(Ty);
715 FieldTy = DBuilder.createMemberType(Unit, "__descriptor", Unit,
716 LineNo, FieldSize, FieldAlign,
717 FieldOffset, 0, FieldTy);
718 EltTys.push_back(FieldTy);
719
720 FieldOffset += FieldSize;
721 Elements = DBuilder.getOrCreateArray(EltTys);
722
723 EltTy = DBuilder.createStructType(Unit, "__block_literal_generic",
724 Unit, LineNo, FieldOffset, 0,
David Blaikie6d4fe152013-02-25 01:07:08 +0000725 Flags, llvm::DIType(), Elements);
Guy Benyei11169dd2012-12-18 14:30:41 +0000726
Guy Benyei11169dd2012-12-18 14:30:41 +0000727 BlockLiteralGeneric = DBuilder.createPointerType(EltTy, Size);
728 return BlockLiteralGeneric;
729}
730
David Blaikie99dab3b2013-09-04 22:03:57 +0000731llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty, llvm::DIFile Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000732 // Typedefs are derived from some other type. If we have a typedef of a
733 // typedef, make sure to emit the whole chain.
David Blaikie99dab3b2013-09-04 22:03:57 +0000734 llvm::DIType Src = getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000735 if (!Src)
Guy Benyei11169dd2012-12-18 14:30:41 +0000736 return llvm::DIType();
737 // We don't set size information, but do specify where the typedef was
738 // declared.
739 unsigned Line = getLineNumber(Ty->getDecl()->getLocation());
740 const TypedefNameDecl *TyDecl = Ty->getDecl();
Eric Christopherb2a008c2013-05-16 00:45:12 +0000741
Guy Benyei11169dd2012-12-18 14:30:41 +0000742 llvm::DIDescriptor TypedefContext =
743 getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext()));
Eric Christopherb2a008c2013-05-16 00:45:12 +0000744
Guy Benyei11169dd2012-12-18 14:30:41 +0000745 return
746 DBuilder.createTypedef(Src, TyDecl->getName(), Unit, Line, TypedefContext);
747}
748
749llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
750 llvm::DIFile Unit) {
751 SmallVector<llvm::Value *, 16> EltTys;
752
753 // Add the result type at least.
David Blaikie99dab3b2013-09-04 22:03:57 +0000754 EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit));
Guy Benyei11169dd2012-12-18 14:30:41 +0000755
756 // Set up remainder of arguments if there is a prototype.
757 // FIXME: IF NOT, HOW IS THIS REPRESENTED? llvm-gcc doesn't represent '...'!
758 if (isa<FunctionNoProtoType>(Ty))
759 EltTys.push_back(DBuilder.createUnspecifiedParameter());
760 else if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Ty)) {
761 for (unsigned i = 0, e = FPT->getNumArgs(); i != e; ++i)
David Blaikie99dab3b2013-09-04 22:03:57 +0000762 EltTys.push_back(getOrCreateType(FPT->getArgType(i), Unit));
Guy Benyei11169dd2012-12-18 14:30:41 +0000763 }
764
765 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
766 return DBuilder.createSubroutineType(Unit, EltTypeArray);
767}
768
769
Guy Benyei11169dd2012-12-18 14:30:41 +0000770llvm::DIType CGDebugInfo::createFieldType(StringRef name,
771 QualType type,
772 uint64_t sizeInBitsOverride,
773 SourceLocation loc,
774 AccessSpecifier AS,
775 uint64_t offsetInBits,
776 llvm::DIFile tunit,
Manman Ren2c826dc2013-09-08 03:45:05 +0000777 llvm::DIScope scope) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000778 llvm::DIType debugType = getOrCreateType(type, tunit);
779
780 // Get the location for the field.
781 llvm::DIFile file = getOrCreateFile(loc);
782 unsigned line = getLineNumber(loc);
783
784 uint64_t sizeInBits = 0;
785 unsigned alignInBits = 0;
786 if (!type->isIncompleteArrayType()) {
787 llvm::tie(sizeInBits, alignInBits) = CGM.getContext().getTypeInfo(type);
788
789 if (sizeInBitsOverride)
790 sizeInBits = sizeInBitsOverride;
791 }
792
793 unsigned flags = 0;
794 if (AS == clang::AS_private)
795 flags |= llvm::DIDescriptor::FlagPrivate;
796 else if (AS == clang::AS_protected)
797 flags |= llvm::DIDescriptor::FlagProtected;
798
799 return DBuilder.createMemberType(scope, name, file, line, sizeInBits,
800 alignInBits, offsetInBits, flags, debugType);
801}
802
Eric Christopher91a31902013-01-16 01:22:32 +0000803/// CollectRecordLambdaFields - Helper for CollectRecordFields.
804void CGDebugInfo::
805CollectRecordLambdaFields(const CXXRecordDecl *CXXDecl,
806 SmallVectorImpl<llvm::Value *> &elements,
807 llvm::DIType RecordTy) {
808 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
809 // has the name and the location of the variable so we should iterate over
810 // both concurrently.
811 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
812 RecordDecl::field_iterator Field = CXXDecl->field_begin();
813 unsigned fieldno = 0;
814 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
815 E = CXXDecl->captures_end(); I != E; ++I, ++Field, ++fieldno) {
816 const LambdaExpr::Capture C = *I;
817 if (C.capturesVariable()) {
818 VarDecl *V = C.getCapturedVar();
819 llvm::DIFile VUnit = getOrCreateFile(C.getLocation());
820 StringRef VName = V->getName();
821 uint64_t SizeInBitsOverride = 0;
822 if (Field->isBitField()) {
823 SizeInBitsOverride = Field->getBitWidthValue(CGM.getContext());
824 assert(SizeInBitsOverride && "found named 0-width bitfield");
825 }
826 llvm::DIType fieldType
827 = createFieldType(VName, Field->getType(), SizeInBitsOverride,
828 C.getLocation(), Field->getAccess(),
829 layout.getFieldOffset(fieldno), VUnit, RecordTy);
830 elements.push_back(fieldType);
831 } else {
832 // TODO: Need to handle 'this' in some way by probably renaming the
833 // this of the lambda class and having a field member of 'this' or
834 // by using AT_object_pointer for the function and having that be
835 // used as 'this' for semantic references.
836 assert(C.capturesThis() && "Field that isn't captured and isn't this?");
837 FieldDecl *f = *Field;
838 llvm::DIFile VUnit = getOrCreateFile(f->getLocation());
839 QualType type = f->getType();
840 llvm::DIType fieldType
841 = createFieldType("this", type, 0, f->getLocation(), f->getAccess(),
842 layout.getFieldOffset(fieldno), VUnit, RecordTy);
843
844 elements.push_back(fieldType);
845 }
846 }
847}
848
David Blaikie6943dea2013-08-20 01:28:15 +0000849/// Helper for CollectRecordFields.
David Blaikieae019462013-08-15 22:50:29 +0000850llvm::DIDerivedType
851CGDebugInfo::CreateRecordStaticField(const VarDecl *Var,
852 llvm::DIType RecordTy) {
Eric Christopher91a31902013-01-16 01:22:32 +0000853 // Create the descriptor for the static variable, with or without
854 // constant initializers.
855 llvm::DIFile VUnit = getOrCreateFile(Var->getLocation());
856 llvm::DIType VTy = getOrCreateType(Var->getType(), VUnit);
857
Eric Christopher91a31902013-01-16 01:22:32 +0000858 unsigned LineNumber = getLineNumber(Var->getLocation());
859 StringRef VName = Var->getName();
David Blaikied42917f2013-01-20 01:19:17 +0000860 llvm::Constant *C = NULL;
Eric Christopher91a31902013-01-16 01:22:32 +0000861 if (Var->getInit()) {
862 const APValue *Value = Var->evaluateValue();
David Blaikied42917f2013-01-20 01:19:17 +0000863 if (Value) {
864 if (Value->isInt())
865 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
866 if (Value->isFloat())
867 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
868 }
Eric Christopher91a31902013-01-16 01:22:32 +0000869 }
870
871 unsigned Flags = 0;
872 AccessSpecifier Access = Var->getAccess();
873 if (Access == clang::AS_private)
874 Flags |= llvm::DIDescriptor::FlagPrivate;
875 else if (Access == clang::AS_protected)
876 Flags |= llvm::DIDescriptor::FlagProtected;
877
David Blaikieae019462013-08-15 22:50:29 +0000878 llvm::DIDerivedType GV = DBuilder.createStaticMemberType(
879 RecordTy, VName, VUnit, LineNumber, VTy, Flags, C);
Eric Christopher91a31902013-01-16 01:22:32 +0000880 StaticDataMemberCache[Var->getCanonicalDecl()] = llvm::WeakVH(GV);
David Blaikieae019462013-08-15 22:50:29 +0000881 return GV;
Eric Christopher91a31902013-01-16 01:22:32 +0000882}
883
884/// CollectRecordNormalField - Helper for CollectRecordFields.
885void CGDebugInfo::
886CollectRecordNormalField(const FieldDecl *field, uint64_t OffsetInBits,
887 llvm::DIFile tunit,
888 SmallVectorImpl<llvm::Value *> &elements,
889 llvm::DIType RecordTy) {
890 StringRef name = field->getName();
891 QualType type = field->getType();
892
893 // Ignore unnamed fields unless they're anonymous structs/unions.
894 if (name.empty() && !type->isRecordType())
895 return;
896
897 uint64_t SizeInBitsOverride = 0;
898 if (field->isBitField()) {
899 SizeInBitsOverride = field->getBitWidthValue(CGM.getContext());
900 assert(SizeInBitsOverride && "found named 0-width bitfield");
901 }
902
903 llvm::DIType fieldType
904 = createFieldType(name, type, SizeInBitsOverride,
905 field->getLocation(), field->getAccess(),
906 OffsetInBits, tunit, RecordTy);
907
908 elements.push_back(fieldType);
909}
910
Guy Benyei11169dd2012-12-18 14:30:41 +0000911/// CollectRecordFields - A helper function to collect debug info for
912/// record fields. This is used while creating debug info entry for a Record.
David Blaikieab255bb2013-08-16 20:40:25 +0000913void CGDebugInfo::CollectRecordFields(const RecordDecl *record,
914 llvm::DIFile tunit,
915 SmallVectorImpl<llvm::Value *> &elements,
916 llvm::DICompositeType RecordTy) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000917 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(record);
918
Eric Christopher91a31902013-01-16 01:22:32 +0000919 if (CXXDecl && CXXDecl->isLambda())
920 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
921 else {
922 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
Guy Benyei11169dd2012-12-18 14:30:41 +0000923
Eric Christopher91a31902013-01-16 01:22:32 +0000924 // Field number for non-static fields.
Eric Christopher0f7594372013-01-04 17:59:07 +0000925 unsigned fieldNo = 0;
Eric Christopher91a31902013-01-16 01:22:32 +0000926
Eric Christopher91a31902013-01-16 01:22:32 +0000927 // Static and non-static members should appear in the same order as
928 // the corresponding declarations in the source program.
929 for (RecordDecl::decl_iterator I = record->decls_begin(),
930 E = record->decls_end(); I != E; ++I)
David Blaikiece763042013-08-20 21:49:21 +0000931 if (const VarDecl *V = dyn_cast<VarDecl>(*I)) {
932 // Reuse the existing static member declaration if one exists
933 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator MI =
934 StaticDataMemberCache.find(V->getCanonicalDecl());
935 if (MI != StaticDataMemberCache.end()) {
936 assert(MI->second &&
937 "Static data member declaration should still exist");
938 elements.push_back(
939 llvm::DIDerivedType(cast<llvm::MDNode>(MI->second)));
940 } else
941 elements.push_back(CreateRecordStaticField(V, RecordTy));
942 } else if (FieldDecl *field = dyn_cast<FieldDecl>(*I)) {
Eric Christopher91a31902013-01-16 01:22:32 +0000943 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo),
944 tunit, elements, RecordTy);
945
946 // Bump field number for next field.
947 ++fieldNo;
Guy Benyei11169dd2012-12-18 14:30:41 +0000948 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000949 }
950}
951
952/// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
953/// function type is not updated to include implicit "this" pointer. Use this
954/// routine to get a method type which includes "this" pointer.
David Blaikie469f0792013-05-22 23:22:42 +0000955llvm::DICompositeType
Guy Benyei11169dd2012-12-18 14:30:41 +0000956CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
957 llvm::DIFile Unit) {
David Blaikie7eb06852013-01-07 23:06:35 +0000958 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
David Blaikie2aaf0652013-01-07 22:24:59 +0000959 if (Method->isStatic())
David Blaikie469f0792013-05-22 23:22:42 +0000960 return llvm::DICompositeType(getOrCreateType(QualType(Func, 0), Unit));
David Blaikie7eb06852013-01-07 23:06:35 +0000961 return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()),
962 Func, Unit);
963}
David Blaikie2aaf0652013-01-07 22:24:59 +0000964
David Blaikie469f0792013-05-22 23:22:42 +0000965llvm::DICompositeType CGDebugInfo::getOrCreateInstanceMethodType(
David Blaikie7eb06852013-01-07 23:06:35 +0000966 QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000967 // Add "this" pointer.
David Blaikie7eb06852013-01-07 23:06:35 +0000968 llvm::DIArray Args = llvm::DICompositeType(
969 getOrCreateType(QualType(Func, 0), Unit)).getTypeArray();
Guy Benyei11169dd2012-12-18 14:30:41 +0000970 assert (Args.getNumElements() && "Invalid number of arguments!");
971
972 SmallVector<llvm::Value *, 16> Elts;
973
974 // First element is always return type. For 'void' functions it is NULL.
975 Elts.push_back(Args.getElement(0));
976
David Blaikie2aaf0652013-01-07 22:24:59 +0000977 // "this" pointer is always first argument.
David Blaikie7eb06852013-01-07 23:06:35 +0000978 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
David Blaikie2aaf0652013-01-07 22:24:59 +0000979 if (isa<ClassTemplateSpecializationDecl>(RD)) {
980 // Create pointer type directly in this case.
981 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
982 QualType PointeeTy = ThisPtrTy->getPointeeType();
983 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCallc8e01702013-04-16 22:48:15 +0000984 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
David Blaikie2aaf0652013-01-07 22:24:59 +0000985 uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy);
986 llvm::DIType PointeeType = getOrCreateType(PointeeTy, Unit);
Eric Christopher0fdcb312013-05-16 00:52:20 +0000987 llvm::DIType ThisPtrType =
988 DBuilder.createPointerType(PointeeType, Size, Align);
David Blaikie2aaf0652013-01-07 22:24:59 +0000989 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
990 // TODO: This and the artificial type below are misleading, the
991 // types aren't artificial the argument is, but the current
992 // metadata doesn't represent that.
993 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
994 Elts.push_back(ThisPtrType);
995 } else {
996 llvm::DIType ThisPtrType = getOrCreateType(ThisPtr, Unit);
997 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
998 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
999 Elts.push_back(ThisPtrType);
Guy Benyei11169dd2012-12-18 14:30:41 +00001000 }
1001
1002 // Copy rest of the arguments.
1003 for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
1004 Elts.push_back(Args.getElement(i));
1005
1006 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
1007
Adrian Prantl0630eb72013-12-18 21:48:18 +00001008 unsigned Flags = 0;
1009 if (Func->getExtProtoInfo().RefQualifier == RQ_LValue)
1010 Flags |= llvm::DIDescriptor::FlagLValueReference;
1011 if (Func->getExtProtoInfo().RefQualifier == RQ_RValue)
1012 Flags |= llvm::DIDescriptor::FlagRValueReference;
1013
1014 return DBuilder.createSubroutineType(Unit, EltTypeArray, Flags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001015}
1016
Eric Christopherb2a008c2013-05-16 00:45:12 +00001017/// isFunctionLocalClass - Return true if CXXRecordDecl is defined
Guy Benyei11169dd2012-12-18 14:30:41 +00001018/// inside a function.
1019static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
1020 if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
1021 return isFunctionLocalClass(NRD);
1022 if (isa<FunctionDecl>(RD->getDeclContext()))
1023 return true;
1024 return false;
1025}
1026
1027/// CreateCXXMemberFunction - A helper function to create a DISubprogram for
1028/// a single member function GlobalDecl.
1029llvm::DISubprogram
1030CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
1031 llvm::DIFile Unit,
1032 llvm::DIType RecordTy) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001033 bool IsCtorOrDtor =
Guy Benyei11169dd2012-12-18 14:30:41 +00001034 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
Eric Christopherb2a008c2013-05-16 00:45:12 +00001035
Guy Benyei11169dd2012-12-18 14:30:41 +00001036 StringRef MethodName = getFunctionName(Method);
David Blaikie469f0792013-05-22 23:22:42 +00001037 llvm::DICompositeType MethodTy = getOrCreateMethodType(Method, Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00001038
1039 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1040 // make sense to give a single ctor/dtor a linkage name.
1041 StringRef MethodLinkageName;
1042 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1043 MethodLinkageName = CGM.getMangledName(Method);
1044
1045 // Get the location for the method.
David Blaikie7fceebf2013-08-19 03:37:48 +00001046 llvm::DIFile MethodDefUnit;
1047 unsigned MethodLine = 0;
1048 if (!Method->isImplicit()) {
1049 MethodDefUnit = getOrCreateFile(Method->getLocation());
1050 MethodLine = getLineNumber(Method->getLocation());
1051 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001052
1053 // Collect virtual method info.
1054 llvm::DIType ContainingType;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001055 unsigned Virtuality = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00001056 unsigned VIndex = 0;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001057
Guy Benyei11169dd2012-12-18 14:30:41 +00001058 if (Method->isVirtual()) {
1059 if (Method->isPure())
1060 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
1061 else
1062 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001063
Guy Benyei11169dd2012-12-18 14:30:41 +00001064 // It doesn't make sense to give a virtual destructor a vtable index,
1065 // since a single destructor has two entries in the vtable.
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001066 // FIXME: Add proper support for debug info for virtual calls in
1067 // the Microsoft ABI, where we may use multiple vptrs to make a vftable
1068 // lookup if we have multiple or virtual inheritance.
1069 if (!isa<CXXDestructorDecl>(Method) &&
1070 !CGM.getTarget().getCXXABI().isMicrosoft())
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001071 VIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(Method);
Guy Benyei11169dd2012-12-18 14:30:41 +00001072 ContainingType = RecordTy;
1073 }
1074
1075 unsigned Flags = 0;
1076 if (Method->isImplicit())
1077 Flags |= llvm::DIDescriptor::FlagArtificial;
1078 AccessSpecifier Access = Method->getAccess();
1079 if (Access == clang::AS_private)
1080 Flags |= llvm::DIDescriptor::FlagPrivate;
1081 else if (Access == clang::AS_protected)
1082 Flags |= llvm::DIDescriptor::FlagProtected;
1083 if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1084 if (CXXC->isExplicit())
1085 Flags |= llvm::DIDescriptor::FlagExplicit;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001086 } else if (const CXXConversionDecl *CXXC =
Guy Benyei11169dd2012-12-18 14:30:41 +00001087 dyn_cast<CXXConversionDecl>(Method)) {
1088 if (CXXC->isExplicit())
1089 Flags |= llvm::DIDescriptor::FlagExplicit;
1090 }
1091 if (Method->hasPrototype())
1092 Flags |= llvm::DIDescriptor::FlagPrototyped;
Adrian Prantl0630eb72013-12-18 21:48:18 +00001093 if (Method->getRefQualifier() == RQ_LValue)
1094 Flags |= llvm::DIDescriptor::FlagLValueReference;
1095 if (Method->getRefQualifier() == RQ_RValue)
1096 Flags |= llvm::DIDescriptor::FlagRValueReference;
Guy Benyei11169dd2012-12-18 14:30:41 +00001097
1098 llvm::DIArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1099 llvm::DISubprogram SP =
Eric Christopherb2a008c2013-05-16 00:45:12 +00001100 DBuilder.createMethod(RecordTy, MethodName, MethodLinkageName,
Guy Benyei11169dd2012-12-18 14:30:41 +00001101 MethodDefUnit, MethodLine,
Eric Christopherb2a008c2013-05-16 00:45:12 +00001102 MethodTy, /*isLocalToUnit=*/false,
Guy Benyei11169dd2012-12-18 14:30:41 +00001103 /* isDefinition=*/ false,
1104 Virtuality, VIndex, ContainingType,
1105 Flags, CGM.getLangOpts().Optimize, NULL,
1106 TParamsArray);
Eric Christopherb2a008c2013-05-16 00:45:12 +00001107
Guy Benyei11169dd2012-12-18 14:30:41 +00001108 SPCache[Method->getCanonicalDecl()] = llvm::WeakVH(SP);
1109
1110 return SP;
1111}
1112
1113/// CollectCXXMemberFunctions - A helper function to collect debug info for
Eric Christopherb2a008c2013-05-16 00:45:12 +00001114/// C++ member functions. This is used while creating debug info entry for
Guy Benyei11169dd2012-12-18 14:30:41 +00001115/// a Record.
1116void CGDebugInfo::
1117CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
1118 SmallVectorImpl<llvm::Value *> &EltTys,
1119 llvm::DIType RecordTy) {
1120
1121 // Since we want more than just the individual member decls if we
1122 // have templated functions iterate over every declaration to gather
1123 // the functions.
1124 for(DeclContext::decl_iterator I = RD->decls_begin(),
1125 E = RD->decls_end(); I != E; ++I) {
David Blaikiefae219a2013-08-28 17:27:13 +00001126 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*I)) {
David Blaikiea6cc8212013-08-28 20:58:00 +00001127 // Reuse the existing member function declaration if it exists.
David Blaikie8c8e8e22013-08-28 20:24:55 +00001128 // It may be associated with the declaration of the type & should be
1129 // reused as we're building the definition.
David Blaikiea6cc8212013-08-28 20:58:00 +00001130 //
1131 // This situation can arise in the vtable-based debug info reduction where
1132 // implicit members are emitted in a non-vtable TU.
David Blaikie6943dea2013-08-20 01:28:15 +00001133 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator MI =
1134 SPCache.find(Method->getCanonicalDecl());
David Blaikiefae219a2013-08-28 17:27:13 +00001135 if (MI == SPCache.end()) {
David Blaikie8c8e8e22013-08-28 20:24:55 +00001136 // If the member is implicit, lazily create it when we see the
1137 // definition, not before. (an ODR-used implicit default ctor that's
1138 // never actually code generated should not produce debug info)
David Blaikiefae219a2013-08-28 17:27:13 +00001139 if (!Method->isImplicit())
1140 EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
1141 } else
David Blaikie6943dea2013-08-20 01:28:15 +00001142 EltTys.push_back(MI->second);
Eric Christopherf86c4052013-08-28 23:12:10 +00001143 } else if (const FunctionTemplateDecl *FTD =
1144 dyn_cast<FunctionTemplateDecl>(*I)) {
David Blaikief2053af2013-08-28 23:06:52 +00001145 // Add any template specializations that have already been seen. Like
1146 // implicit member functions, these may have been added to a declaration
1147 // in the case of vtable-based debug info reduction.
Eric Christopherf86c4052013-08-28 23:12:10 +00001148 for (FunctionTemplateDecl::spec_iterator SI = FTD->spec_begin(),
1149 SE = FTD->spec_end();
1150 SI != SE; ++SI) {
David Blaikief2053af2013-08-28 23:06:52 +00001151 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator MI =
1152 SPCache.find(cast<CXXMethodDecl>(*SI)->getCanonicalDecl());
1153 if (MI != SPCache.end())
1154 EltTys.push_back(MI->second);
1155 }
David Blaikie6943dea2013-08-20 01:28:15 +00001156 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001157 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00001158}
Guy Benyei11169dd2012-12-18 14:30:41 +00001159
Guy Benyei11169dd2012-12-18 14:30:41 +00001160/// CollectCXXBases - A helper function to collect debug info for
Eric Christopherb2a008c2013-05-16 00:45:12 +00001161/// C++ base classes. This is used while creating debug info entry for
Guy Benyei11169dd2012-12-18 14:30:41 +00001162/// a Record.
1163void CGDebugInfo::
1164CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
1165 SmallVectorImpl<llvm::Value *> &EltTys,
1166 llvm::DIType RecordTy) {
1167
1168 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1169 for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
1170 BE = RD->bases_end(); BI != BE; ++BI) {
1171 unsigned BFlags = 0;
1172 uint64_t BaseOffset;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001173
Guy Benyei11169dd2012-12-18 14:30:41 +00001174 const CXXRecordDecl *Base =
1175 cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl());
Eric Christopherb2a008c2013-05-16 00:45:12 +00001176
Guy Benyei11169dd2012-12-18 14:30:41 +00001177 if (BI->isVirtual()) {
1178 // virtual base offset offset is -ve. The code generator emits dwarf
1179 // expression where it expects +ve number.
Eric Christopherb2a008c2013-05-16 00:45:12 +00001180 BaseOffset =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001181 0 - CGM.getItaniumVTableContext()
Guy Benyei11169dd2012-12-18 14:30:41 +00001182 .getVirtualBaseOffsetOffset(RD, Base).getQuantity();
1183 BFlags = llvm::DIDescriptor::FlagVirtual;
1184 } else
1185 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1186 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1187 // BI->isVirtual() and bits when not.
Eric Christopherb2a008c2013-05-16 00:45:12 +00001188
Guy Benyei11169dd2012-12-18 14:30:41 +00001189 AccessSpecifier Access = BI->getAccessSpecifier();
1190 if (Access == clang::AS_private)
1191 BFlags |= llvm::DIDescriptor::FlagPrivate;
1192 else if (Access == clang::AS_protected)
1193 BFlags |= llvm::DIDescriptor::FlagProtected;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001194
1195 llvm::DIType DTy =
1196 DBuilder.createInheritance(RecordTy,
Guy Benyei11169dd2012-12-18 14:30:41 +00001197 getOrCreateType(BI->getType(), Unit),
1198 BaseOffset, BFlags);
1199 EltTys.push_back(DTy);
1200 }
1201}
1202
1203/// CollectTemplateParams - A helper function to collect template parameters.
1204llvm::DIArray CGDebugInfo::
1205CollectTemplateParams(const TemplateParameterList *TPList,
David Blaikie47c11502013-06-22 18:59:18 +00001206 ArrayRef<TemplateArgument> TAList,
Guy Benyei11169dd2012-12-18 14:30:41 +00001207 llvm::DIFile Unit) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001208 SmallVector<llvm::Value *, 16> TemplateParams;
Guy Benyei11169dd2012-12-18 14:30:41 +00001209 for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1210 const TemplateArgument &TA = TAList[i];
David Blaikie47c11502013-06-22 18:59:18 +00001211 StringRef Name;
1212 if (TPList)
1213 Name = TPList->getParam(i)->getName();
David Blaikie38079fd2013-05-10 21:53:14 +00001214 switch (TA.getKind()) {
1215 case TemplateArgument::Type: {
Guy Benyei11169dd2012-12-18 14:30:41 +00001216 llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit);
1217 llvm::DITemplateTypeParameter TTP =
David Blaikie47c11502013-06-22 18:59:18 +00001218 DBuilder.createTemplateTypeParameter(TheCU, Name, TTy);
Guy Benyei11169dd2012-12-18 14:30:41 +00001219 TemplateParams.push_back(TTP);
David Blaikie38079fd2013-05-10 21:53:14 +00001220 } break;
1221 case TemplateArgument::Integral: {
Guy Benyei11169dd2012-12-18 14:30:41 +00001222 llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit);
1223 llvm::DITemplateValueParameter TVP =
David Blaikie38079fd2013-05-10 21:53:14 +00001224 DBuilder.createTemplateValueParameter(
David Blaikie47c11502013-06-22 18:59:18 +00001225 TheCU, Name, TTy,
David Blaikie38079fd2013-05-10 21:53:14 +00001226 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral()));
1227 TemplateParams.push_back(TVP);
1228 } break;
1229 case TemplateArgument::Declaration: {
1230 const ValueDecl *D = TA.getAsDecl();
1231 bool InstanceMember = D->isCXXInstanceMember();
1232 QualType T = InstanceMember
1233 ? CGM.getContext().getMemberPointerType(
1234 D->getType(), cast<RecordDecl>(D->getDeclContext())
1235 ->getTypeForDecl())
1236 : CGM.getContext().getPointerType(D->getType());
1237 llvm::DIType TTy = getOrCreateType(T, Unit);
1238 llvm::Value *V = 0;
1239 // Variable pointer template parameters have a value that is the address
1240 // of the variable.
1241 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1242 V = CGM.GetAddrOfGlobalVar(VD);
1243 // Member function pointers have special support for building them, though
1244 // this is currently unsupported in LLVM CodeGen.
David Blaikied900f982013-05-13 06:57:50 +00001245 if (InstanceMember) {
David Blaikie38079fd2013-05-10 21:53:14 +00001246 if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(D))
1247 V = CGM.getCXXABI().EmitMemberPointer(method);
David Blaikied900f982013-05-13 06:57:50 +00001248 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1249 V = CGM.GetAddrOfFunction(FD);
David Blaikie38079fd2013-05-10 21:53:14 +00001250 // Member data pointers have special handling too to compute the fixed
1251 // offset within the object.
1252 if (isa<FieldDecl>(D)) {
1253 // These five lines (& possibly the above member function pointer
1254 // handling) might be able to be refactored to use similar code in
1255 // CodeGenModule::getMemberPointerConstant
1256 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
1257 CharUnits chars =
1258 CGM.getContext().toCharUnitsFromBits((int64_t) fieldOffset);
1259 V = CGM.getCXXABI().EmitMemberDataPointer(
1260 cast<MemberPointerType>(T.getTypePtr()), chars);
1261 }
1262 llvm::DITemplateValueParameter TVP =
David Majnemera3644d62013-08-25 22:13:27 +00001263 DBuilder.createTemplateValueParameter(TheCU, Name, TTy,
1264 V->stripPointerCasts());
David Blaikie38079fd2013-05-10 21:53:14 +00001265 TemplateParams.push_back(TVP);
1266 } break;
1267 case TemplateArgument::NullPtr: {
1268 QualType T = TA.getNullPtrType();
1269 llvm::DIType TTy = getOrCreateType(T, Unit);
1270 llvm::Value *V = 0;
1271 // Special case member data pointer null values since they're actually -1
1272 // instead of zero.
1273 if (const MemberPointerType *MPT =
1274 dyn_cast<MemberPointerType>(T.getTypePtr()))
1275 // But treat member function pointers as simple zero integers because
1276 // it's easier than having a special case in LLVM's CodeGen. If LLVM
1277 // CodeGen grows handling for values of non-null member function
1278 // pointers then perhaps we could remove this special case and rely on
1279 // EmitNullMemberPointer for member function pointers.
1280 if (MPT->isMemberDataPointer())
1281 V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1282 if (!V)
1283 V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
1284 llvm::DITemplateValueParameter TVP =
David Blaikie47c11502013-06-22 18:59:18 +00001285 DBuilder.createTemplateValueParameter(TheCU, Name, TTy, V);
David Blaikie38079fd2013-05-10 21:53:14 +00001286 TemplateParams.push_back(TVP);
1287 } break;
David Blaikie47c11502013-06-22 18:59:18 +00001288 case TemplateArgument::Template: {
1289 llvm::DITemplateValueParameter TVP =
1290 DBuilder.createTemplateTemplateParameter(
1291 TheCU, Name, llvm::DIType(),
1292 TA.getAsTemplate().getAsTemplateDecl()
1293 ->getQualifiedNameAsString());
1294 TemplateParams.push_back(TVP);
1295 } break;
1296 case TemplateArgument::Pack: {
1297 llvm::DITemplateValueParameter TVP =
1298 DBuilder.createTemplateParameterPack(
1299 TheCU, Name, llvm::DIType(),
1300 CollectTemplateParams(NULL, TA.getPackAsArray(), Unit));
1301 TemplateParams.push_back(TVP);
1302 } break;
David Majnemer5559d472013-08-24 08:21:10 +00001303 case TemplateArgument::Expression: {
1304 const Expr *E = TA.getAsExpr();
1305 QualType T = E->getType();
1306 llvm::Value *V = CGM.EmitConstantExpr(E, T);
1307 assert(V && "Expression in template argument isn't constant");
1308 llvm::DIType TTy = getOrCreateType(T, Unit);
1309 llvm::DITemplateValueParameter TVP =
1310 DBuilder.createTemplateValueParameter(TheCU, Name, TTy,
1311 V->stripPointerCasts());
1312 TemplateParams.push_back(TVP);
1313 } break;
David Blaikie2b93c542013-05-10 23:36:06 +00001314 // And the following should never occur:
David Blaikie38079fd2013-05-10 21:53:14 +00001315 case TemplateArgument::TemplateExpansion:
David Blaikie38079fd2013-05-10 21:53:14 +00001316 case TemplateArgument::Null:
1317 llvm_unreachable(
1318 "These argument types shouldn't exist in concrete types");
Guy Benyei11169dd2012-12-18 14:30:41 +00001319 }
1320 }
1321 return DBuilder.getOrCreateArray(TemplateParams);
1322}
1323
1324/// CollectFunctionTemplateParams - A helper function to collect debug
1325/// info for function template parameters.
1326llvm::DIArray CGDebugInfo::
1327CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) {
1328 if (FD->getTemplatedKind() ==
1329 FunctionDecl::TK_FunctionTemplateSpecialization) {
1330 const TemplateParameterList *TList =
1331 FD->getTemplateSpecializationInfo()->getTemplate()
1332 ->getTemplateParameters();
David Blaikie47c11502013-06-22 18:59:18 +00001333 return CollectTemplateParams(
1334 TList, FD->getTemplateSpecializationArgs()->asArray(), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00001335 }
1336 return llvm::DIArray();
1337}
1338
1339/// CollectCXXTemplateParams - A helper function to collect debug info for
1340/// template parameters.
1341llvm::DIArray CGDebugInfo::
1342CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial,
1343 llvm::DIFile Unit) {
1344 llvm::PointerUnion<ClassTemplateDecl *,
1345 ClassTemplatePartialSpecializationDecl *>
1346 PU = TSpecial->getSpecializedTemplateOrPartial();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001347
Guy Benyei11169dd2012-12-18 14:30:41 +00001348 TemplateParameterList *TPList = PU.is<ClassTemplateDecl *>() ?
1349 PU.get<ClassTemplateDecl *>()->getTemplateParameters() :
1350 PU.get<ClassTemplatePartialSpecializationDecl *>()->getTemplateParameters();
1351 const TemplateArgumentList &TAList = TSpecial->getTemplateInstantiationArgs();
David Blaikie47c11502013-06-22 18:59:18 +00001352 return CollectTemplateParams(TPList, TAList.asArray(), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00001353}
1354
1355/// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
1356llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
1357 if (VTablePtrType.isValid())
1358 return VTablePtrType;
1359
1360 ASTContext &Context = CGM.getContext();
1361
1362 /* Function type */
1363 llvm::Value *STy = getOrCreateType(Context.IntTy, Unit);
1364 llvm::DIArray SElements = DBuilder.getOrCreateArray(STy);
1365 llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements);
1366 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1367 llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0,
1368 "__vtbl_ptr_type");
1369 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1370 return VTablePtrType;
1371}
1372
1373/// getVTableName - Get vtable name for the given Class.
1374StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +00001375 // Copy the gdb compatible name on the side and use its reference.
1376 return internString("_vptr$", RD->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00001377}
1378
1379
1380/// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
1381/// debug info entry in EltTys vector.
1382void CGDebugInfo::
1383CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
1384 SmallVectorImpl<llvm::Value *> &EltTys) {
1385 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1386
1387 // If there is a primary base then it will hold vtable info.
1388 if (RL.getPrimaryBase())
1389 return;
1390
1391 // If this class is not dynamic then there is not any vtable info to collect.
1392 if (!RD->isDynamicClass())
1393 return;
1394
1395 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1396 llvm::DIType VPTR
1397 = DBuilder.createMemberType(Unit, getVTableName(RD), Unit,
Eric Christopher0fdcb312013-05-16 00:52:20 +00001398 0, Size, 0, 0,
1399 llvm::DIDescriptor::FlagArtificial,
Guy Benyei11169dd2012-12-18 14:30:41 +00001400 getOrCreateVTablePtrType(Unit));
1401 EltTys.push_back(VPTR);
1402}
1403
Eric Christopherb2a008c2013-05-16 00:45:12 +00001404/// getOrCreateRecordType - Emit record type's standalone debug info.
1405llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy,
Guy Benyei11169dd2012-12-18 14:30:41 +00001406 SourceLocation Loc) {
Eric Christopher75e17682013-05-16 00:45:23 +00001407 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00001408 llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc));
1409 return T;
1410}
1411
1412/// getOrCreateInterfaceType - Emit an objective c interface type standalone
1413/// debug info.
1414llvm::DIType CGDebugInfo::getOrCreateInterfaceType(QualType D,
Eric Christopherc0c5d462013-02-21 22:35:08 +00001415 SourceLocation Loc) {
Eric Christopher75e17682013-05-16 00:45:23 +00001416 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00001417 llvm::DIType T = getOrCreateType(D, getOrCreateFile(Loc));
Adrian Prantl73409ce2013-03-11 18:33:46 +00001418 RetainedTypes.push_back(D.getAsOpaquePtr());
Guy Benyei11169dd2012-12-18 14:30:41 +00001419 return T;
1420}
1421
David Blaikieb2e86eb2013-08-15 20:49:17 +00001422void CGDebugInfo::completeType(const RecordDecl *RD) {
1423 if (DebugKind > CodeGenOptions::LimitedDebugInfo ||
1424 !CGM.getLangOpts().CPlusPlus)
1425 completeRequiredType(RD);
1426}
1427
1428void CGDebugInfo::completeRequiredType(const RecordDecl *RD) {
David Blaikie6943dea2013-08-20 01:28:15 +00001429 if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
1430 if (CXXDecl->isDynamicClass())
1431 return;
1432
David Blaikieb2e86eb2013-08-15 20:49:17 +00001433 QualType Ty = CGM.getContext().getRecordType(RD);
1434 llvm::DIType T = getTypeOrNull(Ty);
David Blaikie6943dea2013-08-20 01:28:15 +00001435 if (T && T.isForwardDecl())
1436 completeClassData(RD);
1437}
1438
1439void CGDebugInfo::completeClassData(const RecordDecl *RD) {
1440 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
Michael Gottesman349542b2013-08-19 18:46:16 +00001441 return;
David Blaikie6943dea2013-08-20 01:28:15 +00001442 QualType Ty = CGM.getContext().getRecordType(RD);
David Blaikieb2e86eb2013-08-15 20:49:17 +00001443 void* TyPtr = Ty.getAsOpaquePtr();
1444 if (CompletedTypeCache.count(TyPtr))
1445 return;
1446 llvm::DIType Res = CreateTypeDefinition(Ty->castAs<RecordType>());
1447 assert(!Res.isForwardDecl());
1448 CompletedTypeCache[TyPtr] = Res;
1449 TypeCache[TyPtr] = Res;
1450}
1451
Guy Benyei11169dd2012-12-18 14:30:41 +00001452/// CreateType - get structure or union type.
David Blaikie99dab3b2013-09-04 22:03:57 +00001453llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001454 RecordDecl *RD = Ty->getDecl();
David Blaikie6943dea2013-08-20 01:28:15 +00001455 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
David Blaikie99dab3b2013-09-04 22:03:57 +00001456 // Always emit declarations for types that aren't required to be complete when
1457 // in limit-debug-info mode. If the type is later found to be required to be
1458 // complete this declaration will be upgraded to a definition by
1459 // `completeRequiredType`.
1460 // If the type is dynamic, only emit the definition in TUs that require class
1461 // data. This is handled by `completeClassData`.
David Blaikie3b1cc9b2013-09-06 06:45:04 +00001462 llvm::DICompositeType T(getTypeOrNull(QualType(Ty, 0)));
1463 // If we've already emitted the type, just use that, even if it's only a
1464 // declaration. The completeType, completeRequiredType, and completeClassData
1465 // callbacks will handle promoting the declaration to a definition.
1466 if (T ||
1467 (DebugKind <= CodeGenOptions::LimitedDebugInfo &&
1468 // Under -flimit-debug-info, emit only a declaration unless the type is
1469 // required to be complete.
David Blaikie6943dea2013-08-20 01:28:15 +00001470 !RD->isCompleteDefinitionRequired() && CGM.getLangOpts().CPlusPlus) ||
David Blaikie3b1cc9b2013-09-06 06:45:04 +00001471 // If the class is dynamic, only emit a declaration. A definition will be
1472 // emitted whenever the vtable is emitted.
Adrian Prantl5028dc02013-12-23 19:10:57 +00001473 (CXXDecl && CXXDecl->hasDefinition() && CXXDecl->isDynamicClass())) {
David Blaikiee36464c2013-06-05 05:32:23 +00001474 llvm::DIDescriptor FDContext =
1475 getContextDescriptor(cast<Decl>(RD->getDeclContext()));
David Blaikie3b1cc9b2013-09-06 06:45:04 +00001476 if (!T)
1477 T = getOrCreateRecordFwdDecl(Ty, FDContext);
1478 return T;
David Blaikiee36464c2013-06-05 05:32:23 +00001479 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001480
David Blaikieb2e86eb2013-08-15 20:49:17 +00001481 return CreateTypeDefinition(Ty);
1482}
1483
1484llvm::DIType CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {
1485 RecordDecl *RD = Ty->getDecl();
1486
Guy Benyei11169dd2012-12-18 14:30:41 +00001487 // Get overall information about the record type for the debug info.
1488 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1489
1490 // Records and classes and unions can all be recursive. To handle them, we
1491 // first generate a debug descriptor for the struct as a forward declaration.
1492 // Then (if it is a definition) we go through and get debug info for all of
1493 // its members. Finally, we create a descriptor for the complete type (which
1494 // may refer to the forward decl if the struct is recursive) and replace all
1495 // uses of the forward declaration with the final definition.
1496
David Blaikie4a2b5ef2013-08-12 22:24:20 +00001497 llvm::DICompositeType FwdDecl(getOrCreateLimitedType(Ty, DefUnit));
Manman Ren0d441f12013-07-02 19:01:53 +00001498 assert(FwdDecl.isCompositeType() &&
David Blaikie469f0792013-05-22 23:22:42 +00001499 "The debug type of a RecordType should be a llvm::DICompositeType");
Guy Benyei11169dd2012-12-18 14:30:41 +00001500
1501 if (FwdDecl.isForwardDecl())
1502 return FwdDecl;
1503
David Blaikieadfbf992013-08-18 16:55:33 +00001504 if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
1505 CollectContainingType(CXXDecl, FwdDecl);
1506
Guy Benyei11169dd2012-12-18 14:30:41 +00001507 // Push the struct on region stack.
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001508 LexicalBlockStack.push_back(&*FwdDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00001509 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1510
Adrian Prantla03a85a2013-03-06 22:03:30 +00001511 // Add this to the completed-type cache while we're completing it recursively.
Guy Benyei11169dd2012-12-18 14:30:41 +00001512 CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1513
1514 // Convert all the elements.
1515 SmallVector<llvm::Value *, 16> EltTys;
David Blaikie6943dea2013-08-20 01:28:15 +00001516 // what about nested types?
Guy Benyei11169dd2012-12-18 14:30:41 +00001517
1518 // Note: The split of CXXDecl information here is intentional, the
1519 // gdb tests will depend on a certain ordering at printout. The debug
1520 // information offsets are still correct if we merge them all together
1521 // though.
1522 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1523 if (CXXDecl) {
1524 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1525 CollectVTableInfo(CXXDecl, DefUnit, EltTys);
1526 }
1527
Eric Christopher91a31902013-01-16 01:22:32 +00001528 // Collect data fields (including static variables and any initializers).
Guy Benyei11169dd2012-12-18 14:30:41 +00001529 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
Eric Christopher2df080e2013-10-11 18:16:51 +00001530 if (CXXDecl)
Guy Benyei11169dd2012-12-18 14:30:41 +00001531 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00001532
1533 LexicalBlockStack.pop_back();
1534 RegionMap.erase(Ty->getDecl());
1535
1536 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
David Blaikie4a5b8952013-08-01 20:31:40 +00001537 FwdDecl.setTypeArray(Elements);
Guy Benyei11169dd2012-12-18 14:30:41 +00001538
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001539 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1540 return FwdDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00001541}
1542
1543/// CreateType - get objective-c object type.
1544llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1545 llvm::DIFile Unit) {
1546 // Ignore protocols.
1547 return getOrCreateType(Ty->getBaseType(), Unit);
1548}
1549
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001550
1551/// \return true if Getter has the default name for the property PD.
1552static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
1553 const ObjCMethodDecl *Getter) {
1554 assert(PD);
1555 if (!Getter)
1556 return true;
1557
1558 assert(Getter->getDeclName().isObjCZeroArgSelector());
1559 return PD->getName() ==
1560 Getter->getDeclName().getObjCSelector().getNameForSlot(0);
1561}
1562
1563/// \return true if Setter has the default name for the property PD.
1564static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
1565 const ObjCMethodDecl *Setter) {
1566 assert(PD);
1567 if (!Setter)
1568 return true;
1569
1570 assert(Setter->getDeclName().isObjCOneArgSelector());
Adrian Prantla4ce9062013-06-07 22:29:12 +00001571 return SelectorTable::constructSetterName(PD->getName()) ==
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001572 Setter->getDeclName().getObjCSelector().getNameForSlot(0);
1573}
1574
Guy Benyei11169dd2012-12-18 14:30:41 +00001575/// CreateType - get objective-c interface type.
1576llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1577 llvm::DIFile Unit) {
1578 ObjCInterfaceDecl *ID = Ty->getDecl();
1579 if (!ID)
1580 return llvm::DIType();
1581
1582 // Get overall information about the record type for the debug info.
1583 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1584 unsigned Line = getLineNumber(ID->getLocation());
1585 unsigned RuntimeLang = TheCU.getLanguage();
1586
1587 // If this is just a forward declaration return a special forward-declaration
1588 // debug type since we won't be able to lay out the entire type.
1589 ObjCInterfaceDecl *Def = ID->getDefinition();
1590 if (!Def) {
1591 llvm::DIType FwdDecl =
1592 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
Eric Christopherc0c5d462013-02-21 22:35:08 +00001593 ID->getName(), TheCU, DefUnit, Line,
1594 RuntimeLang);
Guy Benyei11169dd2012-12-18 14:30:41 +00001595 return FwdDecl;
1596 }
1597
1598 ID = Def;
1599
1600 // Bit size, align and offset of the type.
1601 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1602 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1603
1604 unsigned Flags = 0;
1605 if (ID->getImplementation())
1606 Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
1607
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001608 llvm::DICompositeType RealDecl =
Guy Benyei11169dd2012-12-18 14:30:41 +00001609 DBuilder.createStructType(Unit, ID->getName(), DefUnit,
1610 Line, Size, Align, Flags,
David Blaikie6d4fe152013-02-25 01:07:08 +00001611 llvm::DIType(), llvm::DIArray(), RuntimeLang);
Guy Benyei11169dd2012-12-18 14:30:41 +00001612
1613 // Otherwise, insert it into the CompletedTypeCache so that recursive uses
1614 // will find it and we're emitting the complete type.
Adrian Prantla03a85a2013-03-06 22:03:30 +00001615 QualType QualTy = QualType(Ty, 0);
1616 CompletedTypeCache[QualTy.getAsOpaquePtr()] = RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00001617
Eric Christopher35f1f9f2013-07-14 21:00:07 +00001618 // Push the struct on region stack.
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001619 LexicalBlockStack.push_back(static_cast<llvm::MDNode*>(RealDecl));
Guy Benyei11169dd2012-12-18 14:30:41 +00001620 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1621
1622 // Convert all the elements.
1623 SmallVector<llvm::Value *, 16> EltTys;
1624
1625 ObjCInterfaceDecl *SClass = ID->getSuperClass();
1626 if (SClass) {
1627 llvm::DIType SClassTy =
1628 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1629 if (!SClassTy.isValid())
1630 return llvm::DIType();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001631
Guy Benyei11169dd2012-12-18 14:30:41 +00001632 llvm::DIType InhTag =
1633 DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
1634 EltTys.push_back(InhTag);
1635 }
1636
Eric Christopher35f1f9f2013-07-14 21:00:07 +00001637 // Create entries for all of the properties.
Guy Benyei11169dd2012-12-18 14:30:41 +00001638 for (ObjCContainerDecl::prop_iterator I = ID->prop_begin(),
1639 E = ID->prop_end(); I != E; ++I) {
1640 const ObjCPropertyDecl *PD = *I;
1641 SourceLocation Loc = PD->getLocation();
1642 llvm::DIFile PUnit = getOrCreateFile(Loc);
1643 unsigned PLine = getLineNumber(Loc);
1644 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1645 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1646 llvm::MDNode *PropertyNode =
1647 DBuilder.createObjCProperty(PD->getName(),
Eric Christopherc0c5d462013-02-21 22:35:08 +00001648 PUnit, PLine,
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001649 hasDefaultGetterName(PD, Getter) ? "" :
Guy Benyei11169dd2012-12-18 14:30:41 +00001650 getSelectorName(PD->getGetterName()),
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001651 hasDefaultSetterName(PD, Setter) ? "" :
Guy Benyei11169dd2012-12-18 14:30:41 +00001652 getSelectorName(PD->getSetterName()),
1653 PD->getPropertyAttributes(),
Eric Christopherc0c5d462013-02-21 22:35:08 +00001654 getOrCreateType(PD->getType(), PUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00001655 EltTys.push_back(PropertyNode);
1656 }
1657
1658 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1659 unsigned FieldNo = 0;
1660 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1661 Field = Field->getNextIvar(), ++FieldNo) {
1662 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1663 if (!FieldTy.isValid())
1664 return llvm::DIType();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001665
Guy Benyei11169dd2012-12-18 14:30:41 +00001666 StringRef FieldName = Field->getName();
1667
1668 // Ignore unnamed fields.
1669 if (FieldName.empty())
1670 continue;
1671
1672 // Get the location for the field.
1673 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1674 unsigned FieldLine = getLineNumber(Field->getLocation());
1675 QualType FType = Field->getType();
1676 uint64_t FieldSize = 0;
1677 unsigned FieldAlign = 0;
1678
1679 if (!FType->isIncompleteArrayType()) {
1680
1681 // Bit size, align and offset of the type.
1682 FieldSize = Field->isBitField()
Eric Christopher35f1f9f2013-07-14 21:00:07 +00001683 ? Field->getBitWidthValue(CGM.getContext())
1684 : CGM.getContext().getTypeSize(FType);
Guy Benyei11169dd2012-12-18 14:30:41 +00001685 FieldAlign = CGM.getContext().getTypeAlign(FType);
1686 }
1687
1688 uint64_t FieldOffset;
1689 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1690 // We don't know the runtime offset of an ivar if we're using the
1691 // non-fragile ABI. For bitfields, use the bit offset into the first
1692 // byte of storage of the bitfield. For other fields, use zero.
1693 if (Field->isBitField()) {
1694 FieldOffset = CGM.getObjCRuntime().ComputeBitfieldBitOffset(
1695 CGM, ID, Field);
1696 FieldOffset %= CGM.getContext().getCharWidth();
1697 } else {
1698 FieldOffset = 0;
1699 }
1700 } else {
1701 FieldOffset = RL.getFieldOffset(FieldNo);
1702 }
1703
1704 unsigned Flags = 0;
1705 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1706 Flags = llvm::DIDescriptor::FlagProtected;
1707 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1708 Flags = llvm::DIDescriptor::FlagPrivate;
1709
1710 llvm::MDNode *PropertyNode = NULL;
1711 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001712 if (ObjCPropertyImplDecl *PImpD =
Guy Benyei11169dd2012-12-18 14:30:41 +00001713 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
1714 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
Eric Christopherc0c5d462013-02-21 22:35:08 +00001715 SourceLocation Loc = PD->getLocation();
1716 llvm::DIFile PUnit = getOrCreateFile(Loc);
1717 unsigned PLine = getLineNumber(Loc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001718 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1719 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1720 PropertyNode =
1721 DBuilder.createObjCProperty(PD->getName(),
1722 PUnit, PLine,
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001723 hasDefaultGetterName(PD, Getter) ? "" :
Guy Benyei11169dd2012-12-18 14:30:41 +00001724 getSelectorName(PD->getGetterName()),
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001725 hasDefaultSetterName(PD, Setter) ? "" :
Guy Benyei11169dd2012-12-18 14:30:41 +00001726 getSelectorName(PD->getSetterName()),
1727 PD->getPropertyAttributes(),
1728 getOrCreateType(PD->getType(), PUnit));
1729 }
1730 }
1731 }
1732 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
1733 FieldLine, FieldSize, FieldAlign,
1734 FieldOffset, Flags, FieldTy,
1735 PropertyNode);
1736 EltTys.push_back(FieldTy);
1737 }
1738
1739 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001740 RealDecl.setTypeArray(Elements);
Adrian Prantla03a85a2013-03-06 22:03:30 +00001741
1742 // If the implementation is not yet set, we do not want to mark it
1743 // as complete. An implementation may declare additional
1744 // private ivars that we would miss otherwise.
1745 if (ID->getImplementation() == 0)
1746 CompletedTypeCache.erase(QualTy.getAsOpaquePtr());
Eric Christopherb2a008c2013-05-16 00:45:12 +00001747
Guy Benyei11169dd2012-12-18 14:30:41 +00001748 LexicalBlockStack.pop_back();
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001749 return RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00001750}
1751
1752llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) {
1753 llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1754 int64_t Count = Ty->getNumElements();
1755 if (Count == 0)
1756 // If number of elements are not known then this is an unbounded array.
1757 // Use Count == -1 to express such arrays.
1758 Count = -1;
1759
1760 llvm::Value *Subscript = DBuilder.getOrCreateSubrange(0, Count);
1761 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1762
1763 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1764 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1765
1766 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1767}
1768
1769llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1770 llvm::DIFile Unit) {
1771 uint64_t Size;
1772 uint64_t Align;
1773
1774 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1775 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1776 Size = 0;
1777 Align =
1778 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1779 } else if (Ty->isIncompleteArrayType()) {
1780 Size = 0;
1781 if (Ty->getElementType()->isIncompleteType())
1782 Align = 0;
1783 else
1784 Align = CGM.getContext().getTypeAlign(Ty->getElementType());
David Blaikief03b2e82013-05-09 20:48:12 +00001785 } else if (Ty->isIncompleteType()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001786 Size = 0;
1787 Align = 0;
1788 } else {
1789 // Size and align of the whole array, not the element type.
1790 Size = CGM.getContext().getTypeSize(Ty);
1791 Align = CGM.getContext().getTypeAlign(Ty);
1792 }
1793
1794 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
1795 // interior arrays, do we care? Why aren't nested arrays represented the
1796 // obvious/recursive way?
1797 SmallVector<llvm::Value *, 8> Subscripts;
1798 QualType EltTy(Ty, 0);
1799 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1800 // If the number of elements is known, then count is that number. Otherwise,
1801 // it's -1. This allows us to represent a subrange with an array of 0
1802 // elements, like this:
1803 //
1804 // struct foo {
1805 // int x[0];
1806 // };
1807 int64_t Count = -1; // Count == -1 is an unbounded array.
1808 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1809 Count = CAT->getSize().getZExtValue();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001810
Guy Benyei11169dd2012-12-18 14:30:41 +00001811 // FIXME: Verify this is right for VLAs.
1812 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
1813 EltTy = Ty->getElementType();
1814 }
1815
1816 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1817
Eric Christopherb2a008c2013-05-16 00:45:12 +00001818 llvm::DIType DbgTy =
Guy Benyei11169dd2012-12-18 14:30:41 +00001819 DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1820 SubscriptArray);
1821 return DbgTy;
1822}
1823
Eric Christopherb2a008c2013-05-16 00:45:12 +00001824llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +00001825 llvm::DIFile Unit) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001826 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
Guy Benyei11169dd2012-12-18 14:30:41 +00001827 Ty, Ty->getPointeeType(), Unit);
1828}
1829
Eric Christopherb2a008c2013-05-16 00:45:12 +00001830llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +00001831 llvm::DIFile Unit) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001832 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
Guy Benyei11169dd2012-12-18 14:30:41 +00001833 Ty, Ty->getPointeeType(), Unit);
1834}
1835
Eric Christopherb2a008c2013-05-16 00:45:12 +00001836llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +00001837 llvm::DIFile U) {
David Blaikie2c705ca2013-01-19 19:20:56 +00001838 llvm::DIType ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
1839 if (!Ty->getPointeeType()->isFunctionType())
1840 return DBuilder.createMemberPointerType(
David Blaikie99dab3b2013-09-04 22:03:57 +00001841 getOrCreateType(Ty->getPointeeType(), U), ClassType);
Adrian Prantl0866acd2013-12-19 01:38:47 +00001842
1843 const FunctionProtoType *FPT =
1844 Ty->getPointeeType()->getAs<FunctionProtoType>();
David Blaikie2c705ca2013-01-19 19:20:56 +00001845 return DBuilder.createMemberPointerType(getOrCreateInstanceMethodType(
Adrian Prantl0866acd2013-12-19 01:38:47 +00001846 CGM.getContext().getPointerType(QualType(Ty->getClass(),
1847 FPT->getTypeQuals())),
1848 FPT, U), ClassType);
Guy Benyei11169dd2012-12-18 14:30:41 +00001849}
1850
Eric Christopherb2a008c2013-05-16 00:45:12 +00001851llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +00001852 llvm::DIFile U) {
1853 // Ignore the atomic wrapping
1854 // FIXME: What is the correct representation?
1855 return getOrCreateType(Ty->getValueType(), U);
1856}
1857
1858/// CreateEnumType - get enumeration type.
Manman Ren501ecf92013-08-28 21:46:36 +00001859llvm::DIType CGDebugInfo::CreateEnumType(const EnumType *Ty) {
Manman Ren1b457022013-08-28 21:20:28 +00001860 const EnumDecl *ED = Ty->getDecl();
Guy Benyei11169dd2012-12-18 14:30:41 +00001861 uint64_t Size = 0;
1862 uint64_t Align = 0;
1863 if (!ED->getTypeForDecl()->isIncompleteType()) {
1864 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1865 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1866 }
1867
Manman Rene0064d82013-08-29 23:19:58 +00001868 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
1869
Guy Benyei11169dd2012-12-18 14:30:41 +00001870 // If this is just a forward declaration, construct an appropriately
1871 // marked node and just return it.
1872 if (!ED->getDefinition()) {
1873 llvm::DIDescriptor EDContext;
1874 EDContext = getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1875 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1876 unsigned Line = getLineNumber(ED->getLocation());
1877 StringRef EDName = ED->getName();
1878 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_enumeration_type,
1879 EDName, EDContext, DefUnit, Line, 0,
Manman Rene0064d82013-08-29 23:19:58 +00001880 Size, Align, FullName);
Guy Benyei11169dd2012-12-18 14:30:41 +00001881 }
1882
1883 // Create DIEnumerator elements for each enumerator.
1884 SmallVector<llvm::Value *, 16> Enumerators;
1885 ED = ED->getDefinition();
1886 for (EnumDecl::enumerator_iterator
1887 Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
1888 Enum != EnumEnd; ++Enum) {
1889 Enumerators.push_back(
1890 DBuilder.createEnumerator(Enum->getName(),
David Blaikiece1ae382013-06-24 07:13:13 +00001891 Enum->getInitVal().getSExtValue()));
Guy Benyei11169dd2012-12-18 14:30:41 +00001892 }
1893
1894 // Return a CompositeType for the enum itself.
1895 llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1896
1897 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1898 unsigned Line = getLineNumber(ED->getLocation());
Eric Christopherb2a008c2013-05-16 00:45:12 +00001899 llvm::DIDescriptor EnumContext =
Guy Benyei11169dd2012-12-18 14:30:41 +00001900 getContextDescriptor(cast<Decl>(ED->getDeclContext()));
Adrian Prantlc60dc712013-04-19 19:56:39 +00001901 llvm::DIType ClassTy = ED->isFixed() ?
Guy Benyei11169dd2012-12-18 14:30:41 +00001902 getOrCreateType(ED->getIntegerType(), DefUnit) : llvm::DIType();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001903 llvm::DIType DbgTy =
Guy Benyei11169dd2012-12-18 14:30:41 +00001904 DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1905 Size, Align, EltArray,
Manman Rene0064d82013-08-29 23:19:58 +00001906 ClassTy, FullName);
Guy Benyei11169dd2012-12-18 14:30:41 +00001907 return DbgTy;
1908}
1909
David Blaikie05491062013-01-21 04:37:12 +00001910static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
1911 Qualifiers Quals;
Guy Benyei11169dd2012-12-18 14:30:41 +00001912 do {
Adrian Prantl179af902013-09-26 21:35:50 +00001913 Qualifiers InnerQuals = T.getLocalQualifiers();
1914 // Qualifiers::operator+() doesn't like it if you add a Qualifier
1915 // that is already there.
1916 Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals);
1917 Quals += InnerQuals;
Guy Benyei11169dd2012-12-18 14:30:41 +00001918 QualType LastT = T;
1919 switch (T->getTypeClass()) {
1920 default:
David Blaikie05491062013-01-21 04:37:12 +00001921 return C.getQualifiedType(T.getTypePtr(), Quals);
Guy Benyei11169dd2012-12-18 14:30:41 +00001922 case Type::TemplateSpecialization:
1923 T = cast<TemplateSpecializationType>(T)->desugar();
1924 break;
1925 case Type::TypeOfExpr:
1926 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1927 break;
1928 case Type::TypeOf:
1929 T = cast<TypeOfType>(T)->getUnderlyingType();
1930 break;
1931 case Type::Decltype:
1932 T = cast<DecltypeType>(T)->getUnderlyingType();
1933 break;
1934 case Type::UnaryTransform:
1935 T = cast<UnaryTransformType>(T)->getUnderlyingType();
1936 break;
1937 case Type::Attributed:
1938 T = cast<AttributedType>(T)->getEquivalentType();
1939 break;
1940 case Type::Elaborated:
1941 T = cast<ElaboratedType>(T)->getNamedType();
1942 break;
1943 case Type::Paren:
1944 T = cast<ParenType>(T)->getInnerType();
1945 break;
David Blaikie05491062013-01-21 04:37:12 +00001946 case Type::SubstTemplateTypeParm:
Guy Benyei11169dd2012-12-18 14:30:41 +00001947 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
Guy Benyei11169dd2012-12-18 14:30:41 +00001948 break;
1949 case Type::Auto:
David Blaikie22c460a02013-05-24 21:24:35 +00001950 QualType DT = cast<AutoType>(T)->getDeducedType();
1951 if (DT.isNull())
1952 return T;
1953 T = DT;
Guy Benyei11169dd2012-12-18 14:30:41 +00001954 break;
1955 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00001956
Guy Benyei11169dd2012-12-18 14:30:41 +00001957 assert(T != LastT && "Type unwrapping failed to unwrap!");
NAKAMURA Takumi3e0a3632013-01-21 10:51:28 +00001958 (void)LastT;
Guy Benyei11169dd2012-12-18 14:30:41 +00001959 } while (true);
1960}
1961
Eric Christopher0fdcb312013-05-16 00:52:20 +00001962/// getType - Get the type from the cache or return null type if it doesn't
1963/// exist.
Guy Benyei11169dd2012-12-18 14:30:41 +00001964llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) {
1965
1966 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00001967 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Eric Christopherb2a008c2013-05-16 00:45:12 +00001968
Guy Benyei11169dd2012-12-18 14:30:41 +00001969 // Check for existing entry.
Adrian Prantl73409ce2013-03-11 18:33:46 +00001970 if (Ty->getTypeClass() == Type::ObjCInterface) {
1971 llvm::Value *V = getCachedInterfaceTypeOrNull(Ty);
1972 if (V)
1973 return llvm::DIType(cast<llvm::MDNode>(V));
1974 else return llvm::DIType();
1975 }
1976
Guy Benyei11169dd2012-12-18 14:30:41 +00001977 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1978 TypeCache.find(Ty.getAsOpaquePtr());
1979 if (it != TypeCache.end()) {
1980 // Verify that the debug info still exists.
1981 if (llvm::Value *V = it->second)
1982 return llvm::DIType(cast<llvm::MDNode>(V));
1983 }
1984
1985 return llvm::DIType();
1986}
1987
1988/// getCompletedTypeOrNull - Get the type from the cache or return null if it
1989/// doesn't exist.
1990llvm::DIType CGDebugInfo::getCompletedTypeOrNull(QualType Ty) {
1991
1992 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00001993 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00001994
1995 // Check for existing entry.
Adrian Prantla03a85a2013-03-06 22:03:30 +00001996 llvm::Value *V = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00001997 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1998 CompletedTypeCache.find(Ty.getAsOpaquePtr());
Adrian Prantla03a85a2013-03-06 22:03:30 +00001999 if (it != CompletedTypeCache.end())
2000 V = it->second;
2001 else {
Adrian Prantl73409ce2013-03-11 18:33:46 +00002002 V = getCachedInterfaceTypeOrNull(Ty);
Guy Benyei11169dd2012-12-18 14:30:41 +00002003 }
2004
Adrian Prantla03a85a2013-03-06 22:03:30 +00002005 // Verify that any cached debug info still exists.
David Blaikie80d28de2013-08-13 04:21:38 +00002006 return llvm::DIType(cast_or_null<llvm::MDNode>(V));
Guy Benyei11169dd2012-12-18 14:30:41 +00002007}
2008
Adrian Prantl73409ce2013-03-11 18:33:46 +00002009/// getCachedInterfaceTypeOrNull - Get the type from the interface
2010/// cache, unless it needs to regenerated. Otherwise return null.
2011llvm::Value *CGDebugInfo::getCachedInterfaceTypeOrNull(QualType Ty) {
2012 // Is there a cached interface that hasn't changed?
2013 llvm::DenseMap<void *, std::pair<llvm::WeakVH, unsigned > >
2014 ::iterator it1 = ObjCInterfaceCache.find(Ty.getAsOpaquePtr());
2015
2016 if (it1 != ObjCInterfaceCache.end())
2017 if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty))
2018 if (Checksum(Decl) == it1->second.second)
2019 // Return cached forward declaration.
2020 return it1->second.first;
2021
2022 return 0;
2023}
Guy Benyei11169dd2012-12-18 14:30:41 +00002024
2025/// getOrCreateType - Get the type from the cache or create a new
2026/// one if necessary.
David Blaikie99dab3b2013-09-04 22:03:57 +00002027llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002028 if (Ty.isNull())
2029 return llvm::DIType();
2030
2031 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00002032 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00002033
David Blaikie99dab3b2013-09-04 22:03:57 +00002034 if (llvm::DIType T = getCompletedTypeOrNull(Ty))
Guy Benyei11169dd2012-12-18 14:30:41 +00002035 return T;
2036
2037 // Otherwise create the type.
David Blaikie99dab3b2013-09-04 22:03:57 +00002038 llvm::DIType Res = CreateTypeNode(Ty, Unit);
Adrian Prantl73409ce2013-03-11 18:33:46 +00002039 void* TyPtr = Ty.getAsOpaquePtr();
2040
2041 // And update the type cache.
2042 TypeCache[TyPtr] = Res;
Guy Benyei11169dd2012-12-18 14:30:41 +00002043
David Blaikie6a723442013-08-15 21:21:19 +00002044 // FIXME: this getTypeOrNull call seems silly when we just inserted the type
2045 // into the cache - but getTypeOrNull has a special case for cached interface
2046 // types. We should probably just pull that out as a special case for the
2047 // "else" block below & skip the otherwise needless lookup.
Guy Benyei11169dd2012-12-18 14:30:41 +00002048 llvm::DIType TC = getTypeOrNull(Ty);
Eric Christopherf8bc4d82013-07-18 00:52:50 +00002049 if (TC && TC.isForwardDecl())
Adrian Prantl73409ce2013-03-11 18:33:46 +00002050 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
2051 else if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty)) {
2052 // Interface types may have elements added to them by a
2053 // subsequent implementation or extension, so we keep them in
2054 // the ObjCInterfaceCache together with a checksum. Instead of
Adrian Prantlc20237d2013-05-08 23:37:22 +00002055 // the (possibly) incomplete interface type, we return a forward
Adrian Prantl73409ce2013-03-11 18:33:46 +00002056 // declaration that gets RAUW'd in CGDebugInfo::finalize().
David Blaikie8e5939b2013-05-21 18:29:40 +00002057 std::pair<llvm::WeakVH, unsigned> &V = ObjCInterfaceCache[TyPtr];
2058 if (V.first)
2059 return llvm::DIType(cast<llvm::MDNode>(V.first));
2060 TC = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
2061 Decl->getName(), TheCU, Unit,
2062 getLineNumber(Decl->getLocation()),
2063 TheCU.getLanguage());
2064 // Store the forward declaration in the cache.
2065 V.first = TC;
2066 V.second = Checksum(Decl);
Adrian Prantl73409ce2013-03-11 18:33:46 +00002067
David Blaikie8e5939b2013-05-21 18:29:40 +00002068 // Register the type for replacement in finalize().
2069 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
2070
Adrian Prantl73409ce2013-03-11 18:33:46 +00002071 return TC;
Adrian Prantla03a85a2013-03-06 22:03:30 +00002072 }
2073
Guy Benyei11169dd2012-12-18 14:30:41 +00002074 if (!Res.isForwardDecl())
Adrian Prantl73409ce2013-03-11 18:33:46 +00002075 CompletedTypeCache[TyPtr] = Res;
Guy Benyei11169dd2012-12-18 14:30:41 +00002076
2077 return Res;
2078}
2079
Adrian Prantlc4de1ef2013-06-07 01:10:41 +00002080/// Currently the checksum of an interface includes the number of
2081/// ivars and property accessors.
Eric Christopher1ecc5632013-06-07 22:54:39 +00002082unsigned CGDebugInfo::Checksum(const ObjCInterfaceDecl *ID) {
Adrian Prantl817bbb32013-06-07 01:10:48 +00002083 // The assumption is that the number of ivars can only increase
2084 // monotonically, so it is safe to just use their current number as
2085 // a checksum.
Adrian Prantlc4de1ef2013-06-07 01:10:41 +00002086 unsigned Sum = 0;
2087 for (const ObjCIvarDecl *Ivar = ID->all_declared_ivar_begin();
2088 Ivar != 0; Ivar = Ivar->getNextIvar())
2089 ++Sum;
2090
2091 return Sum;
Adrian Prantla03a85a2013-03-06 22:03:30 +00002092}
2093
2094ObjCInterfaceDecl *CGDebugInfo::getObjCInterfaceDecl(QualType Ty) {
2095 switch (Ty->getTypeClass()) {
2096 case Type::ObjCObjectPointer:
Eric Christopher0fdcb312013-05-16 00:52:20 +00002097 return getObjCInterfaceDecl(cast<ObjCObjectPointerType>(Ty)
2098 ->getPointeeType());
Adrian Prantla03a85a2013-03-06 22:03:30 +00002099 case Type::ObjCInterface:
2100 return cast<ObjCInterfaceType>(Ty)->getDecl();
2101 default:
2102 return 0;
2103 }
2104}
2105
Guy Benyei11169dd2012-12-18 14:30:41 +00002106/// CreateTypeNode - Create a new debug type node.
David Blaikie99dab3b2013-09-04 22:03:57 +00002107llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002108 // Handle qualifiers, which recursively handles what they refer to.
2109 if (Ty.hasLocalQualifiers())
David Blaikie99dab3b2013-09-04 22:03:57 +00002110 return CreateQualifiedType(Ty, Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00002111
2112 const char *Diag = 0;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002113
Guy Benyei11169dd2012-12-18 14:30:41 +00002114 // Work out details of type.
2115 switch (Ty->getTypeClass()) {
2116#define TYPE(Class, Base)
2117#define ABSTRACT_TYPE(Class, Base)
2118#define NON_CANONICAL_TYPE(Class, Base)
2119#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2120#include "clang/AST/TypeNodes.def"
2121 llvm_unreachable("Dependent types cannot show up in debug information");
2122
2123 case Type::ExtVector:
2124 case Type::Vector:
2125 return CreateType(cast<VectorType>(Ty), Unit);
2126 case Type::ObjCObjectPointer:
2127 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
2128 case Type::ObjCObject:
2129 return CreateType(cast<ObjCObjectType>(Ty), Unit);
2130 case Type::ObjCInterface:
2131 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
2132 case Type::Builtin:
2133 return CreateType(cast<BuiltinType>(Ty));
2134 case Type::Complex:
2135 return CreateType(cast<ComplexType>(Ty));
2136 case Type::Pointer:
2137 return CreateType(cast<PointerType>(Ty), Unit);
Reid Kleckner0503a872013-12-05 01:23:43 +00002138 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00002139 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00002140 // Decayed and adjusted types use the adjusted type in LLVM and DWARF.
Reid Kleckner8a365022013-06-24 17:51:48 +00002141 return CreateType(
Reid Kleckner0503a872013-12-05 01:23:43 +00002142 cast<PointerType>(cast<AdjustedType>(Ty)->getAdjustedType()), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00002143 case Type::BlockPointer:
2144 return CreateType(cast<BlockPointerType>(Ty), Unit);
2145 case Type::Typedef:
David Blaikie99dab3b2013-09-04 22:03:57 +00002146 return CreateType(cast<TypedefType>(Ty), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00002147 case Type::Record:
David Blaikie99dab3b2013-09-04 22:03:57 +00002148 return CreateType(cast<RecordType>(Ty));
Guy Benyei11169dd2012-12-18 14:30:41 +00002149 case Type::Enum:
Manman Ren1b457022013-08-28 21:20:28 +00002150 return CreateEnumType(cast<EnumType>(Ty));
Guy Benyei11169dd2012-12-18 14:30:41 +00002151 case Type::FunctionProto:
2152 case Type::FunctionNoProto:
2153 return CreateType(cast<FunctionType>(Ty), Unit);
2154 case Type::ConstantArray:
2155 case Type::VariableArray:
2156 case Type::IncompleteArray:
2157 return CreateType(cast<ArrayType>(Ty), Unit);
2158
2159 case Type::LValueReference:
2160 return CreateType(cast<LValueReferenceType>(Ty), Unit);
2161 case Type::RValueReference:
2162 return CreateType(cast<RValueReferenceType>(Ty), Unit);
2163
2164 case Type::MemberPointer:
2165 return CreateType(cast<MemberPointerType>(Ty), Unit);
2166
2167 case Type::Atomic:
2168 return CreateType(cast<AtomicType>(Ty), Unit);
2169
2170 case Type::Attributed:
2171 case Type::TemplateSpecialization:
2172 case Type::Elaborated:
2173 case Type::Paren:
2174 case Type::SubstTemplateTypeParm:
2175 case Type::TypeOfExpr:
2176 case Type::TypeOf:
2177 case Type::Decltype:
2178 case Type::UnaryTransform:
David Blaikie66ed89d2013-07-13 21:08:08 +00002179 case Type::PackExpansion:
Guy Benyei11169dd2012-12-18 14:30:41 +00002180 llvm_unreachable("type should have been unwrapped!");
David Blaikie22c460a02013-05-24 21:24:35 +00002181 case Type::Auto:
2182 Diag = "auto";
2183 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002184 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00002185
Guy Benyei11169dd2012-12-18 14:30:41 +00002186 assert(Diag && "Fall through without a diagnostic?");
2187 unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error,
2188 "debug information for %0 is not yet supported");
2189 CGM.getDiags().Report(DiagID)
2190 << Diag;
2191 return llvm::DIType();
2192}
2193
2194/// getOrCreateLimitedType - Get the type from the cache or create a new
2195/// limited type if necessary.
David Blaikie4a2b5ef2013-08-12 22:24:20 +00002196llvm::DIType CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty,
Eric Christopherc0c5d462013-02-21 22:35:08 +00002197 llvm::DIFile Unit) {
David Blaikie4a2b5ef2013-08-12 22:24:20 +00002198 QualType QTy(Ty, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00002199
David Blaikie8d5e1282013-08-20 21:03:29 +00002200 llvm::DICompositeType T(getTypeOrNull(QTy));
Guy Benyei11169dd2012-12-18 14:30:41 +00002201
2202 // We may have cached a forward decl when we could have created
2203 // a non-forward decl. Go ahead and create a non-forward decl
2204 // now.
Eric Christopherf8bc4d82013-07-18 00:52:50 +00002205 if (T && !T.isForwardDecl()) return T;
Guy Benyei11169dd2012-12-18 14:30:41 +00002206
2207 // Otherwise create the type.
David Blaikie8d5e1282013-08-20 21:03:29 +00002208 llvm::DICompositeType Res = CreateLimitedType(Ty);
2209
2210 // Propagate members from the declaration to the definition
2211 // CreateType(const RecordType*) will overwrite this with the members in the
2212 // correct order if the full type is needed.
2213 Res.setTypeArray(T.getTypeArray());
Guy Benyei11169dd2012-12-18 14:30:41 +00002214
Eric Christopherf8bc4d82013-07-18 00:52:50 +00002215 if (T && T.isForwardDecl())
David Blaikie4a2b5ef2013-08-12 22:24:20 +00002216 ReplaceMap.push_back(
2217 std::make_pair(QTy.getAsOpaquePtr(), static_cast<llvm::Value *>(T)));
Guy Benyei11169dd2012-12-18 14:30:41 +00002218
2219 // And update the type cache.
David Blaikie4a2b5ef2013-08-12 22:24:20 +00002220 TypeCache[QTy.getAsOpaquePtr()] = Res;
Guy Benyei11169dd2012-12-18 14:30:41 +00002221 return Res;
2222}
2223
2224// TODO: Currently used for context chains when limiting debug info.
David Blaikie8d5e1282013-08-20 21:03:29 +00002225llvm::DICompositeType CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002226 RecordDecl *RD = Ty->getDecl();
Eric Christopherb2a008c2013-05-16 00:45:12 +00002227
Guy Benyei11169dd2012-12-18 14:30:41 +00002228 // Get overall information about the record type for the debug info.
2229 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
2230 unsigned Line = getLineNumber(RD->getLocation());
2231 StringRef RDName = getClassName(RD);
2232
Eric Christopher07429ff2013-10-15 21:22:34 +00002233 llvm::DIDescriptor RDContext =
2234 getContextDescriptor(cast<Decl>(RD->getDeclContext()));
Guy Benyei11169dd2012-12-18 14:30:41 +00002235
David Blaikied2785892013-08-18 17:36:19 +00002236 // If we ended up creating the type during the context chain construction,
2237 // just return that.
2238 // FIXME: this could be dealt with better if the type was recorded as
2239 // completed before we started this (see the CompletedTypeCache usage in
2240 // CGDebugInfo::CreateTypeDefinition(const RecordType*) - that would need to
2241 // be pushed to before context creation, but after it was known to be
2242 // destined for completion (might still have an issue if this caller only
2243 // required a declaration but the context construction ended up creating a
2244 // definition)
David Blaikie8d5e1282013-08-20 21:03:29 +00002245 llvm::DICompositeType T(getTypeOrNull(CGM.getContext().getRecordType(RD)));
2246 if (T && (!T.isForwardDecl() || !RD->getDefinition()))
David Blaikied2785892013-08-18 17:36:19 +00002247 return T;
2248
Guy Benyei11169dd2012-12-18 14:30:41 +00002249 // If this is just a forward declaration, construct an appropriately
2250 // marked node and just return it.
2251 if (!RD->getDefinition())
Manman Ren1b457022013-08-28 21:20:28 +00002252 return getOrCreateRecordFwdDecl(Ty, RDContext);
Guy Benyei11169dd2012-12-18 14:30:41 +00002253
2254 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2255 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
David Blaikie49ae6a72013-03-26 23:47:35 +00002256 llvm::DICompositeType RealDecl;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002257
Manman Rene0064d82013-08-29 23:19:58 +00002258 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
2259
Guy Benyei11169dd2012-12-18 14:30:41 +00002260 if (RD->isUnion())
2261 RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
Manman Rene0064d82013-08-29 23:19:58 +00002262 Size, Align, 0, llvm::DIArray(), 0,
2263 FullName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002264 else if (RD->isClass()) {
2265 // FIXME: This could be a struct type giving a default visibility different
2266 // than C++ class type, but needs llvm metadata changes first.
2267 RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
Eric Christopherc0c5d462013-02-21 22:35:08 +00002268 Size, Align, 0, 0, llvm::DIType(),
2269 llvm::DIArray(), llvm::DIType(),
Manman Rene0064d82013-08-29 23:19:58 +00002270 llvm::DIArray(), FullName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002271 } else
2272 RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line,
Eric Christopher0fdcb312013-05-16 00:52:20 +00002273 Size, Align, 0, llvm::DIType(),
David Blaikieba477362013-11-18 23:38:26 +00002274 llvm::DIArray(), 0, llvm::DIType(),
2275 FullName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002276
2277 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
David Blaikie49ae6a72013-03-26 23:47:35 +00002278 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00002279
David Blaikieadfbf992013-08-18 16:55:33 +00002280 if (const ClassTemplateSpecializationDecl *TSpecial =
2281 dyn_cast<ClassTemplateSpecializationDecl>(RD))
2282 RealDecl.setTypeArray(llvm::DIArray(),
2283 CollectCXXTemplateParams(TSpecial, DefUnit));
David Blaikie952dac32013-08-15 22:42:12 +00002284 return RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00002285}
2286
David Blaikieadfbf992013-08-18 16:55:33 +00002287void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,
2288 llvm::DICompositeType RealDecl) {
2289 // A class's primary base or the class itself contains the vtable.
2290 llvm::DICompositeType ContainingType;
2291 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2292 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
Alp Tokerd4733632013-12-05 04:47:09 +00002293 // Seek non-virtual primary base root.
David Blaikieadfbf992013-08-18 16:55:33 +00002294 while (1) {
2295 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
2296 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
2297 if (PBT && !BRL.isPrimaryBaseVirtual())
2298 PBase = PBT;
2299 else
2300 break;
2301 }
2302 ContainingType = llvm::DICompositeType(
2303 getOrCreateType(QualType(PBase->getTypeForDecl(), 0),
2304 getOrCreateFile(RD->getLocation())));
2305 } else if (RD->isDynamicClass())
2306 ContainingType = RealDecl;
2307
2308 RealDecl.setContainingType(ContainingType);
2309}
2310
Guy Benyei11169dd2012-12-18 14:30:41 +00002311/// CreateMemberType - Create new member and increase Offset by FType's size.
2312llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
2313 StringRef Name,
2314 uint64_t *Offset) {
2315 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2316 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
2317 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
2318 llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0,
2319 FieldSize, FieldAlign,
2320 *Offset, 0, FieldTy);
2321 *Offset += FieldSize;
2322 return Ty;
2323}
2324
David Blaikiebd483762013-05-20 04:58:53 +00002325llvm::DIDescriptor CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
2326 // We only need a declaration (not a definition) of the type - so use whatever
2327 // we would otherwise do to get a type for a pointee. (forward declarations in
2328 // limited debug info, full definitions (if the type definition is available)
2329 // in unlimited debug info)
David Blaikie6b7d060c2013-08-12 23:14:36 +00002330 if (const TypeDecl *TD = dyn_cast<TypeDecl>(D))
2331 return getOrCreateType(CGM.getContext().getTypeDeclType(TD),
David Blaikie99dab3b2013-09-04 22:03:57 +00002332 getOrCreateFile(TD->getLocation()));
David Blaikiebd483762013-05-20 04:58:53 +00002333 // Otherwise fall back to a fairly rudimentary cache of existing declarations.
2334 // This doesn't handle providing declarations (for functions or variables) for
2335 // entities without definitions in this TU, nor when the definition proceeds
2336 // the call to this function.
2337 // FIXME: This should be split out into more specific maps with support for
2338 // emitting forward declarations and merging definitions with declarations,
2339 // the same way as we do for types.
2340 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator I =
2341 DeclCache.find(D->getCanonicalDecl());
2342 if (I == DeclCache.end())
2343 return llvm::DIDescriptor();
2344 llvm::Value *V = I->second;
2345 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
2346}
2347
Guy Benyei11169dd2012-12-18 14:30:41 +00002348/// getFunctionDeclaration - Return debug info descriptor to describe method
2349/// declaration for the given method definition.
2350llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
David Blaikie18cfbc52013-06-22 00:09:36 +00002351 if (!D || DebugKind == CodeGenOptions::DebugLineTablesOnly)
2352 return llvm::DISubprogram();
2353
Guy Benyei11169dd2012-12-18 14:30:41 +00002354 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
2355 if (!FD) return llvm::DISubprogram();
2356
2357 // Setup context.
David Blaikiefd07c602013-08-09 17:20:05 +00002358 llvm::DIScope S = getContextDescriptor(cast<Decl>(D->getDeclContext()));
Guy Benyei11169dd2012-12-18 14:30:41 +00002359
2360 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2361 MI = SPCache.find(FD->getCanonicalDecl());
David Blaikiefd07c602013-08-09 17:20:05 +00002362 if (MI == SPCache.end()) {
Eric Christopherf86c4052013-08-28 23:12:10 +00002363 if (const CXXMethodDecl *MD =
2364 dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
David Blaikiefd07c602013-08-09 17:20:05 +00002365 llvm::DICompositeType T(S);
Eric Christopherf86c4052013-08-28 23:12:10 +00002366 llvm::DISubprogram SP =
2367 CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()), T);
David Blaikiefd07c602013-08-09 17:20:05 +00002368 return SP;
2369 }
2370 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002371 if (MI != SPCache.end()) {
2372 llvm::Value *V = MI->second;
2373 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
David Blaikie18cfbc52013-06-22 00:09:36 +00002374 if (SP.isSubprogram() && !SP.isDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00002375 return SP;
2376 }
2377
2378 for (FunctionDecl::redecl_iterator I = FD->redecls_begin(),
2379 E = FD->redecls_end(); I != E; ++I) {
2380 const FunctionDecl *NextFD = *I;
2381 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2382 MI = SPCache.find(NextFD->getCanonicalDecl());
2383 if (MI != SPCache.end()) {
2384 llvm::Value *V = MI->second;
2385 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
David Blaikie18cfbc52013-06-22 00:09:36 +00002386 if (SP.isSubprogram() && !SP.isDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00002387 return SP;
2388 }
2389 }
2390 return llvm::DISubprogram();
2391}
2392
2393// getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
2394// implicit parameter "this".
David Blaikie469f0792013-05-22 23:22:42 +00002395llvm::DICompositeType CGDebugInfo::getOrCreateFunctionType(const Decl *D,
2396 QualType FnType,
2397 llvm::DIFile F) {
David Blaikie18cfbc52013-06-22 00:09:36 +00002398 if (!D || DebugKind == CodeGenOptions::DebugLineTablesOnly)
2399 // Create fake but valid subroutine type. Otherwise
2400 // llvm::DISubprogram::Verify() would return false, and
2401 // subprogram DIE will miss DW_AT_decl_file and
2402 // DW_AT_decl_line fields.
2403 return DBuilder.createSubroutineType(F, DBuilder.getOrCreateArray(None));
Guy Benyei11169dd2012-12-18 14:30:41 +00002404
2405 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
2406 return getOrCreateMethodType(Method, F);
2407 if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
2408 // Add "self" and "_cmd"
2409 SmallVector<llvm::Value *, 16> Elts;
2410
2411 // First element is always return type. For 'void' functions it is NULL.
Adrian Prantl5f360102013-05-22 21:37:49 +00002412 QualType ResultTy = OMethod->getResultType();
2413
2414 // Replace the instancetype keyword with the actual type.
2415 if (ResultTy == CGM.getContext().getObjCInstanceType())
2416 ResultTy = CGM.getContext().getPointerType(
2417 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
2418
Adrian Prantl7bec9032013-05-10 21:08:31 +00002419 Elts.push_back(getOrCreateType(ResultTy, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002420 // "self" pointer is always first argument.
Adrian Prantlde17db32013-03-29 19:20:29 +00002421 QualType SelfDeclTy = OMethod->getSelfDecl()->getType();
2422 llvm::DIType SelfTy = getOrCreateType(SelfDeclTy, F);
2423 Elts.push_back(CreateSelfType(SelfDeclTy, SelfTy));
Guy Benyei11169dd2012-12-18 14:30:41 +00002424 // "_cmd" pointer is always second argument.
2425 llvm::DIType CmdTy = getOrCreateType(OMethod->getCmdDecl()->getType(), F);
2426 Elts.push_back(DBuilder.createArtificialType(CmdTy));
2427 // Get rest of the arguments.
Eric Christopherb2a008c2013-05-16 00:45:12 +00002428 for (ObjCMethodDecl::param_const_iterator PI = OMethod->param_begin(),
Guy Benyei11169dd2012-12-18 14:30:41 +00002429 PE = OMethod->param_end(); PI != PE; ++PI)
2430 Elts.push_back(getOrCreateType((*PI)->getType(), F));
2431
2432 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2433 return DBuilder.createSubroutineType(F, EltTypeArray);
2434 }
David Blaikie469f0792013-05-22 23:22:42 +00002435 return llvm::DICompositeType(getOrCreateType(FnType, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002436}
2437
2438/// EmitFunctionStart - Constructs the debug code for entering a function.
2439void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
2440 llvm::Function *Fn,
2441 CGBuilderTy &Builder) {
2442
2443 StringRef Name;
2444 StringRef LinkageName;
2445
2446 FnBeginRegionCount.push_back(LexicalBlockStack.size());
2447
2448 const Decl *D = GD.getDecl();
2449 // Function may lack declaration in source code if it is created by Clang
2450 // CodeGen (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
2451 bool HasDecl = (D != 0);
2452 // Use the location of the declaration.
2453 SourceLocation Loc;
2454 if (HasDecl)
2455 Loc = D->getLocation();
2456
2457 unsigned Flags = 0;
2458 llvm::DIFile Unit = getOrCreateFile(Loc);
2459 llvm::DIDescriptor FDContext(Unit);
2460 llvm::DIArray TParamsArray;
2461 if (!HasDecl) {
2462 // Use llvm function name.
David Blaikieebe87e12013-08-27 23:57:18 +00002463 LinkageName = Fn->getName();
Guy Benyei11169dd2012-12-18 14:30:41 +00002464 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2465 // If there is a DISubprogram for this function available then use it.
2466 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2467 FI = SPCache.find(FD->getCanonicalDecl());
2468 if (FI != SPCache.end()) {
2469 llvm::Value *V = FI->second;
2470 llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(V));
2471 if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
2472 llvm::MDNode *SPN = SP;
2473 LexicalBlockStack.push_back(SPN);
2474 RegionMap[D] = llvm::WeakVH(SP);
2475 return;
2476 }
2477 }
2478 Name = getFunctionName(FD);
Nick Lewyckyc02bbb62013-03-20 01:38:16 +00002479 // Use mangled name as linkage name for C/C++ functions.
Guy Benyei11169dd2012-12-18 14:30:41 +00002480 if (FD->hasPrototype()) {
2481 LinkageName = CGM.getMangledName(GD);
2482 Flags |= llvm::DIDescriptor::FlagPrototyped;
2483 }
Nick Lewyckyc02bbb62013-03-20 01:38:16 +00002484 // No need to replicate the linkage name if it isn't different from the
2485 // subprogram name, no need to have it at all unless coverage is enabled or
2486 // debug is set to more than just line tables.
Guy Benyei11169dd2012-12-18 14:30:41 +00002487 if (LinkageName == Name ||
Nick Lewyckyc02bbb62013-03-20 01:38:16 +00002488 (!CGM.getCodeGenOpts().EmitGcovArcs &&
2489 !CGM.getCodeGenOpts().EmitGcovNotes &&
Eric Christopher75e17682013-05-16 00:45:23 +00002490 DebugKind <= CodeGenOptions::DebugLineTablesOnly))
Guy Benyei11169dd2012-12-18 14:30:41 +00002491 LinkageName = StringRef();
2492
Eric Christopher75e17682013-05-16 00:45:23 +00002493 if (DebugKind >= CodeGenOptions::LimitedDebugInfo) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002494 if (const NamespaceDecl *NSDecl =
Eric Christopher9e6f5f92013-10-17 01:31:21 +00002495 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
Guy Benyei11169dd2012-12-18 14:30:41 +00002496 FDContext = getOrCreateNameSpace(NSDecl);
2497 else if (const RecordDecl *RDecl =
Eric Christopher9e6f5f92013-10-17 01:31:21 +00002498 dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
2499 FDContext = getContextDescriptor(cast<Decl>(RDecl));
Guy Benyei11169dd2012-12-18 14:30:41 +00002500
2501 // Collect template parameters.
2502 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
2503 }
2504 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
2505 Name = getObjCMethodName(OMD);
2506 Flags |= llvm::DIDescriptor::FlagPrototyped;
2507 } else {
2508 // Use llvm function name.
2509 Name = Fn->getName();
2510 Flags |= llvm::DIDescriptor::FlagPrototyped;
2511 }
2512 if (!Name.empty() && Name[0] == '\01')
2513 Name = Name.substr(1);
2514
2515 unsigned LineNo = getLineNumber(Loc);
2516 if (!HasDecl || D->isImplicit())
2517 Flags |= llvm::DIDescriptor::FlagArtificial;
2518
Eric Christopher9e6f5f92013-10-17 01:31:21 +00002519 llvm::DISubprogram SP =
2520 DBuilder.createFunction(FDContext, Name, LinkageName, Unit, LineNo,
2521 getOrCreateFunctionType(D, FnType, Unit),
2522 Fn->hasInternalLinkage(), true /*definition*/,
2523 getLineNumber(CurLoc), Flags,
2524 CGM.getLangOpts().Optimize, Fn, TParamsArray,
2525 getFunctionDeclaration(D));
David Blaikiebd483762013-05-20 04:58:53 +00002526 if (HasDecl)
2527 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(SP)));
Guy Benyei11169dd2012-12-18 14:30:41 +00002528
2529 // Push function on region stack.
2530 llvm::MDNode *SPN = SP;
2531 LexicalBlockStack.push_back(SPN);
2532 if (HasDecl)
2533 RegionMap[D] = llvm::WeakVH(SP);
2534}
2535
2536/// EmitLocation - Emit metadata to indicate a change in line/column
Adrian Prantl02c0caa2013-07-18 00:27:59 +00002537/// information in the source file. If the location is invalid, the
2538/// previous location will be reused.
Adrian Prantlc7822422013-03-12 20:43:25 +00002539void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc,
Adrian Prantl96e70d92014-01-03 23:34:30 +00002540 bool ForceColumnInfo,
2541 llvm::MDNode *ForceScope) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002542 // Update our current location
2543 setLocation(Loc);
2544
2545 if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
2546
2547 // Don't bother if things are the same as last time.
2548 SourceManager &SM = CGM.getContext().getSourceManager();
2549 if (CurLoc == PrevLoc ||
2550 SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc))
2551 // New Builder may not be in sync with CGDebugInfo.
David Blaikie357aafb2013-02-01 19:09:49 +00002552 if (!Builder.getCurrentDebugLocation().isUnknown() &&
2553 Builder.getCurrentDebugLocation().getScope(CGM.getLLVMContext()) ==
2554 LexicalBlockStack.back())
Guy Benyei11169dd2012-12-18 14:30:41 +00002555 return;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002556
Guy Benyei11169dd2012-12-18 14:30:41 +00002557 // Update last state.
2558 PrevLoc = CurLoc;
2559
Adrian Prantl96e70d92014-01-03 23:34:30 +00002560 llvm::MDNode *Scope = ForceScope ? ForceScope : &*LexicalBlockStack.back();
Adrian Prantlc7822422013-03-12 20:43:25 +00002561 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get
2562 (getLineNumber(CurLoc),
2563 getColumnNumber(CurLoc, ForceColumnInfo),
2564 Scope));
Guy Benyei11169dd2012-12-18 14:30:41 +00002565}
2566
2567/// CreateLexicalBlock - Creates a new lexical block node and pushes it on
2568/// the stack.
2569void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
2570 llvm::DIDescriptor D =
2571 DBuilder.createLexicalBlock(LexicalBlockStack.empty() ?
2572 llvm::DIDescriptor() :
2573 llvm::DIDescriptor(LexicalBlockStack.back()),
2574 getOrCreateFile(CurLoc),
2575 getLineNumber(CurLoc),
2576 getColumnNumber(CurLoc));
2577 llvm::MDNode *DN = D;
2578 LexicalBlockStack.push_back(DN);
2579}
2580
2581/// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
2582/// region - beginning of a DW_TAG_lexical_block.
Eric Christopher0fdcb312013-05-16 00:52:20 +00002583void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
2584 SourceLocation Loc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002585 // Set our current location.
2586 setLocation(Loc);
2587
2588 // Create a new lexical block and push it on the stack.
2589 CreateLexicalBlock(Loc);
2590
2591 // Emit a line table change for the current location inside the new scope.
2592 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc),
2593 getColumnNumber(Loc),
2594 LexicalBlockStack.back()));
2595}
2596
2597/// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative
2598/// region - end of a DW_TAG_lexical_block.
Eric Christopher0fdcb312013-05-16 00:52:20 +00002599void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
2600 SourceLocation Loc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002601 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2602
2603 // Provide an entry in the line table for the end of the block.
2604 EmitLocation(Builder, Loc);
2605
2606 LexicalBlockStack.pop_back();
2607}
2608
2609/// EmitFunctionEnd - Constructs the debug code for exiting a function.
2610void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
2611 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2612 unsigned RCount = FnBeginRegionCount.back();
2613 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
2614
2615 // Pop all regions for this function.
2616 while (LexicalBlockStack.size() != RCount)
2617 EmitLexicalBlockEnd(Builder, CurLoc);
2618 FnBeginRegionCount.pop_back();
2619}
2620
Eric Christopherb2a008c2013-05-16 00:45:12 +00002621// EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
Guy Benyei11169dd2012-12-18 14:30:41 +00002622// See BuildByRefType.
2623llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
2624 uint64_t *XOffset) {
2625
2626 SmallVector<llvm::Value *, 5> EltTys;
2627 QualType FType;
2628 uint64_t FieldSize, FieldOffset;
2629 unsigned FieldAlign;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002630
Guy Benyei11169dd2012-12-18 14:30:41 +00002631 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
Eric Christopherb2a008c2013-05-16 00:45:12 +00002632 QualType Type = VD->getType();
Guy Benyei11169dd2012-12-18 14:30:41 +00002633
2634 FieldOffset = 0;
2635 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2636 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
2637 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
2638 FType = CGM.getContext().IntTy;
2639 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
2640 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
2641
2642 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
2643 if (HasCopyAndDispose) {
2644 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2645 EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
2646 &FieldOffset));
2647 EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
2648 &FieldOffset));
2649 }
2650 bool HasByrefExtendedLayout;
2651 Qualifiers::ObjCLifetime Lifetime;
2652 if (CGM.getContext().getByrefLifetime(Type,
2653 Lifetime, HasByrefExtendedLayout)
Adrian Prantlead2ba42013-07-23 00:12:14 +00002654 && HasByrefExtendedLayout) {
2655 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
Guy Benyei11169dd2012-12-18 14:30:41 +00002656 EltTys.push_back(CreateMemberType(Unit, FType,
2657 "__byref_variable_layout",
2658 &FieldOffset));
Adrian Prantlead2ba42013-07-23 00:12:14 +00002659 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00002660
Guy Benyei11169dd2012-12-18 14:30:41 +00002661 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2662 if (Align > CGM.getContext().toCharUnitsFromBits(
John McCallc8e01702013-04-16 22:48:15 +00002663 CGM.getTarget().getPointerAlign(0))) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00002664 CharUnits FieldOffsetInBytes
Guy Benyei11169dd2012-12-18 14:30:41 +00002665 = CGM.getContext().toCharUnitsFromBits(FieldOffset);
2666 CharUnits AlignedOffsetInBytes
2667 = FieldOffsetInBytes.RoundUpToAlignment(Align);
2668 CharUnits NumPaddingBytes
2669 = AlignedOffsetInBytes - FieldOffsetInBytes;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002670
Guy Benyei11169dd2012-12-18 14:30:41 +00002671 if (NumPaddingBytes.isPositive()) {
2672 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
2673 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
2674 pad, ArrayType::Normal, 0);
2675 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
2676 }
2677 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00002678
Guy Benyei11169dd2012-12-18 14:30:41 +00002679 FType = Type;
2680 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2681 FieldSize = CGM.getContext().getTypeSize(FType);
2682 FieldAlign = CGM.getContext().toBits(Align);
2683
Eric Christopherb2a008c2013-05-16 00:45:12 +00002684 *XOffset = FieldOffset;
Guy Benyei11169dd2012-12-18 14:30:41 +00002685 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit,
2686 0, FieldSize, FieldAlign,
2687 FieldOffset, 0, FieldTy);
2688 EltTys.push_back(FieldTy);
2689 FieldOffset += FieldSize;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002690
Guy Benyei11169dd2012-12-18 14:30:41 +00002691 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002692
Guy Benyei11169dd2012-12-18 14:30:41 +00002693 unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002694
Guy Benyei11169dd2012-12-18 14:30:41 +00002695 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
David Blaikie6d4fe152013-02-25 01:07:08 +00002696 llvm::DIType(), Elements);
Guy Benyei11169dd2012-12-18 14:30:41 +00002697}
2698
2699/// EmitDeclare - Emit local variable declaration debug info.
2700void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
Eric Christopherb2a008c2013-05-16 00:45:12 +00002701 llvm::Value *Storage,
Guy Benyei11169dd2012-12-18 14:30:41 +00002702 unsigned ArgNo, CGBuilderTy &Builder) {
Eric Christopher75e17682013-05-16 00:45:23 +00002703 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002704 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2705
David Blaikie7fceebf2013-08-19 03:37:48 +00002706 bool Unwritten =
2707 VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) &&
2708 cast<Decl>(VD->getDeclContext())->isImplicit());
2709 llvm::DIFile Unit;
2710 if (!Unwritten)
2711 Unit = getOrCreateFile(VD->getLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00002712 llvm::DIType Ty;
2713 uint64_t XOffset = 0;
2714 if (VD->hasAttr<BlocksAttr>())
2715 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002716 else
Guy Benyei11169dd2012-12-18 14:30:41 +00002717 Ty = getOrCreateType(VD->getType(), Unit);
2718
2719 // If there is no debug info for this type then do not emit debug info
2720 // for this variable.
2721 if (!Ty)
2722 return;
2723
Guy Benyei11169dd2012-12-18 14:30:41 +00002724 // Get location information.
David Blaikie7fceebf2013-08-19 03:37:48 +00002725 unsigned Line = 0;
2726 unsigned Column = 0;
2727 if (!Unwritten) {
2728 Line = getLineNumber(VD->getLocation());
2729 Column = getColumnNumber(VD->getLocation());
2730 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002731 unsigned Flags = 0;
2732 if (VD->isImplicit())
2733 Flags |= llvm::DIDescriptor::FlagArtificial;
2734 // If this is the first argument and it is implicit then
2735 // give it an object pointer flag.
2736 // FIXME: There has to be a better way to do this, but for static
2737 // functions there won't be an implicit param at arg1 and
2738 // otherwise it is 'self' or 'this'.
2739 if (isa<ImplicitParamDecl>(VD) && ArgNo == 1)
2740 Flags |= llvm::DIDescriptor::FlagObjectPointer;
David Blaikieb9c667d2013-06-19 21:53:53 +00002741 if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage))
Eric Christopherffdeb1e2013-07-17 22:52:53 +00002742 if (Arg->getType()->isPointerTy() && !Arg->hasByValAttr() &&
2743 !VD->getType()->isPointerType())
David Blaikieb9c667d2013-06-19 21:53:53 +00002744 Flags |= llvm::DIDescriptor::FlagIndirectVariable;
Guy Benyei11169dd2012-12-18 14:30:41 +00002745
2746 llvm::MDNode *Scope = LexicalBlockStack.back();
2747
2748 StringRef Name = VD->getName();
2749 if (!Name.empty()) {
2750 if (VD->hasAttr<BlocksAttr>()) {
2751 CharUnits offset = CharUnits::fromQuantity(32);
2752 SmallVector<llvm::Value *, 9> addr;
2753 llvm::Type *Int64Ty = CGM.Int64Ty;
2754 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2755 // offset of __forwarding field
2756 offset = CGM.getContext().toCharUnitsFromBits(
John McCallc8e01702013-04-16 22:48:15 +00002757 CGM.getTarget().getPointerWidth(0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002758 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2759 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2760 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2761 // offset of x field
2762 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2763 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2764
2765 // Create the descriptor for the variable.
2766 llvm::DIVariable D =
Eric Christopherb2a008c2013-05-16 00:45:12 +00002767 DBuilder.createComplexVariable(Tag,
Guy Benyei11169dd2012-12-18 14:30:41 +00002768 llvm::DIDescriptor(Scope),
2769 VD->getName(), Unit, Line, Ty,
2770 addr, ArgNo);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002771
Guy Benyei11169dd2012-12-18 14:30:41 +00002772 // Insert an llvm.dbg.declare into the current block.
2773 llvm::Instruction *Call =
2774 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2775 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2776 return;
Adrian Prantl7f2ef222013-09-18 22:18:17 +00002777 } else if (isa<VariableArrayType>(VD->getType()))
Adrian Prantl0315f382013-09-18 22:08:57 +00002778 Flags |= llvm::DIDescriptor::FlagIndirectVariable;
David Blaikiea76a7c92013-01-05 05:58:35 +00002779 } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2780 // If VD is an anonymous union then Storage represents value for
2781 // all union fields.
Guy Benyei11169dd2012-12-18 14:30:41 +00002782 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
David Blaikie219c7d92013-01-05 20:03:07 +00002783 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002784 for (RecordDecl::field_iterator I = RD->field_begin(),
2785 E = RD->field_end();
2786 I != E; ++I) {
2787 FieldDecl *Field = *I;
2788 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2789 StringRef FieldName = Field->getName();
Eric Christopherb2a008c2013-05-16 00:45:12 +00002790
Guy Benyei11169dd2012-12-18 14:30:41 +00002791 // Ignore unnamed fields. Do not ignore unnamed records.
2792 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2793 continue;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002794
Guy Benyei11169dd2012-12-18 14:30:41 +00002795 // Use VarDecl's Tag, Scope and Line number.
2796 llvm::DIVariable D =
2797 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
Eric Christopherb2a008c2013-05-16 00:45:12 +00002798 FieldName, Unit, Line, FieldTy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002799 CGM.getLangOpts().Optimize, Flags,
2800 ArgNo);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002801
Guy Benyei11169dd2012-12-18 14:30:41 +00002802 // Insert an llvm.dbg.declare into the current block.
2803 llvm::Instruction *Call =
2804 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2805 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2806 }
David Blaikie219c7d92013-01-05 20:03:07 +00002807 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00002808 }
2809 }
David Blaikiea76a7c92013-01-05 05:58:35 +00002810
2811 // Create the descriptor for the variable.
2812 llvm::DIVariable D =
2813 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2814 Name, Unit, Line, Ty,
2815 CGM.getLangOpts().Optimize, Flags, ArgNo);
2816
2817 // Insert an llvm.dbg.declare into the current block.
2818 llvm::Instruction *Call =
2819 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2820 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
Guy Benyei11169dd2012-12-18 14:30:41 +00002821}
2822
2823void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2824 llvm::Value *Storage,
2825 CGBuilderTy &Builder) {
Eric Christopher75e17682013-05-16 00:45:23 +00002826 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002827 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2828}
2829
Adrian Prantlde17db32013-03-29 19:20:29 +00002830/// Look up the completed type for a self pointer in the TypeCache and
2831/// create a copy of it with the ObjectPointer and Artificial flags
2832/// set. If the type is not cached, a new one is created. This should
2833/// never happen though, since creating a type for the implicit self
2834/// argument implies that we already parsed the interface definition
2835/// and the ivar declarations in the implementation.
Eric Christopher0fdcb312013-05-16 00:52:20 +00002836llvm::DIType CGDebugInfo::CreateSelfType(const QualType &QualTy,
2837 llvm::DIType Ty) {
Adrian Prantlde17db32013-03-29 19:20:29 +00002838 llvm::DIType CachedTy = getTypeOrNull(QualTy);
Eric Christopherf8bc4d82013-07-18 00:52:50 +00002839 if (CachedTy) Ty = CachedTy;
Adrian Prantlde17db32013-03-29 19:20:29 +00002840 else DEBUG(llvm::dbgs() << "No cached type for self.");
2841 return DBuilder.createObjectPointerType(Ty);
2842}
2843
Guy Benyei11169dd2012-12-18 14:30:41 +00002844void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(const VarDecl *VD,
2845 llvm::Value *Storage,
2846 CGBuilderTy &Builder,
2847 const CGBlockInfo &blockInfo) {
Eric Christopher75e17682013-05-16 00:45:23 +00002848 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002849 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
Eric Christopherb2a008c2013-05-16 00:45:12 +00002850
Guy Benyei11169dd2012-12-18 14:30:41 +00002851 if (Builder.GetInsertBlock() == 0)
2852 return;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002853
Guy Benyei11169dd2012-12-18 14:30:41 +00002854 bool isByRef = VD->hasAttr<BlocksAttr>();
Eric Christopherb2a008c2013-05-16 00:45:12 +00002855
Guy Benyei11169dd2012-12-18 14:30:41 +00002856 uint64_t XOffset = 0;
2857 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2858 llvm::DIType Ty;
2859 if (isByRef)
2860 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002861 else
Guy Benyei11169dd2012-12-18 14:30:41 +00002862 Ty = getOrCreateType(VD->getType(), Unit);
2863
2864 // Self is passed along as an implicit non-arg variable in a
2865 // block. Mark it as the object pointer.
2866 if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self")
Adrian Prantlde17db32013-03-29 19:20:29 +00002867 Ty = CreateSelfType(VD->getType(), Ty);
Guy Benyei11169dd2012-12-18 14:30:41 +00002868
2869 // Get location information.
2870 unsigned Line = getLineNumber(VD->getLocation());
2871 unsigned Column = getColumnNumber(VD->getLocation());
2872
2873 const llvm::DataLayout &target = CGM.getDataLayout();
2874
2875 CharUnits offset = CharUnits::fromQuantity(
2876 target.getStructLayout(blockInfo.StructureType)
2877 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2878
2879 SmallVector<llvm::Value *, 9> addr;
2880 llvm::Type *Int64Ty = CGM.Int64Ty;
Adrian Prantl0f6df002013-03-29 19:20:35 +00002881 if (isa<llvm::AllocaInst>(Storage))
2882 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
Guy Benyei11169dd2012-12-18 14:30:41 +00002883 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2884 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2885 if (isByRef) {
2886 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2887 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2888 // offset of __forwarding field
2889 offset = CGM.getContext()
2890 .toCharUnitsFromBits(target.getPointerSizeInBits(0));
2891 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2892 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2893 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2894 // offset of x field
2895 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2896 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2897 }
2898
2899 // Create the descriptor for the variable.
2900 llvm::DIVariable D =
Eric Christopherb2a008c2013-05-16 00:45:12 +00002901 DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable,
Guy Benyei11169dd2012-12-18 14:30:41 +00002902 llvm::DIDescriptor(LexicalBlockStack.back()),
2903 VD->getName(), Unit, Line, Ty, addr);
Adrian Prantl0f6df002013-03-29 19:20:35 +00002904
Guy Benyei11169dd2012-12-18 14:30:41 +00002905 // Insert an llvm.dbg.declare into the current block.
2906 llvm::Instruction *Call =
2907 DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
2908 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column,
2909 LexicalBlockStack.back()));
2910}
2911
2912/// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2913/// variable declaration.
2914void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2915 unsigned ArgNo,
2916 CGBuilderTy &Builder) {
Eric Christopher75e17682013-05-16 00:45:23 +00002917 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002918 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2919}
2920
2921namespace {
2922 struct BlockLayoutChunk {
2923 uint64_t OffsetInBits;
2924 const BlockDecl::Capture *Capture;
2925 };
2926 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2927 return l.OffsetInBits < r.OffsetInBits;
2928 }
2929}
2930
2931void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
Adrian Prantl51936dd2013-03-14 17:53:33 +00002932 llvm::Value *Arg,
2933 llvm::Value *LocalAddr,
Guy Benyei11169dd2012-12-18 14:30:41 +00002934 CGBuilderTy &Builder) {
Eric Christopher75e17682013-05-16 00:45:23 +00002935 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002936 ASTContext &C = CGM.getContext();
2937 const BlockDecl *blockDecl = block.getBlockDecl();
2938
2939 // Collect some general information about the block's location.
2940 SourceLocation loc = blockDecl->getCaretLocation();
2941 llvm::DIFile tunit = getOrCreateFile(loc);
2942 unsigned line = getLineNumber(loc);
2943 unsigned column = getColumnNumber(loc);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002944
Guy Benyei11169dd2012-12-18 14:30:41 +00002945 // Build the debug-info type for the block literal.
2946 getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
2947
2948 const llvm::StructLayout *blockLayout =
2949 CGM.getDataLayout().getStructLayout(block.StructureType);
2950
2951 SmallVector<llvm::Value*, 16> fields;
2952 fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
2953 blockLayout->getElementOffsetInBits(0),
2954 tunit, tunit));
2955 fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
2956 blockLayout->getElementOffsetInBits(1),
2957 tunit, tunit));
2958 fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
2959 blockLayout->getElementOffsetInBits(2),
2960 tunit, tunit));
2961 fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
2962 blockLayout->getElementOffsetInBits(3),
2963 tunit, tunit));
2964 fields.push_back(createFieldType("__descriptor",
2965 C.getPointerType(block.NeedsCopyDispose ?
2966 C.getBlockDescriptorExtendedType() :
2967 C.getBlockDescriptorType()),
2968 0, loc, AS_public,
2969 blockLayout->getElementOffsetInBits(4),
2970 tunit, tunit));
2971
2972 // We want to sort the captures by offset, not because DWARF
2973 // requires this, but because we're paranoid about debuggers.
2974 SmallVector<BlockLayoutChunk, 8> chunks;
2975
2976 // 'this' capture.
2977 if (blockDecl->capturesCXXThis()) {
2978 BlockLayoutChunk chunk;
2979 chunk.OffsetInBits =
2980 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
2981 chunk.Capture = 0;
2982 chunks.push_back(chunk);
2983 }
2984
2985 // Variable captures.
2986 for (BlockDecl::capture_const_iterator
2987 i = blockDecl->capture_begin(), e = blockDecl->capture_end();
2988 i != e; ++i) {
2989 const BlockDecl::Capture &capture = *i;
2990 const VarDecl *variable = capture.getVariable();
2991 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
2992
2993 // Ignore constant captures.
2994 if (captureInfo.isConstant())
2995 continue;
2996
2997 BlockLayoutChunk chunk;
2998 chunk.OffsetInBits =
2999 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
3000 chunk.Capture = &capture;
3001 chunks.push_back(chunk);
3002 }
3003
3004 // Sort by offset.
3005 llvm::array_pod_sort(chunks.begin(), chunks.end());
3006
3007 for (SmallVectorImpl<BlockLayoutChunk>::iterator
3008 i = chunks.begin(), e = chunks.end(); i != e; ++i) {
3009 uint64_t offsetInBits = i->OffsetInBits;
3010 const BlockDecl::Capture *capture = i->Capture;
3011
3012 // If we have a null capture, this must be the C++ 'this' capture.
3013 if (!capture) {
3014 const CXXMethodDecl *method =
3015 cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
3016 QualType type = method->getThisType(C);
3017
3018 fields.push_back(createFieldType("this", type, 0, loc, AS_public,
3019 offsetInBits, tunit, tunit));
3020 continue;
3021 }
3022
3023 const VarDecl *variable = capture->getVariable();
3024 StringRef name = variable->getName();
3025
3026 llvm::DIType fieldType;
3027 if (capture->isByRef()) {
3028 std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
3029
3030 // FIXME: this creates a second copy of this type!
3031 uint64_t xoffset;
3032 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
3033 fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
3034 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
3035 ptrInfo.first, ptrInfo.second,
3036 offsetInBits, 0, fieldType);
3037 } else {
3038 fieldType = createFieldType(name, variable->getType(), 0,
3039 loc, AS_public, offsetInBits, tunit, tunit);
3040 }
3041 fields.push_back(fieldType);
3042 }
3043
3044 SmallString<36> typeName;
3045 llvm::raw_svector_ostream(typeName)
3046 << "__block_literal_" << CGM.getUniqueBlockCount();
3047
3048 llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
3049
3050 llvm::DIType type =
3051 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
3052 CGM.getContext().toBits(block.BlockSize),
3053 CGM.getContext().toBits(block.BlockAlign),
David Blaikie6d4fe152013-02-25 01:07:08 +00003054 0, llvm::DIType(), fieldsArray);
Guy Benyei11169dd2012-12-18 14:30:41 +00003055 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
3056
3057 // Get overall information about the block.
3058 unsigned flags = llvm::DIDescriptor::FlagArtificial;
3059 llvm::MDNode *scope = LexicalBlockStack.back();
Guy Benyei11169dd2012-12-18 14:30:41 +00003060
3061 // Create the descriptor for the parameter.
3062 llvm::DIVariable debugVar =
3063 DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
Eric Christopherb2a008c2013-05-16 00:45:12 +00003064 llvm::DIDescriptor(scope),
Adrian Prantl51936dd2013-03-14 17:53:33 +00003065 Arg->getName(), tunit, line, type,
Guy Benyei11169dd2012-12-18 14:30:41 +00003066 CGM.getLangOpts().Optimize, flags,
Adrian Prantl51936dd2013-03-14 17:53:33 +00003067 cast<llvm::Argument>(Arg)->getArgNo() + 1);
3068
Adrian Prantl616bef42013-03-14 21:52:59 +00003069 if (LocalAddr) {
Adrian Prantl51936dd2013-03-14 17:53:33 +00003070 // Insert an llvm.dbg.value into the current block.
Adrian Prantl616bef42013-03-14 21:52:59 +00003071 llvm::Instruction *DbgVal =
3072 DBuilder.insertDbgValueIntrinsic(LocalAddr, 0, debugVar,
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00003073 Builder.GetInsertBlock());
Adrian Prantl616bef42013-03-14 21:52:59 +00003074 DbgVal->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
3075 }
Adrian Prantl51936dd2013-03-14 17:53:33 +00003076
Adrian Prantl616bef42013-03-14 21:52:59 +00003077 // Insert an llvm.dbg.declare into the current block.
3078 llvm::Instruction *DbgDecl =
3079 DBuilder.insertDeclare(Arg, debugVar, Builder.GetInsertBlock());
3080 DbgDecl->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
Guy Benyei11169dd2012-12-18 14:30:41 +00003081}
3082
David Blaikie6943dea2013-08-20 01:28:15 +00003083/// If D is an out-of-class definition of a static data member of a class, find
3084/// its corresponding in-class declaration.
3085llvm::DIDerivedType
3086CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {
3087 if (!D->isStaticDataMember())
3088 return llvm::DIDerivedType();
3089 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator MI =
3090 StaticDataMemberCache.find(D->getCanonicalDecl());
3091 if (MI != StaticDataMemberCache.end()) {
3092 assert(MI->second && "Static data member declaration should still exist");
3093 return llvm::DIDerivedType(cast<llvm::MDNode>(MI->second));
Evgeniy Stepanov37b3f732013-08-16 10:35:31 +00003094 }
David Blaikiece763042013-08-20 21:49:21 +00003095
3096 // If the member wasn't found in the cache, lazily construct and add it to the
3097 // type (used when a limited form of the type is emitted).
David Blaikie6943dea2013-08-20 01:28:15 +00003098 llvm::DICompositeType Ctxt(
3099 getContextDescriptor(cast<Decl>(D->getDeclContext())));
3100 llvm::DIDerivedType T = CreateRecordStaticField(D, Ctxt);
David Blaikie6943dea2013-08-20 01:28:15 +00003101 return T;
3102}
3103
Guy Benyei11169dd2012-12-18 14:30:41 +00003104/// EmitGlobalVariable - Emit information about a global variable.
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003105void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
Guy Benyei11169dd2012-12-18 14:30:41 +00003106 const VarDecl *D) {
Eric Christopher75e17682013-05-16 00:45:23 +00003107 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00003108 // Create global variable debug descriptor.
3109 llvm::DIFile Unit = getOrCreateFile(D->getLocation());
3110 unsigned LineNo = getLineNumber(D->getLocation());
3111
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003112 setLocation(D->getLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00003113
3114 QualType T = D->getType();
3115 if (T->isIncompleteArrayType()) {
3116
3117 // CodeGen turns int[] into int[1] so we'll do the same here.
3118 llvm::APInt ConstVal(32, 1);
3119 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3120
3121 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3122 ArrayType::Normal, 0);
3123 }
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003124 StringRef DeclName = D->getName();
3125 StringRef LinkageName;
3126 if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext())
3127 && !isa<ObjCMethodDecl>(D->getDeclContext()))
3128 LinkageName = Var->getName();
3129 if (LinkageName == DeclName)
3130 LinkageName = StringRef();
Eric Christopherb2a008c2013-05-16 00:45:12 +00003131 llvm::DIDescriptor DContext =
Guy Benyei11169dd2012-12-18 14:30:41 +00003132 getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
David Blaikie6943dea2013-08-20 01:28:15 +00003133 llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(
3134 DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003135 Var->hasInternalLinkage(), Var,
David Blaikie6943dea2013-08-20 01:28:15 +00003136 getOrCreateStaticDataMemberDeclarationOrNull(D));
David Blaikiebd483762013-05-20 04:58:53 +00003137 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(GV)));
Guy Benyei11169dd2012-12-18 14:30:41 +00003138}
3139
3140/// EmitGlobalVariable - Emit information about an objective-c interface.
3141void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
3142 ObjCInterfaceDecl *ID) {
Eric Christopher75e17682013-05-16 00:45:23 +00003143 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00003144 // Create global variable debug descriptor.
3145 llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
3146 unsigned LineNo = getLineNumber(ID->getLocation());
3147
3148 StringRef Name = ID->getName();
3149
3150 QualType T = CGM.getContext().getObjCInterfaceType(ID);
3151 if (T->isIncompleteArrayType()) {
3152
3153 // CodeGen turns int[] into int[1] so we'll do the same here.
3154 llvm::APInt ConstVal(32, 1);
3155 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3156
3157 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3158 ArrayType::Normal, 0);
3159 }
3160
3161 DBuilder.createGlobalVariable(Name, Unit, LineNo,
3162 getOrCreateType(T, Unit),
3163 Var->hasInternalLinkage(), Var);
3164}
3165
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003166/// EmitGlobalVariable - Emit global variable's debug info.
3167void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
3168 llvm::Constant *Init) {
Eric Christopher75e17682013-05-16 00:45:23 +00003169 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003170 // Create the descriptor for the variable.
3171 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
3172 StringRef Name = VD->getName();
3173 llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
3174 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
3175 const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext());
3176 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
3177 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
3178 }
3179 // Do not use DIGlobalVariable for enums.
3180 if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
3181 return;
3182 llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(
3183 Unit, Name, Name, Unit, getLineNumber(VD->getLocation()), Ty, true, Init,
3184 getOrCreateStaticDataMemberDeclarationOrNull(cast<VarDecl>(VD)));
3185 DeclCache.insert(std::make_pair(VD->getCanonicalDecl(), llvm::WeakVH(GV)));
David Blaikiebd483762013-05-20 04:58:53 +00003186}
3187
3188llvm::DIScope CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
3189 if (!LexicalBlockStack.empty())
3190 return llvm::DIScope(LexicalBlockStack.back());
3191 return getContextDescriptor(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00003192}
3193
David Blaikie9f88fe82013-04-22 06:13:21 +00003194void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
David Blaikiebd483762013-05-20 04:58:53 +00003195 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3196 return;
David Blaikie9f88fe82013-04-22 06:13:21 +00003197 DBuilder.createImportedModule(
David Blaikiebd483762013-05-20 04:58:53 +00003198 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
3199 getOrCreateNameSpace(UD.getNominatedNamespace()),
David Blaikie9f88fe82013-04-22 06:13:21 +00003200 getLineNumber(UD.getLocation()));
3201}
3202
David Blaikiebd483762013-05-20 04:58:53 +00003203void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
3204 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3205 return;
3206 assert(UD.shadow_size() &&
3207 "We shouldn't be codegening an invalid UsingDecl containing no decls");
3208 // Emitting one decl is sufficient - debuggers can detect that this is an
3209 // overloaded name & provide lookup for all the overloads.
3210 const UsingShadowDecl &USD = **UD.shadow_begin();
Eric Christopher1ecc5632013-06-07 22:54:39 +00003211 if (llvm::DIDescriptor Target =
3212 getDeclarationOrDefinition(USD.getUnderlyingDecl()))
David Blaikiebd483762013-05-20 04:58:53 +00003213 DBuilder.createImportedDeclaration(
3214 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
3215 getLineNumber(USD.getLocation()));
3216}
3217
David Blaikief121b932013-05-20 22:50:41 +00003218llvm::DIImportedEntity
3219CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
3220 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3221 return llvm::DIImportedEntity(0);
3222 llvm::WeakVH &VH = NamespaceAliasCache[&NA];
3223 if (VH)
3224 return llvm::DIImportedEntity(cast<llvm::MDNode>(VH));
3225 llvm::DIImportedEntity R(0);
3226 if (const NamespaceAliasDecl *Underlying =
3227 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
3228 // This could cache & dedup here rather than relying on metadata deduping.
3229 R = DBuilder.createImportedModule(
3230 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3231 EmitNamespaceAlias(*Underlying), getLineNumber(NA.getLocation()),
3232 NA.getName());
3233 else
3234 R = DBuilder.createImportedModule(
3235 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3236 getOrCreateNameSpace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
3237 getLineNumber(NA.getLocation()), NA.getName());
3238 VH = R;
3239 return R;
3240}
3241
Guy Benyei11169dd2012-12-18 14:30:41 +00003242/// getOrCreateNamesSpace - Return namespace descriptor for the given
3243/// namespace decl.
Eric Christopherb2a008c2013-05-16 00:45:12 +00003244llvm::DINameSpace
Guy Benyei11169dd2012-12-18 14:30:41 +00003245CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
David Blaikie9fdedec2013-08-16 22:52:07 +00003246 NSDecl = NSDecl->getCanonicalDecl();
Eric Christopherb2a008c2013-05-16 00:45:12 +00003247 llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
Guy Benyei11169dd2012-12-18 14:30:41 +00003248 NameSpaceCache.find(NSDecl);
3249 if (I != NameSpaceCache.end())
3250 return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
Eric Christopherb2a008c2013-05-16 00:45:12 +00003251
Guy Benyei11169dd2012-12-18 14:30:41 +00003252 unsigned LineNo = getLineNumber(NSDecl->getLocation());
3253 llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
Eric Christopherb2a008c2013-05-16 00:45:12 +00003254 llvm::DIDescriptor Context =
Guy Benyei11169dd2012-12-18 14:30:41 +00003255 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
3256 llvm::DINameSpace NS =
3257 DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
3258 NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
3259 return NS;
3260}
3261
3262void CGDebugInfo::finalize() {
3263 for (std::vector<std::pair<void *, llvm::WeakVH> >::const_iterator VI
3264 = ReplaceMap.begin(), VE = ReplaceMap.end(); VI != VE; ++VI) {
3265 llvm::DIType Ty, RepTy;
3266 // Verify that the debug info still exists.
3267 if (llvm::Value *V = VI->second)
3268 Ty = llvm::DIType(cast<llvm::MDNode>(V));
Eric Christopherb2a008c2013-05-16 00:45:12 +00003269
Guy Benyei11169dd2012-12-18 14:30:41 +00003270 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
3271 TypeCache.find(VI->first);
3272 if (it != TypeCache.end()) {
3273 // Verify that the debug info still exists.
3274 if (llvm::Value *V = it->second)
3275 RepTy = llvm::DIType(cast<llvm::MDNode>(V));
3276 }
Adrian Prantl73409ce2013-03-11 18:33:46 +00003277
Eric Christopherf8bc4d82013-07-18 00:52:50 +00003278 if (Ty && Ty.isForwardDecl() && RepTy)
Guy Benyei11169dd2012-12-18 14:30:41 +00003279 Ty.replaceAllUsesWith(RepTy);
Guy Benyei11169dd2012-12-18 14:30:41 +00003280 }
Adrian Prantl73409ce2013-03-11 18:33:46 +00003281
3282 // We keep our own list of retained types, because we need to look
3283 // up the final type in the type cache.
3284 for (std::vector<void *>::const_iterator RI = RetainedTypes.begin(),
3285 RE = RetainedTypes.end(); RI != RE; ++RI)
Manman Renf801f802013-08-29 20:48:48 +00003286 DBuilder.retainType(llvm::DIType(cast<llvm::MDNode>(TypeCache[*RI])));
Adrian Prantl73409ce2013-03-11 18:33:46 +00003287
Guy Benyei11169dd2012-12-18 14:30:41 +00003288 DBuilder.finalize();
3289}