blob: 561490d25bea2cac38badbe68c88bcc1cc0addbb [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 Christopher13c97672013-05-16 00:45:23 +000044 : CGM(CGM), DebugKind(CGM.getCodeGenOpts().getDebugInfo()),
45 DBuilder(CGM.getModule()),
Guy Benyei7f92f2d2012-12-18 14:30:41 +000046 BlockLiteralGenericSet(false) {
47 CreateCompileUnit();
48}
49
50CGDebugInfo::~CGDebugInfo() {
51 assert(LexicalBlockStack.empty() &&
52 "Region stack mismatch, stack not empty!");
53}
54
55void CGDebugInfo::setLocation(SourceLocation Loc) {
56 // If the new location isn't valid return.
57 if (!Loc.isValid()) return;
58
59 CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc);
60
61 // If we've changed files in the middle of a lexical scope go ahead
62 // and create a new lexical scope with file node if it's different
63 // from the one in the scope.
64 if (LexicalBlockStack.empty()) return;
65
66 SourceManager &SM = CGM.getContext().getSourceManager();
67 PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
68 PresumedLoc PPLoc = SM.getPresumedLoc(PrevLoc);
69
70 if (PCLoc.isInvalid() || PPLoc.isInvalid() ||
71 !strcmp(PPLoc.getFilename(), PCLoc.getFilename()))
72 return;
73
74 llvm::MDNode *LB = LexicalBlockStack.back();
75 llvm::DIScope Scope = llvm::DIScope(LB);
76 if (Scope.isLexicalBlockFile()) {
77 llvm::DILexicalBlockFile LBF = llvm::DILexicalBlockFile(LB);
78 llvm::DIDescriptor D
79 = DBuilder.createLexicalBlockFile(LBF.getScope(),
80 getOrCreateFile(CurLoc));
81 llvm::MDNode *N = D;
82 LexicalBlockStack.pop_back();
83 LexicalBlockStack.push_back(N);
David Blaikiea6504852013-01-26 22:16:26 +000084 } else if (Scope.isLexicalBlock() || Scope.isSubprogram()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +000085 llvm::DIDescriptor D
86 = DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc));
87 llvm::MDNode *N = D;
88 LexicalBlockStack.pop_back();
89 LexicalBlockStack.push_back(N);
90 }
91}
92
93/// getContextDescriptor - Get context info for the decl.
David Blaikiebb000792013-04-19 06:56:38 +000094llvm::DIScope CGDebugInfo::getContextDescriptor(const Decl *Context) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +000095 if (!Context)
96 return TheCU;
97
98 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
99 I = RegionMap.find(Context);
100 if (I != RegionMap.end()) {
101 llvm::Value *V = I->second;
David Blaikiebb000792013-04-19 06:56:38 +0000102 return llvm::DIScope(dyn_cast_or_null<llvm::MDNode>(V));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000103 }
104
105 // Check namespace.
106 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
David Blaikiebb000792013-04-19 06:56:38 +0000107 return getOrCreateNameSpace(NSDecl);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000108
David Blaikiebb000792013-04-19 06:56:38 +0000109 if (const RecordDecl *RDecl = dyn_cast<RecordDecl>(Context))
110 if (!RDecl->isDependentType())
111 return getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000112 getOrCreateMainFile());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000113 return TheCU;
114}
115
116/// getFunctionName - Get function name for the given FunctionDecl. If the
117/// name is constructred on demand (e.g. C++ destructor) then the name
118/// is stored on the side.
119StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
120 assert (FD && "Invalid FunctionDecl!");
121 IdentifierInfo *FII = FD->getIdentifier();
122 FunctionTemplateSpecializationInfo *Info
123 = FD->getTemplateSpecializationInfo();
124 if (!Info && FII)
125 return FII->getName();
126
127 // Otherwise construct human readable name for debug info.
Benjamin Kramer5eada842013-02-22 15:46:01 +0000128 SmallString<128> NS;
129 llvm::raw_svector_ostream OS(NS);
130 FD->printName(OS);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000131
132 // Add any template specialization args.
133 if (Info) {
134 const TemplateArgumentList *TArgs = Info->TemplateArguments;
135 const TemplateArgument *Args = TArgs->data();
136 unsigned NumArgs = TArgs->size();
137 PrintingPolicy Policy(CGM.getLangOpts());
Benjamin Kramer5eada842013-02-22 15:46:01 +0000138 TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs,
139 Policy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000140 }
141
142 // Copy this name on the side and use its reference.
Benjamin Kramer5eada842013-02-22 15:46:01 +0000143 OS.flush();
144 char *StrPtr = DebugInfoNames.Allocate<char>(NS.size());
145 memcpy(StrPtr, NS.data(), NS.size());
146 return StringRef(StrPtr, NS.size());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000147}
148
149StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
150 SmallString<256> MethodName;
151 llvm::raw_svector_ostream OS(MethodName);
152 OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
153 const DeclContext *DC = OMD->getDeclContext();
Eric Christopher6537f082013-05-16 00:45:12 +0000154 if (const ObjCImplementationDecl *OID =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000155 dyn_cast<const ObjCImplementationDecl>(DC)) {
156 OS << OID->getName();
Eric Christopher6537f082013-05-16 00:45:12 +0000157 } else if (const ObjCInterfaceDecl *OID =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000158 dyn_cast<const ObjCInterfaceDecl>(DC)) {
159 OS << OID->getName();
Eric Christopher6537f082013-05-16 00:45:12 +0000160 } else if (const ObjCCategoryImplDecl *OCD =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000161 dyn_cast<const ObjCCategoryImplDecl>(DC)){
162 OS << ((const NamedDecl *)OCD)->getIdentifier()->getNameStart() << '(' <<
163 OCD->getIdentifier()->getNameStart() << ')';
Adrian Prantlb5092242013-05-17 23:58:45 +0000164 } else if (isa<ObjCProtocolDecl>(DC)) {
Adrian Prantl687ecae2013-05-17 23:49:10 +0000165 // We can extract the type of the class from the self pointer.
166 if (ImplicitParamDecl* SelfDecl = OMD->getSelfDecl()) {
167 QualType ClassTy =
168 cast<ObjCObjectPointerType>(SelfDecl->getType())->getPointeeType();
169 ClassTy.print(OS, PrintingPolicy(LangOptions()));
170 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000171 }
172 OS << ' ' << OMD->getSelector().getAsString() << ']';
173
174 char *StrPtr = DebugInfoNames.Allocate<char>(OS.tell());
175 memcpy(StrPtr, MethodName.begin(), OS.tell());
176 return StringRef(StrPtr, OS.tell());
177}
178
179/// getSelectorName - Return selector name. This is used for debugging
180/// info.
181StringRef CGDebugInfo::getSelectorName(Selector S) {
182 const std::string &SName = S.getAsString();
183 char *StrPtr = DebugInfoNames.Allocate<char>(SName.size());
184 memcpy(StrPtr, SName.data(), SName.size());
185 return StringRef(StrPtr, SName.size());
186}
187
188/// getClassName - Get class name including template argument list.
Eric Christopher6537f082013-05-16 00:45:12 +0000189StringRef
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000190CGDebugInfo::getClassName(const RecordDecl *RD) {
191 const ClassTemplateSpecializationDecl *Spec
192 = dyn_cast<ClassTemplateSpecializationDecl>(RD);
193 if (!Spec)
194 return RD->getName();
195
196 const TemplateArgument *Args;
197 unsigned NumArgs;
198 if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) {
199 const TemplateSpecializationType *TST =
200 cast<TemplateSpecializationType>(TAW->getType());
201 Args = TST->getArgs();
202 NumArgs = TST->getNumArgs();
203 } else {
204 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
205 Args = TemplateArgs.data();
206 NumArgs = TemplateArgs.size();
207 }
208 StringRef Name = RD->getIdentifier()->getName();
209 PrintingPolicy Policy(CGM.getLangOpts());
Benjamin Kramer5eada842013-02-22 15:46:01 +0000210 SmallString<128> TemplateArgList;
211 {
212 llvm::raw_svector_ostream OS(TemplateArgList);
213 TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs,
214 Policy);
215 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000216
217 // Copy this name on the side and use its reference.
218 size_t Length = Name.size() + TemplateArgList.size();
219 char *StrPtr = DebugInfoNames.Allocate<char>(Length);
220 memcpy(StrPtr, Name.data(), Name.size());
221 memcpy(StrPtr + Name.size(), TemplateArgList.data(), TemplateArgList.size());
222 return StringRef(StrPtr, Length);
223}
224
225/// getOrCreateFile - Get the file debug info descriptor for the input location.
226llvm::DIFile CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
227 if (!Loc.isValid())
228 // If Location is not valid then use main input file.
229 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
230
231 SourceManager &SM = CGM.getContext().getSourceManager();
232 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
233
234 if (PLoc.isInvalid() || StringRef(PLoc.getFilename()).empty())
235 // If the location is not valid then use main input file.
236 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
237
238 // Cache the results.
239 const char *fname = PLoc.getFilename();
240 llvm::DenseMap<const char *, llvm::WeakVH>::iterator it =
241 DIFileCache.find(fname);
242
243 if (it != DIFileCache.end()) {
244 // Verify that the information still exists.
245 if (llvm::Value *V = it->second)
246 return llvm::DIFile(cast<llvm::MDNode>(V));
247 }
248
249 llvm::DIFile F = DBuilder.createFile(PLoc.getFilename(), getCurrentDirname());
250
251 DIFileCache[fname] = F;
252 return F;
253}
254
255/// getOrCreateMainFile - Get the file info for main compile unit.
256llvm::DIFile CGDebugInfo::getOrCreateMainFile() {
257 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
258}
259
260/// getLineNumber - Get line number for the location. If location is invalid
261/// then use current location.
262unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
263 if (Loc.isInvalid() && CurLoc.isInvalid())
264 return 0;
265 SourceManager &SM = CGM.getContext().getSourceManager();
266 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
267 return PLoc.isValid()? PLoc.getLine() : 0;
268}
269
270/// getColumnNumber - Get column number for the location.
Adrian Prantl00df5ea2013-03-12 20:43:25 +0000271unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000272 // We may not want column information at all.
Adrian Prantl00df5ea2013-03-12 20:43:25 +0000273 if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000274 return 0;
275
276 // If the location is invalid then use the current column.
277 if (Loc.isInvalid() && CurLoc.isInvalid())
278 return 0;
279 SourceManager &SM = CGM.getContext().getSourceManager();
280 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
281 return PLoc.isValid()? PLoc.getColumn() : 0;
282}
283
284StringRef CGDebugInfo::getCurrentDirname() {
285 if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
286 return CGM.getCodeGenOpts().DebugCompilationDir;
287
288 if (!CWDName.empty())
289 return CWDName;
290 SmallString<256> CWD;
291 llvm::sys::fs::current_path(CWD);
292 char *CompDirnamePtr = DebugInfoNames.Allocate<char>(CWD.size());
293 memcpy(CompDirnamePtr, CWD.data(), CWD.size());
294 return CWDName = StringRef(CompDirnamePtr, CWD.size());
295}
296
297/// CreateCompileUnit - Create new compile unit.
298void CGDebugInfo::CreateCompileUnit() {
299
300 // Get absolute path name.
301 SourceManager &SM = CGM.getContext().getSourceManager();
302 std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
303 if (MainFileName.empty())
304 MainFileName = "<unknown>";
305
306 // The main file name provided via the "-main-file-name" option contains just
307 // the file name itself with no path information. This file name may have had
308 // a relative path, so we look into the actual file entry for the main
309 // file to determine the real absolute path for the file.
310 std::string MainFileDir;
311 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
312 MainFileDir = MainFile->getDir()->getName();
313 if (MainFileDir != ".")
314 MainFileName = MainFileDir + "/" + MainFileName;
315 }
316
317 // Save filename string.
318 char *FilenamePtr = DebugInfoNames.Allocate<char>(MainFileName.length());
319 memcpy(FilenamePtr, MainFileName.c_str(), MainFileName.length());
320 StringRef Filename(FilenamePtr, MainFileName.length());
Eric Christopherff971d72013-02-22 23:50:16 +0000321
322 // Save split dwarf file string.
323 std::string SplitDwarfFile = CGM.getCodeGenOpts().SplitDwarfFile;
324 char *SplitDwarfPtr = DebugInfoNames.Allocate<char>(SplitDwarfFile.length());
325 memcpy(SplitDwarfPtr, SplitDwarfFile.c_str(), SplitDwarfFile.length());
326 StringRef SplitDwarfFilename(SplitDwarfPtr, SplitDwarfFile.length());
Eric Christopher6537f082013-05-16 00:45:12 +0000327
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000328 unsigned LangTag;
329 const LangOptions &LO = CGM.getLangOpts();
330 if (LO.CPlusPlus) {
331 if (LO.ObjC1)
332 LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
333 else
334 LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
335 } else if (LO.ObjC1) {
336 LangTag = llvm::dwarf::DW_LANG_ObjC;
337 } else if (LO.C99) {
338 LangTag = llvm::dwarf::DW_LANG_C99;
339 } else {
340 LangTag = llvm::dwarf::DW_LANG_C89;
341 }
342
343 std::string Producer = getClangFullVersion();
344
345 // Figure out which version of the ObjC runtime we have.
346 unsigned RuntimeVers = 0;
347 if (LO.ObjC1)
348 RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
349
350 // Create new compile unit.
Eric Christopherbe5f1be2013-02-21 22:35:08 +0000351 DBuilder.createCompileUnit(LangTag, Filename, getCurrentDirname(),
352 Producer, LO.Optimize,
Eric Christopherff971d72013-02-22 23:50:16 +0000353 CGM.getCodeGenOpts().DwarfDebugFlags,
354 RuntimeVers, SplitDwarfFilename);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000355 // FIXME - Eliminate TheCU.
356 TheCU = llvm::DICompileUnit(DBuilder.getCU());
357}
358
359/// CreateType - Get the Basic type from the cache or create a new
360/// one if necessary.
361llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT) {
362 unsigned Encoding = 0;
363 StringRef BTName;
364 switch (BT->getKind()) {
365#define BUILTIN_TYPE(Id, SingletonId)
366#define PLACEHOLDER_TYPE(Id, SingletonId) \
367 case BuiltinType::Id:
368#include "clang/AST/BuiltinTypes.def"
369 case BuiltinType::Dependent:
370 llvm_unreachable("Unexpected builtin type");
371 case BuiltinType::NullPtr:
372 return DBuilder.
373 createNullPtrType(BT->getName(CGM.getLangOpts()));
374 case BuiltinType::Void:
375 return llvm::DIType();
376 case BuiltinType::ObjCClass:
377 if (ClassTy.Verify())
378 return ClassTy;
379 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
380 "objc_class", TheCU,
381 getOrCreateMainFile(), 0);
382 return ClassTy;
383 case BuiltinType::ObjCId: {
384 // typedef struct objc_class *Class;
385 // typedef struct objc_object {
386 // Class isa;
387 // } *id;
388
389 if (ObjTy.Verify())
390 return ObjTy;
391
392 if (!ClassTy.Verify())
393 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
394 "objc_class", TheCU,
395 getOrCreateMainFile(), 0);
396
397 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
Eric Christopher6537f082013-05-16 00:45:12 +0000398
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000399 llvm::DIType ISATy = DBuilder.createPointerType(ClassTy, Size);
400
Eric Christopherf068c922013-04-02 22:59:11 +0000401 ObjTy =
David Blaikiec1d0af12013-02-25 01:07:08 +0000402 DBuilder.createStructType(TheCU, "objc_object", getOrCreateMainFile(),
403 0, 0, 0, 0, llvm::DIType(), llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000404
Eric Christopherf068c922013-04-02 22:59:11 +0000405 ObjTy.setTypeArray(DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
406 ObjTy, "isa", getOrCreateMainFile(), 0, Size, 0, 0, 0, ISATy)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000407 return ObjTy;
408 }
409 case BuiltinType::ObjCSel: {
410 if (SelTy.Verify())
411 return SelTy;
412 SelTy =
413 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
414 "objc_selector", TheCU, getOrCreateMainFile(),
415 0);
416 return SelTy;
417 }
Guy Benyeib13621d2012-12-18 14:38:23 +0000418
419 case BuiltinType::OCLImage1d:
420 return getOrCreateStructPtrType("opencl_image1d_t",
421 OCLImage1dDITy);
422 case BuiltinType::OCLImage1dArray:
Eric Christopher6537f082013-05-16 00:45:12 +0000423 return getOrCreateStructPtrType("opencl_image1d_array_t",
Guy Benyeib13621d2012-12-18 14:38:23 +0000424 OCLImage1dArrayDITy);
425 case BuiltinType::OCLImage1dBuffer:
426 return getOrCreateStructPtrType("opencl_image1d_buffer_t",
427 OCLImage1dBufferDITy);
428 case BuiltinType::OCLImage2d:
429 return getOrCreateStructPtrType("opencl_image2d_t",
430 OCLImage2dDITy);
431 case BuiltinType::OCLImage2dArray:
432 return getOrCreateStructPtrType("opencl_image2d_array_t",
433 OCLImage2dArrayDITy);
434 case BuiltinType::OCLImage3d:
435 return getOrCreateStructPtrType("opencl_image3d_t",
436 OCLImage3dDITy);
Guy Benyei21f18c42013-02-07 10:55:47 +0000437 case BuiltinType::OCLSampler:
438 return DBuilder.createBasicType("opencl_sampler_t",
439 CGM.getContext().getTypeSize(BT),
440 CGM.getContext().getTypeAlign(BT),
441 llvm::dwarf::DW_ATE_unsigned);
Guy Benyeie6b9d802013-01-20 12:31:11 +0000442 case BuiltinType::OCLEvent:
443 return getOrCreateStructPtrType("opencl_event_t",
444 OCLEventDITy);
Guy Benyeib13621d2012-12-18 14:38:23 +0000445
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000446 case BuiltinType::UChar:
447 case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
448 case BuiltinType::Char_S:
449 case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
450 case BuiltinType::Char16:
451 case BuiltinType::Char32: Encoding = llvm::dwarf::DW_ATE_UTF; break;
452 case BuiltinType::UShort:
453 case BuiltinType::UInt:
454 case BuiltinType::UInt128:
455 case BuiltinType::ULong:
456 case BuiltinType::WChar_U:
457 case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
458 case BuiltinType::Short:
459 case BuiltinType::Int:
460 case BuiltinType::Int128:
461 case BuiltinType::Long:
462 case BuiltinType::WChar_S:
463 case BuiltinType::LongLong: Encoding = llvm::dwarf::DW_ATE_signed; break;
464 case BuiltinType::Bool: Encoding = llvm::dwarf::DW_ATE_boolean; break;
465 case BuiltinType::Half:
466 case BuiltinType::Float:
467 case BuiltinType::LongDouble:
468 case BuiltinType::Double: Encoding = llvm::dwarf::DW_ATE_float; break;
469 }
470
471 switch (BT->getKind()) {
472 case BuiltinType::Long: BTName = "long int"; break;
473 case BuiltinType::LongLong: BTName = "long long int"; break;
474 case BuiltinType::ULong: BTName = "long unsigned int"; break;
475 case BuiltinType::ULongLong: BTName = "long long unsigned int"; break;
476 default:
477 BTName = BT->getName(CGM.getLangOpts());
478 break;
479 }
480 // Bit size, align and offset of the type.
481 uint64_t Size = CGM.getContext().getTypeSize(BT);
482 uint64_t Align = CGM.getContext().getTypeAlign(BT);
Eric Christopher6537f082013-05-16 00:45:12 +0000483 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000484 DBuilder.createBasicType(BTName, Size, Align, Encoding);
485 return DbgTy;
486}
487
488llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty) {
489 // Bit size, align and offset of the type.
490 unsigned Encoding = llvm::dwarf::DW_ATE_complex_float;
491 if (Ty->isComplexIntegerType())
492 Encoding = llvm::dwarf::DW_ATE_lo_user;
493
494 uint64_t Size = CGM.getContext().getTypeSize(Ty);
495 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
Eric Christopher6537f082013-05-16 00:45:12 +0000496 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000497 DBuilder.createBasicType("complex", Size, Align, Encoding);
498
499 return DbgTy;
500}
501
502/// CreateCVRType - Get the qualified type from the cache or create
503/// a new one if necessary.
504llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit) {
505 QualifierCollector Qc;
506 const Type *T = Qc.strip(Ty);
507
508 // Ignore these qualifiers for now.
509 Qc.removeObjCGCAttr();
510 Qc.removeAddressSpace();
511 Qc.removeObjCLifetime();
512
513 // We will create one Derived type for one qualifier and recurse to handle any
514 // additional ones.
515 unsigned Tag;
516 if (Qc.hasConst()) {
517 Tag = llvm::dwarf::DW_TAG_const_type;
518 Qc.removeConst();
519 } else if (Qc.hasVolatile()) {
520 Tag = llvm::dwarf::DW_TAG_volatile_type;
521 Qc.removeVolatile();
522 } else if (Qc.hasRestrict()) {
523 Tag = llvm::dwarf::DW_TAG_restrict_type;
524 Qc.removeRestrict();
525 } else {
526 assert(Qc.empty() && "Unknown type qualifier for debug info");
527 return getOrCreateType(QualType(T, 0), Unit);
528 }
529
530 llvm::DIType FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
531
532 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
533 // CVR derived types.
534 llvm::DIType DbgTy = DBuilder.createQualifiedType(Tag, FromTy);
Eric Christopher6537f082013-05-16 00:45:12 +0000535
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000536 return DbgTy;
537}
538
539llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
540 llvm::DIFile Unit) {
Fariborz Jahanian05f8ff12013-02-21 20:42:11 +0000541
542 // The frontend treats 'id' as a typedef to an ObjCObjectType,
543 // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
544 // debug info, we want to emit 'id' in both cases.
545 if (Ty->isObjCQualifiedIdType())
546 return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
547
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000548 llvm::DIType DbgTy =
Eric Christopher6537f082013-05-16 00:45:12 +0000549 CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000550 Ty->getPointeeType(), Unit);
551 return DbgTy;
552}
553
554llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
555 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +0000556 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000557 Ty->getPointeeType(), Unit);
558}
559
560// Creates a forward declaration for a RecordDecl in the given context.
561llvm::DIType CGDebugInfo::createRecordFwdDecl(const RecordDecl *RD,
562 llvm::DIDescriptor Ctx) {
563 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
564 unsigned Line = getLineNumber(RD->getLocation());
565 StringRef RDName = getClassName(RD);
566
567 unsigned Tag = 0;
568 if (RD->isStruct() || RD->isInterface())
569 Tag = llvm::dwarf::DW_TAG_structure_type;
570 else if (RD->isUnion())
571 Tag = llvm::dwarf::DW_TAG_union_type;
572 else {
573 assert(RD->isClass());
574 Tag = llvm::dwarf::DW_TAG_class_type;
575 }
576
577 // Create the type.
578 return DBuilder.createForwardDecl(Tag, RDName, Ctx, DefUnit, Line);
579}
580
581// Walk up the context chain and create forward decls for record decls,
582// and normal descriptors for namespaces.
583llvm::DIDescriptor CGDebugInfo::createContextChain(const Decl *Context) {
584 if (!Context)
585 return TheCU;
586
587 // See if we already have the parent.
588 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
589 I = RegionMap.find(Context);
590 if (I != RegionMap.end()) {
591 llvm::Value *V = I->second;
592 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
593 }
Eric Christopher6537f082013-05-16 00:45:12 +0000594
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000595 // Check namespace.
596 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
597 return llvm::DIDescriptor(getOrCreateNameSpace(NSDecl));
598
599 if (const RecordDecl *RD = dyn_cast<RecordDecl>(Context)) {
600 if (!RD->isDependentType()) {
Eric Christopherf0890c42013-05-16 00:52:20 +0000601 llvm::DIType Ty =
602 getOrCreateLimitedType(CGM.getContext().getTypeDeclType(RD),
603 getOrCreateMainFile());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000604 return llvm::DIDescriptor(Ty);
605 }
606 }
607 return TheCU;
608}
609
610/// CreatePointeeType - Create Pointee type. If Pointee is a record
611/// then emit record's fwd if debug info size reduction is enabled.
612llvm::DIType CGDebugInfo::CreatePointeeType(QualType PointeeTy,
613 llvm::DIFile Unit) {
David Blaikie9faebd22013-05-20 04:58:53 +0000614 if (DebugKind > CodeGenOptions::LimitedDebugInfo)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000615 return getOrCreateType(PointeeTy, Unit);
616
617 // Limit debug info for the pointee type.
618
619 // If we have an existing type, use that, it's still smaller than creating
620 // a new type.
621 llvm::DIType Ty = getTypeOrNull(PointeeTy);
622 if (Ty.Verify()) return Ty;
623
624 // Handle qualifiers.
625 if (PointeeTy.hasLocalQualifiers())
626 return CreateQualifiedType(PointeeTy, Unit);
627
628 if (const RecordType *RTy = dyn_cast<RecordType>(PointeeTy)) {
629 RecordDecl *RD = RTy->getDecl();
630 llvm::DIDescriptor FDContext =
631 getContextDescriptor(cast<Decl>(RD->getDeclContext()));
632 llvm::DIType RetTy = createRecordFwdDecl(RD, FDContext);
633 TypeCache[QualType(RTy, 0).getAsOpaquePtr()] = RetTy;
634 return RetTy;
635 }
636 return getOrCreateType(PointeeTy, Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000637}
638
639llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag,
Eric Christopher6537f082013-05-16 00:45:12 +0000640 const Type *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000641 QualType PointeeTy,
642 llvm::DIFile Unit) {
643 if (Tag == llvm::dwarf::DW_TAG_reference_type ||
644 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
645 return DBuilder.createReferenceType(Tag,
646 CreatePointeeType(PointeeTy, Unit));
Fariborz Jahanian05f8ff12013-02-21 20:42:11 +0000647
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000648 // Bit size, align and offset of the type.
649 // Size is always the size of a pointer. We can't use getTypeSize here
650 // because that does not return the correct value for references.
651 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCall64aa4b32013-04-16 22:48:15 +0000652 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000653 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
654
655 return DBuilder.createPointerType(CreatePointeeType(PointeeTy, Unit),
656 Size, Align);
657}
658
Eric Christopherf0890c42013-05-16 00:52:20 +0000659llvm::DIType CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
660 llvm::DIType &Cache) {
David Blaikie1e97c1e2013-05-21 17:58:54 +0000661 if (Cache.Verify())
Guy Benyeib13621d2012-12-18 14:38:23 +0000662 return Cache;
David Blaikie1e97c1e2013-05-21 17:58:54 +0000663 Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
664 TheCU, getOrCreateMainFile(), 0);
665 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
666 Cache = DBuilder.createPointerType(Cache, Size);
667 return Cache;
Guy Benyeib13621d2012-12-18 14:38:23 +0000668}
669
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000670llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
671 llvm::DIFile Unit) {
672 if (BlockLiteralGenericSet)
673 return BlockLiteralGeneric;
674
675 SmallVector<llvm::Value *, 8> EltTys;
676 llvm::DIType FieldTy;
677 QualType FType;
678 uint64_t FieldSize, FieldOffset;
679 unsigned FieldAlign;
680 llvm::DIArray Elements;
681 llvm::DIType EltTy, DescTy;
682
683 FieldOffset = 0;
684 FType = CGM.getContext().UnsignedLongTy;
685 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
686 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
687
688 Elements = DBuilder.getOrCreateArray(EltTys);
689 EltTys.clear();
690
691 unsigned Flags = llvm::DIDescriptor::FlagAppleBlock;
692 unsigned LineNo = getLineNumber(CurLoc);
693
694 EltTy = DBuilder.createStructType(Unit, "__block_descriptor",
695 Unit, LineNo, FieldOffset, 0,
David Blaikiec1d0af12013-02-25 01:07:08 +0000696 Flags, llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000697
698 // Bit size, align and offset of the type.
699 uint64_t Size = CGM.getContext().getTypeSize(Ty);
700
701 DescTy = DBuilder.createPointerType(EltTy, Size);
702
703 FieldOffset = 0;
704 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
705 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
706 FType = CGM.getContext().IntTy;
707 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
708 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
709 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
710 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
711
712 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
713 FieldTy = DescTy;
714 FieldSize = CGM.getContext().getTypeSize(Ty);
715 FieldAlign = CGM.getContext().getTypeAlign(Ty);
716 FieldTy = DBuilder.createMemberType(Unit, "__descriptor", Unit,
717 LineNo, FieldSize, FieldAlign,
718 FieldOffset, 0, FieldTy);
719 EltTys.push_back(FieldTy);
720
721 FieldOffset += FieldSize;
722 Elements = DBuilder.getOrCreateArray(EltTys);
723
724 EltTy = DBuilder.createStructType(Unit, "__block_literal_generic",
725 Unit, LineNo, FieldOffset, 0,
David Blaikiec1d0af12013-02-25 01:07:08 +0000726 Flags, llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000727
728 BlockLiteralGenericSet = true;
729 BlockLiteralGeneric = DBuilder.createPointerType(EltTy, Size);
730 return BlockLiteralGeneric;
731}
732
733llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty, llvm::DIFile Unit) {
734 // Typedefs are derived from some other type. If we have a typedef of a
735 // typedef, make sure to emit the whole chain.
David Blaikie9faebd22013-05-20 04:58:53 +0000736 llvm::DIType Src = CreatePointeeType(Ty->getDecl()->getUnderlyingType(), Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000737 if (!Src.Verify())
738 return llvm::DIType();
739 // We don't set size information, but do specify where the typedef was
740 // declared.
741 unsigned Line = getLineNumber(Ty->getDecl()->getLocation());
742 const TypedefNameDecl *TyDecl = Ty->getDecl();
Eric Christopher6537f082013-05-16 00:45:12 +0000743
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000744 llvm::DIDescriptor TypedefContext =
745 getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext()));
Eric Christopher6537f082013-05-16 00:45:12 +0000746
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000747 return
748 DBuilder.createTypedef(Src, TyDecl->getName(), Unit, Line, TypedefContext);
749}
750
751llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
752 llvm::DIFile Unit) {
753 SmallVector<llvm::Value *, 16> EltTys;
754
755 // Add the result type at least.
756 EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit));
757
758 // Set up remainder of arguments if there is a prototype.
759 // FIXME: IF NOT, HOW IS THIS REPRESENTED? llvm-gcc doesn't represent '...'!
760 if (isa<FunctionNoProtoType>(Ty))
761 EltTys.push_back(DBuilder.createUnspecifiedParameter());
762 else if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Ty)) {
763 for (unsigned i = 0, e = FPT->getNumArgs(); i != e; ++i)
764 EltTys.push_back(getOrCreateType(FPT->getArgType(i), Unit));
765 }
766
767 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
768 return DBuilder.createSubroutineType(Unit, EltTypeArray);
769}
770
771
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000772llvm::DIType CGDebugInfo::createFieldType(StringRef name,
773 QualType type,
774 uint64_t sizeInBitsOverride,
775 SourceLocation loc,
776 AccessSpecifier AS,
777 uint64_t offsetInBits,
778 llvm::DIFile tunit,
779 llvm::DIDescriptor scope) {
780 llvm::DIType debugType = getOrCreateType(type, tunit);
781
782 // Get the location for the field.
783 llvm::DIFile file = getOrCreateFile(loc);
784 unsigned line = getLineNumber(loc);
785
786 uint64_t sizeInBits = 0;
787 unsigned alignInBits = 0;
788 if (!type->isIncompleteArrayType()) {
789 llvm::tie(sizeInBits, alignInBits) = CGM.getContext().getTypeInfo(type);
790
791 if (sizeInBitsOverride)
792 sizeInBits = sizeInBitsOverride;
793 }
794
795 unsigned flags = 0;
796 if (AS == clang::AS_private)
797 flags |= llvm::DIDescriptor::FlagPrivate;
798 else if (AS == clang::AS_protected)
799 flags |= llvm::DIDescriptor::FlagProtected;
800
801 return DBuilder.createMemberType(scope, name, file, line, sizeInBits,
802 alignInBits, offsetInBits, flags, debugType);
803}
804
Eric Christopher0395de32013-01-16 01:22:32 +0000805/// CollectRecordLambdaFields - Helper for CollectRecordFields.
806void CGDebugInfo::
807CollectRecordLambdaFields(const CXXRecordDecl *CXXDecl,
808 SmallVectorImpl<llvm::Value *> &elements,
809 llvm::DIType RecordTy) {
810 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
811 // has the name and the location of the variable so we should iterate over
812 // both concurrently.
813 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
814 RecordDecl::field_iterator Field = CXXDecl->field_begin();
815 unsigned fieldno = 0;
816 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
817 E = CXXDecl->captures_end(); I != E; ++I, ++Field, ++fieldno) {
818 const LambdaExpr::Capture C = *I;
819 if (C.capturesVariable()) {
820 VarDecl *V = C.getCapturedVar();
821 llvm::DIFile VUnit = getOrCreateFile(C.getLocation());
822 StringRef VName = V->getName();
823 uint64_t SizeInBitsOverride = 0;
824 if (Field->isBitField()) {
825 SizeInBitsOverride = Field->getBitWidthValue(CGM.getContext());
826 assert(SizeInBitsOverride && "found named 0-width bitfield");
827 }
828 llvm::DIType fieldType
829 = createFieldType(VName, Field->getType(), SizeInBitsOverride,
830 C.getLocation(), Field->getAccess(),
831 layout.getFieldOffset(fieldno), VUnit, RecordTy);
832 elements.push_back(fieldType);
833 } else {
834 // TODO: Need to handle 'this' in some way by probably renaming the
835 // this of the lambda class and having a field member of 'this' or
836 // by using AT_object_pointer for the function and having that be
837 // used as 'this' for semantic references.
838 assert(C.capturesThis() && "Field that isn't captured and isn't this?");
839 FieldDecl *f = *Field;
840 llvm::DIFile VUnit = getOrCreateFile(f->getLocation());
841 QualType type = f->getType();
842 llvm::DIType fieldType
843 = createFieldType("this", type, 0, f->getLocation(), f->getAccess(),
844 layout.getFieldOffset(fieldno), VUnit, RecordTy);
845
846 elements.push_back(fieldType);
847 }
848 }
849}
850
851/// CollectRecordStaticField - Helper for CollectRecordFields.
852void CGDebugInfo::
853CollectRecordStaticField(const VarDecl *Var,
854 SmallVectorImpl<llvm::Value *> &elements,
855 llvm::DIType RecordTy) {
856 // Create the descriptor for the static variable, with or without
857 // constant initializers.
858 llvm::DIFile VUnit = getOrCreateFile(Var->getLocation());
859 llvm::DIType VTy = getOrCreateType(Var->getType(), VUnit);
860
861 // Do not describe enums as static members.
862 if (VTy.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
863 return;
864
865 unsigned LineNumber = getLineNumber(Var->getLocation());
866 StringRef VName = Var->getName();
David Blaikiea89701b2013-01-20 01:19:17 +0000867 llvm::Constant *C = NULL;
Eric Christopher0395de32013-01-16 01:22:32 +0000868 if (Var->getInit()) {
869 const APValue *Value = Var->evaluateValue();
David Blaikiea89701b2013-01-20 01:19:17 +0000870 if (Value) {
871 if (Value->isInt())
872 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
873 if (Value->isFloat())
874 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
875 }
Eric Christopher0395de32013-01-16 01:22:32 +0000876 }
877
878 unsigned Flags = 0;
879 AccessSpecifier Access = Var->getAccess();
880 if (Access == clang::AS_private)
881 Flags |= llvm::DIDescriptor::FlagPrivate;
882 else if (Access == clang::AS_protected)
883 Flags |= llvm::DIDescriptor::FlagProtected;
884
885 llvm::DIType GV = DBuilder.createStaticMemberType(RecordTy, VName, VUnit,
David Blaikiea89701b2013-01-20 01:19:17 +0000886 LineNumber, VTy, Flags, C);
Eric Christopher0395de32013-01-16 01:22:32 +0000887 elements.push_back(GV);
888 StaticDataMemberCache[Var->getCanonicalDecl()] = llvm::WeakVH(GV);
889}
890
891/// CollectRecordNormalField - Helper for CollectRecordFields.
892void CGDebugInfo::
893CollectRecordNormalField(const FieldDecl *field, uint64_t OffsetInBits,
894 llvm::DIFile tunit,
895 SmallVectorImpl<llvm::Value *> &elements,
896 llvm::DIType RecordTy) {
897 StringRef name = field->getName();
898 QualType type = field->getType();
899
900 // Ignore unnamed fields unless they're anonymous structs/unions.
901 if (name.empty() && !type->isRecordType())
902 return;
903
904 uint64_t SizeInBitsOverride = 0;
905 if (field->isBitField()) {
906 SizeInBitsOverride = field->getBitWidthValue(CGM.getContext());
907 assert(SizeInBitsOverride && "found named 0-width bitfield");
908 }
909
910 llvm::DIType fieldType
911 = createFieldType(name, type, SizeInBitsOverride,
912 field->getLocation(), field->getAccess(),
913 OffsetInBits, tunit, RecordTy);
914
915 elements.push_back(fieldType);
916}
917
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000918/// CollectRecordFields - A helper function to collect debug info for
919/// record fields. This is used while creating debug info entry for a Record.
920void CGDebugInfo::
921CollectRecordFields(const RecordDecl *record, llvm::DIFile tunit,
922 SmallVectorImpl<llvm::Value *> &elements,
923 llvm::DIType RecordTy) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000924 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(record);
925
Eric Christopher0395de32013-01-16 01:22:32 +0000926 if (CXXDecl && CXXDecl->isLambda())
927 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
928 else {
929 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000930
Eric Christopher0395de32013-01-16 01:22:32 +0000931 // Field number for non-static fields.
Eric Christopherfd5ac0d2013-01-04 17:59:07 +0000932 unsigned fieldNo = 0;
Eric Christopher0395de32013-01-16 01:22:32 +0000933
934 // Bookkeeping for an ms struct, which ignores certain fields.
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000935 bool IsMsStruct = record->isMsStruct(CGM.getContext());
936 const FieldDecl *LastFD = 0;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000937
Eric Christopher0395de32013-01-16 01:22:32 +0000938 // Static and non-static members should appear in the same order as
939 // the corresponding declarations in the source program.
940 for (RecordDecl::decl_iterator I = record->decls_begin(),
941 E = record->decls_end(); I != E; ++I)
942 if (const VarDecl *V = dyn_cast<VarDecl>(*I))
943 CollectRecordStaticField(V, elements, RecordTy);
944 else if (FieldDecl *field = dyn_cast<FieldDecl>(*I)) {
945 if (IsMsStruct) {
946 // Zero-length bitfields following non-bitfield members are
947 // completely ignored; we don't even count them.
948 if (CGM.getContext().ZeroBitfieldFollowsNonBitfield((field), LastFD))
949 continue;
950 LastFD = field;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000951 }
Eric Christopher0395de32013-01-16 01:22:32 +0000952 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo),
953 tunit, elements, RecordTy);
954
955 // Bump field number for next field.
956 ++fieldNo;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000957 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000958 }
959}
960
961/// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
962/// function type is not updated to include implicit "this" pointer. Use this
963/// routine to get a method type which includes "this" pointer.
David Blaikie9a845292013-05-22 23:22:42 +0000964llvm::DICompositeType
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000965CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
966 llvm::DIFile Unit) {
David Blaikie9c78f9b2013-01-07 23:06:35 +0000967 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
David Blaikie67f8b5e2013-01-07 22:24:59 +0000968 if (Method->isStatic())
David Blaikie9a845292013-05-22 23:22:42 +0000969 return llvm::DICompositeType(getOrCreateType(QualType(Func, 0), Unit));
David Blaikie9c78f9b2013-01-07 23:06:35 +0000970 return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()),
971 Func, Unit);
972}
David Blaikie67f8b5e2013-01-07 22:24:59 +0000973
David Blaikie9a845292013-05-22 23:22:42 +0000974llvm::DICompositeType CGDebugInfo::getOrCreateInstanceMethodType(
David Blaikie9c78f9b2013-01-07 23:06:35 +0000975 QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile Unit) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000976 // Add "this" pointer.
David Blaikie9c78f9b2013-01-07 23:06:35 +0000977 llvm::DIArray Args = llvm::DICompositeType(
978 getOrCreateType(QualType(Func, 0), Unit)).getTypeArray();
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000979 assert (Args.getNumElements() && "Invalid number of arguments!");
980
981 SmallVector<llvm::Value *, 16> Elts;
982
983 // First element is always return type. For 'void' functions it is NULL.
984 Elts.push_back(Args.getElement(0));
985
David Blaikie67f8b5e2013-01-07 22:24:59 +0000986 // "this" pointer is always first argument.
David Blaikie9c78f9b2013-01-07 23:06:35 +0000987 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
David Blaikie67f8b5e2013-01-07 22:24:59 +0000988 if (isa<ClassTemplateSpecializationDecl>(RD)) {
989 // Create pointer type directly in this case.
990 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
991 QualType PointeeTy = ThisPtrTy->getPointeeType();
992 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCall64aa4b32013-04-16 22:48:15 +0000993 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
David Blaikie67f8b5e2013-01-07 22:24:59 +0000994 uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy);
995 llvm::DIType PointeeType = getOrCreateType(PointeeTy, Unit);
Eric Christopherf0890c42013-05-16 00:52:20 +0000996 llvm::DIType ThisPtrType =
997 DBuilder.createPointerType(PointeeType, Size, Align);
David Blaikie67f8b5e2013-01-07 22:24:59 +0000998 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
999 // TODO: This and the artificial type below are misleading, the
1000 // types aren't artificial the argument is, but the current
1001 // metadata doesn't represent that.
1002 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1003 Elts.push_back(ThisPtrType);
1004 } else {
1005 llvm::DIType ThisPtrType = getOrCreateType(ThisPtr, Unit);
1006 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
1007 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1008 Elts.push_back(ThisPtrType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001009 }
1010
1011 // Copy rest of the arguments.
1012 for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
1013 Elts.push_back(Args.getElement(i));
1014
1015 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
1016
1017 return DBuilder.createSubroutineType(Unit, EltTypeArray);
1018}
1019
Eric Christopher6537f082013-05-16 00:45:12 +00001020/// isFunctionLocalClass - Return true if CXXRecordDecl is defined
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001021/// inside a function.
1022static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
1023 if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
1024 return isFunctionLocalClass(NRD);
1025 if (isa<FunctionDecl>(RD->getDeclContext()))
1026 return true;
1027 return false;
1028}
1029
1030/// CreateCXXMemberFunction - A helper function to create a DISubprogram for
1031/// a single member function GlobalDecl.
1032llvm::DISubprogram
1033CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
1034 llvm::DIFile Unit,
1035 llvm::DIType RecordTy) {
Eric Christopher6537f082013-05-16 00:45:12 +00001036 bool IsCtorOrDtor =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001037 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
Eric Christopher6537f082013-05-16 00:45:12 +00001038
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001039 StringRef MethodName = getFunctionName(Method);
David Blaikie9a845292013-05-22 23:22:42 +00001040 llvm::DICompositeType MethodTy = getOrCreateMethodType(Method, Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001041
1042 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1043 // make sense to give a single ctor/dtor a linkage name.
1044 StringRef MethodLinkageName;
1045 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1046 MethodLinkageName = CGM.getMangledName(Method);
1047
1048 // Get the location for the method.
1049 llvm::DIFile MethodDefUnit = getOrCreateFile(Method->getLocation());
1050 unsigned MethodLine = getLineNumber(Method->getLocation());
1051
1052 // Collect virtual method info.
1053 llvm::DIType ContainingType;
Eric Christopher6537f082013-05-16 00:45:12 +00001054 unsigned Virtuality = 0;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001055 unsigned VIndex = 0;
Eric Christopher6537f082013-05-16 00:45:12 +00001056
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001057 if (Method->isVirtual()) {
1058 if (Method->isPure())
1059 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
1060 else
1061 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
Eric Christopher6537f082013-05-16 00:45:12 +00001062
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001063 // It doesn't make sense to give a virtual destructor a vtable index,
1064 // since a single destructor has two entries in the vtable.
1065 if (!isa<CXXDestructorDecl>(Method))
1066 VIndex = CGM.getVTableContext().getMethodVTableIndex(Method);
1067 ContainingType = RecordTy;
1068 }
1069
1070 unsigned Flags = 0;
1071 if (Method->isImplicit())
1072 Flags |= llvm::DIDescriptor::FlagArtificial;
1073 AccessSpecifier Access = Method->getAccess();
1074 if (Access == clang::AS_private)
1075 Flags |= llvm::DIDescriptor::FlagPrivate;
1076 else if (Access == clang::AS_protected)
1077 Flags |= llvm::DIDescriptor::FlagProtected;
1078 if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1079 if (CXXC->isExplicit())
1080 Flags |= llvm::DIDescriptor::FlagExplicit;
Eric Christopher6537f082013-05-16 00:45:12 +00001081 } else if (const CXXConversionDecl *CXXC =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001082 dyn_cast<CXXConversionDecl>(Method)) {
1083 if (CXXC->isExplicit())
1084 Flags |= llvm::DIDescriptor::FlagExplicit;
1085 }
1086 if (Method->hasPrototype())
1087 Flags |= llvm::DIDescriptor::FlagPrototyped;
1088
1089 llvm::DIArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1090 llvm::DISubprogram SP =
Eric Christopher6537f082013-05-16 00:45:12 +00001091 DBuilder.createMethod(RecordTy, MethodName, MethodLinkageName,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001092 MethodDefUnit, MethodLine,
Eric Christopher6537f082013-05-16 00:45:12 +00001093 MethodTy, /*isLocalToUnit=*/false,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001094 /* isDefinition=*/ false,
1095 Virtuality, VIndex, ContainingType,
1096 Flags, CGM.getLangOpts().Optimize, NULL,
1097 TParamsArray);
Eric Christopher6537f082013-05-16 00:45:12 +00001098
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001099 SPCache[Method->getCanonicalDecl()] = llvm::WeakVH(SP);
1100
1101 return SP;
1102}
1103
1104/// CollectCXXMemberFunctions - A helper function to collect debug info for
Eric Christopher6537f082013-05-16 00:45:12 +00001105/// C++ member functions. This is used while creating debug info entry for
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001106/// a Record.
1107void CGDebugInfo::
1108CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
1109 SmallVectorImpl<llvm::Value *> &EltTys,
1110 llvm::DIType RecordTy) {
1111
1112 // Since we want more than just the individual member decls if we
1113 // have templated functions iterate over every declaration to gather
1114 // the functions.
1115 for(DeclContext::decl_iterator I = RD->decls_begin(),
1116 E = RD->decls_end(); I != E; ++I) {
1117 Decl *D = *I;
1118 if (D->isImplicit() && !D->isUsed())
1119 continue;
1120
1121 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1122 EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
1123 else if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
1124 for (FunctionTemplateDecl::spec_iterator SI = FTD->spec_begin(),
1125 SE = FTD->spec_end(); SI != SE; ++SI)
1126 EltTys.push_back(CreateCXXMemberFunction(cast<CXXMethodDecl>(*SI), Unit,
1127 RecordTy));
1128 }
Eric Christopher6537f082013-05-16 00:45:12 +00001129}
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001130
1131/// CollectCXXFriends - A helper function to collect debug info for
1132/// C++ base classes. This is used while creating debug info entry for
1133/// a Record.
1134void CGDebugInfo::
1135CollectCXXFriends(const CXXRecordDecl *RD, llvm::DIFile Unit,
1136 SmallVectorImpl<llvm::Value *> &EltTys,
1137 llvm::DIType RecordTy) {
1138 for (CXXRecordDecl::friend_iterator BI = RD->friend_begin(),
1139 BE = RD->friend_end(); BI != BE; ++BI) {
1140 if ((*BI)->isUnsupportedFriend())
1141 continue;
1142 if (TypeSourceInfo *TInfo = (*BI)->getFriendType())
Eric Christopher6537f082013-05-16 00:45:12 +00001143 EltTys.push_back(DBuilder.createFriend(RecordTy,
1144 getOrCreateType(TInfo->getType(),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001145 Unit)));
1146 }
1147}
1148
1149/// CollectCXXBases - A helper function to collect debug info for
Eric Christopher6537f082013-05-16 00:45:12 +00001150/// C++ base classes. This is used while creating debug info entry for
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001151/// a Record.
1152void CGDebugInfo::
1153CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
1154 SmallVectorImpl<llvm::Value *> &EltTys,
1155 llvm::DIType RecordTy) {
1156
1157 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1158 for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
1159 BE = RD->bases_end(); BI != BE; ++BI) {
1160 unsigned BFlags = 0;
1161 uint64_t BaseOffset;
Eric Christopher6537f082013-05-16 00:45:12 +00001162
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001163 const CXXRecordDecl *Base =
1164 cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl());
Eric Christopher6537f082013-05-16 00:45:12 +00001165
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001166 if (BI->isVirtual()) {
1167 // virtual base offset offset is -ve. The code generator emits dwarf
1168 // expression where it expects +ve number.
Eric Christopher6537f082013-05-16 00:45:12 +00001169 BaseOffset =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001170 0 - CGM.getVTableContext()
1171 .getVirtualBaseOffsetOffset(RD, Base).getQuantity();
1172 BFlags = llvm::DIDescriptor::FlagVirtual;
1173 } else
1174 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1175 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1176 // BI->isVirtual() and bits when not.
Eric Christopher6537f082013-05-16 00:45:12 +00001177
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001178 AccessSpecifier Access = BI->getAccessSpecifier();
1179 if (Access == clang::AS_private)
1180 BFlags |= llvm::DIDescriptor::FlagPrivate;
1181 else if (Access == clang::AS_protected)
1182 BFlags |= llvm::DIDescriptor::FlagProtected;
Eric Christopher6537f082013-05-16 00:45:12 +00001183
1184 llvm::DIType DTy =
1185 DBuilder.createInheritance(RecordTy,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001186 getOrCreateType(BI->getType(), Unit),
1187 BaseOffset, BFlags);
1188 EltTys.push_back(DTy);
1189 }
1190}
1191
1192/// CollectTemplateParams - A helper function to collect template parameters.
1193llvm::DIArray CGDebugInfo::
1194CollectTemplateParams(const TemplateParameterList *TPList,
1195 const TemplateArgumentList &TAList,
1196 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +00001197 SmallVector<llvm::Value *, 16> TemplateParams;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001198 for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1199 const TemplateArgument &TA = TAList[i];
1200 const NamedDecl *ND = TPList->getParam(i);
David Blaikie9dfd2432013-05-10 21:53:14 +00001201 switch (TA.getKind()) {
1202 case TemplateArgument::Type: {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001203 llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit);
1204 llvm::DITemplateTypeParameter TTP =
1205 DBuilder.createTemplateTypeParameter(TheCU, ND->getName(), TTy);
1206 TemplateParams.push_back(TTP);
David Blaikie9dfd2432013-05-10 21:53:14 +00001207 } break;
1208 case TemplateArgument::Integral: {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001209 llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit);
1210 llvm::DITemplateValueParameter TVP =
David Blaikie9dfd2432013-05-10 21:53:14 +00001211 DBuilder.createTemplateValueParameter(
1212 TheCU, ND->getName(), TTy,
1213 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral()));
1214 TemplateParams.push_back(TVP);
1215 } break;
1216 case TemplateArgument::Declaration: {
1217 const ValueDecl *D = TA.getAsDecl();
1218 bool InstanceMember = D->isCXXInstanceMember();
1219 QualType T = InstanceMember
1220 ? CGM.getContext().getMemberPointerType(
1221 D->getType(), cast<RecordDecl>(D->getDeclContext())
1222 ->getTypeForDecl())
1223 : CGM.getContext().getPointerType(D->getType());
1224 llvm::DIType TTy = getOrCreateType(T, Unit);
1225 llvm::Value *V = 0;
1226 // Variable pointer template parameters have a value that is the address
1227 // of the variable.
1228 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1229 V = CGM.GetAddrOfGlobalVar(VD);
1230 // Member function pointers have special support for building them, though
1231 // this is currently unsupported in LLVM CodeGen.
David Blaikief8aa1552013-05-13 06:57:50 +00001232 if (InstanceMember) {
David Blaikie9dfd2432013-05-10 21:53:14 +00001233 if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(D))
1234 V = CGM.getCXXABI().EmitMemberPointer(method);
David Blaikief8aa1552013-05-13 06:57:50 +00001235 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1236 V = CGM.GetAddrOfFunction(FD);
David Blaikie9dfd2432013-05-10 21:53:14 +00001237 // Member data pointers have special handling too to compute the fixed
1238 // offset within the object.
1239 if (isa<FieldDecl>(D)) {
1240 // These five lines (& possibly the above member function pointer
1241 // handling) might be able to be refactored to use similar code in
1242 // CodeGenModule::getMemberPointerConstant
1243 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
1244 CharUnits chars =
1245 CGM.getContext().toCharUnitsFromBits((int64_t) fieldOffset);
1246 V = CGM.getCXXABI().EmitMemberDataPointer(
1247 cast<MemberPointerType>(T.getTypePtr()), chars);
1248 }
1249 llvm::DITemplateValueParameter TVP =
1250 DBuilder.createTemplateValueParameter(TheCU, ND->getName(), TTy, V);
1251 TemplateParams.push_back(TVP);
1252 } break;
1253 case TemplateArgument::NullPtr: {
1254 QualType T = TA.getNullPtrType();
1255 llvm::DIType TTy = getOrCreateType(T, Unit);
1256 llvm::Value *V = 0;
1257 // Special case member data pointer null values since they're actually -1
1258 // instead of zero.
1259 if (const MemberPointerType *MPT =
1260 dyn_cast<MemberPointerType>(T.getTypePtr()))
1261 // But treat member function pointers as simple zero integers because
1262 // it's easier than having a special case in LLVM's CodeGen. If LLVM
1263 // CodeGen grows handling for values of non-null member function
1264 // pointers then perhaps we could remove this special case and rely on
1265 // EmitNullMemberPointer for member function pointers.
1266 if (MPT->isMemberDataPointer())
1267 V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1268 if (!V)
1269 V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
1270 llvm::DITemplateValueParameter TVP =
1271 DBuilder.createTemplateValueParameter(TheCU, ND->getName(), TTy, V);
1272 TemplateParams.push_back(TVP);
1273 } break;
1274 case TemplateArgument::Template:
1275 // We could support this with the GCC extension
1276 // DW_TAG_GNU_template_template_param
1277 break;
David Blaikie776a3642013-05-10 22:53:25 +00001278 case TemplateArgument::Pack:
1279 // And this with DW_TAG_GNU_template_parameter_pack
1280 break;
David Blaikiee8065122013-05-10 23:36:06 +00001281 // And the following should never occur:
David Blaikie9dfd2432013-05-10 21:53:14 +00001282 case TemplateArgument::Expression:
1283 case TemplateArgument::TemplateExpansion:
David Blaikie9dfd2432013-05-10 21:53:14 +00001284 case TemplateArgument::Null:
1285 llvm_unreachable(
1286 "These argument types shouldn't exist in concrete types");
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001287 }
1288 }
1289 return DBuilder.getOrCreateArray(TemplateParams);
1290}
1291
1292/// CollectFunctionTemplateParams - A helper function to collect debug
1293/// info for function template parameters.
1294llvm::DIArray CGDebugInfo::
1295CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) {
1296 if (FD->getTemplatedKind() ==
1297 FunctionDecl::TK_FunctionTemplateSpecialization) {
1298 const TemplateParameterList *TList =
1299 FD->getTemplateSpecializationInfo()->getTemplate()
1300 ->getTemplateParameters();
Eric Christopher6537f082013-05-16 00:45:12 +00001301 return
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001302 CollectTemplateParams(TList, *FD->getTemplateSpecializationArgs(), Unit);
1303 }
1304 return llvm::DIArray();
1305}
1306
1307/// CollectCXXTemplateParams - A helper function to collect debug info for
1308/// template parameters.
1309llvm::DIArray CGDebugInfo::
1310CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial,
1311 llvm::DIFile Unit) {
1312 llvm::PointerUnion<ClassTemplateDecl *,
1313 ClassTemplatePartialSpecializationDecl *>
1314 PU = TSpecial->getSpecializedTemplateOrPartial();
Eric Christopher6537f082013-05-16 00:45:12 +00001315
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001316 TemplateParameterList *TPList = PU.is<ClassTemplateDecl *>() ?
1317 PU.get<ClassTemplateDecl *>()->getTemplateParameters() :
1318 PU.get<ClassTemplatePartialSpecializationDecl *>()->getTemplateParameters();
1319 const TemplateArgumentList &TAList = TSpecial->getTemplateInstantiationArgs();
1320 return CollectTemplateParams(TPList, TAList, Unit);
1321}
1322
1323/// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
1324llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
1325 if (VTablePtrType.isValid())
1326 return VTablePtrType;
1327
1328 ASTContext &Context = CGM.getContext();
1329
1330 /* Function type */
1331 llvm::Value *STy = getOrCreateType(Context.IntTy, Unit);
1332 llvm::DIArray SElements = DBuilder.getOrCreateArray(STy);
1333 llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements);
1334 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1335 llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0,
1336 "__vtbl_ptr_type");
1337 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1338 return VTablePtrType;
1339}
1340
1341/// getVTableName - Get vtable name for the given Class.
1342StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
1343 // Construct gdb compatible name name.
1344 std::string Name = "_vptr$" + RD->getNameAsString();
1345
1346 // Copy this name on the side and use its reference.
1347 char *StrPtr = DebugInfoNames.Allocate<char>(Name.length());
1348 memcpy(StrPtr, Name.data(), Name.length());
1349 return StringRef(StrPtr, Name.length());
1350}
1351
1352
1353/// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
1354/// debug info entry in EltTys vector.
1355void CGDebugInfo::
1356CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
1357 SmallVectorImpl<llvm::Value *> &EltTys) {
1358 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1359
1360 // If there is a primary base then it will hold vtable info.
1361 if (RL.getPrimaryBase())
1362 return;
1363
1364 // If this class is not dynamic then there is not any vtable info to collect.
1365 if (!RD->isDynamicClass())
1366 return;
1367
1368 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1369 llvm::DIType VPTR
1370 = DBuilder.createMemberType(Unit, getVTableName(RD), Unit,
Eric Christopherf0890c42013-05-16 00:52:20 +00001371 0, Size, 0, 0,
1372 llvm::DIDescriptor::FlagArtificial,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001373 getOrCreateVTablePtrType(Unit));
1374 EltTys.push_back(VPTR);
1375}
1376
Eric Christopher6537f082013-05-16 00:45:12 +00001377/// getOrCreateRecordType - Emit record type's standalone debug info.
1378llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001379 SourceLocation Loc) {
Eric Christopher13c97672013-05-16 00:45:23 +00001380 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001381 llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc));
1382 return T;
1383}
1384
1385/// getOrCreateInterfaceType - Emit an objective c interface type standalone
1386/// debug info.
1387llvm::DIType CGDebugInfo::getOrCreateInterfaceType(QualType D,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001388 SourceLocation Loc) {
Eric Christopher13c97672013-05-16 00:45:23 +00001389 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001390 llvm::DIType T = getOrCreateType(D, getOrCreateFile(Loc));
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001391 RetainedTypes.push_back(D.getAsOpaquePtr());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001392 return T;
1393}
1394
1395/// CreateType - get structure or union type.
1396llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty) {
1397 RecordDecl *RD = Ty->getDecl();
1398
1399 // Get overall information about the record type for the debug info.
1400 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1401
1402 // Records and classes and unions can all be recursive. To handle them, we
1403 // first generate a debug descriptor for the struct as a forward declaration.
1404 // Then (if it is a definition) we go through and get debug info for all of
1405 // its members. Finally, we create a descriptor for the complete type (which
1406 // may refer to the forward decl if the struct is recursive) and replace all
1407 // uses of the forward declaration with the final definition.
1408
Eric Christopherf068c922013-04-02 22:59:11 +00001409 llvm::DICompositeType FwdDecl(
1410 getOrCreateLimitedType(QualType(Ty, 0), DefUnit));
1411 assert(FwdDecl.Verify() &&
David Blaikie9a845292013-05-22 23:22:42 +00001412 "The debug type of a RecordType should be a llvm::DICompositeType");
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001413
1414 if (FwdDecl.isForwardDecl())
1415 return FwdDecl;
1416
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001417 // Push the struct on region stack.
Eric Christopherf068c922013-04-02 22:59:11 +00001418 LexicalBlockStack.push_back(&*FwdDecl);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001419 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1420
Adrian Prantl4919de62013-03-06 22:03:30 +00001421 // Add this to the completed-type cache while we're completing it recursively.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001422 CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1423
1424 // Convert all the elements.
1425 SmallVector<llvm::Value *, 16> EltTys;
1426
1427 // Note: The split of CXXDecl information here is intentional, the
1428 // gdb tests will depend on a certain ordering at printout. The debug
1429 // information offsets are still correct if we merge them all together
1430 // though.
1431 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1432 if (CXXDecl) {
1433 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1434 CollectVTableInfo(CXXDecl, DefUnit, EltTys);
1435 }
1436
Eric Christopher0395de32013-01-16 01:22:32 +00001437 // Collect data fields (including static variables and any initializers).
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001438 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
1439 llvm::DIArray TParamsArray;
1440 if (CXXDecl) {
1441 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
1442 CollectCXXFriends(CXXDecl, DefUnit, EltTys, FwdDecl);
1443 if (const ClassTemplateSpecializationDecl *TSpecial
1444 = dyn_cast<ClassTemplateSpecializationDecl>(RD))
1445 TParamsArray = CollectCXXTemplateParams(TSpecial, DefUnit);
1446 }
1447
1448 LexicalBlockStack.pop_back();
1449 RegionMap.erase(Ty->getDecl());
1450
1451 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopherf068c922013-04-02 22:59:11 +00001452 FwdDecl.setTypeArray(Elements, TParamsArray);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001453
Eric Christopherf068c922013-04-02 22:59:11 +00001454 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1455 return FwdDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001456}
1457
1458/// CreateType - get objective-c object type.
1459llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1460 llvm::DIFile Unit) {
1461 // Ignore protocols.
1462 return getOrCreateType(Ty->getBaseType(), Unit);
1463}
1464
1465/// CreateType - get objective-c interface type.
1466llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1467 llvm::DIFile Unit) {
1468 ObjCInterfaceDecl *ID = Ty->getDecl();
1469 if (!ID)
1470 return llvm::DIType();
1471
1472 // Get overall information about the record type for the debug info.
1473 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1474 unsigned Line = getLineNumber(ID->getLocation());
1475 unsigned RuntimeLang = TheCU.getLanguage();
1476
1477 // If this is just a forward declaration return a special forward-declaration
1478 // debug type since we won't be able to lay out the entire type.
1479 ObjCInterfaceDecl *Def = ID->getDefinition();
1480 if (!Def) {
1481 llvm::DIType FwdDecl =
1482 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001483 ID->getName(), TheCU, DefUnit, Line,
1484 RuntimeLang);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001485 return FwdDecl;
1486 }
1487
1488 ID = Def;
1489
1490 // Bit size, align and offset of the type.
1491 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1492 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1493
1494 unsigned Flags = 0;
1495 if (ID->getImplementation())
1496 Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
1497
Eric Christopherf068c922013-04-02 22:59:11 +00001498 llvm::DICompositeType RealDecl =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001499 DBuilder.createStructType(Unit, ID->getName(), DefUnit,
1500 Line, Size, Align, Flags,
David Blaikiec1d0af12013-02-25 01:07:08 +00001501 llvm::DIType(), llvm::DIArray(), RuntimeLang);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001502
1503 // Otherwise, insert it into the CompletedTypeCache so that recursive uses
1504 // will find it and we're emitting the complete type.
Adrian Prantl4919de62013-03-06 22:03:30 +00001505 QualType QualTy = QualType(Ty, 0);
1506 CompletedTypeCache[QualTy.getAsOpaquePtr()] = RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001507 // Push the struct on region stack.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001508
Eric Christopherf068c922013-04-02 22:59:11 +00001509 LexicalBlockStack.push_back(static_cast<llvm::MDNode*>(RealDecl));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001510 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1511
1512 // Convert all the elements.
1513 SmallVector<llvm::Value *, 16> EltTys;
1514
1515 ObjCInterfaceDecl *SClass = ID->getSuperClass();
1516 if (SClass) {
1517 llvm::DIType SClassTy =
1518 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1519 if (!SClassTy.isValid())
1520 return llvm::DIType();
Eric Christopher6537f082013-05-16 00:45:12 +00001521
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001522 llvm::DIType InhTag =
1523 DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
1524 EltTys.push_back(InhTag);
1525 }
1526
1527 for (ObjCContainerDecl::prop_iterator I = ID->prop_begin(),
1528 E = ID->prop_end(); I != E; ++I) {
1529 const ObjCPropertyDecl *PD = *I;
1530 SourceLocation Loc = PD->getLocation();
1531 llvm::DIFile PUnit = getOrCreateFile(Loc);
1532 unsigned PLine = getLineNumber(Loc);
1533 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1534 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1535 llvm::MDNode *PropertyNode =
1536 DBuilder.createObjCProperty(PD->getName(),
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001537 PUnit, PLine,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001538 (Getter && Getter->isImplicit()) ? "" :
1539 getSelectorName(PD->getGetterName()),
1540 (Setter && Setter->isImplicit()) ? "" :
1541 getSelectorName(PD->getSetterName()),
1542 PD->getPropertyAttributes(),
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001543 getOrCreateType(PD->getType(), PUnit));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001544 EltTys.push_back(PropertyNode);
1545 }
1546
1547 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1548 unsigned FieldNo = 0;
1549 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1550 Field = Field->getNextIvar(), ++FieldNo) {
1551 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1552 if (!FieldTy.isValid())
1553 return llvm::DIType();
Eric Christopher6537f082013-05-16 00:45:12 +00001554
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001555 StringRef FieldName = Field->getName();
1556
1557 // Ignore unnamed fields.
1558 if (FieldName.empty())
1559 continue;
1560
1561 // Get the location for the field.
1562 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1563 unsigned FieldLine = getLineNumber(Field->getLocation());
1564 QualType FType = Field->getType();
1565 uint64_t FieldSize = 0;
1566 unsigned FieldAlign = 0;
1567
1568 if (!FType->isIncompleteArrayType()) {
1569
1570 // Bit size, align and offset of the type.
1571 FieldSize = Field->isBitField()
1572 ? Field->getBitWidthValue(CGM.getContext())
1573 : CGM.getContext().getTypeSize(FType);
1574 FieldAlign = CGM.getContext().getTypeAlign(FType);
1575 }
1576
1577 uint64_t FieldOffset;
1578 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1579 // We don't know the runtime offset of an ivar if we're using the
1580 // non-fragile ABI. For bitfields, use the bit offset into the first
1581 // byte of storage of the bitfield. For other fields, use zero.
1582 if (Field->isBitField()) {
1583 FieldOffset = CGM.getObjCRuntime().ComputeBitfieldBitOffset(
1584 CGM, ID, Field);
1585 FieldOffset %= CGM.getContext().getCharWidth();
1586 } else {
1587 FieldOffset = 0;
1588 }
1589 } else {
1590 FieldOffset = RL.getFieldOffset(FieldNo);
1591 }
1592
1593 unsigned Flags = 0;
1594 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1595 Flags = llvm::DIDescriptor::FlagProtected;
1596 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1597 Flags = llvm::DIDescriptor::FlagPrivate;
1598
1599 llvm::MDNode *PropertyNode = NULL;
1600 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
Eric Christopher6537f082013-05-16 00:45:12 +00001601 if (ObjCPropertyImplDecl *PImpD =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001602 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
1603 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001604 SourceLocation Loc = PD->getLocation();
1605 llvm::DIFile PUnit = getOrCreateFile(Loc);
1606 unsigned PLine = getLineNumber(Loc);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001607 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1608 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1609 PropertyNode =
1610 DBuilder.createObjCProperty(PD->getName(),
1611 PUnit, PLine,
1612 (Getter && Getter->isImplicit()) ? "" :
1613 getSelectorName(PD->getGetterName()),
1614 (Setter && Setter->isImplicit()) ? "" :
1615 getSelectorName(PD->getSetterName()),
1616 PD->getPropertyAttributes(),
1617 getOrCreateType(PD->getType(), PUnit));
1618 }
1619 }
1620 }
1621 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
1622 FieldLine, FieldSize, FieldAlign,
1623 FieldOffset, Flags, FieldTy,
1624 PropertyNode);
1625 EltTys.push_back(FieldTy);
1626 }
1627
1628 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopherf068c922013-04-02 22:59:11 +00001629 RealDecl.setTypeArray(Elements);
Adrian Prantl4919de62013-03-06 22:03:30 +00001630
1631 // If the implementation is not yet set, we do not want to mark it
1632 // as complete. An implementation may declare additional
1633 // private ivars that we would miss otherwise.
1634 if (ID->getImplementation() == 0)
1635 CompletedTypeCache.erase(QualTy.getAsOpaquePtr());
Eric Christopher6537f082013-05-16 00:45:12 +00001636
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001637 LexicalBlockStack.pop_back();
Eric Christopherf068c922013-04-02 22:59:11 +00001638 return RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001639}
1640
1641llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) {
1642 llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1643 int64_t Count = Ty->getNumElements();
1644 if (Count == 0)
1645 // If number of elements are not known then this is an unbounded array.
1646 // Use Count == -1 to express such arrays.
1647 Count = -1;
1648
1649 llvm::Value *Subscript = DBuilder.getOrCreateSubrange(0, Count);
1650 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1651
1652 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1653 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1654
1655 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1656}
1657
1658llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1659 llvm::DIFile Unit) {
1660 uint64_t Size;
1661 uint64_t Align;
1662
1663 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1664 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1665 Size = 0;
1666 Align =
1667 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1668 } else if (Ty->isIncompleteArrayType()) {
1669 Size = 0;
1670 if (Ty->getElementType()->isIncompleteType())
1671 Align = 0;
1672 else
1673 Align = CGM.getContext().getTypeAlign(Ty->getElementType());
David Blaikie089db2e2013-05-09 20:48:12 +00001674 } else if (Ty->isIncompleteType()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001675 Size = 0;
1676 Align = 0;
1677 } else {
1678 // Size and align of the whole array, not the element type.
1679 Size = CGM.getContext().getTypeSize(Ty);
1680 Align = CGM.getContext().getTypeAlign(Ty);
1681 }
1682
1683 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
1684 // interior arrays, do we care? Why aren't nested arrays represented the
1685 // obvious/recursive way?
1686 SmallVector<llvm::Value *, 8> Subscripts;
1687 QualType EltTy(Ty, 0);
1688 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1689 // If the number of elements is known, then count is that number. Otherwise,
1690 // it's -1. This allows us to represent a subrange with an array of 0
1691 // elements, like this:
1692 //
1693 // struct foo {
1694 // int x[0];
1695 // };
1696 int64_t Count = -1; // Count == -1 is an unbounded array.
1697 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1698 Count = CAT->getSize().getZExtValue();
Eric Christopher6537f082013-05-16 00:45:12 +00001699
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001700 // FIXME: Verify this is right for VLAs.
1701 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
1702 EltTy = Ty->getElementType();
1703 }
1704
1705 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1706
Eric Christopher6537f082013-05-16 00:45:12 +00001707 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001708 DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1709 SubscriptArray);
1710 return DbgTy;
1711}
1712
Eric Christopher6537f082013-05-16 00:45:12 +00001713llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001714 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +00001715 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001716 Ty, Ty->getPointeeType(), Unit);
1717}
1718
Eric Christopher6537f082013-05-16 00:45:12 +00001719llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001720 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +00001721 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001722 Ty, Ty->getPointeeType(), Unit);
1723}
1724
Eric Christopher6537f082013-05-16 00:45:12 +00001725llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001726 llvm::DIFile U) {
David Blaikiee8d75142013-01-19 19:20:56 +00001727 llvm::DIType ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
1728 if (!Ty->getPointeeType()->isFunctionType())
1729 return DBuilder.createMemberPointerType(
1730 CreatePointeeType(Ty->getPointeeType(), U), ClassType);
1731 return DBuilder.createMemberPointerType(getOrCreateInstanceMethodType(
1732 CGM.getContext().getPointerType(
1733 QualType(Ty->getClass(), Ty->getPointeeType().getCVRQualifiers())),
1734 Ty->getPointeeType()->getAs<FunctionProtoType>(), U),
1735 ClassType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001736}
1737
Eric Christopher6537f082013-05-16 00:45:12 +00001738llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001739 llvm::DIFile U) {
1740 // Ignore the atomic wrapping
1741 // FIXME: What is the correct representation?
1742 return getOrCreateType(Ty->getValueType(), U);
1743}
1744
1745/// CreateEnumType - get enumeration type.
1746llvm::DIType CGDebugInfo::CreateEnumType(const EnumDecl *ED) {
1747 uint64_t Size = 0;
1748 uint64_t Align = 0;
1749 if (!ED->getTypeForDecl()->isIncompleteType()) {
1750 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1751 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1752 }
1753
1754 // If this is just a forward declaration, construct an appropriately
1755 // marked node and just return it.
1756 if (!ED->getDefinition()) {
1757 llvm::DIDescriptor EDContext;
1758 EDContext = getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1759 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1760 unsigned Line = getLineNumber(ED->getLocation());
1761 StringRef EDName = ED->getName();
1762 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_enumeration_type,
1763 EDName, EDContext, DefUnit, Line, 0,
1764 Size, Align);
1765 }
1766
1767 // Create DIEnumerator elements for each enumerator.
1768 SmallVector<llvm::Value *, 16> Enumerators;
1769 ED = ED->getDefinition();
1770 for (EnumDecl::enumerator_iterator
1771 Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
1772 Enum != EnumEnd; ++Enum) {
1773 Enumerators.push_back(
1774 DBuilder.createEnumerator(Enum->getName(),
1775 Enum->getInitVal().getZExtValue()));
1776 }
1777
1778 // Return a CompositeType for the enum itself.
1779 llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1780
1781 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1782 unsigned Line = getLineNumber(ED->getLocation());
Eric Christopher6537f082013-05-16 00:45:12 +00001783 llvm::DIDescriptor EnumContext =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001784 getContextDescriptor(cast<Decl>(ED->getDeclContext()));
Adrian Prantl59d6a712013-04-19 19:56:39 +00001785 llvm::DIType ClassTy = ED->isFixed() ?
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001786 getOrCreateType(ED->getIntegerType(), DefUnit) : llvm::DIType();
Eric Christopher6537f082013-05-16 00:45:12 +00001787 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001788 DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1789 Size, Align, EltArray,
1790 ClassTy);
1791 return DbgTy;
1792}
1793
David Blaikie4b12be62013-01-21 04:37:12 +00001794static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
1795 Qualifiers Quals;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001796 do {
David Blaikie4b12be62013-01-21 04:37:12 +00001797 Quals += T.getLocalQualifiers();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001798 QualType LastT = T;
1799 switch (T->getTypeClass()) {
1800 default:
David Blaikie4b12be62013-01-21 04:37:12 +00001801 return C.getQualifiedType(T.getTypePtr(), Quals);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001802 case Type::TemplateSpecialization:
1803 T = cast<TemplateSpecializationType>(T)->desugar();
1804 break;
1805 case Type::TypeOfExpr:
1806 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1807 break;
1808 case Type::TypeOf:
1809 T = cast<TypeOfType>(T)->getUnderlyingType();
1810 break;
1811 case Type::Decltype:
1812 T = cast<DecltypeType>(T)->getUnderlyingType();
1813 break;
1814 case Type::UnaryTransform:
1815 T = cast<UnaryTransformType>(T)->getUnderlyingType();
1816 break;
1817 case Type::Attributed:
1818 T = cast<AttributedType>(T)->getEquivalentType();
1819 break;
1820 case Type::Elaborated:
1821 T = cast<ElaboratedType>(T)->getNamedType();
1822 break;
1823 case Type::Paren:
1824 T = cast<ParenType>(T)->getInnerType();
1825 break;
David Blaikie4b12be62013-01-21 04:37:12 +00001826 case Type::SubstTemplateTypeParm:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001827 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001828 break;
1829 case Type::Auto:
1830 T = cast<AutoType>(T)->getDeducedType();
1831 break;
1832 }
Eric Christopher6537f082013-05-16 00:45:12 +00001833
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001834 assert(T != LastT && "Type unwrapping failed to unwrap!");
NAKAMURA Takumid24c9ab2013-01-21 10:51:28 +00001835 (void)LastT;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001836 } while (true);
1837}
1838
Eric Christopherf0890c42013-05-16 00:52:20 +00001839/// getType - Get the type from the cache or return null type if it doesn't
1840/// exist.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001841llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) {
1842
1843 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00001844 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Eric Christopher6537f082013-05-16 00:45:12 +00001845
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001846 // Check for existing entry.
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001847 if (Ty->getTypeClass() == Type::ObjCInterface) {
1848 llvm::Value *V = getCachedInterfaceTypeOrNull(Ty);
1849 if (V)
1850 return llvm::DIType(cast<llvm::MDNode>(V));
1851 else return llvm::DIType();
1852 }
1853
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001854 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1855 TypeCache.find(Ty.getAsOpaquePtr());
1856 if (it != TypeCache.end()) {
1857 // Verify that the debug info still exists.
1858 if (llvm::Value *V = it->second)
1859 return llvm::DIType(cast<llvm::MDNode>(V));
1860 }
1861
1862 return llvm::DIType();
1863}
1864
1865/// getCompletedTypeOrNull - Get the type from the cache or return null if it
1866/// doesn't exist.
1867llvm::DIType CGDebugInfo::getCompletedTypeOrNull(QualType Ty) {
1868
1869 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00001870 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001871
1872 // Check for existing entry.
Adrian Prantl4919de62013-03-06 22:03:30 +00001873 llvm::Value *V = 0;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001874 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1875 CompletedTypeCache.find(Ty.getAsOpaquePtr());
Adrian Prantl4919de62013-03-06 22:03:30 +00001876 if (it != CompletedTypeCache.end())
1877 V = it->second;
1878 else {
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001879 V = getCachedInterfaceTypeOrNull(Ty);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001880 }
1881
Adrian Prantl4919de62013-03-06 22:03:30 +00001882 // Verify that any cached debug info still exists.
1883 if (V != 0)
1884 return llvm::DIType(cast<llvm::MDNode>(V));
1885
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001886 return llvm::DIType();
1887}
1888
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001889/// getCachedInterfaceTypeOrNull - Get the type from the interface
1890/// cache, unless it needs to regenerated. Otherwise return null.
1891llvm::Value *CGDebugInfo::getCachedInterfaceTypeOrNull(QualType Ty) {
1892 // Is there a cached interface that hasn't changed?
1893 llvm::DenseMap<void *, std::pair<llvm::WeakVH, unsigned > >
1894 ::iterator it1 = ObjCInterfaceCache.find(Ty.getAsOpaquePtr());
1895
1896 if (it1 != ObjCInterfaceCache.end())
1897 if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty))
1898 if (Checksum(Decl) == it1->second.second)
1899 // Return cached forward declaration.
1900 return it1->second.first;
1901
1902 return 0;
1903}
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001904
1905/// getOrCreateType - Get the type from the cache or create a new
1906/// one if necessary.
1907llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit) {
1908 if (Ty.isNull())
1909 return llvm::DIType();
1910
1911 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00001912 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001913
1914 llvm::DIType T = getCompletedTypeOrNull(Ty);
1915
1916 if (T.Verify())
1917 return T;
1918
1919 // Otherwise create the type.
1920 llvm::DIType Res = CreateTypeNode(Ty, Unit);
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001921 void* TyPtr = Ty.getAsOpaquePtr();
1922
1923 // And update the type cache.
1924 TypeCache[TyPtr] = Res;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001925
1926 llvm::DIType TC = getTypeOrNull(Ty);
1927 if (TC.Verify() && TC.isForwardDecl())
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001928 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
1929 else if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty)) {
1930 // Interface types may have elements added to them by a
1931 // subsequent implementation or extension, so we keep them in
1932 // the ObjCInterfaceCache together with a checksum. Instead of
Adrian Prantlf06989b2013-05-08 23:37:22 +00001933 // the (possibly) incomplete interface type, we return a forward
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001934 // declaration that gets RAUW'd in CGDebugInfo::finalize().
David Blaikiee2eb89a2013-05-21 18:29:40 +00001935 std::pair<llvm::WeakVH, unsigned> &V = ObjCInterfaceCache[TyPtr];
1936 if (V.first)
1937 return llvm::DIType(cast<llvm::MDNode>(V.first));
1938 TC = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
1939 Decl->getName(), TheCU, Unit,
1940 getLineNumber(Decl->getLocation()),
1941 TheCU.getLanguage());
1942 // Store the forward declaration in the cache.
1943 V.first = TC;
1944 V.second = Checksum(Decl);
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001945
David Blaikiee2eb89a2013-05-21 18:29:40 +00001946 // Register the type for replacement in finalize().
1947 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
1948
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001949 return TC;
Adrian Prantl4919de62013-03-06 22:03:30 +00001950 }
1951
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001952 if (!Res.isForwardDecl())
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001953 CompletedTypeCache[TyPtr] = Res;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001954
1955 return Res;
1956}
1957
Adrian Prantl4919de62013-03-06 22:03:30 +00001958/// Currently the checksum merely consists of the number of ivars.
1959unsigned CGDebugInfo::Checksum(const ObjCInterfaceDecl
Adrian Prantl00df5ea2013-03-12 20:43:25 +00001960 *InterfaceDecl) {
Adrian Prantl4919de62013-03-06 22:03:30 +00001961 unsigned IvarNo = 0;
1962 for (const ObjCIvarDecl *Ivar = InterfaceDecl->all_declared_ivar_begin();
1963 Ivar != 0; Ivar = Ivar->getNextIvar()) ++IvarNo;
1964 return IvarNo;
1965}
1966
1967ObjCInterfaceDecl *CGDebugInfo::getObjCInterfaceDecl(QualType Ty) {
1968 switch (Ty->getTypeClass()) {
1969 case Type::ObjCObjectPointer:
Eric Christopherf0890c42013-05-16 00:52:20 +00001970 return getObjCInterfaceDecl(cast<ObjCObjectPointerType>(Ty)
1971 ->getPointeeType());
Adrian Prantl4919de62013-03-06 22:03:30 +00001972 case Type::ObjCInterface:
1973 return cast<ObjCInterfaceType>(Ty)->getDecl();
1974 default:
1975 return 0;
1976 }
1977}
1978
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001979/// CreateTypeNode - Create a new debug type node.
1980llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit) {
1981 // Handle qualifiers, which recursively handles what they refer to.
1982 if (Ty.hasLocalQualifiers())
1983 return CreateQualifiedType(Ty, Unit);
1984
1985 const char *Diag = 0;
Eric Christopher6537f082013-05-16 00:45:12 +00001986
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001987 // Work out details of type.
1988 switch (Ty->getTypeClass()) {
1989#define TYPE(Class, Base)
1990#define ABSTRACT_TYPE(Class, Base)
1991#define NON_CANONICAL_TYPE(Class, Base)
1992#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1993#include "clang/AST/TypeNodes.def"
1994 llvm_unreachable("Dependent types cannot show up in debug information");
1995
1996 case Type::ExtVector:
1997 case Type::Vector:
1998 return CreateType(cast<VectorType>(Ty), Unit);
1999 case Type::ObjCObjectPointer:
2000 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
2001 case Type::ObjCObject:
2002 return CreateType(cast<ObjCObjectType>(Ty), Unit);
2003 case Type::ObjCInterface:
2004 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
2005 case Type::Builtin:
2006 return CreateType(cast<BuiltinType>(Ty));
2007 case Type::Complex:
2008 return CreateType(cast<ComplexType>(Ty));
2009 case Type::Pointer:
2010 return CreateType(cast<PointerType>(Ty), Unit);
2011 case Type::BlockPointer:
2012 return CreateType(cast<BlockPointerType>(Ty), Unit);
2013 case Type::Typedef:
2014 return CreateType(cast<TypedefType>(Ty), Unit);
2015 case Type::Record:
2016 return CreateType(cast<RecordType>(Ty));
2017 case Type::Enum:
2018 return CreateEnumType(cast<EnumType>(Ty)->getDecl());
2019 case Type::FunctionProto:
2020 case Type::FunctionNoProto:
2021 return CreateType(cast<FunctionType>(Ty), Unit);
2022 case Type::ConstantArray:
2023 case Type::VariableArray:
2024 case Type::IncompleteArray:
2025 return CreateType(cast<ArrayType>(Ty), Unit);
2026
2027 case Type::LValueReference:
2028 return CreateType(cast<LValueReferenceType>(Ty), Unit);
2029 case Type::RValueReference:
2030 return CreateType(cast<RValueReferenceType>(Ty), Unit);
2031
2032 case Type::MemberPointer:
2033 return CreateType(cast<MemberPointerType>(Ty), Unit);
2034
2035 case Type::Atomic:
2036 return CreateType(cast<AtomicType>(Ty), Unit);
2037
2038 case Type::Attributed:
2039 case Type::TemplateSpecialization:
2040 case Type::Elaborated:
2041 case Type::Paren:
2042 case Type::SubstTemplateTypeParm:
2043 case Type::TypeOfExpr:
2044 case Type::TypeOf:
2045 case Type::Decltype:
2046 case Type::UnaryTransform:
2047 case Type::Auto:
2048 llvm_unreachable("type should have been unwrapped!");
2049 }
Eric Christopher6537f082013-05-16 00:45:12 +00002050
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002051 assert(Diag && "Fall through without a diagnostic?");
2052 unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error,
2053 "debug information for %0 is not yet supported");
2054 CGM.getDiags().Report(DiagID)
2055 << Diag;
2056 return llvm::DIType();
2057}
2058
2059/// getOrCreateLimitedType - Get the type from the cache or create a new
2060/// limited type if necessary.
2061llvm::DIType CGDebugInfo::getOrCreateLimitedType(QualType Ty,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002062 llvm::DIFile Unit) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002063 if (Ty.isNull())
2064 return llvm::DIType();
2065
2066 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00002067 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002068
2069 llvm::DIType T = getTypeOrNull(Ty);
2070
2071 // We may have cached a forward decl when we could have created
2072 // a non-forward decl. Go ahead and create a non-forward decl
2073 // now.
2074 if (T.Verify() && !T.isForwardDecl()) return T;
2075
2076 // Otherwise create the type.
2077 llvm::DIType Res = CreateLimitedTypeNode(Ty, Unit);
2078
2079 if (T.Verify() && T.isForwardDecl())
2080 ReplaceMap.push_back(std::make_pair(Ty.getAsOpaquePtr(),
2081 static_cast<llvm::Value*>(T)));
2082
2083 // And update the type cache.
2084 TypeCache[Ty.getAsOpaquePtr()] = Res;
2085 return Res;
2086}
2087
2088// TODO: Currently used for context chains when limiting debug info.
2089llvm::DIType CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
2090 RecordDecl *RD = Ty->getDecl();
Eric Christopher6537f082013-05-16 00:45:12 +00002091
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002092 // Get overall information about the record type for the debug info.
2093 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
2094 unsigned Line = getLineNumber(RD->getLocation());
2095 StringRef RDName = getClassName(RD);
2096
2097 llvm::DIDescriptor RDContext;
Eric Christopher13c97672013-05-16 00:45:23 +00002098 if (DebugKind == CodeGenOptions::LimitedDebugInfo)
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002099 RDContext = createContextChain(cast<Decl>(RD->getDeclContext()));
2100 else
2101 RDContext = getContextDescriptor(cast<Decl>(RD->getDeclContext()));
2102
2103 // If this is just a forward declaration, construct an appropriately
2104 // marked node and just return it.
2105 if (!RD->getDefinition())
2106 return createRecordFwdDecl(RD, RDContext);
2107
2108 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2109 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
2110 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
David Blaikie2fcadbe2013-03-26 23:47:35 +00002111 llvm::DICompositeType RealDecl;
Eric Christopher6537f082013-05-16 00:45:12 +00002112
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002113 if (RD->isUnion())
2114 RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002115 Size, Align, 0, llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002116 else if (RD->isClass()) {
2117 // FIXME: This could be a struct type giving a default visibility different
2118 // than C++ class type, but needs llvm metadata changes first.
2119 RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002120 Size, Align, 0, 0, llvm::DIType(),
2121 llvm::DIArray(), llvm::DIType(),
2122 llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002123 } else
2124 RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line,
Eric Christopherf0890c42013-05-16 00:52:20 +00002125 Size, Align, 0, llvm::DIType(),
2126 llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002127
2128 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
David Blaikie2fcadbe2013-03-26 23:47:35 +00002129 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002130
2131 if (CXXDecl) {
2132 // A class's primary base or the class itself contains the vtable.
David Blaikie2fcadbe2013-03-26 23:47:35 +00002133 llvm::DICompositeType ContainingType;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002134 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2135 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
2136 // Seek non virtual primary base root.
2137 while (1) {
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002138 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
2139 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
2140 if (PBT && !BRL.isPrimaryBaseVirtual())
2141 PBase = PBT;
2142 else
2143 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002144 }
David Blaikie2fcadbe2013-03-26 23:47:35 +00002145 ContainingType = llvm::DICompositeType(
2146 getOrCreateType(QualType(PBase->getTypeForDecl(), 0), DefUnit));
2147 } else if (CXXDecl->isDynamicClass())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002148 ContainingType = RealDecl;
2149
David Blaikie2fcadbe2013-03-26 23:47:35 +00002150 RealDecl.setContainingType(ContainingType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002151 }
2152 return llvm::DIType(RealDecl);
2153}
2154
2155/// CreateLimitedTypeNode - Create a new debug type node, but only forward
2156/// declare composite types that haven't been processed yet.
2157llvm::DIType CGDebugInfo::CreateLimitedTypeNode(QualType Ty,llvm::DIFile Unit) {
2158
2159 // Work out details of type.
2160 switch (Ty->getTypeClass()) {
2161#define TYPE(Class, Base)
2162#define ABSTRACT_TYPE(Class, Base)
2163#define NON_CANONICAL_TYPE(Class, Base)
2164#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2165 #include "clang/AST/TypeNodes.def"
2166 llvm_unreachable("Dependent types cannot show up in debug information");
2167
2168 case Type::Record:
2169 return CreateLimitedType(cast<RecordType>(Ty));
2170 default:
2171 return CreateTypeNode(Ty, Unit);
2172 }
2173}
2174
2175/// CreateMemberType - Create new member and increase Offset by FType's size.
2176llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
2177 StringRef Name,
2178 uint64_t *Offset) {
2179 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2180 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
2181 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
2182 llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0,
2183 FieldSize, FieldAlign,
2184 *Offset, 0, FieldTy);
2185 *Offset += FieldSize;
2186 return Ty;
2187}
2188
David Blaikie9faebd22013-05-20 04:58:53 +00002189llvm::DIDescriptor CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
2190 // We only need a declaration (not a definition) of the type - so use whatever
2191 // we would otherwise do to get a type for a pointee. (forward declarations in
2192 // limited debug info, full definitions (if the type definition is available)
2193 // in unlimited debug info)
2194 if (const TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
2195 llvm::DIFile DefUnit = getOrCreateFile(TD->getLocation());
2196 return CreatePointeeType(CGM.getContext().getTypeDeclType(TD), DefUnit);
2197 }
2198 // Otherwise fall back to a fairly rudimentary cache of existing declarations.
2199 // This doesn't handle providing declarations (for functions or variables) for
2200 // entities without definitions in this TU, nor when the definition proceeds
2201 // the call to this function.
2202 // FIXME: This should be split out into more specific maps with support for
2203 // emitting forward declarations and merging definitions with declarations,
2204 // the same way as we do for types.
2205 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator I =
2206 DeclCache.find(D->getCanonicalDecl());
2207 if (I == DeclCache.end())
2208 return llvm::DIDescriptor();
2209 llvm::Value *V = I->second;
2210 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
2211}
2212
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002213/// getFunctionDeclaration - Return debug info descriptor to describe method
2214/// declaration for the given method definition.
2215llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
2216 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
2217 if (!FD) return llvm::DISubprogram();
2218
2219 // Setup context.
2220 getContextDescriptor(cast<Decl>(D->getDeclContext()));
2221
2222 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2223 MI = SPCache.find(FD->getCanonicalDecl());
2224 if (MI != SPCache.end()) {
2225 llvm::Value *V = MI->second;
2226 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
2227 if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
2228 return SP;
2229 }
2230
2231 for (FunctionDecl::redecl_iterator I = FD->redecls_begin(),
2232 E = FD->redecls_end(); I != E; ++I) {
2233 const FunctionDecl *NextFD = *I;
2234 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2235 MI = SPCache.find(NextFD->getCanonicalDecl());
2236 if (MI != SPCache.end()) {
2237 llvm::Value *V = MI->second;
2238 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
2239 if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
2240 return SP;
2241 }
2242 }
2243 return llvm::DISubprogram();
2244}
2245
2246// getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
2247// implicit parameter "this".
David Blaikie9a845292013-05-22 23:22:42 +00002248llvm::DICompositeType CGDebugInfo::getOrCreateFunctionType(const Decl *D,
2249 QualType FnType,
2250 llvm::DIFile F) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002251
2252 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
2253 return getOrCreateMethodType(Method, F);
2254 if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
2255 // Add "self" and "_cmd"
2256 SmallVector<llvm::Value *, 16> Elts;
2257
2258 // First element is always return type. For 'void' functions it is NULL.
Adrian Prantl0cb00022013-05-22 21:37:49 +00002259 QualType ResultTy = OMethod->getResultType();
2260
2261 // Replace the instancetype keyword with the actual type.
2262 if (ResultTy == CGM.getContext().getObjCInstanceType())
2263 ResultTy = CGM.getContext().getPointerType(
2264 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
2265
Adrian Prantl566a9c32013-05-10 21:08:31 +00002266 Elts.push_back(getOrCreateType(ResultTy, F));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002267 // "self" pointer is always first argument.
Adrian Prantle86fcc42013-03-29 19:20:29 +00002268 QualType SelfDeclTy = OMethod->getSelfDecl()->getType();
2269 llvm::DIType SelfTy = getOrCreateType(SelfDeclTy, F);
2270 Elts.push_back(CreateSelfType(SelfDeclTy, SelfTy));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002271 // "_cmd" pointer is always second argument.
2272 llvm::DIType CmdTy = getOrCreateType(OMethod->getCmdDecl()->getType(), F);
2273 Elts.push_back(DBuilder.createArtificialType(CmdTy));
2274 // Get rest of the arguments.
Eric Christopher6537f082013-05-16 00:45:12 +00002275 for (ObjCMethodDecl::param_const_iterator PI = OMethod->param_begin(),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002276 PE = OMethod->param_end(); PI != PE; ++PI)
2277 Elts.push_back(getOrCreateType((*PI)->getType(), F));
2278
2279 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2280 return DBuilder.createSubroutineType(F, EltTypeArray);
2281 }
David Blaikie9a845292013-05-22 23:22:42 +00002282 return llvm::DICompositeType(getOrCreateType(FnType, F));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002283}
2284
2285/// EmitFunctionStart - Constructs the debug code for entering a function.
2286void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
2287 llvm::Function *Fn,
2288 CGBuilderTy &Builder) {
2289
2290 StringRef Name;
2291 StringRef LinkageName;
2292
2293 FnBeginRegionCount.push_back(LexicalBlockStack.size());
2294
2295 const Decl *D = GD.getDecl();
2296 // Function may lack declaration in source code if it is created by Clang
2297 // CodeGen (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
2298 bool HasDecl = (D != 0);
2299 // Use the location of the declaration.
2300 SourceLocation Loc;
2301 if (HasDecl)
2302 Loc = D->getLocation();
2303
2304 unsigned Flags = 0;
2305 llvm::DIFile Unit = getOrCreateFile(Loc);
2306 llvm::DIDescriptor FDContext(Unit);
2307 llvm::DIArray TParamsArray;
2308 if (!HasDecl) {
2309 // Use llvm function name.
2310 Name = Fn->getName();
2311 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2312 // If there is a DISubprogram for this function available then use it.
2313 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2314 FI = SPCache.find(FD->getCanonicalDecl());
2315 if (FI != SPCache.end()) {
2316 llvm::Value *V = FI->second;
2317 llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(V));
2318 if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
2319 llvm::MDNode *SPN = SP;
2320 LexicalBlockStack.push_back(SPN);
2321 RegionMap[D] = llvm::WeakVH(SP);
2322 return;
2323 }
2324 }
2325 Name = getFunctionName(FD);
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002326 // Use mangled name as linkage name for C/C++ functions.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002327 if (FD->hasPrototype()) {
2328 LinkageName = CGM.getMangledName(GD);
2329 Flags |= llvm::DIDescriptor::FlagPrototyped;
2330 }
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002331 // No need to replicate the linkage name if it isn't different from the
2332 // subprogram name, no need to have it at all unless coverage is enabled or
2333 // debug is set to more than just line tables.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002334 if (LinkageName == Name ||
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002335 (!CGM.getCodeGenOpts().EmitGcovArcs &&
2336 !CGM.getCodeGenOpts().EmitGcovNotes &&
Eric Christopher13c97672013-05-16 00:45:23 +00002337 DebugKind <= CodeGenOptions::DebugLineTablesOnly))
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002338 LinkageName = StringRef();
2339
Eric Christopher13c97672013-05-16 00:45:23 +00002340 if (DebugKind >= CodeGenOptions::LimitedDebugInfo) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002341 if (const NamespaceDecl *NSDecl =
2342 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
2343 FDContext = getOrCreateNameSpace(NSDecl);
2344 else if (const RecordDecl *RDecl =
2345 dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
2346 FDContext = getContextDescriptor(cast<Decl>(RDecl->getDeclContext()));
2347
2348 // Collect template parameters.
2349 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
2350 }
2351 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
2352 Name = getObjCMethodName(OMD);
2353 Flags |= llvm::DIDescriptor::FlagPrototyped;
2354 } else {
2355 // Use llvm function name.
2356 Name = Fn->getName();
2357 Flags |= llvm::DIDescriptor::FlagPrototyped;
2358 }
2359 if (!Name.empty() && Name[0] == '\01')
2360 Name = Name.substr(1);
2361
2362 unsigned LineNo = getLineNumber(Loc);
2363 if (!HasDecl || D->isImplicit())
2364 Flags |= llvm::DIDescriptor::FlagArtificial;
2365
David Blaikie9a845292013-05-22 23:22:42 +00002366 llvm::DICompositeType DIFnType;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002367 llvm::DISubprogram SPDecl;
2368 if (HasDecl &&
Eric Christopher13c97672013-05-16 00:45:23 +00002369 DebugKind >= CodeGenOptions::LimitedDebugInfo) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002370 DIFnType = getOrCreateFunctionType(D, FnType, Unit);
2371 SPDecl = getFunctionDeclaration(D);
2372 } else {
2373 // Create fake but valid subroutine type. Otherwise
2374 // llvm::DISubprogram::Verify() would return false, and
2375 // subprogram DIE will miss DW_AT_decl_file and
2376 // DW_AT_decl_line fields.
2377 SmallVector<llvm::Value*, 16> Elts;
2378 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2379 DIFnType = DBuilder.createSubroutineType(Unit, EltTypeArray);
2380 }
2381 llvm::DISubprogram SP;
2382 SP = DBuilder.createFunction(FDContext, Name, LinkageName, Unit,
2383 LineNo, DIFnType,
2384 Fn->hasInternalLinkage(), true/*definition*/,
2385 getLineNumber(CurLoc), Flags,
2386 CGM.getLangOpts().Optimize,
2387 Fn, TParamsArray, SPDecl);
David Blaikie9faebd22013-05-20 04:58:53 +00002388 if (HasDecl)
2389 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(SP)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002390
2391 // Push function on region stack.
2392 llvm::MDNode *SPN = SP;
2393 LexicalBlockStack.push_back(SPN);
2394 if (HasDecl)
2395 RegionMap[D] = llvm::WeakVH(SP);
2396}
2397
2398/// EmitLocation - Emit metadata to indicate a change in line/column
2399/// information in the source file.
Adrian Prantl00df5ea2013-03-12 20:43:25 +00002400void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc,
2401 bool ForceColumnInfo) {
Eric Christopher6537f082013-05-16 00:45:12 +00002402
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002403 // Update our current location
2404 setLocation(Loc);
2405
2406 if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
2407
2408 // Don't bother if things are the same as last time.
2409 SourceManager &SM = CGM.getContext().getSourceManager();
2410 if (CurLoc == PrevLoc ||
2411 SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc))
2412 // New Builder may not be in sync with CGDebugInfo.
David Blaikie0a0f93c2013-02-01 19:09:49 +00002413 if (!Builder.getCurrentDebugLocation().isUnknown() &&
2414 Builder.getCurrentDebugLocation().getScope(CGM.getLLVMContext()) ==
2415 LexicalBlockStack.back())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002416 return;
Eric Christopher6537f082013-05-16 00:45:12 +00002417
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002418 // Update last state.
2419 PrevLoc = CurLoc;
2420
2421 llvm::MDNode *Scope = LexicalBlockStack.back();
Adrian Prantl00df5ea2013-03-12 20:43:25 +00002422 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get
2423 (getLineNumber(CurLoc),
2424 getColumnNumber(CurLoc, ForceColumnInfo),
2425 Scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002426}
2427
2428/// CreateLexicalBlock - Creates a new lexical block node and pushes it on
2429/// the stack.
2430void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
2431 llvm::DIDescriptor D =
2432 DBuilder.createLexicalBlock(LexicalBlockStack.empty() ?
2433 llvm::DIDescriptor() :
2434 llvm::DIDescriptor(LexicalBlockStack.back()),
2435 getOrCreateFile(CurLoc),
2436 getLineNumber(CurLoc),
2437 getColumnNumber(CurLoc));
2438 llvm::MDNode *DN = D;
2439 LexicalBlockStack.push_back(DN);
2440}
2441
2442/// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
2443/// region - beginning of a DW_TAG_lexical_block.
Eric Christopherf0890c42013-05-16 00:52:20 +00002444void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
2445 SourceLocation Loc) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002446 // Set our current location.
2447 setLocation(Loc);
2448
2449 // Create a new lexical block and push it on the stack.
2450 CreateLexicalBlock(Loc);
2451
2452 // Emit a line table change for the current location inside the new scope.
2453 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc),
2454 getColumnNumber(Loc),
2455 LexicalBlockStack.back()));
2456}
2457
2458/// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative
2459/// region - end of a DW_TAG_lexical_block.
Eric Christopherf0890c42013-05-16 00:52:20 +00002460void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
2461 SourceLocation Loc) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002462 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2463
2464 // Provide an entry in the line table for the end of the block.
2465 EmitLocation(Builder, Loc);
2466
2467 LexicalBlockStack.pop_back();
2468}
2469
2470/// EmitFunctionEnd - Constructs the debug code for exiting a function.
2471void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
2472 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2473 unsigned RCount = FnBeginRegionCount.back();
2474 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
2475
2476 // Pop all regions for this function.
2477 while (LexicalBlockStack.size() != RCount)
2478 EmitLexicalBlockEnd(Builder, CurLoc);
2479 FnBeginRegionCount.pop_back();
2480}
2481
Eric Christopher6537f082013-05-16 00:45:12 +00002482// EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002483// See BuildByRefType.
2484llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
2485 uint64_t *XOffset) {
2486
2487 SmallVector<llvm::Value *, 5> EltTys;
2488 QualType FType;
2489 uint64_t FieldSize, FieldOffset;
2490 unsigned FieldAlign;
Eric Christopher6537f082013-05-16 00:45:12 +00002491
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002492 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
Eric Christopher6537f082013-05-16 00:45:12 +00002493 QualType Type = VD->getType();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002494
2495 FieldOffset = 0;
2496 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2497 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
2498 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
2499 FType = CGM.getContext().IntTy;
2500 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
2501 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
2502
2503 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
2504 if (HasCopyAndDispose) {
2505 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2506 EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
2507 &FieldOffset));
2508 EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
2509 &FieldOffset));
2510 }
2511 bool HasByrefExtendedLayout;
2512 Qualifiers::ObjCLifetime Lifetime;
2513 if (CGM.getContext().getByrefLifetime(Type,
2514 Lifetime, HasByrefExtendedLayout)
2515 && HasByrefExtendedLayout)
2516 EltTys.push_back(CreateMemberType(Unit, FType,
2517 "__byref_variable_layout",
2518 &FieldOffset));
Eric Christopher6537f082013-05-16 00:45:12 +00002519
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002520 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2521 if (Align > CGM.getContext().toCharUnitsFromBits(
John McCall64aa4b32013-04-16 22:48:15 +00002522 CGM.getTarget().getPointerAlign(0))) {
Eric Christopher6537f082013-05-16 00:45:12 +00002523 CharUnits FieldOffsetInBytes
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002524 = CGM.getContext().toCharUnitsFromBits(FieldOffset);
2525 CharUnits AlignedOffsetInBytes
2526 = FieldOffsetInBytes.RoundUpToAlignment(Align);
2527 CharUnits NumPaddingBytes
2528 = AlignedOffsetInBytes - FieldOffsetInBytes;
Eric Christopher6537f082013-05-16 00:45:12 +00002529
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002530 if (NumPaddingBytes.isPositive()) {
2531 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
2532 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
2533 pad, ArrayType::Normal, 0);
2534 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
2535 }
2536 }
Eric Christopher6537f082013-05-16 00:45:12 +00002537
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002538 FType = Type;
2539 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2540 FieldSize = CGM.getContext().getTypeSize(FType);
2541 FieldAlign = CGM.getContext().toBits(Align);
2542
Eric Christopher6537f082013-05-16 00:45:12 +00002543 *XOffset = FieldOffset;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002544 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit,
2545 0, FieldSize, FieldAlign,
2546 FieldOffset, 0, FieldTy);
2547 EltTys.push_back(FieldTy);
2548 FieldOffset += FieldSize;
Eric Christopher6537f082013-05-16 00:45:12 +00002549
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002550 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopher6537f082013-05-16 00:45:12 +00002551
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002552 unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
Eric Christopher6537f082013-05-16 00:45:12 +00002553
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002554 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
David Blaikiec1d0af12013-02-25 01:07:08 +00002555 llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002556}
2557
2558/// EmitDeclare - Emit local variable declaration debug info.
2559void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
Eric Christopher6537f082013-05-16 00:45:12 +00002560 llvm::Value *Storage,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002561 unsigned ArgNo, CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002562 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002563 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2564
2565 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2566 llvm::DIType Ty;
2567 uint64_t XOffset = 0;
2568 if (VD->hasAttr<BlocksAttr>())
2569 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopher6537f082013-05-16 00:45:12 +00002570 else
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002571 Ty = getOrCreateType(VD->getType(), Unit);
2572
2573 // If there is no debug info for this type then do not emit debug info
2574 // for this variable.
2575 if (!Ty)
2576 return;
2577
2578 if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage)) {
2579 // If Storage is an aggregate returned as 'sret' then let debugger know
2580 // about this.
2581 if (Arg->hasStructRetAttr())
2582 Ty = DBuilder.createReferenceType(llvm::dwarf::DW_TAG_reference_type, Ty);
2583 else if (CXXRecordDecl *Record = VD->getType()->getAsCXXRecordDecl()) {
2584 // If an aggregate variable has non trivial destructor or non trivial copy
2585 // constructor than it is pass indirectly. Let debug info know about this
2586 // by using reference of the aggregate type as a argument type.
2587 if (Record->hasNonTrivialCopyConstructor() ||
2588 !Record->hasTrivialDestructor())
Eric Christopherf0890c42013-05-16 00:52:20 +00002589 Ty = DBuilder.createReferenceType(llvm::dwarf::DW_TAG_reference_type,
2590 Ty);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002591 }
2592 }
Eric Christopher6537f082013-05-16 00:45:12 +00002593
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002594 // Get location information.
2595 unsigned Line = getLineNumber(VD->getLocation());
2596 unsigned Column = getColumnNumber(VD->getLocation());
2597 unsigned Flags = 0;
2598 if (VD->isImplicit())
2599 Flags |= llvm::DIDescriptor::FlagArtificial;
2600 // If this is the first argument and it is implicit then
2601 // give it an object pointer flag.
2602 // FIXME: There has to be a better way to do this, but for static
2603 // functions there won't be an implicit param at arg1 and
2604 // otherwise it is 'self' or 'this'.
2605 if (isa<ImplicitParamDecl>(VD) && ArgNo == 1)
2606 Flags |= llvm::DIDescriptor::FlagObjectPointer;
2607
2608 llvm::MDNode *Scope = LexicalBlockStack.back();
2609
2610 StringRef Name = VD->getName();
2611 if (!Name.empty()) {
2612 if (VD->hasAttr<BlocksAttr>()) {
2613 CharUnits offset = CharUnits::fromQuantity(32);
2614 SmallVector<llvm::Value *, 9> addr;
2615 llvm::Type *Int64Ty = CGM.Int64Ty;
2616 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2617 // offset of __forwarding field
2618 offset = CGM.getContext().toCharUnitsFromBits(
John McCall64aa4b32013-04-16 22:48:15 +00002619 CGM.getTarget().getPointerWidth(0));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002620 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2621 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2622 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2623 // offset of x field
2624 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2625 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2626
2627 // Create the descriptor for the variable.
2628 llvm::DIVariable D =
Eric Christopher6537f082013-05-16 00:45:12 +00002629 DBuilder.createComplexVariable(Tag,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002630 llvm::DIDescriptor(Scope),
2631 VD->getName(), Unit, Line, Ty,
2632 addr, ArgNo);
Eric Christopher6537f082013-05-16 00:45:12 +00002633
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002634 // Insert an llvm.dbg.declare into the current block.
2635 llvm::Instruction *Call =
2636 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2637 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2638 return;
Adrian Prantl230ea412013-04-30 22:45:09 +00002639 } else if (isa<VariableArrayType>(VD->getType())) {
2640 // These are "complex" variables in that they need an op_deref.
2641 // Create the descriptor for the variable.
2642 llvm::Value *Addr = llvm::ConstantInt::get(CGM.Int64Ty,
2643 llvm::DIBuilder::OpDeref);
2644 llvm::DIVariable D =
2645 DBuilder.createComplexVariable(Tag,
2646 llvm::DIDescriptor(Scope),
2647 Name, Unit, Line, Ty,
2648 Addr, ArgNo);
2649
2650 // Insert an llvm.dbg.declare into the current block.
2651 llvm::Instruction *Call =
2652 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2653 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2654 return;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002655 }
David Blaikie436653b2013-01-05 05:58:35 +00002656 } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2657 // If VD is an anonymous union then Storage represents value for
2658 // all union fields.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002659 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
David Blaikied8180cf2013-01-05 20:03:07 +00002660 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002661 for (RecordDecl::field_iterator I = RD->field_begin(),
2662 E = RD->field_end();
2663 I != E; ++I) {
2664 FieldDecl *Field = *I;
2665 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2666 StringRef FieldName = Field->getName();
Eric Christopher6537f082013-05-16 00:45:12 +00002667
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002668 // Ignore unnamed fields. Do not ignore unnamed records.
2669 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2670 continue;
Eric Christopher6537f082013-05-16 00:45:12 +00002671
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002672 // Use VarDecl's Tag, Scope and Line number.
2673 llvm::DIVariable D =
2674 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
Eric Christopher6537f082013-05-16 00:45:12 +00002675 FieldName, Unit, Line, FieldTy,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002676 CGM.getLangOpts().Optimize, Flags,
2677 ArgNo);
Eric Christopher6537f082013-05-16 00:45:12 +00002678
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002679 // Insert an llvm.dbg.declare into the current block.
2680 llvm::Instruction *Call =
2681 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2682 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2683 }
David Blaikied8180cf2013-01-05 20:03:07 +00002684 return;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002685 }
2686 }
David Blaikie436653b2013-01-05 05:58:35 +00002687
2688 // Create the descriptor for the variable.
2689 llvm::DIVariable D =
2690 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2691 Name, Unit, Line, Ty,
2692 CGM.getLangOpts().Optimize, Flags, ArgNo);
2693
2694 // Insert an llvm.dbg.declare into the current block.
2695 llvm::Instruction *Call =
2696 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2697 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002698}
2699
2700void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2701 llvm::Value *Storage,
2702 CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002703 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002704 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2705}
2706
Adrian Prantle86fcc42013-03-29 19:20:29 +00002707/// Look up the completed type for a self pointer in the TypeCache and
2708/// create a copy of it with the ObjectPointer and Artificial flags
2709/// set. If the type is not cached, a new one is created. This should
2710/// never happen though, since creating a type for the implicit self
2711/// argument implies that we already parsed the interface definition
2712/// and the ivar declarations in the implementation.
Eric Christopherf0890c42013-05-16 00:52:20 +00002713llvm::DIType CGDebugInfo::CreateSelfType(const QualType &QualTy,
2714 llvm::DIType Ty) {
Adrian Prantle86fcc42013-03-29 19:20:29 +00002715 llvm::DIType CachedTy = getTypeOrNull(QualTy);
2716 if (CachedTy.Verify()) Ty = CachedTy;
2717 else DEBUG(llvm::dbgs() << "No cached type for self.");
2718 return DBuilder.createObjectPointerType(Ty);
2719}
2720
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002721void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(const VarDecl *VD,
2722 llvm::Value *Storage,
2723 CGBuilderTy &Builder,
2724 const CGBlockInfo &blockInfo) {
Eric Christopher13c97672013-05-16 00:45:23 +00002725 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002726 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
Eric Christopher6537f082013-05-16 00:45:12 +00002727
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002728 if (Builder.GetInsertBlock() == 0)
2729 return;
Eric Christopher6537f082013-05-16 00:45:12 +00002730
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002731 bool isByRef = VD->hasAttr<BlocksAttr>();
Eric Christopher6537f082013-05-16 00:45:12 +00002732
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002733 uint64_t XOffset = 0;
2734 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2735 llvm::DIType Ty;
2736 if (isByRef)
2737 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopher6537f082013-05-16 00:45:12 +00002738 else
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002739 Ty = getOrCreateType(VD->getType(), Unit);
2740
2741 // Self is passed along as an implicit non-arg variable in a
2742 // block. Mark it as the object pointer.
2743 if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self")
Adrian Prantle86fcc42013-03-29 19:20:29 +00002744 Ty = CreateSelfType(VD->getType(), Ty);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002745
2746 // Get location information.
2747 unsigned Line = getLineNumber(VD->getLocation());
2748 unsigned Column = getColumnNumber(VD->getLocation());
2749
2750 const llvm::DataLayout &target = CGM.getDataLayout();
2751
2752 CharUnits offset = CharUnits::fromQuantity(
2753 target.getStructLayout(blockInfo.StructureType)
2754 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2755
2756 SmallVector<llvm::Value *, 9> addr;
2757 llvm::Type *Int64Ty = CGM.Int64Ty;
Adrian Prantl9b97adf2013-03-29 19:20:35 +00002758 if (isa<llvm::AllocaInst>(Storage))
2759 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002760 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2761 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2762 if (isByRef) {
2763 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2764 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2765 // offset of __forwarding field
2766 offset = CGM.getContext()
2767 .toCharUnitsFromBits(target.getPointerSizeInBits(0));
2768 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2769 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2770 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2771 // offset of x field
2772 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2773 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2774 }
2775
2776 // Create the descriptor for the variable.
2777 llvm::DIVariable D =
Eric Christopher6537f082013-05-16 00:45:12 +00002778 DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002779 llvm::DIDescriptor(LexicalBlockStack.back()),
2780 VD->getName(), Unit, Line, Ty, addr);
Adrian Prantl9b97adf2013-03-29 19:20:35 +00002781
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002782 // Insert an llvm.dbg.declare into the current block.
2783 llvm::Instruction *Call =
2784 DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
2785 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column,
2786 LexicalBlockStack.back()));
2787}
2788
2789/// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2790/// variable declaration.
2791void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2792 unsigned ArgNo,
2793 CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002794 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002795 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2796}
2797
2798namespace {
2799 struct BlockLayoutChunk {
2800 uint64_t OffsetInBits;
2801 const BlockDecl::Capture *Capture;
2802 };
2803 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2804 return l.OffsetInBits < r.OffsetInBits;
2805 }
2806}
2807
2808void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
Adrian Prantl836e7c92013-03-14 17:53:33 +00002809 llvm::Value *Arg,
2810 llvm::Value *LocalAddr,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002811 CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002812 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002813 ASTContext &C = CGM.getContext();
2814 const BlockDecl *blockDecl = block.getBlockDecl();
2815
2816 // Collect some general information about the block's location.
2817 SourceLocation loc = blockDecl->getCaretLocation();
2818 llvm::DIFile tunit = getOrCreateFile(loc);
2819 unsigned line = getLineNumber(loc);
2820 unsigned column = getColumnNumber(loc);
Eric Christopher6537f082013-05-16 00:45:12 +00002821
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002822 // Build the debug-info type for the block literal.
2823 getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
2824
2825 const llvm::StructLayout *blockLayout =
2826 CGM.getDataLayout().getStructLayout(block.StructureType);
2827
2828 SmallVector<llvm::Value*, 16> fields;
2829 fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
2830 blockLayout->getElementOffsetInBits(0),
2831 tunit, tunit));
2832 fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
2833 blockLayout->getElementOffsetInBits(1),
2834 tunit, tunit));
2835 fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
2836 blockLayout->getElementOffsetInBits(2),
2837 tunit, tunit));
2838 fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
2839 blockLayout->getElementOffsetInBits(3),
2840 tunit, tunit));
2841 fields.push_back(createFieldType("__descriptor",
2842 C.getPointerType(block.NeedsCopyDispose ?
2843 C.getBlockDescriptorExtendedType() :
2844 C.getBlockDescriptorType()),
2845 0, loc, AS_public,
2846 blockLayout->getElementOffsetInBits(4),
2847 tunit, tunit));
2848
2849 // We want to sort the captures by offset, not because DWARF
2850 // requires this, but because we're paranoid about debuggers.
2851 SmallVector<BlockLayoutChunk, 8> chunks;
2852
2853 // 'this' capture.
2854 if (blockDecl->capturesCXXThis()) {
2855 BlockLayoutChunk chunk;
2856 chunk.OffsetInBits =
2857 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
2858 chunk.Capture = 0;
2859 chunks.push_back(chunk);
2860 }
2861
2862 // Variable captures.
2863 for (BlockDecl::capture_const_iterator
2864 i = blockDecl->capture_begin(), e = blockDecl->capture_end();
2865 i != e; ++i) {
2866 const BlockDecl::Capture &capture = *i;
2867 const VarDecl *variable = capture.getVariable();
2868 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
2869
2870 // Ignore constant captures.
2871 if (captureInfo.isConstant())
2872 continue;
2873
2874 BlockLayoutChunk chunk;
2875 chunk.OffsetInBits =
2876 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
2877 chunk.Capture = &capture;
2878 chunks.push_back(chunk);
2879 }
2880
2881 // Sort by offset.
2882 llvm::array_pod_sort(chunks.begin(), chunks.end());
2883
2884 for (SmallVectorImpl<BlockLayoutChunk>::iterator
2885 i = chunks.begin(), e = chunks.end(); i != e; ++i) {
2886 uint64_t offsetInBits = i->OffsetInBits;
2887 const BlockDecl::Capture *capture = i->Capture;
2888
2889 // If we have a null capture, this must be the C++ 'this' capture.
2890 if (!capture) {
2891 const CXXMethodDecl *method =
2892 cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
2893 QualType type = method->getThisType(C);
2894
2895 fields.push_back(createFieldType("this", type, 0, loc, AS_public,
2896 offsetInBits, tunit, tunit));
2897 continue;
2898 }
2899
2900 const VarDecl *variable = capture->getVariable();
2901 StringRef name = variable->getName();
2902
2903 llvm::DIType fieldType;
2904 if (capture->isByRef()) {
2905 std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
2906
2907 // FIXME: this creates a second copy of this type!
2908 uint64_t xoffset;
2909 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
2910 fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
2911 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
2912 ptrInfo.first, ptrInfo.second,
2913 offsetInBits, 0, fieldType);
2914 } else {
2915 fieldType = createFieldType(name, variable->getType(), 0,
2916 loc, AS_public, offsetInBits, tunit, tunit);
2917 }
2918 fields.push_back(fieldType);
2919 }
2920
2921 SmallString<36> typeName;
2922 llvm::raw_svector_ostream(typeName)
2923 << "__block_literal_" << CGM.getUniqueBlockCount();
2924
2925 llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
2926
2927 llvm::DIType type =
2928 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
2929 CGM.getContext().toBits(block.BlockSize),
2930 CGM.getContext().toBits(block.BlockAlign),
David Blaikiec1d0af12013-02-25 01:07:08 +00002931 0, llvm::DIType(), fieldsArray);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002932 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
2933
2934 // Get overall information about the block.
2935 unsigned flags = llvm::DIDescriptor::FlagArtificial;
2936 llvm::MDNode *scope = LexicalBlockStack.back();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002937
2938 // Create the descriptor for the parameter.
2939 llvm::DIVariable debugVar =
2940 DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
Eric Christopher6537f082013-05-16 00:45:12 +00002941 llvm::DIDescriptor(scope),
Adrian Prantl836e7c92013-03-14 17:53:33 +00002942 Arg->getName(), tunit, line, type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002943 CGM.getLangOpts().Optimize, flags,
Adrian Prantl836e7c92013-03-14 17:53:33 +00002944 cast<llvm::Argument>(Arg)->getArgNo() + 1);
2945
Adrian Prantlbea407c2013-03-14 21:52:59 +00002946 if (LocalAddr) {
Adrian Prantl836e7c92013-03-14 17:53:33 +00002947 // Insert an llvm.dbg.value into the current block.
Adrian Prantlbea407c2013-03-14 21:52:59 +00002948 llvm::Instruction *DbgVal =
2949 DBuilder.insertDbgValueIntrinsic(LocalAddr, 0, debugVar,
Eric Christopherf068c922013-04-02 22:59:11 +00002950 Builder.GetInsertBlock());
Adrian Prantlbea407c2013-03-14 21:52:59 +00002951 DbgVal->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
2952 }
Adrian Prantl836e7c92013-03-14 17:53:33 +00002953
Adrian Prantlbea407c2013-03-14 21:52:59 +00002954 // Insert an llvm.dbg.declare into the current block.
2955 llvm::Instruction *DbgDecl =
2956 DBuilder.insertDeclare(Arg, debugVar, Builder.GetInsertBlock());
2957 DbgDecl->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002958}
2959
Eric Christopher0395de32013-01-16 01:22:32 +00002960/// getStaticDataMemberDeclaration - If D is an out-of-class definition of
2961/// a static data member of a class, find its corresponding in-class
2962/// declaration.
2963llvm::DIDerivedType CGDebugInfo::getStaticDataMemberDeclaration(const Decl *D) {
2964 if (cast<VarDecl>(D)->isStaticDataMember()) {
2965 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
2966 MI = StaticDataMemberCache.find(D->getCanonicalDecl());
2967 if (MI != StaticDataMemberCache.end())
2968 // Verify the info still exists.
2969 if (llvm::Value *V = MI->second)
2970 return llvm::DIDerivedType(cast<llvm::MDNode>(V));
2971 }
2972 return llvm::DIDerivedType();
2973}
2974
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002975/// EmitGlobalVariable - Emit information about a global variable.
2976void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
2977 const VarDecl *D) {
Eric Christopher13c97672013-05-16 00:45:23 +00002978 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002979 // Create global variable debug descriptor.
2980 llvm::DIFile Unit = getOrCreateFile(D->getLocation());
2981 unsigned LineNo = getLineNumber(D->getLocation());
2982
2983 setLocation(D->getLocation());
2984
2985 QualType T = D->getType();
2986 if (T->isIncompleteArrayType()) {
2987
2988 // CodeGen turns int[] into int[1] so we'll do the same here.
2989 llvm::APInt ConstVal(32, 1);
2990 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
2991
2992 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
2993 ArrayType::Normal, 0);
2994 }
2995 StringRef DeclName = D->getName();
2996 StringRef LinkageName;
2997 if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext())
2998 && !isa<ObjCMethodDecl>(D->getDeclContext()))
2999 LinkageName = Var->getName();
3000 if (LinkageName == DeclName)
3001 LinkageName = StringRef();
Eric Christopher6537f082013-05-16 00:45:12 +00003002 llvm::DIDescriptor DContext =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003003 getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
David Blaikie9faebd22013-05-20 04:58:53 +00003004 llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(DContext, DeclName, LinkageName,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003005 Unit, LineNo, getOrCreateType(T, Unit),
Eric Christopher0395de32013-01-16 01:22:32 +00003006 Var->hasInternalLinkage(), Var,
3007 getStaticDataMemberDeclaration(D));
David Blaikie9faebd22013-05-20 04:58:53 +00003008 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(GV)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003009}
3010
3011/// EmitGlobalVariable - Emit information about an objective-c interface.
3012void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
3013 ObjCInterfaceDecl *ID) {
Eric Christopher13c97672013-05-16 00:45:23 +00003014 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003015 // Create global variable debug descriptor.
3016 llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
3017 unsigned LineNo = getLineNumber(ID->getLocation());
3018
3019 StringRef Name = ID->getName();
3020
3021 QualType T = CGM.getContext().getObjCInterfaceType(ID);
3022 if (T->isIncompleteArrayType()) {
3023
3024 // CodeGen turns int[] into int[1] so we'll do the same here.
3025 llvm::APInt ConstVal(32, 1);
3026 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3027
3028 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3029 ArrayType::Normal, 0);
3030 }
3031
3032 DBuilder.createGlobalVariable(Name, Unit, LineNo,
3033 getOrCreateType(T, Unit),
3034 Var->hasInternalLinkage(), Var);
3035}
3036
3037/// EmitGlobalVariable - Emit global variable's debug info.
Eric Christopher6537f082013-05-16 00:45:12 +00003038void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003039 llvm::Constant *Init) {
Eric Christopher13c97672013-05-16 00:45:23 +00003040 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003041 // Create the descriptor for the variable.
3042 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
3043 StringRef Name = VD->getName();
3044 llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
3045 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
3046 const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext());
3047 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
3048 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
3049 }
3050 // Do not use DIGlobalVariable for enums.
3051 if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
3052 return;
David Blaikie9faebd22013-05-20 04:58:53 +00003053 llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(Unit, Name, Name, Unit,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003054 getLineNumber(VD->getLocation()),
Eric Christopher0395de32013-01-16 01:22:32 +00003055 Ty, true, Init,
3056 getStaticDataMemberDeclaration(VD));
David Blaikie9faebd22013-05-20 04:58:53 +00003057 DeclCache.insert(std::make_pair(VD->getCanonicalDecl(), llvm::WeakVH(GV)));
3058}
3059
3060llvm::DIScope CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
3061 if (!LexicalBlockStack.empty())
3062 return llvm::DIScope(LexicalBlockStack.back());
3063 return getContextDescriptor(D);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003064}
3065
David Blaikie957dac52013-04-22 06:13:21 +00003066void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
David Blaikie9faebd22013-05-20 04:58:53 +00003067 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3068 return;
David Blaikie957dac52013-04-22 06:13:21 +00003069 DBuilder.createImportedModule(
David Blaikie9faebd22013-05-20 04:58:53 +00003070 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
3071 getOrCreateNameSpace(UD.getNominatedNamespace()),
David Blaikie957dac52013-04-22 06:13:21 +00003072 getLineNumber(UD.getLocation()));
3073}
3074
David Blaikie9faebd22013-05-20 04:58:53 +00003075void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
3076 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3077 return;
3078 assert(UD.shadow_size() &&
3079 "We shouldn't be codegening an invalid UsingDecl containing no decls");
3080 // Emitting one decl is sufficient - debuggers can detect that this is an
3081 // overloaded name & provide lookup for all the overloads.
3082 const UsingShadowDecl &USD = **UD.shadow_begin();
3083 if (llvm::DIDescriptor Target = getDeclarationOrDefinition(USD.getUnderlyingDecl()))
3084 DBuilder.createImportedDeclaration(
3085 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
3086 getLineNumber(USD.getLocation()));
3087}
3088
David Blaikiefc46ebc2013-05-20 22:50:41 +00003089llvm::DIImportedEntity
3090CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
3091 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3092 return llvm::DIImportedEntity(0);
3093 llvm::WeakVH &VH = NamespaceAliasCache[&NA];
3094 if (VH)
3095 return llvm::DIImportedEntity(cast<llvm::MDNode>(VH));
3096 llvm::DIImportedEntity R(0);
3097 if (const NamespaceAliasDecl *Underlying =
3098 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
3099 // This could cache & dedup here rather than relying on metadata deduping.
3100 R = DBuilder.createImportedModule(
3101 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3102 EmitNamespaceAlias(*Underlying), getLineNumber(NA.getLocation()),
3103 NA.getName());
3104 else
3105 R = DBuilder.createImportedModule(
3106 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3107 getOrCreateNameSpace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
3108 getLineNumber(NA.getLocation()), NA.getName());
3109 VH = R;
3110 return R;
3111}
3112
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003113/// getOrCreateNamesSpace - Return namespace descriptor for the given
3114/// namespace decl.
Eric Christopher6537f082013-05-16 00:45:12 +00003115llvm::DINameSpace
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003116CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
Eric Christopher6537f082013-05-16 00:45:12 +00003117 llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003118 NameSpaceCache.find(NSDecl);
3119 if (I != NameSpaceCache.end())
3120 return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
Eric Christopher6537f082013-05-16 00:45:12 +00003121
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003122 unsigned LineNo = getLineNumber(NSDecl->getLocation());
3123 llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
Eric Christopher6537f082013-05-16 00:45:12 +00003124 llvm::DIDescriptor Context =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003125 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
3126 llvm::DINameSpace NS =
3127 DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
3128 NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
3129 return NS;
3130}
3131
3132void CGDebugInfo::finalize() {
3133 for (std::vector<std::pair<void *, llvm::WeakVH> >::const_iterator VI
3134 = ReplaceMap.begin(), VE = ReplaceMap.end(); VI != VE; ++VI) {
3135 llvm::DIType Ty, RepTy;
3136 // Verify that the debug info still exists.
3137 if (llvm::Value *V = VI->second)
3138 Ty = llvm::DIType(cast<llvm::MDNode>(V));
Eric Christopher6537f082013-05-16 00:45:12 +00003139
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003140 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
3141 TypeCache.find(VI->first);
3142 if (it != TypeCache.end()) {
3143 // Verify that the debug info still exists.
3144 if (llvm::Value *V = it->second)
3145 RepTy = llvm::DIType(cast<llvm::MDNode>(V));
3146 }
Adrian Prantlebbd7e02013-03-11 18:33:46 +00003147
Adrian Prantl9b97adf2013-03-29 19:20:35 +00003148 if (Ty.Verify() && Ty.isForwardDecl() && RepTy.Verify())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003149 Ty.replaceAllUsesWith(RepTy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003150 }
Adrian Prantlebbd7e02013-03-11 18:33:46 +00003151
3152 // We keep our own list of retained types, because we need to look
3153 // up the final type in the type cache.
3154 for (std::vector<void *>::const_iterator RI = RetainedTypes.begin(),
3155 RE = RetainedTypes.end(); RI != RE; ++RI)
3156 DBuilder.retainType(llvm::DIType(cast<llvm::MDNode>(TypeCache[*RI])));
3157
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003158 DBuilder.finalize();
3159}