blob: b6cf2f914601283f5e93129c70d2a5059603a971 [file] [log] [blame]
Guy Benyei7f92f2d2012-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 Blaikie9dfd2432013-05-10 21:53:14 +000016#include "CGCXXABI.h"
Guy Benyei7f92f2d2012-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 Carruth3b844ba2013-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 Benyei7f92f2d2012-12-18 14:30:41 +000038#include "llvm/Support/Dwarf.h"
39#include "llvm/Support/FileSystem.h"
40using namespace clang;
41using namespace clang::CodeGen;
42
43CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
Eric Christopher688cf5b2013-07-14 21:12:44 +000044 : CGM(CGM), DebugKind(CGM.getCodeGenOpts().getDebugInfo()),
45 DBuilder(CGM.getModule()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +000046 CreateCompileUnit();
47}
48
49CGDebugInfo::~CGDebugInfo() {
50 assert(LexicalBlockStack.empty() &&
51 "Region stack mismatch, stack not empty!");
52}
53
Adrian Prantled6bbe42013-07-18 00:28:02 +000054
55NoLocation::NoLocation(CodeGenFunction &CGF, CGBuilderTy &B)
56 : DI(CGF.getDebugInfo()), Builder(B) {
57 if (DI) {
58 SavedLoc = DI->getLocation();
59 DI->CurLoc = SourceLocation();
60 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
61 }
62}
63
64NoLocation::~NoLocation() {
65 if (DI) {
66 assert(Builder.getCurrentDebugLocation().isUnknown());
67 DI->CurLoc = SavedLoc;
68 }
69}
70
Adrian Prantlb061ce22013-07-18 01:36:04 +000071ArtificialLocation::ArtificialLocation(CodeGenFunction &CGF, CGBuilderTy &B)
Adrian Prantled6bbe42013-07-18 00:28:02 +000072 : DI(CGF.getDebugInfo()), Builder(B) {
73 if (DI) {
74 SavedLoc = DI->getLocation();
75 // Sync the Builder.
76 DI->EmitLocation(Builder, SavedLoc);
77 DI->CurLoc = SourceLocation();
78 // Construct a location that has a valid scope, but no line info.
Adrian Prantl0a103232013-07-18 00:47:12 +000079 llvm::DIDescriptor Scope = DI->LexicalBlockStack.empty() ?
80 llvm::DIDescriptor(DI->TheCU) :
81 llvm::DIDescriptor(DI->LexicalBlockStack.back());
Adrian Prantled6bbe42013-07-18 00:28:02 +000082 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(0, 0, Scope));
83 }
84}
85
Adrian Prantlb061ce22013-07-18 01:36:04 +000086ArtificialLocation::~ArtificialLocation() {
Adrian Prantled6bbe42013-07-18 00:28:02 +000087 if (DI) {
88 assert(Builder.getCurrentDebugLocation().getLine() == 0);
89 DI->CurLoc = SavedLoc;
90 }
91}
92
Guy Benyei7f92f2d2012-12-18 14:30:41 +000093void CGDebugInfo::setLocation(SourceLocation Loc) {
94 // If the new location isn't valid return.
Adrian Prantl5f4554f2013-07-18 00:27:56 +000095 if (Loc.isInvalid()) return;
Guy Benyei7f92f2d2012-12-18 14:30:41 +000096
97 CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc);
98
99 // If we've changed files in the middle of a lexical scope go ahead
100 // and create a new lexical scope with file node if it's different
101 // from the one in the scope.
102 if (LexicalBlockStack.empty()) return;
103
104 SourceManager &SM = CGM.getContext().getSourceManager();
105 PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
106 PresumedLoc PPLoc = SM.getPresumedLoc(PrevLoc);
107
108 if (PCLoc.isInvalid() || PPLoc.isInvalid() ||
109 !strcmp(PPLoc.getFilename(), PCLoc.getFilename()))
110 return;
111
112 llvm::MDNode *LB = LexicalBlockStack.back();
113 llvm::DIScope Scope = llvm::DIScope(LB);
114 if (Scope.isLexicalBlockFile()) {
115 llvm::DILexicalBlockFile LBF = llvm::DILexicalBlockFile(LB);
116 llvm::DIDescriptor D
117 = DBuilder.createLexicalBlockFile(LBF.getScope(),
118 getOrCreateFile(CurLoc));
119 llvm::MDNode *N = D;
120 LexicalBlockStack.pop_back();
121 LexicalBlockStack.push_back(N);
David Blaikiea6504852013-01-26 22:16:26 +0000122 } else if (Scope.isLexicalBlock() || Scope.isSubprogram()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000123 llvm::DIDescriptor D
124 = DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc));
125 llvm::MDNode *N = D;
126 LexicalBlockStack.pop_back();
127 LexicalBlockStack.push_back(N);
128 }
129}
130
131/// getContextDescriptor - Get context info for the decl.
David Blaikiebb000792013-04-19 06:56:38 +0000132llvm::DIScope CGDebugInfo::getContextDescriptor(const Decl *Context) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000133 if (!Context)
134 return TheCU;
135
136 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
137 I = RegionMap.find(Context);
138 if (I != RegionMap.end()) {
139 llvm::Value *V = I->second;
David Blaikiebb000792013-04-19 06:56:38 +0000140 return llvm::DIScope(dyn_cast_or_null<llvm::MDNode>(V));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000141 }
142
143 // Check namespace.
144 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
David Blaikiebb000792013-04-19 06:56:38 +0000145 return getOrCreateNameSpace(NSDecl);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000146
David Blaikiebb000792013-04-19 06:56:38 +0000147 if (const RecordDecl *RDecl = dyn_cast<RecordDecl>(Context))
148 if (!RDecl->isDependentType())
149 return getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000150 getOrCreateMainFile());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000151 return TheCU;
152}
153
154/// getFunctionName - Get function name for the given FunctionDecl. If the
155/// name is constructred on demand (e.g. C++ destructor) then the name
156/// is stored on the side.
157StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
158 assert (FD && "Invalid FunctionDecl!");
159 IdentifierInfo *FII = FD->getIdentifier();
160 FunctionTemplateSpecializationInfo *Info
161 = FD->getTemplateSpecializationInfo();
162 if (!Info && FII)
163 return FII->getName();
164
165 // Otherwise construct human readable name for debug info.
Benjamin Kramer5eada842013-02-22 15:46:01 +0000166 SmallString<128> NS;
167 llvm::raw_svector_ostream OS(NS);
168 FD->printName(OS);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000169
170 // Add any template specialization args.
171 if (Info) {
172 const TemplateArgumentList *TArgs = Info->TemplateArguments;
173 const TemplateArgument *Args = TArgs->data();
174 unsigned NumArgs = TArgs->size();
175 PrintingPolicy Policy(CGM.getLangOpts());
Benjamin Kramer5eada842013-02-22 15:46:01 +0000176 TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs,
177 Policy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000178 }
179
180 // Copy this name on the side and use its reference.
Benjamin Kramer5eada842013-02-22 15:46:01 +0000181 OS.flush();
182 char *StrPtr = DebugInfoNames.Allocate<char>(NS.size());
183 memcpy(StrPtr, NS.data(), NS.size());
184 return StringRef(StrPtr, NS.size());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000185}
186
187StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
188 SmallString<256> MethodName;
189 llvm::raw_svector_ostream OS(MethodName);
190 OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
191 const DeclContext *DC = OMD->getDeclContext();
Eric Christopher6537f082013-05-16 00:45:12 +0000192 if (const ObjCImplementationDecl *OID =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000193 dyn_cast<const ObjCImplementationDecl>(DC)) {
194 OS << OID->getName();
Eric Christopher6537f082013-05-16 00:45:12 +0000195 } else if (const ObjCInterfaceDecl *OID =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000196 dyn_cast<const ObjCInterfaceDecl>(DC)) {
197 OS << OID->getName();
Eric Christopher6537f082013-05-16 00:45:12 +0000198 } else if (const ObjCCategoryImplDecl *OCD =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000199 dyn_cast<const ObjCCategoryImplDecl>(DC)){
200 OS << ((const NamedDecl *)OCD)->getIdentifier()->getNameStart() << '(' <<
201 OCD->getIdentifier()->getNameStart() << ')';
Adrian Prantlb5092242013-05-17 23:58:45 +0000202 } else if (isa<ObjCProtocolDecl>(DC)) {
Adrian Prantl687ecae2013-05-17 23:49:10 +0000203 // We can extract the type of the class from the self pointer.
204 if (ImplicitParamDecl* SelfDecl = OMD->getSelfDecl()) {
205 QualType ClassTy =
206 cast<ObjCObjectPointerType>(SelfDecl->getType())->getPointeeType();
207 ClassTy.print(OS, PrintingPolicy(LangOptions()));
208 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000209 }
210 OS << ' ' << OMD->getSelector().getAsString() << ']';
211
212 char *StrPtr = DebugInfoNames.Allocate<char>(OS.tell());
213 memcpy(StrPtr, MethodName.begin(), OS.tell());
214 return StringRef(StrPtr, OS.tell());
215}
216
217/// getSelectorName - Return selector name. This is used for debugging
218/// info.
219StringRef CGDebugInfo::getSelectorName(Selector S) {
220 const std::string &SName = S.getAsString();
221 char *StrPtr = DebugInfoNames.Allocate<char>(SName.size());
222 memcpy(StrPtr, SName.data(), SName.size());
223 return StringRef(StrPtr, SName.size());
224}
225
226/// getClassName - Get class name including template argument list.
Eric Christopher6537f082013-05-16 00:45:12 +0000227StringRef
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000228CGDebugInfo::getClassName(const RecordDecl *RD) {
229 const ClassTemplateSpecializationDecl *Spec
230 = dyn_cast<ClassTemplateSpecializationDecl>(RD);
231 if (!Spec)
232 return RD->getName();
233
234 const TemplateArgument *Args;
235 unsigned NumArgs;
236 if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) {
237 const TemplateSpecializationType *TST =
238 cast<TemplateSpecializationType>(TAW->getType());
239 Args = TST->getArgs();
240 NumArgs = TST->getNumArgs();
241 } else {
242 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
243 Args = TemplateArgs.data();
244 NumArgs = TemplateArgs.size();
245 }
246 StringRef Name = RD->getIdentifier()->getName();
247 PrintingPolicy Policy(CGM.getLangOpts());
Benjamin Kramer5eada842013-02-22 15:46:01 +0000248 SmallString<128> TemplateArgList;
249 {
250 llvm::raw_svector_ostream OS(TemplateArgList);
251 TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs,
252 Policy);
253 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000254
255 // Copy this name on the side and use its reference.
256 size_t Length = Name.size() + TemplateArgList.size();
257 char *StrPtr = DebugInfoNames.Allocate<char>(Length);
258 memcpy(StrPtr, Name.data(), Name.size());
259 memcpy(StrPtr + Name.size(), TemplateArgList.data(), TemplateArgList.size());
260 return StringRef(StrPtr, Length);
261}
262
263/// getOrCreateFile - Get the file debug info descriptor for the input location.
264llvm::DIFile CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
265 if (!Loc.isValid())
266 // If Location is not valid then use main input file.
267 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
268
269 SourceManager &SM = CGM.getContext().getSourceManager();
270 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
271
272 if (PLoc.isInvalid() || StringRef(PLoc.getFilename()).empty())
273 // If the location is not valid then use main input file.
274 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
275
276 // Cache the results.
277 const char *fname = PLoc.getFilename();
278 llvm::DenseMap<const char *, llvm::WeakVH>::iterator it =
279 DIFileCache.find(fname);
280
281 if (it != DIFileCache.end()) {
282 // Verify that the information still exists.
283 if (llvm::Value *V = it->second)
284 return llvm::DIFile(cast<llvm::MDNode>(V));
285 }
286
287 llvm::DIFile F = DBuilder.createFile(PLoc.getFilename(), getCurrentDirname());
288
289 DIFileCache[fname] = F;
290 return F;
291}
292
293/// getOrCreateMainFile - Get the file info for main compile unit.
294llvm::DIFile CGDebugInfo::getOrCreateMainFile() {
295 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
296}
297
298/// getLineNumber - Get line number for the location. If location is invalid
299/// then use current location.
300unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
301 if (Loc.isInvalid() && CurLoc.isInvalid())
302 return 0;
303 SourceManager &SM = CGM.getContext().getSourceManager();
304 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
305 return PLoc.isValid()? PLoc.getLine() : 0;
306}
307
308/// getColumnNumber - Get column number for the location.
Adrian Prantl00df5ea2013-03-12 20:43:25 +0000309unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000310 // We may not want column information at all.
Adrian Prantl00df5ea2013-03-12 20:43:25 +0000311 if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000312 return 0;
313
314 // If the location is invalid then use the current column.
315 if (Loc.isInvalid() && CurLoc.isInvalid())
316 return 0;
317 SourceManager &SM = CGM.getContext().getSourceManager();
318 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
319 return PLoc.isValid()? PLoc.getColumn() : 0;
320}
321
322StringRef CGDebugInfo::getCurrentDirname() {
323 if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
324 return CGM.getCodeGenOpts().DebugCompilationDir;
325
326 if (!CWDName.empty())
327 return CWDName;
328 SmallString<256> CWD;
329 llvm::sys::fs::current_path(CWD);
330 char *CompDirnamePtr = DebugInfoNames.Allocate<char>(CWD.size());
331 memcpy(CompDirnamePtr, CWD.data(), CWD.size());
332 return CWDName = StringRef(CompDirnamePtr, CWD.size());
333}
334
335/// CreateCompileUnit - Create new compile unit.
336void CGDebugInfo::CreateCompileUnit() {
337
338 // Get absolute path name.
339 SourceManager &SM = CGM.getContext().getSourceManager();
340 std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
341 if (MainFileName.empty())
342 MainFileName = "<unknown>";
343
344 // The main file name provided via the "-main-file-name" option contains just
345 // the file name itself with no path information. This file name may have had
346 // a relative path, so we look into the actual file entry for the main
347 // file to determine the real absolute path for the file.
348 std::string MainFileDir;
349 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
350 MainFileDir = MainFile->getDir()->getName();
351 if (MainFileDir != ".")
352 MainFileName = MainFileDir + "/" + MainFileName;
353 }
354
355 // Save filename string.
356 char *FilenamePtr = DebugInfoNames.Allocate<char>(MainFileName.length());
357 memcpy(FilenamePtr, MainFileName.c_str(), MainFileName.length());
358 StringRef Filename(FilenamePtr, MainFileName.length());
Eric Christopherff971d72013-02-22 23:50:16 +0000359
360 // Save split dwarf file string.
361 std::string SplitDwarfFile = CGM.getCodeGenOpts().SplitDwarfFile;
362 char *SplitDwarfPtr = DebugInfoNames.Allocate<char>(SplitDwarfFile.length());
363 memcpy(SplitDwarfPtr, SplitDwarfFile.c_str(), SplitDwarfFile.length());
364 StringRef SplitDwarfFilename(SplitDwarfPtr, SplitDwarfFile.length());
Eric Christopher6537f082013-05-16 00:45:12 +0000365
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000366 unsigned LangTag;
367 const LangOptions &LO = CGM.getLangOpts();
368 if (LO.CPlusPlus) {
369 if (LO.ObjC1)
370 LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
371 else
372 LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
373 } else if (LO.ObjC1) {
374 LangTag = llvm::dwarf::DW_LANG_ObjC;
375 } else if (LO.C99) {
376 LangTag = llvm::dwarf::DW_LANG_C99;
377 } else {
378 LangTag = llvm::dwarf::DW_LANG_C89;
379 }
380
381 std::string Producer = getClangFullVersion();
382
383 // Figure out which version of the ObjC runtime we have.
384 unsigned RuntimeVers = 0;
385 if (LO.ObjC1)
386 RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
387
388 // Create new compile unit.
Eric Christopherbe5f1be2013-02-21 22:35:08 +0000389 DBuilder.createCompileUnit(LangTag, Filename, getCurrentDirname(),
390 Producer, LO.Optimize,
Eric Christopherff971d72013-02-22 23:50:16 +0000391 CGM.getCodeGenOpts().DwarfDebugFlags,
392 RuntimeVers, SplitDwarfFilename);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000393 // FIXME - Eliminate TheCU.
394 TheCU = llvm::DICompileUnit(DBuilder.getCU());
395}
396
397/// CreateType - Get the Basic type from the cache or create a new
398/// one if necessary.
399llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT) {
400 unsigned Encoding = 0;
401 StringRef BTName;
402 switch (BT->getKind()) {
403#define BUILTIN_TYPE(Id, SingletonId)
404#define PLACEHOLDER_TYPE(Id, SingletonId) \
405 case BuiltinType::Id:
406#include "clang/AST/BuiltinTypes.def"
407 case BuiltinType::Dependent:
408 llvm_unreachable("Unexpected builtin type");
409 case BuiltinType::NullPtr:
Peter Collingbourne24118f52013-06-27 22:51:01 +0000410 return DBuilder.createNullPtrType();
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000411 case BuiltinType::Void:
412 return llvm::DIType();
413 case BuiltinType::ObjCClass:
Eric Christopherb2d13922013-07-18 00:52:50 +0000414 if (ClassTy)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000415 return ClassTy;
416 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
417 "objc_class", TheCU,
418 getOrCreateMainFile(), 0);
419 return ClassTy;
420 case BuiltinType::ObjCId: {
421 // typedef struct objc_class *Class;
422 // typedef struct objc_object {
423 // Class isa;
424 // } *id;
425
Eric Christopherb2d13922013-07-18 00:52:50 +0000426 if (ObjTy)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000427 return ObjTy;
428
Eric Christopherb2d13922013-07-18 00:52:50 +0000429 if (!ClassTy)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000430 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
431 "objc_class", TheCU,
432 getOrCreateMainFile(), 0);
433
434 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
Eric Christopher6537f082013-05-16 00:45:12 +0000435
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000436 llvm::DIType ISATy = DBuilder.createPointerType(ClassTy, Size);
437
Eric Christopherf068c922013-04-02 22:59:11 +0000438 ObjTy =
David Blaikiec1d0af12013-02-25 01:07:08 +0000439 DBuilder.createStructType(TheCU, "objc_object", getOrCreateMainFile(),
440 0, 0, 0, 0, llvm::DIType(), llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000441
Eric Christopherf068c922013-04-02 22:59:11 +0000442 ObjTy.setTypeArray(DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
443 ObjTy, "isa", getOrCreateMainFile(), 0, Size, 0, 0, 0, ISATy)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000444 return ObjTy;
445 }
446 case BuiltinType::ObjCSel: {
Eric Christopherb2d13922013-07-18 00:52:50 +0000447 if (SelTy)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000448 return SelTy;
449 SelTy =
450 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
451 "objc_selector", TheCU, getOrCreateMainFile(),
452 0);
453 return SelTy;
454 }
Guy Benyeib13621d2012-12-18 14:38:23 +0000455
456 case BuiltinType::OCLImage1d:
457 return getOrCreateStructPtrType("opencl_image1d_t",
458 OCLImage1dDITy);
459 case BuiltinType::OCLImage1dArray:
Eric Christopher6537f082013-05-16 00:45:12 +0000460 return getOrCreateStructPtrType("opencl_image1d_array_t",
Guy Benyeib13621d2012-12-18 14:38:23 +0000461 OCLImage1dArrayDITy);
462 case BuiltinType::OCLImage1dBuffer:
463 return getOrCreateStructPtrType("opencl_image1d_buffer_t",
464 OCLImage1dBufferDITy);
465 case BuiltinType::OCLImage2d:
466 return getOrCreateStructPtrType("opencl_image2d_t",
467 OCLImage2dDITy);
468 case BuiltinType::OCLImage2dArray:
469 return getOrCreateStructPtrType("opencl_image2d_array_t",
470 OCLImage2dArrayDITy);
471 case BuiltinType::OCLImage3d:
472 return getOrCreateStructPtrType("opencl_image3d_t",
473 OCLImage3dDITy);
Guy Benyei21f18c42013-02-07 10:55:47 +0000474 case BuiltinType::OCLSampler:
475 return DBuilder.createBasicType("opencl_sampler_t",
476 CGM.getContext().getTypeSize(BT),
477 CGM.getContext().getTypeAlign(BT),
478 llvm::dwarf::DW_ATE_unsigned);
Guy Benyeie6b9d802013-01-20 12:31:11 +0000479 case BuiltinType::OCLEvent:
480 return getOrCreateStructPtrType("opencl_event_t",
481 OCLEventDITy);
Guy Benyeib13621d2012-12-18 14:38:23 +0000482
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000483 case BuiltinType::UChar:
484 case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
485 case BuiltinType::Char_S:
486 case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
487 case BuiltinType::Char16:
488 case BuiltinType::Char32: Encoding = llvm::dwarf::DW_ATE_UTF; break;
489 case BuiltinType::UShort:
490 case BuiltinType::UInt:
491 case BuiltinType::UInt128:
492 case BuiltinType::ULong:
493 case BuiltinType::WChar_U:
494 case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
495 case BuiltinType::Short:
496 case BuiltinType::Int:
497 case BuiltinType::Int128:
498 case BuiltinType::Long:
499 case BuiltinType::WChar_S:
500 case BuiltinType::LongLong: Encoding = llvm::dwarf::DW_ATE_signed; break;
501 case BuiltinType::Bool: Encoding = llvm::dwarf::DW_ATE_boolean; break;
502 case BuiltinType::Half:
503 case BuiltinType::Float:
504 case BuiltinType::LongDouble:
505 case BuiltinType::Double: Encoding = llvm::dwarf::DW_ATE_float; break;
506 }
507
508 switch (BT->getKind()) {
509 case BuiltinType::Long: BTName = "long int"; break;
510 case BuiltinType::LongLong: BTName = "long long int"; break;
511 case BuiltinType::ULong: BTName = "long unsigned int"; break;
512 case BuiltinType::ULongLong: BTName = "long long unsigned int"; break;
513 default:
514 BTName = BT->getName(CGM.getLangOpts());
515 break;
516 }
517 // Bit size, align and offset of the type.
518 uint64_t Size = CGM.getContext().getTypeSize(BT);
519 uint64_t Align = CGM.getContext().getTypeAlign(BT);
Eric Christopher6537f082013-05-16 00:45:12 +0000520 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000521 DBuilder.createBasicType(BTName, Size, Align, Encoding);
522 return DbgTy;
523}
524
525llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty) {
526 // Bit size, align and offset of the type.
527 unsigned Encoding = llvm::dwarf::DW_ATE_complex_float;
528 if (Ty->isComplexIntegerType())
529 Encoding = llvm::dwarf::DW_ATE_lo_user;
530
531 uint64_t Size = CGM.getContext().getTypeSize(Ty);
532 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
Eric Christopher6537f082013-05-16 00:45:12 +0000533 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000534 DBuilder.createBasicType("complex", Size, Align, Encoding);
535
536 return DbgTy;
537}
538
539/// CreateCVRType - Get the qualified type from the cache or create
540/// a new one if necessary.
Eric Christopher56b108a2013-06-07 22:54:39 +0000541llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit,
542 bool Declaration) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000543 QualifierCollector Qc;
544 const Type *T = Qc.strip(Ty);
545
546 // Ignore these qualifiers for now.
547 Qc.removeObjCGCAttr();
548 Qc.removeAddressSpace();
549 Qc.removeObjCLifetime();
550
551 // We will create one Derived type for one qualifier and recurse to handle any
552 // additional ones.
553 unsigned Tag;
554 if (Qc.hasConst()) {
555 Tag = llvm::dwarf::DW_TAG_const_type;
556 Qc.removeConst();
557 } else if (Qc.hasVolatile()) {
558 Tag = llvm::dwarf::DW_TAG_volatile_type;
559 Qc.removeVolatile();
560 } else if (Qc.hasRestrict()) {
561 Tag = llvm::dwarf::DW_TAG_restrict_type;
562 Qc.removeRestrict();
563 } else {
564 assert(Qc.empty() && "Unknown type qualifier for debug info");
565 return getOrCreateType(QualType(T, 0), Unit);
566 }
567
Eric Christopher56b108a2013-06-07 22:54:39 +0000568 llvm::DIType FromTy =
569 getOrCreateType(Qc.apply(CGM.getContext(), T), Unit, Declaration);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000570
571 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
572 // CVR derived types.
573 llvm::DIType DbgTy = DBuilder.createQualifiedType(Tag, FromTy);
Eric Christopher6537f082013-05-16 00:45:12 +0000574
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000575 return DbgTy;
576}
577
578llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
579 llvm::DIFile Unit) {
Fariborz Jahanian05f8ff12013-02-21 20:42:11 +0000580
581 // The frontend treats 'id' as a typedef to an ObjCObjectType,
582 // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
583 // debug info, we want to emit 'id' in both cases.
584 if (Ty->isObjCQualifiedIdType())
585 return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
586
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000587 llvm::DIType DbgTy =
Eric Christopher6537f082013-05-16 00:45:12 +0000588 CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000589 Ty->getPointeeType(), Unit);
590 return DbgTy;
591}
592
593llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
594 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +0000595 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000596 Ty->getPointeeType(), Unit);
597}
598
599// Creates a forward declaration for a RecordDecl in the given context.
600llvm::DIType CGDebugInfo::createRecordFwdDecl(const RecordDecl *RD,
601 llvm::DIDescriptor Ctx) {
602 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
603 unsigned Line = getLineNumber(RD->getLocation());
604 StringRef RDName = getClassName(RD);
605
606 unsigned Tag = 0;
607 if (RD->isStruct() || RD->isInterface())
608 Tag = llvm::dwarf::DW_TAG_structure_type;
609 else if (RD->isUnion())
610 Tag = llvm::dwarf::DW_TAG_union_type;
611 else {
612 assert(RD->isClass());
613 Tag = llvm::dwarf::DW_TAG_class_type;
614 }
615
616 // Create the type.
617 return DBuilder.createForwardDecl(Tag, RDName, Ctx, DefUnit, Line);
618}
619
620// Walk up the context chain and create forward decls for record decls,
621// and normal descriptors for namespaces.
622llvm::DIDescriptor CGDebugInfo::createContextChain(const Decl *Context) {
623 if (!Context)
624 return TheCU;
625
626 // See if we already have the parent.
627 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
628 I = RegionMap.find(Context);
629 if (I != RegionMap.end()) {
630 llvm::Value *V = I->second;
631 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
632 }
Eric Christopher6537f082013-05-16 00:45:12 +0000633
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000634 // Check namespace.
635 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
636 return llvm::DIDescriptor(getOrCreateNameSpace(NSDecl));
637
638 if (const RecordDecl *RD = dyn_cast<RecordDecl>(Context)) {
639 if (!RD->isDependentType()) {
Eric Christopherf0890c42013-05-16 00:52:20 +0000640 llvm::DIType Ty =
641 getOrCreateLimitedType(CGM.getContext().getTypeDeclType(RD),
642 getOrCreateMainFile());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000643 return llvm::DIDescriptor(Ty);
644 }
645 }
646 return TheCU;
647}
648
David Blaikieb0f77b02013-05-24 21:33:22 +0000649/// getOrCreateTypeDeclaration - Create Pointee type. If Pointee is a record
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000650/// then emit record's fwd if debug info size reduction is enabled.
David Blaikieb0f77b02013-05-24 21:33:22 +0000651llvm::DIType CGDebugInfo::getOrCreateTypeDeclaration(QualType PointeeTy,
652 llvm::DIFile Unit) {
David Blaikie9faebd22013-05-20 04:58:53 +0000653 if (DebugKind > CodeGenOptions::LimitedDebugInfo)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000654 return getOrCreateType(PointeeTy, Unit);
David Blaikie5f6e2f42013-06-05 05:32:23 +0000655 return getOrCreateType(PointeeTy, Unit, true);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000656}
657
658llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag,
Eric Christopher6537f082013-05-16 00:45:12 +0000659 const Type *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000660 QualType PointeeTy,
661 llvm::DIFile Unit) {
662 if (Tag == llvm::dwarf::DW_TAG_reference_type ||
663 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
David Blaikieb0f77b02013-05-24 21:33:22 +0000664 return DBuilder.createReferenceType(
665 Tag, getOrCreateTypeDeclaration(PointeeTy, Unit));
Fariborz Jahanian05f8ff12013-02-21 20:42:11 +0000666
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000667 // Bit size, align and offset of the type.
668 // Size is always the size of a pointer. We can't use getTypeSize here
669 // because that does not return the correct value for references.
670 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCall64aa4b32013-04-16 22:48:15 +0000671 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000672 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
673
David Blaikieb0f77b02013-05-24 21:33:22 +0000674 return DBuilder.createPointerType(getOrCreateTypeDeclaration(PointeeTy, Unit),
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000675 Size, Align);
676}
677
Eric Christopherf0890c42013-05-16 00:52:20 +0000678llvm::DIType CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
679 llvm::DIType &Cache) {
Eric Christopherb2d13922013-07-18 00:52:50 +0000680 if (Cache)
Guy Benyeib13621d2012-12-18 14:38:23 +0000681 return Cache;
David Blaikie1e97c1e2013-05-21 17:58:54 +0000682 Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
683 TheCU, getOrCreateMainFile(), 0);
684 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
685 Cache = DBuilder.createPointerType(Cache, Size);
686 return Cache;
Guy Benyeib13621d2012-12-18 14:38:23 +0000687}
688
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000689llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
690 llvm::DIFile Unit) {
Eric Christopherb2d13922013-07-18 00:52:50 +0000691 if (BlockLiteralGeneric)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000692 return BlockLiteralGeneric;
693
694 SmallVector<llvm::Value *, 8> EltTys;
695 llvm::DIType FieldTy;
696 QualType FType;
697 uint64_t FieldSize, FieldOffset;
698 unsigned FieldAlign;
699 llvm::DIArray Elements;
700 llvm::DIType EltTy, DescTy;
701
702 FieldOffset = 0;
703 FType = CGM.getContext().UnsignedLongTy;
704 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
705 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
706
707 Elements = DBuilder.getOrCreateArray(EltTys);
708 EltTys.clear();
709
710 unsigned Flags = llvm::DIDescriptor::FlagAppleBlock;
711 unsigned LineNo = getLineNumber(CurLoc);
712
713 EltTy = DBuilder.createStructType(Unit, "__block_descriptor",
714 Unit, LineNo, FieldOffset, 0,
David Blaikiec1d0af12013-02-25 01:07:08 +0000715 Flags, llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000716
717 // Bit size, align and offset of the type.
718 uint64_t Size = CGM.getContext().getTypeSize(Ty);
719
720 DescTy = DBuilder.createPointerType(EltTy, Size);
721
722 FieldOffset = 0;
723 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
724 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
725 FType = CGM.getContext().IntTy;
726 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
727 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
728 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
729 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
730
731 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
732 FieldTy = DescTy;
733 FieldSize = CGM.getContext().getTypeSize(Ty);
734 FieldAlign = CGM.getContext().getTypeAlign(Ty);
735 FieldTy = DBuilder.createMemberType(Unit, "__descriptor", Unit,
736 LineNo, FieldSize, FieldAlign,
737 FieldOffset, 0, FieldTy);
738 EltTys.push_back(FieldTy);
739
740 FieldOffset += FieldSize;
741 Elements = DBuilder.getOrCreateArray(EltTys);
742
743 EltTy = DBuilder.createStructType(Unit, "__block_literal_generic",
744 Unit, LineNo, FieldOffset, 0,
David Blaikiec1d0af12013-02-25 01:07:08 +0000745 Flags, llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000746
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000747 BlockLiteralGeneric = DBuilder.createPointerType(EltTy, Size);
748 return BlockLiteralGeneric;
749}
750
David Blaikie5f6e2f42013-06-05 05:32:23 +0000751llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty, llvm::DIFile Unit,
752 bool Declaration) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000753 // Typedefs are derived from some other type. If we have a typedef of a
754 // typedef, make sure to emit the whole chain.
David Blaikieb0f77b02013-05-24 21:33:22 +0000755 llvm::DIType Src =
David Blaikie5f6e2f42013-06-05 05:32:23 +0000756 getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit, Declaration);
Eric Christopherb2d13922013-07-18 00:52:50 +0000757 if (!Src)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000758 return llvm::DIType();
759 // We don't set size information, but do specify where the typedef was
760 // declared.
761 unsigned Line = getLineNumber(Ty->getDecl()->getLocation());
762 const TypedefNameDecl *TyDecl = Ty->getDecl();
Eric Christopher6537f082013-05-16 00:45:12 +0000763
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000764 llvm::DIDescriptor TypedefContext =
765 getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext()));
Eric Christopher6537f082013-05-16 00:45:12 +0000766
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000767 return
768 DBuilder.createTypedef(Src, TyDecl->getName(), Unit, Line, TypedefContext);
769}
770
771llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
772 llvm::DIFile Unit) {
773 SmallVector<llvm::Value *, 16> EltTys;
774
775 // Add the result type at least.
776 EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit));
777
778 // Set up remainder of arguments if there is a prototype.
779 // FIXME: IF NOT, HOW IS THIS REPRESENTED? llvm-gcc doesn't represent '...'!
780 if (isa<FunctionNoProtoType>(Ty))
781 EltTys.push_back(DBuilder.createUnspecifiedParameter());
782 else if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Ty)) {
783 for (unsigned i = 0, e = FPT->getNumArgs(); i != e; ++i)
784 EltTys.push_back(getOrCreateType(FPT->getArgType(i), Unit));
785 }
786
787 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
788 return DBuilder.createSubroutineType(Unit, EltTypeArray);
789}
790
791
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000792llvm::DIType CGDebugInfo::createFieldType(StringRef name,
793 QualType type,
794 uint64_t sizeInBitsOverride,
795 SourceLocation loc,
796 AccessSpecifier AS,
797 uint64_t offsetInBits,
798 llvm::DIFile tunit,
799 llvm::DIDescriptor scope) {
800 llvm::DIType debugType = getOrCreateType(type, tunit);
801
802 // Get the location for the field.
803 llvm::DIFile file = getOrCreateFile(loc);
804 unsigned line = getLineNumber(loc);
805
806 uint64_t sizeInBits = 0;
807 unsigned alignInBits = 0;
808 if (!type->isIncompleteArrayType()) {
809 llvm::tie(sizeInBits, alignInBits) = CGM.getContext().getTypeInfo(type);
810
811 if (sizeInBitsOverride)
812 sizeInBits = sizeInBitsOverride;
813 }
814
815 unsigned flags = 0;
816 if (AS == clang::AS_private)
817 flags |= llvm::DIDescriptor::FlagPrivate;
818 else if (AS == clang::AS_protected)
819 flags |= llvm::DIDescriptor::FlagProtected;
820
821 return DBuilder.createMemberType(scope, name, file, line, sizeInBits,
822 alignInBits, offsetInBits, flags, debugType);
823}
824
Eric Christopher0395de32013-01-16 01:22:32 +0000825/// CollectRecordLambdaFields - Helper for CollectRecordFields.
826void CGDebugInfo::
827CollectRecordLambdaFields(const CXXRecordDecl *CXXDecl,
828 SmallVectorImpl<llvm::Value *> &elements,
829 llvm::DIType RecordTy) {
830 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
831 // has the name and the location of the variable so we should iterate over
832 // both concurrently.
833 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
834 RecordDecl::field_iterator Field = CXXDecl->field_begin();
835 unsigned fieldno = 0;
836 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
837 E = CXXDecl->captures_end(); I != E; ++I, ++Field, ++fieldno) {
838 const LambdaExpr::Capture C = *I;
839 if (C.capturesVariable()) {
840 VarDecl *V = C.getCapturedVar();
841 llvm::DIFile VUnit = getOrCreateFile(C.getLocation());
842 StringRef VName = V->getName();
843 uint64_t SizeInBitsOverride = 0;
844 if (Field->isBitField()) {
845 SizeInBitsOverride = Field->getBitWidthValue(CGM.getContext());
846 assert(SizeInBitsOverride && "found named 0-width bitfield");
847 }
848 llvm::DIType fieldType
849 = createFieldType(VName, Field->getType(), SizeInBitsOverride,
850 C.getLocation(), Field->getAccess(),
851 layout.getFieldOffset(fieldno), VUnit, RecordTy);
852 elements.push_back(fieldType);
853 } else {
854 // TODO: Need to handle 'this' in some way by probably renaming the
855 // this of the lambda class and having a field member of 'this' or
856 // by using AT_object_pointer for the function and having that be
857 // used as 'this' for semantic references.
858 assert(C.capturesThis() && "Field that isn't captured and isn't this?");
859 FieldDecl *f = *Field;
860 llvm::DIFile VUnit = getOrCreateFile(f->getLocation());
861 QualType type = f->getType();
862 llvm::DIType fieldType
863 = createFieldType("this", type, 0, f->getLocation(), f->getAccess(),
864 layout.getFieldOffset(fieldno), VUnit, RecordTy);
865
866 elements.push_back(fieldType);
867 }
868 }
869}
870
871/// CollectRecordStaticField - Helper for CollectRecordFields.
872void CGDebugInfo::
873CollectRecordStaticField(const VarDecl *Var,
874 SmallVectorImpl<llvm::Value *> &elements,
875 llvm::DIType RecordTy) {
876 // Create the descriptor for the static variable, with or without
877 // constant initializers.
878 llvm::DIFile VUnit = getOrCreateFile(Var->getLocation());
879 llvm::DIType VTy = getOrCreateType(Var->getType(), VUnit);
880
881 // Do not describe enums as static members.
882 if (VTy.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
883 return;
884
885 unsigned LineNumber = getLineNumber(Var->getLocation());
886 StringRef VName = Var->getName();
David Blaikiea89701b2013-01-20 01:19:17 +0000887 llvm::Constant *C = NULL;
Eric Christopher0395de32013-01-16 01:22:32 +0000888 if (Var->getInit()) {
889 const APValue *Value = Var->evaluateValue();
David Blaikiea89701b2013-01-20 01:19:17 +0000890 if (Value) {
891 if (Value->isInt())
892 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
893 if (Value->isFloat())
894 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
895 }
Eric Christopher0395de32013-01-16 01:22:32 +0000896 }
897
898 unsigned Flags = 0;
899 AccessSpecifier Access = Var->getAccess();
900 if (Access == clang::AS_private)
901 Flags |= llvm::DIDescriptor::FlagPrivate;
902 else if (Access == clang::AS_protected)
903 Flags |= llvm::DIDescriptor::FlagProtected;
904
905 llvm::DIType GV = DBuilder.createStaticMemberType(RecordTy, VName, VUnit,
David Blaikiea89701b2013-01-20 01:19:17 +0000906 LineNumber, VTy, Flags, C);
Eric Christopher0395de32013-01-16 01:22:32 +0000907 elements.push_back(GV);
908 StaticDataMemberCache[Var->getCanonicalDecl()] = llvm::WeakVH(GV);
909}
910
911/// CollectRecordNormalField - Helper for CollectRecordFields.
912void CGDebugInfo::
913CollectRecordNormalField(const FieldDecl *field, uint64_t OffsetInBits,
914 llvm::DIFile tunit,
915 SmallVectorImpl<llvm::Value *> &elements,
916 llvm::DIType RecordTy) {
917 StringRef name = field->getName();
918 QualType type = field->getType();
919
920 // Ignore unnamed fields unless they're anonymous structs/unions.
921 if (name.empty() && !type->isRecordType())
922 return;
923
924 uint64_t SizeInBitsOverride = 0;
925 if (field->isBitField()) {
926 SizeInBitsOverride = field->getBitWidthValue(CGM.getContext());
927 assert(SizeInBitsOverride && "found named 0-width bitfield");
928 }
929
930 llvm::DIType fieldType
931 = createFieldType(name, type, SizeInBitsOverride,
932 field->getLocation(), field->getAccess(),
933 OffsetInBits, tunit, RecordTy);
934
935 elements.push_back(fieldType);
936}
937
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000938/// CollectRecordFields - A helper function to collect debug info for
939/// record fields. This is used while creating debug info entry for a Record.
940void CGDebugInfo::
941CollectRecordFields(const RecordDecl *record, llvm::DIFile tunit,
942 SmallVectorImpl<llvm::Value *> &elements,
943 llvm::DIType RecordTy) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000944 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(record);
945
Eric Christopher0395de32013-01-16 01:22:32 +0000946 if (CXXDecl && CXXDecl->isLambda())
947 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
948 else {
949 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000950
Eric Christopher0395de32013-01-16 01:22:32 +0000951 // Field number for non-static fields.
Eric Christopherfd5ac0d2013-01-04 17:59:07 +0000952 unsigned fieldNo = 0;
Eric Christopher0395de32013-01-16 01:22:32 +0000953
Eric Christopher0395de32013-01-16 01:22:32 +0000954 // Static and non-static members should appear in the same order as
955 // the corresponding declarations in the source program.
956 for (RecordDecl::decl_iterator I = record->decls_begin(),
957 E = record->decls_end(); I != E; ++I)
958 if (const VarDecl *V = dyn_cast<VarDecl>(*I))
959 CollectRecordStaticField(V, elements, RecordTy);
960 else if (FieldDecl *field = dyn_cast<FieldDecl>(*I)) {
Eric Christopher0395de32013-01-16 01:22:32 +0000961 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo),
962 tunit, elements, RecordTy);
963
964 // Bump field number for next field.
965 ++fieldNo;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000966 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000967 }
968}
969
970/// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
971/// function type is not updated to include implicit "this" pointer. Use this
972/// routine to get a method type which includes "this" pointer.
David Blaikie9a845292013-05-22 23:22:42 +0000973llvm::DICompositeType
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000974CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
975 llvm::DIFile Unit) {
David Blaikie9c78f9b2013-01-07 23:06:35 +0000976 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
David Blaikie67f8b5e2013-01-07 22:24:59 +0000977 if (Method->isStatic())
David Blaikie9a845292013-05-22 23:22:42 +0000978 return llvm::DICompositeType(getOrCreateType(QualType(Func, 0), Unit));
David Blaikie9c78f9b2013-01-07 23:06:35 +0000979 return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()),
980 Func, Unit);
981}
David Blaikie67f8b5e2013-01-07 22:24:59 +0000982
David Blaikie9a845292013-05-22 23:22:42 +0000983llvm::DICompositeType CGDebugInfo::getOrCreateInstanceMethodType(
David Blaikie9c78f9b2013-01-07 23:06:35 +0000984 QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile Unit) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000985 // Add "this" pointer.
David Blaikie9c78f9b2013-01-07 23:06:35 +0000986 llvm::DIArray Args = llvm::DICompositeType(
987 getOrCreateType(QualType(Func, 0), Unit)).getTypeArray();
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000988 assert (Args.getNumElements() && "Invalid number of arguments!");
989
990 SmallVector<llvm::Value *, 16> Elts;
991
992 // First element is always return type. For 'void' functions it is NULL.
993 Elts.push_back(Args.getElement(0));
994
David Blaikie67f8b5e2013-01-07 22:24:59 +0000995 // "this" pointer is always first argument.
David Blaikie9c78f9b2013-01-07 23:06:35 +0000996 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
David Blaikie67f8b5e2013-01-07 22:24:59 +0000997 if (isa<ClassTemplateSpecializationDecl>(RD)) {
998 // Create pointer type directly in this case.
999 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
1000 QualType PointeeTy = ThisPtrTy->getPointeeType();
1001 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCall64aa4b32013-04-16 22:48:15 +00001002 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
David Blaikie67f8b5e2013-01-07 22:24:59 +00001003 uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy);
1004 llvm::DIType PointeeType = getOrCreateType(PointeeTy, Unit);
Eric Christopherf0890c42013-05-16 00:52:20 +00001005 llvm::DIType ThisPtrType =
1006 DBuilder.createPointerType(PointeeType, Size, Align);
David Blaikie67f8b5e2013-01-07 22:24:59 +00001007 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
1008 // TODO: This and the artificial type below are misleading, the
1009 // types aren't artificial the argument is, but the current
1010 // metadata doesn't represent that.
1011 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1012 Elts.push_back(ThisPtrType);
1013 } else {
1014 llvm::DIType ThisPtrType = getOrCreateType(ThisPtr, Unit);
1015 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
1016 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1017 Elts.push_back(ThisPtrType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001018 }
1019
1020 // Copy rest of the arguments.
1021 for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
1022 Elts.push_back(Args.getElement(i));
1023
1024 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
1025
1026 return DBuilder.createSubroutineType(Unit, EltTypeArray);
1027}
1028
Eric Christopher6537f082013-05-16 00:45:12 +00001029/// isFunctionLocalClass - Return true if CXXRecordDecl is defined
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001030/// inside a function.
1031static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
1032 if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
1033 return isFunctionLocalClass(NRD);
1034 if (isa<FunctionDecl>(RD->getDeclContext()))
1035 return true;
1036 return false;
1037}
1038
1039/// CreateCXXMemberFunction - A helper function to create a DISubprogram for
1040/// a single member function GlobalDecl.
1041llvm::DISubprogram
1042CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
1043 llvm::DIFile Unit,
1044 llvm::DIType RecordTy) {
Eric Christopher6537f082013-05-16 00:45:12 +00001045 bool IsCtorOrDtor =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001046 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
Eric Christopher6537f082013-05-16 00:45:12 +00001047
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001048 StringRef MethodName = getFunctionName(Method);
David Blaikie9a845292013-05-22 23:22:42 +00001049 llvm::DICompositeType MethodTy = getOrCreateMethodType(Method, Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001050
1051 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1052 // make sense to give a single ctor/dtor a linkage name.
1053 StringRef MethodLinkageName;
1054 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1055 MethodLinkageName = CGM.getMangledName(Method);
1056
1057 // Get the location for the method.
1058 llvm::DIFile MethodDefUnit = getOrCreateFile(Method->getLocation());
1059 unsigned MethodLine = getLineNumber(Method->getLocation());
1060
1061 // Collect virtual method info.
1062 llvm::DIType ContainingType;
Eric Christopher6537f082013-05-16 00:45:12 +00001063 unsigned Virtuality = 0;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001064 unsigned VIndex = 0;
Eric Christopher6537f082013-05-16 00:45:12 +00001065
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001066 if (Method->isVirtual()) {
1067 if (Method->isPure())
1068 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
1069 else
1070 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
Eric Christopher6537f082013-05-16 00:45:12 +00001071
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001072 // It doesn't make sense to give a virtual destructor a vtable index,
1073 // since a single destructor has two entries in the vtable.
1074 if (!isa<CXXDestructorDecl>(Method))
1075 VIndex = CGM.getVTableContext().getMethodVTableIndex(Method);
1076 ContainingType = RecordTy;
1077 }
1078
1079 unsigned Flags = 0;
1080 if (Method->isImplicit())
1081 Flags |= llvm::DIDescriptor::FlagArtificial;
1082 AccessSpecifier Access = Method->getAccess();
1083 if (Access == clang::AS_private)
1084 Flags |= llvm::DIDescriptor::FlagPrivate;
1085 else if (Access == clang::AS_protected)
1086 Flags |= llvm::DIDescriptor::FlagProtected;
1087 if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1088 if (CXXC->isExplicit())
1089 Flags |= llvm::DIDescriptor::FlagExplicit;
Eric Christopher6537f082013-05-16 00:45:12 +00001090 } else if (const CXXConversionDecl *CXXC =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001091 dyn_cast<CXXConversionDecl>(Method)) {
1092 if (CXXC->isExplicit())
1093 Flags |= llvm::DIDescriptor::FlagExplicit;
1094 }
1095 if (Method->hasPrototype())
1096 Flags |= llvm::DIDescriptor::FlagPrototyped;
1097
1098 llvm::DIArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1099 llvm::DISubprogram SP =
Eric Christopher6537f082013-05-16 00:45:12 +00001100 DBuilder.createMethod(RecordTy, MethodName, MethodLinkageName,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001101 MethodDefUnit, MethodLine,
Eric Christopher6537f082013-05-16 00:45:12 +00001102 MethodTy, /*isLocalToUnit=*/false,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001103 /* isDefinition=*/ false,
1104 Virtuality, VIndex, ContainingType,
1105 Flags, CGM.getLangOpts().Optimize, NULL,
1106 TParamsArray);
Eric Christopher6537f082013-05-16 00:45:12 +00001107
Guy Benyei7f92f2d2012-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 Christopher6537f082013-05-16 00:45:12 +00001114/// C++ member functions. This is used while creating debug info entry for
Guy Benyei7f92f2d2012-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) {
1126 Decl *D = *I;
1127 if (D->isImplicit() && !D->isUsed())
1128 continue;
1129
1130 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1131 EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
1132 else if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
1133 for (FunctionTemplateDecl::spec_iterator SI = FTD->spec_begin(),
1134 SE = FTD->spec_end(); SI != SE; ++SI)
1135 EltTys.push_back(CreateCXXMemberFunction(cast<CXXMethodDecl>(*SI), Unit,
1136 RecordTy));
1137 }
Eric Christopher6537f082013-05-16 00:45:12 +00001138}
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001139
1140/// CollectCXXFriends - A helper function to collect debug info for
1141/// C++ base classes. This is used while creating debug info entry for
1142/// a Record.
1143void CGDebugInfo::
1144CollectCXXFriends(const CXXRecordDecl *RD, llvm::DIFile Unit,
1145 SmallVectorImpl<llvm::Value *> &EltTys,
1146 llvm::DIType RecordTy) {
1147 for (CXXRecordDecl::friend_iterator BI = RD->friend_begin(),
1148 BE = RD->friend_end(); BI != BE; ++BI) {
1149 if ((*BI)->isUnsupportedFriend())
1150 continue;
1151 if (TypeSourceInfo *TInfo = (*BI)->getFriendType())
Eric Christopher6537f082013-05-16 00:45:12 +00001152 EltTys.push_back(DBuilder.createFriend(RecordTy,
1153 getOrCreateType(TInfo->getType(),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001154 Unit)));
1155 }
1156}
1157
1158/// CollectCXXBases - A helper function to collect debug info for
Eric Christopher6537f082013-05-16 00:45:12 +00001159/// C++ base classes. This is used while creating debug info entry for
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001160/// a Record.
1161void CGDebugInfo::
1162CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
1163 SmallVectorImpl<llvm::Value *> &EltTys,
1164 llvm::DIType RecordTy) {
1165
1166 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1167 for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
1168 BE = RD->bases_end(); BI != BE; ++BI) {
1169 unsigned BFlags = 0;
1170 uint64_t BaseOffset;
Eric Christopher6537f082013-05-16 00:45:12 +00001171
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001172 const CXXRecordDecl *Base =
1173 cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl());
Eric Christopher6537f082013-05-16 00:45:12 +00001174
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001175 if (BI->isVirtual()) {
1176 // virtual base offset offset is -ve. The code generator emits dwarf
1177 // expression where it expects +ve number.
Eric Christopher6537f082013-05-16 00:45:12 +00001178 BaseOffset =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001179 0 - CGM.getVTableContext()
1180 .getVirtualBaseOffsetOffset(RD, Base).getQuantity();
1181 BFlags = llvm::DIDescriptor::FlagVirtual;
1182 } else
1183 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1184 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1185 // BI->isVirtual() and bits when not.
Eric Christopher6537f082013-05-16 00:45:12 +00001186
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001187 AccessSpecifier Access = BI->getAccessSpecifier();
1188 if (Access == clang::AS_private)
1189 BFlags |= llvm::DIDescriptor::FlagPrivate;
1190 else if (Access == clang::AS_protected)
1191 BFlags |= llvm::DIDescriptor::FlagProtected;
Eric Christopher6537f082013-05-16 00:45:12 +00001192
1193 llvm::DIType DTy =
1194 DBuilder.createInheritance(RecordTy,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001195 getOrCreateType(BI->getType(), Unit),
1196 BaseOffset, BFlags);
1197 EltTys.push_back(DTy);
1198 }
1199}
1200
1201/// CollectTemplateParams - A helper function to collect template parameters.
1202llvm::DIArray CGDebugInfo::
1203CollectTemplateParams(const TemplateParameterList *TPList,
David Blaikie35178dc2013-06-22 18:59:18 +00001204 ArrayRef<TemplateArgument> TAList,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001205 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +00001206 SmallVector<llvm::Value *, 16> TemplateParams;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001207 for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1208 const TemplateArgument &TA = TAList[i];
David Blaikie35178dc2013-06-22 18:59:18 +00001209 StringRef Name;
1210 if (TPList)
1211 Name = TPList->getParam(i)->getName();
David Blaikie9dfd2432013-05-10 21:53:14 +00001212 switch (TA.getKind()) {
1213 case TemplateArgument::Type: {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001214 llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit);
1215 llvm::DITemplateTypeParameter TTP =
David Blaikie35178dc2013-06-22 18:59:18 +00001216 DBuilder.createTemplateTypeParameter(TheCU, Name, TTy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001217 TemplateParams.push_back(TTP);
David Blaikie9dfd2432013-05-10 21:53:14 +00001218 } break;
1219 case TemplateArgument::Integral: {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001220 llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit);
1221 llvm::DITemplateValueParameter TVP =
David Blaikie9dfd2432013-05-10 21:53:14 +00001222 DBuilder.createTemplateValueParameter(
David Blaikie35178dc2013-06-22 18:59:18 +00001223 TheCU, Name, TTy,
David Blaikie9dfd2432013-05-10 21:53:14 +00001224 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral()));
1225 TemplateParams.push_back(TVP);
1226 } break;
1227 case TemplateArgument::Declaration: {
1228 const ValueDecl *D = TA.getAsDecl();
1229 bool InstanceMember = D->isCXXInstanceMember();
1230 QualType T = InstanceMember
1231 ? CGM.getContext().getMemberPointerType(
1232 D->getType(), cast<RecordDecl>(D->getDeclContext())
1233 ->getTypeForDecl())
1234 : CGM.getContext().getPointerType(D->getType());
1235 llvm::DIType TTy = getOrCreateType(T, Unit);
1236 llvm::Value *V = 0;
1237 // Variable pointer template parameters have a value that is the address
1238 // of the variable.
1239 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1240 V = CGM.GetAddrOfGlobalVar(VD);
1241 // Member function pointers have special support for building them, though
1242 // this is currently unsupported in LLVM CodeGen.
David Blaikief8aa1552013-05-13 06:57:50 +00001243 if (InstanceMember) {
David Blaikie9dfd2432013-05-10 21:53:14 +00001244 if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(D))
1245 V = CGM.getCXXABI().EmitMemberPointer(method);
David Blaikief8aa1552013-05-13 06:57:50 +00001246 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1247 V = CGM.GetAddrOfFunction(FD);
David Blaikie9dfd2432013-05-10 21:53:14 +00001248 // Member data pointers have special handling too to compute the fixed
1249 // offset within the object.
1250 if (isa<FieldDecl>(D)) {
1251 // These five lines (& possibly the above member function pointer
1252 // handling) might be able to be refactored to use similar code in
1253 // CodeGenModule::getMemberPointerConstant
1254 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
1255 CharUnits chars =
1256 CGM.getContext().toCharUnitsFromBits((int64_t) fieldOffset);
1257 V = CGM.getCXXABI().EmitMemberDataPointer(
1258 cast<MemberPointerType>(T.getTypePtr()), chars);
1259 }
1260 llvm::DITemplateValueParameter TVP =
David Blaikie35178dc2013-06-22 18:59:18 +00001261 DBuilder.createTemplateValueParameter(TheCU, Name, TTy, V);
David Blaikie9dfd2432013-05-10 21:53:14 +00001262 TemplateParams.push_back(TVP);
1263 } break;
1264 case TemplateArgument::NullPtr: {
1265 QualType T = TA.getNullPtrType();
1266 llvm::DIType TTy = getOrCreateType(T, Unit);
1267 llvm::Value *V = 0;
1268 // Special case member data pointer null values since they're actually -1
1269 // instead of zero.
1270 if (const MemberPointerType *MPT =
1271 dyn_cast<MemberPointerType>(T.getTypePtr()))
1272 // But treat member function pointers as simple zero integers because
1273 // it's easier than having a special case in LLVM's CodeGen. If LLVM
1274 // CodeGen grows handling for values of non-null member function
1275 // pointers then perhaps we could remove this special case and rely on
1276 // EmitNullMemberPointer for member function pointers.
1277 if (MPT->isMemberDataPointer())
1278 V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1279 if (!V)
1280 V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
1281 llvm::DITemplateValueParameter TVP =
David Blaikie35178dc2013-06-22 18:59:18 +00001282 DBuilder.createTemplateValueParameter(TheCU, Name, TTy, V);
David Blaikie9dfd2432013-05-10 21:53:14 +00001283 TemplateParams.push_back(TVP);
1284 } break;
David Blaikie35178dc2013-06-22 18:59:18 +00001285 case TemplateArgument::Template: {
1286 llvm::DITemplateValueParameter TVP =
1287 DBuilder.createTemplateTemplateParameter(
1288 TheCU, Name, llvm::DIType(),
1289 TA.getAsTemplate().getAsTemplateDecl()
1290 ->getQualifiedNameAsString());
1291 TemplateParams.push_back(TVP);
1292 } break;
1293 case TemplateArgument::Pack: {
1294 llvm::DITemplateValueParameter TVP =
1295 DBuilder.createTemplateParameterPack(
1296 TheCU, Name, llvm::DIType(),
1297 CollectTemplateParams(NULL, TA.getPackAsArray(), Unit));
1298 TemplateParams.push_back(TVP);
1299 } break;
David Blaikiee8065122013-05-10 23:36:06 +00001300 // And the following should never occur:
David Blaikie9dfd2432013-05-10 21:53:14 +00001301 case TemplateArgument::Expression:
1302 case TemplateArgument::TemplateExpansion:
David Blaikie9dfd2432013-05-10 21:53:14 +00001303 case TemplateArgument::Null:
1304 llvm_unreachable(
1305 "These argument types shouldn't exist in concrete types");
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001306 }
1307 }
1308 return DBuilder.getOrCreateArray(TemplateParams);
1309}
1310
1311/// CollectFunctionTemplateParams - A helper function to collect debug
1312/// info for function template parameters.
1313llvm::DIArray CGDebugInfo::
1314CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) {
1315 if (FD->getTemplatedKind() ==
1316 FunctionDecl::TK_FunctionTemplateSpecialization) {
1317 const TemplateParameterList *TList =
1318 FD->getTemplateSpecializationInfo()->getTemplate()
1319 ->getTemplateParameters();
David Blaikie35178dc2013-06-22 18:59:18 +00001320 return CollectTemplateParams(
1321 TList, FD->getTemplateSpecializationArgs()->asArray(), Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001322 }
1323 return llvm::DIArray();
1324}
1325
1326/// CollectCXXTemplateParams - A helper function to collect debug info for
1327/// template parameters.
1328llvm::DIArray CGDebugInfo::
1329CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial,
1330 llvm::DIFile Unit) {
1331 llvm::PointerUnion<ClassTemplateDecl *,
1332 ClassTemplatePartialSpecializationDecl *>
1333 PU = TSpecial->getSpecializedTemplateOrPartial();
Eric Christopher6537f082013-05-16 00:45:12 +00001334
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001335 TemplateParameterList *TPList = PU.is<ClassTemplateDecl *>() ?
1336 PU.get<ClassTemplateDecl *>()->getTemplateParameters() :
1337 PU.get<ClassTemplatePartialSpecializationDecl *>()->getTemplateParameters();
1338 const TemplateArgumentList &TAList = TSpecial->getTemplateInstantiationArgs();
David Blaikie35178dc2013-06-22 18:59:18 +00001339 return CollectTemplateParams(TPList, TAList.asArray(), Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001340}
1341
1342/// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
1343llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
1344 if (VTablePtrType.isValid())
1345 return VTablePtrType;
1346
1347 ASTContext &Context = CGM.getContext();
1348
1349 /* Function type */
1350 llvm::Value *STy = getOrCreateType(Context.IntTy, Unit);
1351 llvm::DIArray SElements = DBuilder.getOrCreateArray(STy);
1352 llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements);
1353 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1354 llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0,
1355 "__vtbl_ptr_type");
1356 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1357 return VTablePtrType;
1358}
1359
1360/// getVTableName - Get vtable name for the given Class.
1361StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
1362 // Construct gdb compatible name name.
1363 std::string Name = "_vptr$" + RD->getNameAsString();
1364
1365 // Copy this name on the side and use its reference.
1366 char *StrPtr = DebugInfoNames.Allocate<char>(Name.length());
1367 memcpy(StrPtr, Name.data(), Name.length());
1368 return StringRef(StrPtr, Name.length());
1369}
1370
1371
1372/// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
1373/// debug info entry in EltTys vector.
1374void CGDebugInfo::
1375CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
1376 SmallVectorImpl<llvm::Value *> &EltTys) {
1377 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1378
1379 // If there is a primary base then it will hold vtable info.
1380 if (RL.getPrimaryBase())
1381 return;
1382
1383 // If this class is not dynamic then there is not any vtable info to collect.
1384 if (!RD->isDynamicClass())
1385 return;
1386
1387 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1388 llvm::DIType VPTR
1389 = DBuilder.createMemberType(Unit, getVTableName(RD), Unit,
Eric Christopherf0890c42013-05-16 00:52:20 +00001390 0, Size, 0, 0,
1391 llvm::DIDescriptor::FlagArtificial,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001392 getOrCreateVTablePtrType(Unit));
1393 EltTys.push_back(VPTR);
1394}
1395
Eric Christopher6537f082013-05-16 00:45:12 +00001396/// getOrCreateRecordType - Emit record type's standalone debug info.
1397llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001398 SourceLocation Loc) {
Eric Christopher13c97672013-05-16 00:45:23 +00001399 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001400 llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc));
1401 return T;
1402}
1403
1404/// getOrCreateInterfaceType - Emit an objective c interface type standalone
1405/// debug info.
1406llvm::DIType CGDebugInfo::getOrCreateInterfaceType(QualType D,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001407 SourceLocation Loc) {
Eric Christopher13c97672013-05-16 00:45:23 +00001408 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001409 llvm::DIType T = getOrCreateType(D, getOrCreateFile(Loc));
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001410 RetainedTypes.push_back(D.getAsOpaquePtr());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001411 return T;
1412}
1413
1414/// CreateType - get structure or union type.
David Blaikie5f6e2f42013-06-05 05:32:23 +00001415llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty, bool Declaration) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001416 RecordDecl *RD = Ty->getDecl();
Adrian Prantl776bfa12013-06-18 23:32:21 +00001417 // Limited debug info should only remove struct definitions that can
1418 // safely be replaced by a forward declaration in the source code.
David Blaikie658cd2c2013-07-13 21:08:14 +00001419 if (DebugKind <= CodeGenOptions::LimitedDebugInfo && Declaration &&
1420 !RD->isCompleteDefinitionRequired()) {
Adrian Prantl776bfa12013-06-18 23:32:21 +00001421 // FIXME: This implementation is problematic; there are some test
1422 // cases where we violate the above principle, such as
1423 // test/CodeGen/debug-info-records.c .
David Blaikie5f6e2f42013-06-05 05:32:23 +00001424 llvm::DIDescriptor FDContext =
1425 getContextDescriptor(cast<Decl>(RD->getDeclContext()));
1426 llvm::DIType RetTy = createRecordFwdDecl(RD, FDContext);
1427 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RetTy;
1428 return RetTy;
1429 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001430
1431 // Get overall information about the record type for the debug info.
1432 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1433
1434 // Records and classes and unions can all be recursive. To handle them, we
1435 // first generate a debug descriptor for the struct as a forward declaration.
1436 // Then (if it is a definition) we go through and get debug info for all of
1437 // its members. Finally, we create a descriptor for the complete type (which
1438 // may refer to the forward decl if the struct is recursive) and replace all
1439 // uses of the forward declaration with the final definition.
1440
Eric Christopherf068c922013-04-02 22:59:11 +00001441 llvm::DICompositeType FwdDecl(
1442 getOrCreateLimitedType(QualType(Ty, 0), DefUnit));
Manman Renb6b0a712013-07-02 19:01:53 +00001443 assert(FwdDecl.isCompositeType() &&
David Blaikie9a845292013-05-22 23:22:42 +00001444 "The debug type of a RecordType should be a llvm::DICompositeType");
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001445
1446 if (FwdDecl.isForwardDecl())
1447 return FwdDecl;
1448
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001449 // Push the struct on region stack.
Eric Christopherf068c922013-04-02 22:59:11 +00001450 LexicalBlockStack.push_back(&*FwdDecl);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001451 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1452
Adrian Prantl4919de62013-03-06 22:03:30 +00001453 // Add this to the completed-type cache while we're completing it recursively.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001454 CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1455
1456 // Convert all the elements.
1457 SmallVector<llvm::Value *, 16> EltTys;
1458
1459 // Note: The split of CXXDecl information here is intentional, the
1460 // gdb tests will depend on a certain ordering at printout. The debug
1461 // information offsets are still correct if we merge them all together
1462 // though.
1463 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1464 if (CXXDecl) {
1465 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1466 CollectVTableInfo(CXXDecl, DefUnit, EltTys);
1467 }
1468
Eric Christopher0395de32013-01-16 01:22:32 +00001469 // Collect data fields (including static variables and any initializers).
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001470 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
1471 llvm::DIArray TParamsArray;
1472 if (CXXDecl) {
1473 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
1474 CollectCXXFriends(CXXDecl, DefUnit, EltTys, FwdDecl);
1475 if (const ClassTemplateSpecializationDecl *TSpecial
1476 = dyn_cast<ClassTemplateSpecializationDecl>(RD))
1477 TParamsArray = CollectCXXTemplateParams(TSpecial, DefUnit);
1478 }
1479
1480 LexicalBlockStack.pop_back();
1481 RegionMap.erase(Ty->getDecl());
1482
1483 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopherf068c922013-04-02 22:59:11 +00001484 FwdDecl.setTypeArray(Elements, TParamsArray);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001485
Eric Christopherf068c922013-04-02 22:59:11 +00001486 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1487 return FwdDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001488}
1489
1490/// CreateType - get objective-c object type.
1491llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1492 llvm::DIFile Unit) {
1493 // Ignore protocols.
1494 return getOrCreateType(Ty->getBaseType(), Unit);
1495}
1496
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001497
1498/// \return true if Getter has the default name for the property PD.
1499static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
1500 const ObjCMethodDecl *Getter) {
1501 assert(PD);
1502 if (!Getter)
1503 return true;
1504
1505 assert(Getter->getDeclName().isObjCZeroArgSelector());
1506 return PD->getName() ==
1507 Getter->getDeclName().getObjCSelector().getNameForSlot(0);
1508}
1509
1510/// \return true if Setter has the default name for the property PD.
1511static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
1512 const ObjCMethodDecl *Setter) {
1513 assert(PD);
1514 if (!Setter)
1515 return true;
1516
1517 assert(Setter->getDeclName().isObjCOneArgSelector());
Adrian Prantl80e8ea92013-06-07 22:29:12 +00001518 return SelectorTable::constructSetterName(PD->getName()) ==
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001519 Setter->getDeclName().getObjCSelector().getNameForSlot(0);
1520}
1521
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001522/// CreateType - get objective-c interface type.
1523llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1524 llvm::DIFile Unit) {
1525 ObjCInterfaceDecl *ID = Ty->getDecl();
1526 if (!ID)
1527 return llvm::DIType();
1528
1529 // Get overall information about the record type for the debug info.
1530 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1531 unsigned Line = getLineNumber(ID->getLocation());
1532 unsigned RuntimeLang = TheCU.getLanguage();
1533
1534 // If this is just a forward declaration return a special forward-declaration
1535 // debug type since we won't be able to lay out the entire type.
1536 ObjCInterfaceDecl *Def = ID->getDefinition();
1537 if (!Def) {
1538 llvm::DIType FwdDecl =
1539 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001540 ID->getName(), TheCU, DefUnit, Line,
1541 RuntimeLang);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001542 return FwdDecl;
1543 }
1544
1545 ID = Def;
1546
1547 // Bit size, align and offset of the type.
1548 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1549 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1550
1551 unsigned Flags = 0;
1552 if (ID->getImplementation())
1553 Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
1554
Eric Christopherf068c922013-04-02 22:59:11 +00001555 llvm::DICompositeType RealDecl =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001556 DBuilder.createStructType(Unit, ID->getName(), DefUnit,
1557 Line, Size, Align, Flags,
David Blaikiec1d0af12013-02-25 01:07:08 +00001558 llvm::DIType(), llvm::DIArray(), RuntimeLang);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001559
1560 // Otherwise, insert it into the CompletedTypeCache so that recursive uses
1561 // will find it and we're emitting the complete type.
Adrian Prantl4919de62013-03-06 22:03:30 +00001562 QualType QualTy = QualType(Ty, 0);
1563 CompletedTypeCache[QualTy.getAsOpaquePtr()] = RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001564
Eric Christopherd3003dc2013-07-14 21:00:07 +00001565 // Push the struct on region stack.
Eric Christopherf068c922013-04-02 22:59:11 +00001566 LexicalBlockStack.push_back(static_cast<llvm::MDNode*>(RealDecl));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001567 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1568
1569 // Convert all the elements.
1570 SmallVector<llvm::Value *, 16> EltTys;
1571
1572 ObjCInterfaceDecl *SClass = ID->getSuperClass();
1573 if (SClass) {
1574 llvm::DIType SClassTy =
1575 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1576 if (!SClassTy.isValid())
1577 return llvm::DIType();
Eric Christopher6537f082013-05-16 00:45:12 +00001578
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001579 llvm::DIType InhTag =
1580 DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
1581 EltTys.push_back(InhTag);
1582 }
1583
Eric Christopherd3003dc2013-07-14 21:00:07 +00001584 // Create entries for all of the properties.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001585 for (ObjCContainerDecl::prop_iterator I = ID->prop_begin(),
1586 E = ID->prop_end(); I != E; ++I) {
1587 const ObjCPropertyDecl *PD = *I;
1588 SourceLocation Loc = PD->getLocation();
1589 llvm::DIFile PUnit = getOrCreateFile(Loc);
1590 unsigned PLine = getLineNumber(Loc);
1591 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1592 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1593 llvm::MDNode *PropertyNode =
1594 DBuilder.createObjCProperty(PD->getName(),
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001595 PUnit, PLine,
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001596 hasDefaultGetterName(PD, Getter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001597 getSelectorName(PD->getGetterName()),
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001598 hasDefaultSetterName(PD, Setter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001599 getSelectorName(PD->getSetterName()),
1600 PD->getPropertyAttributes(),
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001601 getOrCreateType(PD->getType(), PUnit));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001602 EltTys.push_back(PropertyNode);
1603 }
1604
1605 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1606 unsigned FieldNo = 0;
1607 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1608 Field = Field->getNextIvar(), ++FieldNo) {
1609 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1610 if (!FieldTy.isValid())
1611 return llvm::DIType();
Eric Christopher6537f082013-05-16 00:45:12 +00001612
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001613 StringRef FieldName = Field->getName();
1614
1615 // Ignore unnamed fields.
1616 if (FieldName.empty())
1617 continue;
1618
1619 // Get the location for the field.
1620 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1621 unsigned FieldLine = getLineNumber(Field->getLocation());
1622 QualType FType = Field->getType();
1623 uint64_t FieldSize = 0;
1624 unsigned FieldAlign = 0;
1625
1626 if (!FType->isIncompleteArrayType()) {
1627
1628 // Bit size, align and offset of the type.
1629 FieldSize = Field->isBitField()
Eric Christopherd3003dc2013-07-14 21:00:07 +00001630 ? Field->getBitWidthValue(CGM.getContext())
1631 : CGM.getContext().getTypeSize(FType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001632 FieldAlign = CGM.getContext().getTypeAlign(FType);
1633 }
1634
1635 uint64_t FieldOffset;
1636 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1637 // We don't know the runtime offset of an ivar if we're using the
1638 // non-fragile ABI. For bitfields, use the bit offset into the first
1639 // byte of storage of the bitfield. For other fields, use zero.
1640 if (Field->isBitField()) {
1641 FieldOffset = CGM.getObjCRuntime().ComputeBitfieldBitOffset(
1642 CGM, ID, Field);
1643 FieldOffset %= CGM.getContext().getCharWidth();
1644 } else {
1645 FieldOffset = 0;
1646 }
1647 } else {
1648 FieldOffset = RL.getFieldOffset(FieldNo);
1649 }
1650
1651 unsigned Flags = 0;
1652 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1653 Flags = llvm::DIDescriptor::FlagProtected;
1654 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1655 Flags = llvm::DIDescriptor::FlagPrivate;
1656
1657 llvm::MDNode *PropertyNode = NULL;
1658 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
Eric Christopher6537f082013-05-16 00:45:12 +00001659 if (ObjCPropertyImplDecl *PImpD =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001660 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
1661 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001662 SourceLocation Loc = PD->getLocation();
1663 llvm::DIFile PUnit = getOrCreateFile(Loc);
1664 unsigned PLine = getLineNumber(Loc);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001665 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1666 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1667 PropertyNode =
1668 DBuilder.createObjCProperty(PD->getName(),
1669 PUnit, PLine,
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001670 hasDefaultGetterName(PD, Getter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001671 getSelectorName(PD->getGetterName()),
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001672 hasDefaultSetterName(PD, Setter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001673 getSelectorName(PD->getSetterName()),
1674 PD->getPropertyAttributes(),
1675 getOrCreateType(PD->getType(), PUnit));
1676 }
1677 }
1678 }
1679 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
1680 FieldLine, FieldSize, FieldAlign,
1681 FieldOffset, Flags, FieldTy,
1682 PropertyNode);
1683 EltTys.push_back(FieldTy);
1684 }
1685
1686 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopherf068c922013-04-02 22:59:11 +00001687 RealDecl.setTypeArray(Elements);
Adrian Prantl4919de62013-03-06 22:03:30 +00001688
1689 // If the implementation is not yet set, we do not want to mark it
1690 // as complete. An implementation may declare additional
1691 // private ivars that we would miss otherwise.
1692 if (ID->getImplementation() == 0)
1693 CompletedTypeCache.erase(QualTy.getAsOpaquePtr());
Eric Christopher6537f082013-05-16 00:45:12 +00001694
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001695 LexicalBlockStack.pop_back();
Eric Christopherf068c922013-04-02 22:59:11 +00001696 return RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001697}
1698
1699llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) {
1700 llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1701 int64_t Count = Ty->getNumElements();
1702 if (Count == 0)
1703 // If number of elements are not known then this is an unbounded array.
1704 // Use Count == -1 to express such arrays.
1705 Count = -1;
1706
1707 llvm::Value *Subscript = DBuilder.getOrCreateSubrange(0, Count);
1708 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1709
1710 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1711 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1712
1713 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1714}
1715
1716llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1717 llvm::DIFile Unit) {
1718 uint64_t Size;
1719 uint64_t Align;
1720
1721 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1722 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1723 Size = 0;
1724 Align =
1725 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1726 } else if (Ty->isIncompleteArrayType()) {
1727 Size = 0;
1728 if (Ty->getElementType()->isIncompleteType())
1729 Align = 0;
1730 else
1731 Align = CGM.getContext().getTypeAlign(Ty->getElementType());
David Blaikie089db2e2013-05-09 20:48:12 +00001732 } else if (Ty->isIncompleteType()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001733 Size = 0;
1734 Align = 0;
1735 } else {
1736 // Size and align of the whole array, not the element type.
1737 Size = CGM.getContext().getTypeSize(Ty);
1738 Align = CGM.getContext().getTypeAlign(Ty);
1739 }
1740
1741 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
1742 // interior arrays, do we care? Why aren't nested arrays represented the
1743 // obvious/recursive way?
1744 SmallVector<llvm::Value *, 8> Subscripts;
1745 QualType EltTy(Ty, 0);
1746 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1747 // If the number of elements is known, then count is that number. Otherwise,
1748 // it's -1. This allows us to represent a subrange with an array of 0
1749 // elements, like this:
1750 //
1751 // struct foo {
1752 // int x[0];
1753 // };
1754 int64_t Count = -1; // Count == -1 is an unbounded array.
1755 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1756 Count = CAT->getSize().getZExtValue();
Eric Christopher6537f082013-05-16 00:45:12 +00001757
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001758 // FIXME: Verify this is right for VLAs.
1759 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
1760 EltTy = Ty->getElementType();
1761 }
1762
1763 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1764
Eric Christopher6537f082013-05-16 00:45:12 +00001765 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001766 DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1767 SubscriptArray);
1768 return DbgTy;
1769}
1770
Eric Christopher6537f082013-05-16 00:45:12 +00001771llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001772 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +00001773 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001774 Ty, Ty->getPointeeType(), Unit);
1775}
1776
Eric Christopher6537f082013-05-16 00:45:12 +00001777llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001778 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +00001779 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001780 Ty, Ty->getPointeeType(), Unit);
1781}
1782
Eric Christopher6537f082013-05-16 00:45:12 +00001783llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001784 llvm::DIFile U) {
David Blaikiee8d75142013-01-19 19:20:56 +00001785 llvm::DIType ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
1786 if (!Ty->getPointeeType()->isFunctionType())
1787 return DBuilder.createMemberPointerType(
David Blaikieb0f77b02013-05-24 21:33:22 +00001788 getOrCreateTypeDeclaration(Ty->getPointeeType(), U), ClassType);
David Blaikiee8d75142013-01-19 19:20:56 +00001789 return DBuilder.createMemberPointerType(getOrCreateInstanceMethodType(
1790 CGM.getContext().getPointerType(
1791 QualType(Ty->getClass(), Ty->getPointeeType().getCVRQualifiers())),
1792 Ty->getPointeeType()->getAs<FunctionProtoType>(), U),
1793 ClassType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001794}
1795
Eric Christopher6537f082013-05-16 00:45:12 +00001796llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001797 llvm::DIFile U) {
1798 // Ignore the atomic wrapping
1799 // FIXME: What is the correct representation?
1800 return getOrCreateType(Ty->getValueType(), U);
1801}
1802
1803/// CreateEnumType - get enumeration type.
1804llvm::DIType CGDebugInfo::CreateEnumType(const EnumDecl *ED) {
1805 uint64_t Size = 0;
1806 uint64_t Align = 0;
1807 if (!ED->getTypeForDecl()->isIncompleteType()) {
1808 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1809 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1810 }
1811
1812 // If this is just a forward declaration, construct an appropriately
1813 // marked node and just return it.
1814 if (!ED->getDefinition()) {
1815 llvm::DIDescriptor EDContext;
1816 EDContext = getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1817 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1818 unsigned Line = getLineNumber(ED->getLocation());
1819 StringRef EDName = ED->getName();
1820 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_enumeration_type,
1821 EDName, EDContext, DefUnit, Line, 0,
1822 Size, Align);
1823 }
1824
1825 // Create DIEnumerator elements for each enumerator.
1826 SmallVector<llvm::Value *, 16> Enumerators;
1827 ED = ED->getDefinition();
1828 for (EnumDecl::enumerator_iterator
1829 Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
1830 Enum != EnumEnd; ++Enum) {
1831 Enumerators.push_back(
1832 DBuilder.createEnumerator(Enum->getName(),
David Blaikieac8f43c2013-06-24 07:13:13 +00001833 Enum->getInitVal().getSExtValue()));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001834 }
1835
1836 // Return a CompositeType for the enum itself.
1837 llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1838
1839 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1840 unsigned Line = getLineNumber(ED->getLocation());
Eric Christopher6537f082013-05-16 00:45:12 +00001841 llvm::DIDescriptor EnumContext =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001842 getContextDescriptor(cast<Decl>(ED->getDeclContext()));
Adrian Prantl59d6a712013-04-19 19:56:39 +00001843 llvm::DIType ClassTy = ED->isFixed() ?
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001844 getOrCreateType(ED->getIntegerType(), DefUnit) : llvm::DIType();
Eric Christopher6537f082013-05-16 00:45:12 +00001845 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001846 DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1847 Size, Align, EltArray,
1848 ClassTy);
1849 return DbgTy;
1850}
1851
David Blaikie4b12be62013-01-21 04:37:12 +00001852static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
1853 Qualifiers Quals;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001854 do {
David Blaikie4b12be62013-01-21 04:37:12 +00001855 Quals += T.getLocalQualifiers();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001856 QualType LastT = T;
1857 switch (T->getTypeClass()) {
1858 default:
David Blaikie4b12be62013-01-21 04:37:12 +00001859 return C.getQualifiedType(T.getTypePtr(), Quals);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001860 case Type::TemplateSpecialization:
1861 T = cast<TemplateSpecializationType>(T)->desugar();
1862 break;
1863 case Type::TypeOfExpr:
1864 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1865 break;
1866 case Type::TypeOf:
1867 T = cast<TypeOfType>(T)->getUnderlyingType();
1868 break;
1869 case Type::Decltype:
1870 T = cast<DecltypeType>(T)->getUnderlyingType();
1871 break;
1872 case Type::UnaryTransform:
1873 T = cast<UnaryTransformType>(T)->getUnderlyingType();
1874 break;
1875 case Type::Attributed:
1876 T = cast<AttributedType>(T)->getEquivalentType();
1877 break;
1878 case Type::Elaborated:
1879 T = cast<ElaboratedType>(T)->getNamedType();
1880 break;
1881 case Type::Paren:
1882 T = cast<ParenType>(T)->getInnerType();
1883 break;
David Blaikie4b12be62013-01-21 04:37:12 +00001884 case Type::SubstTemplateTypeParm:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001885 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001886 break;
1887 case Type::Auto:
David Blaikie91296482013-05-24 21:24:35 +00001888 QualType DT = cast<AutoType>(T)->getDeducedType();
1889 if (DT.isNull())
1890 return T;
1891 T = DT;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001892 break;
1893 }
Eric Christopher6537f082013-05-16 00:45:12 +00001894
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001895 assert(T != LastT && "Type unwrapping failed to unwrap!");
NAKAMURA Takumid24c9ab2013-01-21 10:51:28 +00001896 (void)LastT;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001897 } while (true);
1898}
1899
Eric Christopherf0890c42013-05-16 00:52:20 +00001900/// getType - Get the type from the cache or return null type if it doesn't
1901/// exist.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001902llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) {
1903
1904 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00001905 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Eric Christopher6537f082013-05-16 00:45:12 +00001906
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001907 // Check for existing entry.
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001908 if (Ty->getTypeClass() == Type::ObjCInterface) {
1909 llvm::Value *V = getCachedInterfaceTypeOrNull(Ty);
1910 if (V)
1911 return llvm::DIType(cast<llvm::MDNode>(V));
1912 else return llvm::DIType();
1913 }
1914
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001915 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1916 TypeCache.find(Ty.getAsOpaquePtr());
1917 if (it != TypeCache.end()) {
1918 // Verify that the debug info still exists.
1919 if (llvm::Value *V = it->second)
1920 return llvm::DIType(cast<llvm::MDNode>(V));
1921 }
1922
1923 return llvm::DIType();
1924}
1925
1926/// getCompletedTypeOrNull - Get the type from the cache or return null if it
1927/// doesn't exist.
1928llvm::DIType CGDebugInfo::getCompletedTypeOrNull(QualType Ty) {
1929
1930 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00001931 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001932
1933 // Check for existing entry.
Adrian Prantl4919de62013-03-06 22:03:30 +00001934 llvm::Value *V = 0;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001935 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1936 CompletedTypeCache.find(Ty.getAsOpaquePtr());
Adrian Prantl4919de62013-03-06 22:03:30 +00001937 if (it != CompletedTypeCache.end())
1938 V = it->second;
1939 else {
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001940 V = getCachedInterfaceTypeOrNull(Ty);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001941 }
1942
Adrian Prantl4919de62013-03-06 22:03:30 +00001943 // Verify that any cached debug info still exists.
David Blaikieeab6a362013-06-21 00:40:50 +00001944 if (V != 0)
1945 return llvm::DIType(cast<llvm::MDNode>(V));
Adrian Prantl4919de62013-03-06 22:03:30 +00001946
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001947 return llvm::DIType();
1948}
1949
David Blaikieeab6a362013-06-21 00:40:50 +00001950void CGDebugInfo::completeFwdDecl(const RecordDecl &RD) {
1951 // In limited debug info we only want to do this if the complete type was
1952 // required.
1953 if (DebugKind <= CodeGenOptions::LimitedDebugInfo)
1954 return;
1955
David Blaikie076f51f2013-06-21 00:59:44 +00001956 QualType QTy = CGM.getContext().getRecordType(&RD);
1957 llvm::DIType T = getTypeOrNull(QTy);
David Blaikieeab6a362013-06-21 00:40:50 +00001958
Eric Christopherb2d13922013-07-18 00:52:50 +00001959 if (T && T.isForwardDecl())
David Blaikie076f51f2013-06-21 00:59:44 +00001960 getOrCreateType(QTy, getOrCreateFile(RD.getLocation()));
David Blaikieeab6a362013-06-21 00:40:50 +00001961}
1962
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001963/// getCachedInterfaceTypeOrNull - Get the type from the interface
1964/// cache, unless it needs to regenerated. Otherwise return null.
1965llvm::Value *CGDebugInfo::getCachedInterfaceTypeOrNull(QualType Ty) {
1966 // Is there a cached interface that hasn't changed?
1967 llvm::DenseMap<void *, std::pair<llvm::WeakVH, unsigned > >
1968 ::iterator it1 = ObjCInterfaceCache.find(Ty.getAsOpaquePtr());
1969
1970 if (it1 != ObjCInterfaceCache.end())
1971 if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty))
1972 if (Checksum(Decl) == it1->second.second)
1973 // Return cached forward declaration.
1974 return it1->second.first;
1975
1976 return 0;
1977}
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001978
1979/// getOrCreateType - Get the type from the cache or create a new
1980/// one if necessary.
Eric Christopher56b108a2013-06-07 22:54:39 +00001981llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit,
1982 bool Declaration) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001983 if (Ty.isNull())
1984 return llvm::DIType();
1985
1986 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00001987 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001988
1989 llvm::DIType T = getCompletedTypeOrNull(Ty);
1990
Eric Christopherb2d13922013-07-18 00:52:50 +00001991 if (T) {
David Blaikief0c31d92013-06-21 21:03:11 +00001992 // If we're looking for a definition, make sure we have definitions of any
1993 // underlying types.
1994 if (const TypedefType* TTy = dyn_cast<TypedefType>(Ty))
1995 getOrCreateType(TTy->getDecl()->getUnderlyingType(), Unit, Declaration);
1996 if (Ty.hasLocalQualifiers())
1997 getOrCreateType(QualType(Ty.getTypePtr(), 0), Unit, Declaration);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001998 return T;
David Blaikief0c31d92013-06-21 21:03:11 +00001999 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002000
2001 // Otherwise create the type.
David Blaikie5f6e2f42013-06-05 05:32:23 +00002002 llvm::DIType Res = CreateTypeNode(Ty, Unit, Declaration);
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002003 void* TyPtr = Ty.getAsOpaquePtr();
2004
2005 // And update the type cache.
2006 TypeCache[TyPtr] = Res;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002007
2008 llvm::DIType TC = getTypeOrNull(Ty);
Eric Christopherb2d13922013-07-18 00:52:50 +00002009 if (TC && TC.isForwardDecl())
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002010 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
2011 else if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty)) {
2012 // Interface types may have elements added to them by a
2013 // subsequent implementation or extension, so we keep them in
2014 // the ObjCInterfaceCache together with a checksum. Instead of
Adrian Prantlf06989b2013-05-08 23:37:22 +00002015 // the (possibly) incomplete interface type, we return a forward
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002016 // declaration that gets RAUW'd in CGDebugInfo::finalize().
David Blaikiee2eb89a2013-05-21 18:29:40 +00002017 std::pair<llvm::WeakVH, unsigned> &V = ObjCInterfaceCache[TyPtr];
2018 if (V.first)
2019 return llvm::DIType(cast<llvm::MDNode>(V.first));
2020 TC = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
2021 Decl->getName(), TheCU, Unit,
2022 getLineNumber(Decl->getLocation()),
2023 TheCU.getLanguage());
2024 // Store the forward declaration in the cache.
2025 V.first = TC;
2026 V.second = Checksum(Decl);
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002027
David Blaikiee2eb89a2013-05-21 18:29:40 +00002028 // Register the type for replacement in finalize().
2029 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
2030
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002031 return TC;
Adrian Prantl4919de62013-03-06 22:03:30 +00002032 }
2033
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002034 if (!Res.isForwardDecl())
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002035 CompletedTypeCache[TyPtr] = Res;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002036
2037 return Res;
2038}
2039
Adrian Prantlb5a50072013-06-07 01:10:41 +00002040/// Currently the checksum of an interface includes the number of
2041/// ivars and property accessors.
Eric Christopher56b108a2013-06-07 22:54:39 +00002042unsigned CGDebugInfo::Checksum(const ObjCInterfaceDecl *ID) {
Adrian Prantl4f97f852013-06-07 01:10:48 +00002043 // The assumption is that the number of ivars can only increase
2044 // monotonically, so it is safe to just use their current number as
2045 // a checksum.
Adrian Prantlb5a50072013-06-07 01:10:41 +00002046 unsigned Sum = 0;
2047 for (const ObjCIvarDecl *Ivar = ID->all_declared_ivar_begin();
2048 Ivar != 0; Ivar = Ivar->getNextIvar())
2049 ++Sum;
2050
2051 return Sum;
Adrian Prantl4919de62013-03-06 22:03:30 +00002052}
2053
2054ObjCInterfaceDecl *CGDebugInfo::getObjCInterfaceDecl(QualType Ty) {
2055 switch (Ty->getTypeClass()) {
2056 case Type::ObjCObjectPointer:
Eric Christopherf0890c42013-05-16 00:52:20 +00002057 return getObjCInterfaceDecl(cast<ObjCObjectPointerType>(Ty)
2058 ->getPointeeType());
Adrian Prantl4919de62013-03-06 22:03:30 +00002059 case Type::ObjCInterface:
2060 return cast<ObjCInterfaceType>(Ty)->getDecl();
2061 default:
2062 return 0;
2063 }
2064}
2065
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002066/// CreateTypeNode - Create a new debug type node.
Eric Christopher56b108a2013-06-07 22:54:39 +00002067llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit,
2068 bool Declaration) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002069 // Handle qualifiers, which recursively handles what they refer to.
2070 if (Ty.hasLocalQualifiers())
David Blaikie5f6e2f42013-06-05 05:32:23 +00002071 return CreateQualifiedType(Ty, Unit, Declaration);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002072
2073 const char *Diag = 0;
Eric Christopher6537f082013-05-16 00:45:12 +00002074
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002075 // Work out details of type.
2076 switch (Ty->getTypeClass()) {
2077#define TYPE(Class, Base)
2078#define ABSTRACT_TYPE(Class, Base)
2079#define NON_CANONICAL_TYPE(Class, Base)
2080#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2081#include "clang/AST/TypeNodes.def"
2082 llvm_unreachable("Dependent types cannot show up in debug information");
2083
2084 case Type::ExtVector:
2085 case Type::Vector:
2086 return CreateType(cast<VectorType>(Ty), Unit);
2087 case Type::ObjCObjectPointer:
2088 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
2089 case Type::ObjCObject:
2090 return CreateType(cast<ObjCObjectType>(Ty), Unit);
2091 case Type::ObjCInterface:
2092 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
2093 case Type::Builtin:
2094 return CreateType(cast<BuiltinType>(Ty));
2095 case Type::Complex:
2096 return CreateType(cast<ComplexType>(Ty));
2097 case Type::Pointer:
2098 return CreateType(cast<PointerType>(Ty), Unit);
Reid Kleckner12df2462013-06-24 17:51:48 +00002099 case Type::Decayed:
2100 // Decayed types are just pointers in LLVM and DWARF.
2101 return CreateType(
2102 cast<PointerType>(cast<DecayedType>(Ty)->getDecayedType()), Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002103 case Type::BlockPointer:
2104 return CreateType(cast<BlockPointerType>(Ty), Unit);
2105 case Type::Typedef:
David Blaikie5f6e2f42013-06-05 05:32:23 +00002106 return CreateType(cast<TypedefType>(Ty), Unit, Declaration);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002107 case Type::Record:
David Blaikie5f6e2f42013-06-05 05:32:23 +00002108 return CreateType(cast<RecordType>(Ty), Declaration);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002109 case Type::Enum:
2110 return CreateEnumType(cast<EnumType>(Ty)->getDecl());
2111 case Type::FunctionProto:
2112 case Type::FunctionNoProto:
2113 return CreateType(cast<FunctionType>(Ty), Unit);
2114 case Type::ConstantArray:
2115 case Type::VariableArray:
2116 case Type::IncompleteArray:
2117 return CreateType(cast<ArrayType>(Ty), Unit);
2118
2119 case Type::LValueReference:
2120 return CreateType(cast<LValueReferenceType>(Ty), Unit);
2121 case Type::RValueReference:
2122 return CreateType(cast<RValueReferenceType>(Ty), Unit);
2123
2124 case Type::MemberPointer:
2125 return CreateType(cast<MemberPointerType>(Ty), Unit);
2126
2127 case Type::Atomic:
2128 return CreateType(cast<AtomicType>(Ty), Unit);
2129
2130 case Type::Attributed:
2131 case Type::TemplateSpecialization:
2132 case Type::Elaborated:
2133 case Type::Paren:
2134 case Type::SubstTemplateTypeParm:
2135 case Type::TypeOfExpr:
2136 case Type::TypeOf:
2137 case Type::Decltype:
2138 case Type::UnaryTransform:
David Blaikie226399c2013-07-13 21:08:08 +00002139 case Type::PackExpansion:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002140 llvm_unreachable("type should have been unwrapped!");
David Blaikie91296482013-05-24 21:24:35 +00002141 case Type::Auto:
2142 Diag = "auto";
2143 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002144 }
Eric Christopher6537f082013-05-16 00:45:12 +00002145
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002146 assert(Diag && "Fall through without a diagnostic?");
2147 unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error,
2148 "debug information for %0 is not yet supported");
2149 CGM.getDiags().Report(DiagID)
2150 << Diag;
2151 return llvm::DIType();
2152}
2153
2154/// getOrCreateLimitedType - Get the type from the cache or create a new
2155/// limited type if necessary.
2156llvm::DIType CGDebugInfo::getOrCreateLimitedType(QualType Ty,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002157 llvm::DIFile Unit) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002158 if (Ty.isNull())
2159 return llvm::DIType();
2160
2161 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00002162 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002163
2164 llvm::DIType T = getTypeOrNull(Ty);
2165
2166 // We may have cached a forward decl when we could have created
2167 // a non-forward decl. Go ahead and create a non-forward decl
2168 // now.
Eric Christopherb2d13922013-07-18 00:52:50 +00002169 if (T && !T.isForwardDecl()) return T;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002170
2171 // Otherwise create the type.
2172 llvm::DIType Res = CreateLimitedTypeNode(Ty, Unit);
2173
Eric Christopherb2d13922013-07-18 00:52:50 +00002174 if (T && T.isForwardDecl())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002175 ReplaceMap.push_back(std::make_pair(Ty.getAsOpaquePtr(),
2176 static_cast<llvm::Value*>(T)));
2177
2178 // And update the type cache.
2179 TypeCache[Ty.getAsOpaquePtr()] = Res;
2180 return Res;
2181}
2182
2183// TODO: Currently used for context chains when limiting debug info.
2184llvm::DIType CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
2185 RecordDecl *RD = Ty->getDecl();
Eric Christopher6537f082013-05-16 00:45:12 +00002186
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002187 // Get overall information about the record type for the debug info.
2188 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
2189 unsigned Line = getLineNumber(RD->getLocation());
2190 StringRef RDName = getClassName(RD);
2191
2192 llvm::DIDescriptor RDContext;
Eric Christopher13c97672013-05-16 00:45:23 +00002193 if (DebugKind == CodeGenOptions::LimitedDebugInfo)
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002194 RDContext = createContextChain(cast<Decl>(RD->getDeclContext()));
2195 else
2196 RDContext = getContextDescriptor(cast<Decl>(RD->getDeclContext()));
2197
2198 // If this is just a forward declaration, construct an appropriately
2199 // marked node and just return it.
2200 if (!RD->getDefinition())
2201 return createRecordFwdDecl(RD, RDContext);
2202
2203 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2204 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
2205 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
David Blaikie2fcadbe2013-03-26 23:47:35 +00002206 llvm::DICompositeType RealDecl;
Eric Christopher6537f082013-05-16 00:45:12 +00002207
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002208 if (RD->isUnion())
2209 RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002210 Size, Align, 0, llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002211 else if (RD->isClass()) {
2212 // FIXME: This could be a struct type giving a default visibility different
2213 // than C++ class type, but needs llvm metadata changes first.
2214 RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002215 Size, Align, 0, 0, llvm::DIType(),
2216 llvm::DIArray(), llvm::DIType(),
2217 llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002218 } else
2219 RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line,
Eric Christopherf0890c42013-05-16 00:52:20 +00002220 Size, Align, 0, llvm::DIType(),
2221 llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002222
2223 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
David Blaikie2fcadbe2013-03-26 23:47:35 +00002224 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002225
2226 if (CXXDecl) {
2227 // A class's primary base or the class itself contains the vtable.
David Blaikie2fcadbe2013-03-26 23:47:35 +00002228 llvm::DICompositeType ContainingType;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002229 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2230 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
2231 // Seek non virtual primary base root.
2232 while (1) {
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002233 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
2234 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
2235 if (PBT && !BRL.isPrimaryBaseVirtual())
2236 PBase = PBT;
2237 else
2238 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002239 }
David Blaikie2fcadbe2013-03-26 23:47:35 +00002240 ContainingType = llvm::DICompositeType(
2241 getOrCreateType(QualType(PBase->getTypeForDecl(), 0), DefUnit));
2242 } else if (CXXDecl->isDynamicClass())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002243 ContainingType = RealDecl;
2244
David Blaikie2fcadbe2013-03-26 23:47:35 +00002245 RealDecl.setContainingType(ContainingType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002246 }
2247 return llvm::DIType(RealDecl);
2248}
2249
2250/// CreateLimitedTypeNode - Create a new debug type node, but only forward
2251/// declare composite types that haven't been processed yet.
2252llvm::DIType CGDebugInfo::CreateLimitedTypeNode(QualType Ty,llvm::DIFile Unit) {
2253
2254 // Work out details of type.
2255 switch (Ty->getTypeClass()) {
2256#define TYPE(Class, Base)
2257#define ABSTRACT_TYPE(Class, Base)
2258#define NON_CANONICAL_TYPE(Class, Base)
2259#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2260 #include "clang/AST/TypeNodes.def"
2261 llvm_unreachable("Dependent types cannot show up in debug information");
2262
2263 case Type::Record:
2264 return CreateLimitedType(cast<RecordType>(Ty));
2265 default:
David Blaikie5f6e2f42013-06-05 05:32:23 +00002266 return CreateTypeNode(Ty, Unit, false);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002267 }
2268}
2269
2270/// CreateMemberType - Create new member and increase Offset by FType's size.
2271llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
2272 StringRef Name,
2273 uint64_t *Offset) {
2274 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2275 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
2276 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
2277 llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0,
2278 FieldSize, FieldAlign,
2279 *Offset, 0, FieldTy);
2280 *Offset += FieldSize;
2281 return Ty;
2282}
2283
David Blaikie9faebd22013-05-20 04:58:53 +00002284llvm::DIDescriptor CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
2285 // We only need a declaration (not a definition) of the type - so use whatever
2286 // we would otherwise do to get a type for a pointee. (forward declarations in
2287 // limited debug info, full definitions (if the type definition is available)
2288 // in unlimited debug info)
2289 if (const TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
2290 llvm::DIFile DefUnit = getOrCreateFile(TD->getLocation());
David Blaikieb0f77b02013-05-24 21:33:22 +00002291 return getOrCreateTypeDeclaration(CGM.getContext().getTypeDeclType(TD),
2292 DefUnit);
David Blaikie9faebd22013-05-20 04:58:53 +00002293 }
2294 // Otherwise fall back to a fairly rudimentary cache of existing declarations.
2295 // This doesn't handle providing declarations (for functions or variables) for
2296 // entities without definitions in this TU, nor when the definition proceeds
2297 // the call to this function.
2298 // FIXME: This should be split out into more specific maps with support for
2299 // emitting forward declarations and merging definitions with declarations,
2300 // the same way as we do for types.
2301 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator I =
2302 DeclCache.find(D->getCanonicalDecl());
2303 if (I == DeclCache.end())
2304 return llvm::DIDescriptor();
2305 llvm::Value *V = I->second;
2306 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
2307}
2308
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002309/// getFunctionDeclaration - Return debug info descriptor to describe method
2310/// declaration for the given method definition.
2311llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
David Blaikie23e66db2013-06-22 00:09:36 +00002312 if (!D || DebugKind == CodeGenOptions::DebugLineTablesOnly)
2313 return llvm::DISubprogram();
2314
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002315 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
2316 if (!FD) return llvm::DISubprogram();
2317
2318 // Setup context.
2319 getContextDescriptor(cast<Decl>(D->getDeclContext()));
2320
2321 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2322 MI = SPCache.find(FD->getCanonicalDecl());
2323 if (MI != SPCache.end()) {
2324 llvm::Value *V = MI->second;
2325 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
David Blaikie23e66db2013-06-22 00:09:36 +00002326 if (SP.isSubprogram() && !SP.isDefinition())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002327 return SP;
2328 }
2329
2330 for (FunctionDecl::redecl_iterator I = FD->redecls_begin(),
2331 E = FD->redecls_end(); I != E; ++I) {
2332 const FunctionDecl *NextFD = *I;
2333 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2334 MI = SPCache.find(NextFD->getCanonicalDecl());
2335 if (MI != SPCache.end()) {
2336 llvm::Value *V = MI->second;
2337 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
David Blaikie23e66db2013-06-22 00:09:36 +00002338 if (SP.isSubprogram() && !SP.isDefinition())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002339 return SP;
2340 }
2341 }
2342 return llvm::DISubprogram();
2343}
2344
2345// getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
2346// implicit parameter "this".
David Blaikie9a845292013-05-22 23:22:42 +00002347llvm::DICompositeType CGDebugInfo::getOrCreateFunctionType(const Decl *D,
2348 QualType FnType,
2349 llvm::DIFile F) {
David Blaikie23e66db2013-06-22 00:09:36 +00002350 if (!D || DebugKind == CodeGenOptions::DebugLineTablesOnly)
2351 // Create fake but valid subroutine type. Otherwise
2352 // llvm::DISubprogram::Verify() would return false, and
2353 // subprogram DIE will miss DW_AT_decl_file and
2354 // DW_AT_decl_line fields.
2355 return DBuilder.createSubroutineType(F, DBuilder.getOrCreateArray(None));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002356
2357 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
2358 return getOrCreateMethodType(Method, F);
2359 if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
2360 // Add "self" and "_cmd"
2361 SmallVector<llvm::Value *, 16> Elts;
2362
2363 // First element is always return type. For 'void' functions it is NULL.
Adrian Prantl0cb00022013-05-22 21:37:49 +00002364 QualType ResultTy = OMethod->getResultType();
2365
2366 // Replace the instancetype keyword with the actual type.
2367 if (ResultTy == CGM.getContext().getObjCInstanceType())
2368 ResultTy = CGM.getContext().getPointerType(
2369 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
2370
Adrian Prantl566a9c32013-05-10 21:08:31 +00002371 Elts.push_back(getOrCreateType(ResultTy, F));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002372 // "self" pointer is always first argument.
Adrian Prantle86fcc42013-03-29 19:20:29 +00002373 QualType SelfDeclTy = OMethod->getSelfDecl()->getType();
2374 llvm::DIType SelfTy = getOrCreateType(SelfDeclTy, F);
2375 Elts.push_back(CreateSelfType(SelfDeclTy, SelfTy));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002376 // "_cmd" pointer is always second argument.
2377 llvm::DIType CmdTy = getOrCreateType(OMethod->getCmdDecl()->getType(), F);
2378 Elts.push_back(DBuilder.createArtificialType(CmdTy));
2379 // Get rest of the arguments.
Eric Christopher6537f082013-05-16 00:45:12 +00002380 for (ObjCMethodDecl::param_const_iterator PI = OMethod->param_begin(),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002381 PE = OMethod->param_end(); PI != PE; ++PI)
2382 Elts.push_back(getOrCreateType((*PI)->getType(), F));
2383
2384 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2385 return DBuilder.createSubroutineType(F, EltTypeArray);
2386 }
David Blaikie9a845292013-05-22 23:22:42 +00002387 return llvm::DICompositeType(getOrCreateType(FnType, F));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002388}
2389
2390/// EmitFunctionStart - Constructs the debug code for entering a function.
2391void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
2392 llvm::Function *Fn,
2393 CGBuilderTy &Builder) {
2394
2395 StringRef Name;
2396 StringRef LinkageName;
2397
2398 FnBeginRegionCount.push_back(LexicalBlockStack.size());
2399
2400 const Decl *D = GD.getDecl();
2401 // Function may lack declaration in source code if it is created by Clang
2402 // CodeGen (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
2403 bool HasDecl = (D != 0);
2404 // Use the location of the declaration.
2405 SourceLocation Loc;
2406 if (HasDecl)
2407 Loc = D->getLocation();
2408
2409 unsigned Flags = 0;
2410 llvm::DIFile Unit = getOrCreateFile(Loc);
2411 llvm::DIDescriptor FDContext(Unit);
2412 llvm::DIArray TParamsArray;
2413 if (!HasDecl) {
2414 // Use llvm function name.
2415 Name = Fn->getName();
2416 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2417 // If there is a DISubprogram for this function available then use it.
2418 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2419 FI = SPCache.find(FD->getCanonicalDecl());
2420 if (FI != SPCache.end()) {
2421 llvm::Value *V = FI->second;
2422 llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(V));
2423 if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
2424 llvm::MDNode *SPN = SP;
2425 LexicalBlockStack.push_back(SPN);
2426 RegionMap[D] = llvm::WeakVH(SP);
2427 return;
2428 }
2429 }
2430 Name = getFunctionName(FD);
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002431 // Use mangled name as linkage name for C/C++ functions.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002432 if (FD->hasPrototype()) {
2433 LinkageName = CGM.getMangledName(GD);
2434 Flags |= llvm::DIDescriptor::FlagPrototyped;
2435 }
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002436 // No need to replicate the linkage name if it isn't different from the
2437 // subprogram name, no need to have it at all unless coverage is enabled or
2438 // debug is set to more than just line tables.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002439 if (LinkageName == Name ||
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002440 (!CGM.getCodeGenOpts().EmitGcovArcs &&
2441 !CGM.getCodeGenOpts().EmitGcovNotes &&
Eric Christopher13c97672013-05-16 00:45:23 +00002442 DebugKind <= CodeGenOptions::DebugLineTablesOnly))
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002443 LinkageName = StringRef();
2444
Eric Christopher13c97672013-05-16 00:45:23 +00002445 if (DebugKind >= CodeGenOptions::LimitedDebugInfo) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002446 if (const NamespaceDecl *NSDecl =
2447 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
2448 FDContext = getOrCreateNameSpace(NSDecl);
2449 else if (const RecordDecl *RDecl =
2450 dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
2451 FDContext = getContextDescriptor(cast<Decl>(RDecl->getDeclContext()));
2452
2453 // Collect template parameters.
2454 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
2455 }
2456 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
2457 Name = getObjCMethodName(OMD);
2458 Flags |= llvm::DIDescriptor::FlagPrototyped;
2459 } else {
2460 // Use llvm function name.
2461 Name = Fn->getName();
2462 Flags |= llvm::DIDescriptor::FlagPrototyped;
2463 }
2464 if (!Name.empty() && Name[0] == '\01')
2465 Name = Name.substr(1);
2466
2467 unsigned LineNo = getLineNumber(Loc);
2468 if (!HasDecl || D->isImplicit())
2469 Flags |= llvm::DIDescriptor::FlagArtificial;
2470
David Blaikie23e66db2013-06-22 00:09:36 +00002471 llvm::DISubprogram SP = DBuilder.createFunction(
2472 FDContext, Name, LinkageName, Unit, LineNo,
2473 getOrCreateFunctionType(D, FnType, Unit), Fn->hasInternalLinkage(),
2474 true /*definition*/, getLineNumber(CurLoc), Flags,
2475 CGM.getLangOpts().Optimize, Fn, TParamsArray, getFunctionDeclaration(D));
David Blaikie9faebd22013-05-20 04:58:53 +00002476 if (HasDecl)
2477 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(SP)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002478
2479 // Push function on region stack.
2480 llvm::MDNode *SPN = SP;
2481 LexicalBlockStack.push_back(SPN);
2482 if (HasDecl)
2483 RegionMap[D] = llvm::WeakVH(SP);
2484}
2485
2486/// EmitLocation - Emit metadata to indicate a change in line/column
Adrian Prantl18a0cd52013-07-18 00:27:59 +00002487/// information in the source file. If the location is invalid, the
2488/// previous location will be reused.
Adrian Prantl00df5ea2013-03-12 20:43:25 +00002489void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc,
2490 bool ForceColumnInfo) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002491 // Update our current location
2492 setLocation(Loc);
2493
2494 if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
2495
2496 // Don't bother if things are the same as last time.
2497 SourceManager &SM = CGM.getContext().getSourceManager();
2498 if (CurLoc == PrevLoc ||
2499 SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc))
2500 // New Builder may not be in sync with CGDebugInfo.
David Blaikie0a0f93c2013-02-01 19:09:49 +00002501 if (!Builder.getCurrentDebugLocation().isUnknown() &&
2502 Builder.getCurrentDebugLocation().getScope(CGM.getLLVMContext()) ==
2503 LexicalBlockStack.back())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002504 return;
Eric Christopher6537f082013-05-16 00:45:12 +00002505
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002506 // Update last state.
2507 PrevLoc = CurLoc;
2508
2509 llvm::MDNode *Scope = LexicalBlockStack.back();
Adrian Prantl00df5ea2013-03-12 20:43:25 +00002510 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get
2511 (getLineNumber(CurLoc),
2512 getColumnNumber(CurLoc, ForceColumnInfo),
2513 Scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002514}
2515
2516/// CreateLexicalBlock - Creates a new lexical block node and pushes it on
2517/// the stack.
2518void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
2519 llvm::DIDescriptor D =
2520 DBuilder.createLexicalBlock(LexicalBlockStack.empty() ?
2521 llvm::DIDescriptor() :
2522 llvm::DIDescriptor(LexicalBlockStack.back()),
2523 getOrCreateFile(CurLoc),
2524 getLineNumber(CurLoc),
2525 getColumnNumber(CurLoc));
2526 llvm::MDNode *DN = D;
2527 LexicalBlockStack.push_back(DN);
2528}
2529
2530/// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
2531/// region - beginning of a DW_TAG_lexical_block.
Eric Christopherf0890c42013-05-16 00:52:20 +00002532void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
2533 SourceLocation Loc) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002534 // Set our current location.
2535 setLocation(Loc);
2536
2537 // Create a new lexical block and push it on the stack.
2538 CreateLexicalBlock(Loc);
2539
2540 // Emit a line table change for the current location inside the new scope.
2541 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc),
2542 getColumnNumber(Loc),
2543 LexicalBlockStack.back()));
2544}
2545
2546/// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative
2547/// region - end of a DW_TAG_lexical_block.
Eric Christopherf0890c42013-05-16 00:52:20 +00002548void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
2549 SourceLocation Loc) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002550 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2551
2552 // Provide an entry in the line table for the end of the block.
2553 EmitLocation(Builder, Loc);
2554
2555 LexicalBlockStack.pop_back();
2556}
2557
2558/// EmitFunctionEnd - Constructs the debug code for exiting a function.
2559void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
2560 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2561 unsigned RCount = FnBeginRegionCount.back();
2562 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
2563
2564 // Pop all regions for this function.
2565 while (LexicalBlockStack.size() != RCount)
2566 EmitLexicalBlockEnd(Builder, CurLoc);
2567 FnBeginRegionCount.pop_back();
2568}
2569
Eric Christopher6537f082013-05-16 00:45:12 +00002570// EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002571// See BuildByRefType.
2572llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
2573 uint64_t *XOffset) {
2574
2575 SmallVector<llvm::Value *, 5> EltTys;
2576 QualType FType;
2577 uint64_t FieldSize, FieldOffset;
2578 unsigned FieldAlign;
Eric Christopher6537f082013-05-16 00:45:12 +00002579
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002580 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
Eric Christopher6537f082013-05-16 00:45:12 +00002581 QualType Type = VD->getType();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002582
2583 FieldOffset = 0;
2584 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2585 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
2586 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
2587 FType = CGM.getContext().IntTy;
2588 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
2589 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
2590
2591 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
2592 if (HasCopyAndDispose) {
2593 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2594 EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
2595 &FieldOffset));
2596 EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
2597 &FieldOffset));
2598 }
2599 bool HasByrefExtendedLayout;
2600 Qualifiers::ObjCLifetime Lifetime;
2601 if (CGM.getContext().getByrefLifetime(Type,
2602 Lifetime, HasByrefExtendedLayout)
2603 && HasByrefExtendedLayout)
2604 EltTys.push_back(CreateMemberType(Unit, FType,
2605 "__byref_variable_layout",
2606 &FieldOffset));
Eric Christopher6537f082013-05-16 00:45:12 +00002607
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002608 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2609 if (Align > CGM.getContext().toCharUnitsFromBits(
John McCall64aa4b32013-04-16 22:48:15 +00002610 CGM.getTarget().getPointerAlign(0))) {
Eric Christopher6537f082013-05-16 00:45:12 +00002611 CharUnits FieldOffsetInBytes
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002612 = CGM.getContext().toCharUnitsFromBits(FieldOffset);
2613 CharUnits AlignedOffsetInBytes
2614 = FieldOffsetInBytes.RoundUpToAlignment(Align);
2615 CharUnits NumPaddingBytes
2616 = AlignedOffsetInBytes - FieldOffsetInBytes;
Eric Christopher6537f082013-05-16 00:45:12 +00002617
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002618 if (NumPaddingBytes.isPositive()) {
2619 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
2620 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
2621 pad, ArrayType::Normal, 0);
2622 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
2623 }
2624 }
Eric Christopher6537f082013-05-16 00:45:12 +00002625
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002626 FType = Type;
2627 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2628 FieldSize = CGM.getContext().getTypeSize(FType);
2629 FieldAlign = CGM.getContext().toBits(Align);
2630
Eric Christopher6537f082013-05-16 00:45:12 +00002631 *XOffset = FieldOffset;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002632 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit,
2633 0, FieldSize, FieldAlign,
2634 FieldOffset, 0, FieldTy);
2635 EltTys.push_back(FieldTy);
2636 FieldOffset += FieldSize;
Eric Christopher6537f082013-05-16 00:45:12 +00002637
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002638 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopher6537f082013-05-16 00:45:12 +00002639
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002640 unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
Eric Christopher6537f082013-05-16 00:45:12 +00002641
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002642 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
David Blaikiec1d0af12013-02-25 01:07:08 +00002643 llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002644}
2645
2646/// EmitDeclare - Emit local variable declaration debug info.
2647void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
Eric Christopher6537f082013-05-16 00:45:12 +00002648 llvm::Value *Storage,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002649 unsigned ArgNo, CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002650 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002651 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2652
2653 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2654 llvm::DIType Ty;
2655 uint64_t XOffset = 0;
2656 if (VD->hasAttr<BlocksAttr>())
2657 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopher6537f082013-05-16 00:45:12 +00002658 else
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002659 Ty = getOrCreateType(VD->getType(), Unit);
2660
2661 // If there is no debug info for this type then do not emit debug info
2662 // for this variable.
2663 if (!Ty)
2664 return;
2665
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002666 // Get location information.
2667 unsigned Line = getLineNumber(VD->getLocation());
2668 unsigned Column = getColumnNumber(VD->getLocation());
2669 unsigned Flags = 0;
2670 if (VD->isImplicit())
2671 Flags |= llvm::DIDescriptor::FlagArtificial;
2672 // If this is the first argument and it is implicit then
2673 // give it an object pointer flag.
2674 // FIXME: There has to be a better way to do this, but for static
2675 // functions there won't be an implicit param at arg1 and
2676 // otherwise it is 'self' or 'this'.
2677 if (isa<ImplicitParamDecl>(VD) && ArgNo == 1)
2678 Flags |= llvm::DIDescriptor::FlagObjectPointer;
David Blaikie41c9bae2013-06-19 21:53:53 +00002679 if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage))
Eric Christopher7dab97b2013-07-17 22:52:53 +00002680 if (Arg->getType()->isPointerTy() && !Arg->hasByValAttr() &&
2681 !VD->getType()->isPointerType())
David Blaikie41c9bae2013-06-19 21:53:53 +00002682 Flags |= llvm::DIDescriptor::FlagIndirectVariable;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002683
2684 llvm::MDNode *Scope = LexicalBlockStack.back();
2685
2686 StringRef Name = VD->getName();
2687 if (!Name.empty()) {
2688 if (VD->hasAttr<BlocksAttr>()) {
2689 CharUnits offset = CharUnits::fromQuantity(32);
2690 SmallVector<llvm::Value *, 9> addr;
2691 llvm::Type *Int64Ty = CGM.Int64Ty;
2692 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2693 // offset of __forwarding field
2694 offset = CGM.getContext().toCharUnitsFromBits(
John McCall64aa4b32013-04-16 22:48:15 +00002695 CGM.getTarget().getPointerWidth(0));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002696 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2697 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2698 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2699 // offset of x field
2700 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2701 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2702
2703 // Create the descriptor for the variable.
2704 llvm::DIVariable D =
Eric Christopher6537f082013-05-16 00:45:12 +00002705 DBuilder.createComplexVariable(Tag,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002706 llvm::DIDescriptor(Scope),
2707 VD->getName(), Unit, Line, Ty,
2708 addr, ArgNo);
Eric Christopher6537f082013-05-16 00:45:12 +00002709
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002710 // Insert an llvm.dbg.declare into the current block.
2711 llvm::Instruction *Call =
2712 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2713 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2714 return;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002715 }
David Blaikie436653b2013-01-05 05:58:35 +00002716 } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2717 // If VD is an anonymous union then Storage represents value for
2718 // all union fields.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002719 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
David Blaikied8180cf2013-01-05 20:03:07 +00002720 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002721 for (RecordDecl::field_iterator I = RD->field_begin(),
2722 E = RD->field_end();
2723 I != E; ++I) {
2724 FieldDecl *Field = *I;
2725 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2726 StringRef FieldName = Field->getName();
Eric Christopher6537f082013-05-16 00:45:12 +00002727
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002728 // Ignore unnamed fields. Do not ignore unnamed records.
2729 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2730 continue;
Eric Christopher6537f082013-05-16 00:45:12 +00002731
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002732 // Use VarDecl's Tag, Scope and Line number.
2733 llvm::DIVariable D =
2734 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
Eric Christopher6537f082013-05-16 00:45:12 +00002735 FieldName, Unit, Line, FieldTy,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002736 CGM.getLangOpts().Optimize, Flags,
2737 ArgNo);
Eric Christopher6537f082013-05-16 00:45:12 +00002738
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002739 // Insert an llvm.dbg.declare into the current block.
2740 llvm::Instruction *Call =
2741 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2742 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2743 }
David Blaikied8180cf2013-01-05 20:03:07 +00002744 return;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002745 }
2746 }
David Blaikie436653b2013-01-05 05:58:35 +00002747
2748 // Create the descriptor for the variable.
2749 llvm::DIVariable D =
2750 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2751 Name, Unit, Line, Ty,
2752 CGM.getLangOpts().Optimize, Flags, ArgNo);
2753
2754 // Insert an llvm.dbg.declare into the current block.
2755 llvm::Instruction *Call =
2756 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2757 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002758}
2759
2760void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2761 llvm::Value *Storage,
2762 CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002763 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002764 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2765}
2766
Adrian Prantle86fcc42013-03-29 19:20:29 +00002767/// Look up the completed type for a self pointer in the TypeCache and
2768/// create a copy of it with the ObjectPointer and Artificial flags
2769/// set. If the type is not cached, a new one is created. This should
2770/// never happen though, since creating a type for the implicit self
2771/// argument implies that we already parsed the interface definition
2772/// and the ivar declarations in the implementation.
Eric Christopherf0890c42013-05-16 00:52:20 +00002773llvm::DIType CGDebugInfo::CreateSelfType(const QualType &QualTy,
2774 llvm::DIType Ty) {
Adrian Prantle86fcc42013-03-29 19:20:29 +00002775 llvm::DIType CachedTy = getTypeOrNull(QualTy);
Eric Christopherb2d13922013-07-18 00:52:50 +00002776 if (CachedTy) Ty = CachedTy;
Adrian Prantle86fcc42013-03-29 19:20:29 +00002777 else DEBUG(llvm::dbgs() << "No cached type for self.");
2778 return DBuilder.createObjectPointerType(Ty);
2779}
2780
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002781void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(const VarDecl *VD,
2782 llvm::Value *Storage,
2783 CGBuilderTy &Builder,
2784 const CGBlockInfo &blockInfo) {
Eric Christopher13c97672013-05-16 00:45:23 +00002785 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002786 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
Eric Christopher6537f082013-05-16 00:45:12 +00002787
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002788 if (Builder.GetInsertBlock() == 0)
2789 return;
Eric Christopher6537f082013-05-16 00:45:12 +00002790
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002791 bool isByRef = VD->hasAttr<BlocksAttr>();
Eric Christopher6537f082013-05-16 00:45:12 +00002792
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002793 uint64_t XOffset = 0;
2794 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2795 llvm::DIType Ty;
2796 if (isByRef)
2797 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopher6537f082013-05-16 00:45:12 +00002798 else
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002799 Ty = getOrCreateType(VD->getType(), Unit);
2800
2801 // Self is passed along as an implicit non-arg variable in a
2802 // block. Mark it as the object pointer.
2803 if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self")
Adrian Prantle86fcc42013-03-29 19:20:29 +00002804 Ty = CreateSelfType(VD->getType(), Ty);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002805
2806 // Get location information.
2807 unsigned Line = getLineNumber(VD->getLocation());
2808 unsigned Column = getColumnNumber(VD->getLocation());
2809
2810 const llvm::DataLayout &target = CGM.getDataLayout();
2811
2812 CharUnits offset = CharUnits::fromQuantity(
2813 target.getStructLayout(blockInfo.StructureType)
2814 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2815
2816 SmallVector<llvm::Value *, 9> addr;
2817 llvm::Type *Int64Ty = CGM.Int64Ty;
Adrian Prantl9b97adf2013-03-29 19:20:35 +00002818 if (isa<llvm::AllocaInst>(Storage))
2819 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002820 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2821 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2822 if (isByRef) {
2823 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2824 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2825 // offset of __forwarding field
2826 offset = CGM.getContext()
2827 .toCharUnitsFromBits(target.getPointerSizeInBits(0));
2828 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2829 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2830 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2831 // offset of x field
2832 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2833 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2834 }
2835
2836 // Create the descriptor for the variable.
2837 llvm::DIVariable D =
Eric Christopher6537f082013-05-16 00:45:12 +00002838 DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002839 llvm::DIDescriptor(LexicalBlockStack.back()),
2840 VD->getName(), Unit, Line, Ty, addr);
Adrian Prantl9b97adf2013-03-29 19:20:35 +00002841
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002842 // Insert an llvm.dbg.declare into the current block.
2843 llvm::Instruction *Call =
2844 DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
2845 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column,
2846 LexicalBlockStack.back()));
2847}
2848
2849/// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2850/// variable declaration.
2851void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2852 unsigned ArgNo,
2853 CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002854 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002855 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2856}
2857
2858namespace {
2859 struct BlockLayoutChunk {
2860 uint64_t OffsetInBits;
2861 const BlockDecl::Capture *Capture;
2862 };
2863 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2864 return l.OffsetInBits < r.OffsetInBits;
2865 }
2866}
2867
2868void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
Adrian Prantl836e7c92013-03-14 17:53:33 +00002869 llvm::Value *Arg,
2870 llvm::Value *LocalAddr,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002871 CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002872 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002873 ASTContext &C = CGM.getContext();
2874 const BlockDecl *blockDecl = block.getBlockDecl();
2875
2876 // Collect some general information about the block's location.
2877 SourceLocation loc = blockDecl->getCaretLocation();
2878 llvm::DIFile tunit = getOrCreateFile(loc);
2879 unsigned line = getLineNumber(loc);
2880 unsigned column = getColumnNumber(loc);
Eric Christopher6537f082013-05-16 00:45:12 +00002881
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002882 // Build the debug-info type for the block literal.
2883 getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
2884
2885 const llvm::StructLayout *blockLayout =
2886 CGM.getDataLayout().getStructLayout(block.StructureType);
2887
2888 SmallVector<llvm::Value*, 16> fields;
2889 fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
2890 blockLayout->getElementOffsetInBits(0),
2891 tunit, tunit));
2892 fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
2893 blockLayout->getElementOffsetInBits(1),
2894 tunit, tunit));
2895 fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
2896 blockLayout->getElementOffsetInBits(2),
2897 tunit, tunit));
2898 fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
2899 blockLayout->getElementOffsetInBits(3),
2900 tunit, tunit));
2901 fields.push_back(createFieldType("__descriptor",
2902 C.getPointerType(block.NeedsCopyDispose ?
2903 C.getBlockDescriptorExtendedType() :
2904 C.getBlockDescriptorType()),
2905 0, loc, AS_public,
2906 blockLayout->getElementOffsetInBits(4),
2907 tunit, tunit));
2908
2909 // We want to sort the captures by offset, not because DWARF
2910 // requires this, but because we're paranoid about debuggers.
2911 SmallVector<BlockLayoutChunk, 8> chunks;
2912
2913 // 'this' capture.
2914 if (blockDecl->capturesCXXThis()) {
2915 BlockLayoutChunk chunk;
2916 chunk.OffsetInBits =
2917 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
2918 chunk.Capture = 0;
2919 chunks.push_back(chunk);
2920 }
2921
2922 // Variable captures.
2923 for (BlockDecl::capture_const_iterator
2924 i = blockDecl->capture_begin(), e = blockDecl->capture_end();
2925 i != e; ++i) {
2926 const BlockDecl::Capture &capture = *i;
2927 const VarDecl *variable = capture.getVariable();
2928 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
2929
2930 // Ignore constant captures.
2931 if (captureInfo.isConstant())
2932 continue;
2933
2934 BlockLayoutChunk chunk;
2935 chunk.OffsetInBits =
2936 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
2937 chunk.Capture = &capture;
2938 chunks.push_back(chunk);
2939 }
2940
2941 // Sort by offset.
2942 llvm::array_pod_sort(chunks.begin(), chunks.end());
2943
2944 for (SmallVectorImpl<BlockLayoutChunk>::iterator
2945 i = chunks.begin(), e = chunks.end(); i != e; ++i) {
2946 uint64_t offsetInBits = i->OffsetInBits;
2947 const BlockDecl::Capture *capture = i->Capture;
2948
2949 // If we have a null capture, this must be the C++ 'this' capture.
2950 if (!capture) {
2951 const CXXMethodDecl *method =
2952 cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
2953 QualType type = method->getThisType(C);
2954
2955 fields.push_back(createFieldType("this", type, 0, loc, AS_public,
2956 offsetInBits, tunit, tunit));
2957 continue;
2958 }
2959
2960 const VarDecl *variable = capture->getVariable();
2961 StringRef name = variable->getName();
2962
2963 llvm::DIType fieldType;
2964 if (capture->isByRef()) {
2965 std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
2966
2967 // FIXME: this creates a second copy of this type!
2968 uint64_t xoffset;
2969 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
2970 fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
2971 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
2972 ptrInfo.first, ptrInfo.second,
2973 offsetInBits, 0, fieldType);
2974 } else {
2975 fieldType = createFieldType(name, variable->getType(), 0,
2976 loc, AS_public, offsetInBits, tunit, tunit);
2977 }
2978 fields.push_back(fieldType);
2979 }
2980
2981 SmallString<36> typeName;
2982 llvm::raw_svector_ostream(typeName)
2983 << "__block_literal_" << CGM.getUniqueBlockCount();
2984
2985 llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
2986
2987 llvm::DIType type =
2988 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
2989 CGM.getContext().toBits(block.BlockSize),
2990 CGM.getContext().toBits(block.BlockAlign),
David Blaikiec1d0af12013-02-25 01:07:08 +00002991 0, llvm::DIType(), fieldsArray);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002992 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
2993
2994 // Get overall information about the block.
2995 unsigned flags = llvm::DIDescriptor::FlagArtificial;
2996 llvm::MDNode *scope = LexicalBlockStack.back();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002997
2998 // Create the descriptor for the parameter.
2999 llvm::DIVariable debugVar =
3000 DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
Eric Christopher6537f082013-05-16 00:45:12 +00003001 llvm::DIDescriptor(scope),
Adrian Prantl836e7c92013-03-14 17:53:33 +00003002 Arg->getName(), tunit, line, type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003003 CGM.getLangOpts().Optimize, flags,
Adrian Prantl836e7c92013-03-14 17:53:33 +00003004 cast<llvm::Argument>(Arg)->getArgNo() + 1);
3005
Adrian Prantlbea407c2013-03-14 21:52:59 +00003006 if (LocalAddr) {
Adrian Prantl836e7c92013-03-14 17:53:33 +00003007 // Insert an llvm.dbg.value into the current block.
Adrian Prantlbea407c2013-03-14 21:52:59 +00003008 llvm::Instruction *DbgVal =
3009 DBuilder.insertDbgValueIntrinsic(LocalAddr, 0, debugVar,
Eric Christopherf068c922013-04-02 22:59:11 +00003010 Builder.GetInsertBlock());
Adrian Prantlbea407c2013-03-14 21:52:59 +00003011 DbgVal->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
3012 }
Adrian Prantl836e7c92013-03-14 17:53:33 +00003013
Adrian Prantlbea407c2013-03-14 21:52:59 +00003014 // Insert an llvm.dbg.declare into the current block.
3015 llvm::Instruction *DbgDecl =
3016 DBuilder.insertDeclare(Arg, debugVar, Builder.GetInsertBlock());
3017 DbgDecl->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003018}
3019
Eric Christopher0395de32013-01-16 01:22:32 +00003020/// getStaticDataMemberDeclaration - If D is an out-of-class definition of
3021/// a static data member of a class, find its corresponding in-class
3022/// declaration.
3023llvm::DIDerivedType CGDebugInfo::getStaticDataMemberDeclaration(const Decl *D) {
3024 if (cast<VarDecl>(D)->isStaticDataMember()) {
3025 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
3026 MI = StaticDataMemberCache.find(D->getCanonicalDecl());
3027 if (MI != StaticDataMemberCache.end())
3028 // Verify the info still exists.
3029 if (llvm::Value *V = MI->second)
3030 return llvm::DIDerivedType(cast<llvm::MDNode>(V));
3031 }
3032 return llvm::DIDerivedType();
3033}
3034
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003035/// EmitGlobalVariable - Emit information about a global variable.
3036void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
3037 const VarDecl *D) {
Eric Christopher13c97672013-05-16 00:45:23 +00003038 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003039 // Create global variable debug descriptor.
3040 llvm::DIFile Unit = getOrCreateFile(D->getLocation());
3041 unsigned LineNo = getLineNumber(D->getLocation());
3042
3043 setLocation(D->getLocation());
3044
3045 QualType T = D->getType();
3046 if (T->isIncompleteArrayType()) {
3047
3048 // CodeGen turns int[] into int[1] so we'll do the same here.
3049 llvm::APInt ConstVal(32, 1);
3050 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3051
3052 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3053 ArrayType::Normal, 0);
3054 }
3055 StringRef DeclName = D->getName();
3056 StringRef LinkageName;
3057 if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext())
3058 && !isa<ObjCMethodDecl>(D->getDeclContext()))
3059 LinkageName = Var->getName();
3060 if (LinkageName == DeclName)
3061 LinkageName = StringRef();
Eric Christopher6537f082013-05-16 00:45:12 +00003062 llvm::DIDescriptor DContext =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003063 getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
Eric Christopher56b108a2013-06-07 22:54:39 +00003064 llvm::DIGlobalVariable GV =
3065 DBuilder.createStaticVariable(DContext, DeclName, LinkageName, Unit,
3066 LineNo, getOrCreateType(T, Unit),
3067 Var->hasInternalLinkage(), Var,
3068 getStaticDataMemberDeclaration(D));
David Blaikie9faebd22013-05-20 04:58:53 +00003069 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(GV)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003070}
3071
3072/// EmitGlobalVariable - Emit information about an objective-c interface.
3073void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
3074 ObjCInterfaceDecl *ID) {
Eric Christopher13c97672013-05-16 00:45:23 +00003075 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003076 // Create global variable debug descriptor.
3077 llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
3078 unsigned LineNo = getLineNumber(ID->getLocation());
3079
3080 StringRef Name = ID->getName();
3081
3082 QualType T = CGM.getContext().getObjCInterfaceType(ID);
3083 if (T->isIncompleteArrayType()) {
3084
3085 // CodeGen turns int[] into int[1] so we'll do the same here.
3086 llvm::APInt ConstVal(32, 1);
3087 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3088
3089 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3090 ArrayType::Normal, 0);
3091 }
3092
3093 DBuilder.createGlobalVariable(Name, Unit, LineNo,
3094 getOrCreateType(T, Unit),
3095 Var->hasInternalLinkage(), Var);
3096}
3097
3098/// EmitGlobalVariable - Emit global variable's debug info.
Eric Christopher6537f082013-05-16 00:45:12 +00003099void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003100 llvm::Constant *Init) {
Eric Christopher13c97672013-05-16 00:45:23 +00003101 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003102 // Create the descriptor for the variable.
3103 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
3104 StringRef Name = VD->getName();
3105 llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
3106 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
3107 const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext());
3108 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
3109 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
3110 }
3111 // Do not use DIGlobalVariable for enums.
3112 if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
3113 return;
Eric Christopher56b108a2013-06-07 22:54:39 +00003114 llvm::DIGlobalVariable GV =
3115 DBuilder.createStaticVariable(Unit, Name, Name, Unit,
3116 getLineNumber(VD->getLocation()), Ty, true,
3117 Init, getStaticDataMemberDeclaration(VD));
David Blaikie9faebd22013-05-20 04:58:53 +00003118 DeclCache.insert(std::make_pair(VD->getCanonicalDecl(), llvm::WeakVH(GV)));
3119}
3120
3121llvm::DIScope CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
3122 if (!LexicalBlockStack.empty())
3123 return llvm::DIScope(LexicalBlockStack.back());
3124 return getContextDescriptor(D);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003125}
3126
David Blaikie957dac52013-04-22 06:13:21 +00003127void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
David Blaikie9faebd22013-05-20 04:58:53 +00003128 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3129 return;
David Blaikie957dac52013-04-22 06:13:21 +00003130 DBuilder.createImportedModule(
David Blaikie9faebd22013-05-20 04:58:53 +00003131 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
3132 getOrCreateNameSpace(UD.getNominatedNamespace()),
David Blaikie957dac52013-04-22 06:13:21 +00003133 getLineNumber(UD.getLocation()));
3134}
3135
David Blaikie9faebd22013-05-20 04:58:53 +00003136void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
3137 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3138 return;
3139 assert(UD.shadow_size() &&
3140 "We shouldn't be codegening an invalid UsingDecl containing no decls");
3141 // Emitting one decl is sufficient - debuggers can detect that this is an
3142 // overloaded name & provide lookup for all the overloads.
3143 const UsingShadowDecl &USD = **UD.shadow_begin();
Eric Christopher56b108a2013-06-07 22:54:39 +00003144 if (llvm::DIDescriptor Target =
3145 getDeclarationOrDefinition(USD.getUnderlyingDecl()))
David Blaikie9faebd22013-05-20 04:58:53 +00003146 DBuilder.createImportedDeclaration(
3147 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
3148 getLineNumber(USD.getLocation()));
3149}
3150
David Blaikiefc46ebc2013-05-20 22:50:41 +00003151llvm::DIImportedEntity
3152CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
3153 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3154 return llvm::DIImportedEntity(0);
3155 llvm::WeakVH &VH = NamespaceAliasCache[&NA];
3156 if (VH)
3157 return llvm::DIImportedEntity(cast<llvm::MDNode>(VH));
3158 llvm::DIImportedEntity R(0);
3159 if (const NamespaceAliasDecl *Underlying =
3160 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
3161 // This could cache & dedup here rather than relying on metadata deduping.
3162 R = DBuilder.createImportedModule(
3163 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3164 EmitNamespaceAlias(*Underlying), getLineNumber(NA.getLocation()),
3165 NA.getName());
3166 else
3167 R = DBuilder.createImportedModule(
3168 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3169 getOrCreateNameSpace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
3170 getLineNumber(NA.getLocation()), NA.getName());
3171 VH = R;
3172 return R;
3173}
3174
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003175/// getOrCreateNamesSpace - Return namespace descriptor for the given
3176/// namespace decl.
Eric Christopher6537f082013-05-16 00:45:12 +00003177llvm::DINameSpace
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003178CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
Eric Christopher6537f082013-05-16 00:45:12 +00003179 llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003180 NameSpaceCache.find(NSDecl);
3181 if (I != NameSpaceCache.end())
3182 return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
Eric Christopher6537f082013-05-16 00:45:12 +00003183
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003184 unsigned LineNo = getLineNumber(NSDecl->getLocation());
3185 llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
Eric Christopher6537f082013-05-16 00:45:12 +00003186 llvm::DIDescriptor Context =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003187 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
3188 llvm::DINameSpace NS =
3189 DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
3190 NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
3191 return NS;
3192}
3193
3194void CGDebugInfo::finalize() {
3195 for (std::vector<std::pair<void *, llvm::WeakVH> >::const_iterator VI
3196 = ReplaceMap.begin(), VE = ReplaceMap.end(); VI != VE; ++VI) {
3197 llvm::DIType Ty, RepTy;
3198 // Verify that the debug info still exists.
3199 if (llvm::Value *V = VI->second)
3200 Ty = llvm::DIType(cast<llvm::MDNode>(V));
Eric Christopher6537f082013-05-16 00:45:12 +00003201
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003202 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
3203 TypeCache.find(VI->first);
3204 if (it != TypeCache.end()) {
3205 // Verify that the debug info still exists.
3206 if (llvm::Value *V = it->second)
3207 RepTy = llvm::DIType(cast<llvm::MDNode>(V));
3208 }
Adrian Prantlebbd7e02013-03-11 18:33:46 +00003209
Eric Christopherb2d13922013-07-18 00:52:50 +00003210 if (Ty && Ty.isForwardDecl() && RepTy)
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003211 Ty.replaceAllUsesWith(RepTy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003212 }
Adrian Prantlebbd7e02013-03-11 18:33:46 +00003213
3214 // We keep our own list of retained types, because we need to look
3215 // up the final type in the type cache.
3216 for (std::vector<void *>::const_iterator RI = RetainedTypes.begin(),
3217 RE = RetainedTypes.end(); RI != RE; ++RI)
3218 DBuilder.retainType(llvm::DIType(cast<llvm::MDNode>(TypeCache[*RI])));
3219
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003220 DBuilder.finalize();
3221}