blob: c1d095ddd6c62fc5a0cbeecd511b688b92671317 [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
David Blaikieb0f77b02013-05-24 21:33:22 +0000610/// getOrCreateTypeDeclaration - Create Pointee type. If Pointee is a record
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000611/// then emit record's fwd if debug info size reduction is enabled.
David Blaikieb0f77b02013-05-24 21:33:22 +0000612llvm::DIType CGDebugInfo::getOrCreateTypeDeclaration(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)
David Blaikieb0f77b02013-05-24 21:33:22 +0000645 return DBuilder.createReferenceType(
646 Tag, getOrCreateTypeDeclaration(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
David Blaikieb0f77b02013-05-24 21:33:22 +0000655 return DBuilder.createPointerType(getOrCreateTypeDeclaration(PointeeTy, Unit),
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000656 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 Blaikieb0f77b02013-05-24 21:33:22 +0000736 llvm::DIType Src =
737 getOrCreateTypeDeclaration(Ty->getDecl()->getUnderlyingType(), Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000738 if (!Src.Verify())
739 return llvm::DIType();
740 // We don't set size information, but do specify where the typedef was
741 // declared.
742 unsigned Line = getLineNumber(Ty->getDecl()->getLocation());
743 const TypedefNameDecl *TyDecl = Ty->getDecl();
Eric Christopher6537f082013-05-16 00:45:12 +0000744
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000745 llvm::DIDescriptor TypedefContext =
746 getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext()));
Eric Christopher6537f082013-05-16 00:45:12 +0000747
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000748 return
749 DBuilder.createTypedef(Src, TyDecl->getName(), Unit, Line, TypedefContext);
750}
751
752llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
753 llvm::DIFile Unit) {
754 SmallVector<llvm::Value *, 16> EltTys;
755
756 // Add the result type at least.
757 EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit));
758
759 // Set up remainder of arguments if there is a prototype.
760 // FIXME: IF NOT, HOW IS THIS REPRESENTED? llvm-gcc doesn't represent '...'!
761 if (isa<FunctionNoProtoType>(Ty))
762 EltTys.push_back(DBuilder.createUnspecifiedParameter());
763 else if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Ty)) {
764 for (unsigned i = 0, e = FPT->getNumArgs(); i != e; ++i)
765 EltTys.push_back(getOrCreateType(FPT->getArgType(i), Unit));
766 }
767
768 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
769 return DBuilder.createSubroutineType(Unit, EltTypeArray);
770}
771
772
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000773llvm::DIType CGDebugInfo::createFieldType(StringRef name,
774 QualType type,
775 uint64_t sizeInBitsOverride,
776 SourceLocation loc,
777 AccessSpecifier AS,
778 uint64_t offsetInBits,
779 llvm::DIFile tunit,
780 llvm::DIDescriptor scope) {
781 llvm::DIType debugType = getOrCreateType(type, tunit);
782
783 // Get the location for the field.
784 llvm::DIFile file = getOrCreateFile(loc);
785 unsigned line = getLineNumber(loc);
786
787 uint64_t sizeInBits = 0;
788 unsigned alignInBits = 0;
789 if (!type->isIncompleteArrayType()) {
790 llvm::tie(sizeInBits, alignInBits) = CGM.getContext().getTypeInfo(type);
791
792 if (sizeInBitsOverride)
793 sizeInBits = sizeInBitsOverride;
794 }
795
796 unsigned flags = 0;
797 if (AS == clang::AS_private)
798 flags |= llvm::DIDescriptor::FlagPrivate;
799 else if (AS == clang::AS_protected)
800 flags |= llvm::DIDescriptor::FlagProtected;
801
802 return DBuilder.createMemberType(scope, name, file, line, sizeInBits,
803 alignInBits, offsetInBits, flags, debugType);
804}
805
Eric Christopher0395de32013-01-16 01:22:32 +0000806/// CollectRecordLambdaFields - Helper for CollectRecordFields.
807void CGDebugInfo::
808CollectRecordLambdaFields(const CXXRecordDecl *CXXDecl,
809 SmallVectorImpl<llvm::Value *> &elements,
810 llvm::DIType RecordTy) {
811 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
812 // has the name and the location of the variable so we should iterate over
813 // both concurrently.
814 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
815 RecordDecl::field_iterator Field = CXXDecl->field_begin();
816 unsigned fieldno = 0;
817 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
818 E = CXXDecl->captures_end(); I != E; ++I, ++Field, ++fieldno) {
819 const LambdaExpr::Capture C = *I;
820 if (C.capturesVariable()) {
821 VarDecl *V = C.getCapturedVar();
822 llvm::DIFile VUnit = getOrCreateFile(C.getLocation());
823 StringRef VName = V->getName();
824 uint64_t SizeInBitsOverride = 0;
825 if (Field->isBitField()) {
826 SizeInBitsOverride = Field->getBitWidthValue(CGM.getContext());
827 assert(SizeInBitsOverride && "found named 0-width bitfield");
828 }
829 llvm::DIType fieldType
830 = createFieldType(VName, Field->getType(), SizeInBitsOverride,
831 C.getLocation(), Field->getAccess(),
832 layout.getFieldOffset(fieldno), VUnit, RecordTy);
833 elements.push_back(fieldType);
834 } else {
835 // TODO: Need to handle 'this' in some way by probably renaming the
836 // this of the lambda class and having a field member of 'this' or
837 // by using AT_object_pointer for the function and having that be
838 // used as 'this' for semantic references.
839 assert(C.capturesThis() && "Field that isn't captured and isn't this?");
840 FieldDecl *f = *Field;
841 llvm::DIFile VUnit = getOrCreateFile(f->getLocation());
842 QualType type = f->getType();
843 llvm::DIType fieldType
844 = createFieldType("this", type, 0, f->getLocation(), f->getAccess(),
845 layout.getFieldOffset(fieldno), VUnit, RecordTy);
846
847 elements.push_back(fieldType);
848 }
849 }
850}
851
852/// CollectRecordStaticField - Helper for CollectRecordFields.
853void CGDebugInfo::
854CollectRecordStaticField(const VarDecl *Var,
855 SmallVectorImpl<llvm::Value *> &elements,
856 llvm::DIType RecordTy) {
857 // Create the descriptor for the static variable, with or without
858 // constant initializers.
859 llvm::DIFile VUnit = getOrCreateFile(Var->getLocation());
860 llvm::DIType VTy = getOrCreateType(Var->getType(), VUnit);
861
862 // Do not describe enums as static members.
863 if (VTy.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
864 return;
865
866 unsigned LineNumber = getLineNumber(Var->getLocation());
867 StringRef VName = Var->getName();
David Blaikiea89701b2013-01-20 01:19:17 +0000868 llvm::Constant *C = NULL;
Eric Christopher0395de32013-01-16 01:22:32 +0000869 if (Var->getInit()) {
870 const APValue *Value = Var->evaluateValue();
David Blaikiea89701b2013-01-20 01:19:17 +0000871 if (Value) {
872 if (Value->isInt())
873 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
874 if (Value->isFloat())
875 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
876 }
Eric Christopher0395de32013-01-16 01:22:32 +0000877 }
878
879 unsigned Flags = 0;
880 AccessSpecifier Access = Var->getAccess();
881 if (Access == clang::AS_private)
882 Flags |= llvm::DIDescriptor::FlagPrivate;
883 else if (Access == clang::AS_protected)
884 Flags |= llvm::DIDescriptor::FlagProtected;
885
886 llvm::DIType GV = DBuilder.createStaticMemberType(RecordTy, VName, VUnit,
David Blaikiea89701b2013-01-20 01:19:17 +0000887 LineNumber, VTy, Flags, C);
Eric Christopher0395de32013-01-16 01:22:32 +0000888 elements.push_back(GV);
889 StaticDataMemberCache[Var->getCanonicalDecl()] = llvm::WeakVH(GV);
890}
891
892/// CollectRecordNormalField - Helper for CollectRecordFields.
893void CGDebugInfo::
894CollectRecordNormalField(const FieldDecl *field, uint64_t OffsetInBits,
895 llvm::DIFile tunit,
896 SmallVectorImpl<llvm::Value *> &elements,
897 llvm::DIType RecordTy) {
898 StringRef name = field->getName();
899 QualType type = field->getType();
900
901 // Ignore unnamed fields unless they're anonymous structs/unions.
902 if (name.empty() && !type->isRecordType())
903 return;
904
905 uint64_t SizeInBitsOverride = 0;
906 if (field->isBitField()) {
907 SizeInBitsOverride = field->getBitWidthValue(CGM.getContext());
908 assert(SizeInBitsOverride && "found named 0-width bitfield");
909 }
910
911 llvm::DIType fieldType
912 = createFieldType(name, type, SizeInBitsOverride,
913 field->getLocation(), field->getAccess(),
914 OffsetInBits, tunit, RecordTy);
915
916 elements.push_back(fieldType);
917}
918
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000919/// CollectRecordFields - A helper function to collect debug info for
920/// record fields. This is used while creating debug info entry for a Record.
921void CGDebugInfo::
922CollectRecordFields(const RecordDecl *record, llvm::DIFile tunit,
923 SmallVectorImpl<llvm::Value *> &elements,
924 llvm::DIType RecordTy) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000925 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(record);
926
Eric Christopher0395de32013-01-16 01:22:32 +0000927 if (CXXDecl && CXXDecl->isLambda())
928 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
929 else {
930 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000931
Eric Christopher0395de32013-01-16 01:22:32 +0000932 // Field number for non-static fields.
Eric Christopherfd5ac0d2013-01-04 17:59:07 +0000933 unsigned fieldNo = 0;
Eric Christopher0395de32013-01-16 01:22:32 +0000934
935 // Bookkeeping for an ms struct, which ignores certain fields.
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000936 bool IsMsStruct = record->isMsStruct(CGM.getContext());
937 const FieldDecl *LastFD = 0;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000938
Eric Christopher0395de32013-01-16 01:22:32 +0000939 // Static and non-static members should appear in the same order as
940 // the corresponding declarations in the source program.
941 for (RecordDecl::decl_iterator I = record->decls_begin(),
942 E = record->decls_end(); I != E; ++I)
943 if (const VarDecl *V = dyn_cast<VarDecl>(*I))
944 CollectRecordStaticField(V, elements, RecordTy);
945 else if (FieldDecl *field = dyn_cast<FieldDecl>(*I)) {
946 if (IsMsStruct) {
947 // Zero-length bitfields following non-bitfield members are
948 // completely ignored; we don't even count them.
949 if (CGM.getContext().ZeroBitfieldFollowsNonBitfield((field), LastFD))
950 continue;
951 LastFD = field;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000952 }
Eric Christopher0395de32013-01-16 01:22:32 +0000953 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo),
954 tunit, elements, RecordTy);
955
956 // Bump field number for next field.
957 ++fieldNo;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000958 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000959 }
960}
961
962/// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
963/// function type is not updated to include implicit "this" pointer. Use this
964/// routine to get a method type which includes "this" pointer.
David Blaikie9a845292013-05-22 23:22:42 +0000965llvm::DICompositeType
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000966CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
967 llvm::DIFile Unit) {
David Blaikie9c78f9b2013-01-07 23:06:35 +0000968 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
David Blaikie67f8b5e2013-01-07 22:24:59 +0000969 if (Method->isStatic())
David Blaikie9a845292013-05-22 23:22:42 +0000970 return llvm::DICompositeType(getOrCreateType(QualType(Func, 0), Unit));
David Blaikie9c78f9b2013-01-07 23:06:35 +0000971 return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()),
972 Func, Unit);
973}
David Blaikie67f8b5e2013-01-07 22:24:59 +0000974
David Blaikie9a845292013-05-22 23:22:42 +0000975llvm::DICompositeType CGDebugInfo::getOrCreateInstanceMethodType(
David Blaikie9c78f9b2013-01-07 23:06:35 +0000976 QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile Unit) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000977 // Add "this" pointer.
David Blaikie9c78f9b2013-01-07 23:06:35 +0000978 llvm::DIArray Args = llvm::DICompositeType(
979 getOrCreateType(QualType(Func, 0), Unit)).getTypeArray();
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000980 assert (Args.getNumElements() && "Invalid number of arguments!");
981
982 SmallVector<llvm::Value *, 16> Elts;
983
984 // First element is always return type. For 'void' functions it is NULL.
985 Elts.push_back(Args.getElement(0));
986
David Blaikie67f8b5e2013-01-07 22:24:59 +0000987 // "this" pointer is always first argument.
David Blaikie9c78f9b2013-01-07 23:06:35 +0000988 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
David Blaikie67f8b5e2013-01-07 22:24:59 +0000989 if (isa<ClassTemplateSpecializationDecl>(RD)) {
990 // Create pointer type directly in this case.
991 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
992 QualType PointeeTy = ThisPtrTy->getPointeeType();
993 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCall64aa4b32013-04-16 22:48:15 +0000994 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
David Blaikie67f8b5e2013-01-07 22:24:59 +0000995 uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy);
996 llvm::DIType PointeeType = getOrCreateType(PointeeTy, Unit);
Eric Christopherf0890c42013-05-16 00:52:20 +0000997 llvm::DIType ThisPtrType =
998 DBuilder.createPointerType(PointeeType, Size, Align);
David Blaikie67f8b5e2013-01-07 22:24:59 +0000999 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
1000 // TODO: This and the artificial type below are misleading, the
1001 // types aren't artificial the argument is, but the current
1002 // metadata doesn't represent that.
1003 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1004 Elts.push_back(ThisPtrType);
1005 } else {
1006 llvm::DIType ThisPtrType = getOrCreateType(ThisPtr, Unit);
1007 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
1008 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1009 Elts.push_back(ThisPtrType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001010 }
1011
1012 // Copy rest of the arguments.
1013 for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
1014 Elts.push_back(Args.getElement(i));
1015
1016 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
1017
1018 return DBuilder.createSubroutineType(Unit, EltTypeArray);
1019}
1020
Eric Christopher6537f082013-05-16 00:45:12 +00001021/// isFunctionLocalClass - Return true if CXXRecordDecl is defined
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001022/// inside a function.
1023static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
1024 if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
1025 return isFunctionLocalClass(NRD);
1026 if (isa<FunctionDecl>(RD->getDeclContext()))
1027 return true;
1028 return false;
1029}
1030
1031/// CreateCXXMemberFunction - A helper function to create a DISubprogram for
1032/// a single member function GlobalDecl.
1033llvm::DISubprogram
1034CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
1035 llvm::DIFile Unit,
1036 llvm::DIType RecordTy) {
Eric Christopher6537f082013-05-16 00:45:12 +00001037 bool IsCtorOrDtor =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001038 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
Eric Christopher6537f082013-05-16 00:45:12 +00001039
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001040 StringRef MethodName = getFunctionName(Method);
David Blaikie9a845292013-05-22 23:22:42 +00001041 llvm::DICompositeType MethodTy = getOrCreateMethodType(Method, Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001042
1043 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1044 // make sense to give a single ctor/dtor a linkage name.
1045 StringRef MethodLinkageName;
1046 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1047 MethodLinkageName = CGM.getMangledName(Method);
1048
1049 // Get the location for the method.
1050 llvm::DIFile MethodDefUnit = getOrCreateFile(Method->getLocation());
1051 unsigned MethodLine = getLineNumber(Method->getLocation());
1052
1053 // Collect virtual method info.
1054 llvm::DIType ContainingType;
Eric Christopher6537f082013-05-16 00:45:12 +00001055 unsigned Virtuality = 0;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001056 unsigned VIndex = 0;
Eric Christopher6537f082013-05-16 00:45:12 +00001057
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001058 if (Method->isVirtual()) {
1059 if (Method->isPure())
1060 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
1061 else
1062 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
Eric Christopher6537f082013-05-16 00:45:12 +00001063
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001064 // It doesn't make sense to give a virtual destructor a vtable index,
1065 // since a single destructor has two entries in the vtable.
1066 if (!isa<CXXDestructorDecl>(Method))
1067 VIndex = CGM.getVTableContext().getMethodVTableIndex(Method);
1068 ContainingType = RecordTy;
1069 }
1070
1071 unsigned Flags = 0;
1072 if (Method->isImplicit())
1073 Flags |= llvm::DIDescriptor::FlagArtificial;
1074 AccessSpecifier Access = Method->getAccess();
1075 if (Access == clang::AS_private)
1076 Flags |= llvm::DIDescriptor::FlagPrivate;
1077 else if (Access == clang::AS_protected)
1078 Flags |= llvm::DIDescriptor::FlagProtected;
1079 if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1080 if (CXXC->isExplicit())
1081 Flags |= llvm::DIDescriptor::FlagExplicit;
Eric Christopher6537f082013-05-16 00:45:12 +00001082 } else if (const CXXConversionDecl *CXXC =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001083 dyn_cast<CXXConversionDecl>(Method)) {
1084 if (CXXC->isExplicit())
1085 Flags |= llvm::DIDescriptor::FlagExplicit;
1086 }
1087 if (Method->hasPrototype())
1088 Flags |= llvm::DIDescriptor::FlagPrototyped;
1089
1090 llvm::DIArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1091 llvm::DISubprogram SP =
Eric Christopher6537f082013-05-16 00:45:12 +00001092 DBuilder.createMethod(RecordTy, MethodName, MethodLinkageName,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001093 MethodDefUnit, MethodLine,
Eric Christopher6537f082013-05-16 00:45:12 +00001094 MethodTy, /*isLocalToUnit=*/false,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001095 /* isDefinition=*/ false,
1096 Virtuality, VIndex, ContainingType,
1097 Flags, CGM.getLangOpts().Optimize, NULL,
1098 TParamsArray);
Eric Christopher6537f082013-05-16 00:45:12 +00001099
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001100 SPCache[Method->getCanonicalDecl()] = llvm::WeakVH(SP);
1101
1102 return SP;
1103}
1104
1105/// CollectCXXMemberFunctions - A helper function to collect debug info for
Eric Christopher6537f082013-05-16 00:45:12 +00001106/// C++ member functions. This is used while creating debug info entry for
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001107/// a Record.
1108void CGDebugInfo::
1109CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
1110 SmallVectorImpl<llvm::Value *> &EltTys,
1111 llvm::DIType RecordTy) {
1112
1113 // Since we want more than just the individual member decls if we
1114 // have templated functions iterate over every declaration to gather
1115 // the functions.
1116 for(DeclContext::decl_iterator I = RD->decls_begin(),
1117 E = RD->decls_end(); I != E; ++I) {
1118 Decl *D = *I;
1119 if (D->isImplicit() && !D->isUsed())
1120 continue;
1121
1122 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1123 EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
1124 else if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
1125 for (FunctionTemplateDecl::spec_iterator SI = FTD->spec_begin(),
1126 SE = FTD->spec_end(); SI != SE; ++SI)
1127 EltTys.push_back(CreateCXXMemberFunction(cast<CXXMethodDecl>(*SI), Unit,
1128 RecordTy));
1129 }
Eric Christopher6537f082013-05-16 00:45:12 +00001130}
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001131
1132/// CollectCXXFriends - A helper function to collect debug info for
1133/// C++ base classes. This is used while creating debug info entry for
1134/// a Record.
1135void CGDebugInfo::
1136CollectCXXFriends(const CXXRecordDecl *RD, llvm::DIFile Unit,
1137 SmallVectorImpl<llvm::Value *> &EltTys,
1138 llvm::DIType RecordTy) {
1139 for (CXXRecordDecl::friend_iterator BI = RD->friend_begin(),
1140 BE = RD->friend_end(); BI != BE; ++BI) {
1141 if ((*BI)->isUnsupportedFriend())
1142 continue;
1143 if (TypeSourceInfo *TInfo = (*BI)->getFriendType())
Eric Christopher6537f082013-05-16 00:45:12 +00001144 EltTys.push_back(DBuilder.createFriend(RecordTy,
1145 getOrCreateType(TInfo->getType(),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001146 Unit)));
1147 }
1148}
1149
1150/// CollectCXXBases - A helper function to collect debug info for
Eric Christopher6537f082013-05-16 00:45:12 +00001151/// C++ base classes. This is used while creating debug info entry for
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001152/// a Record.
1153void CGDebugInfo::
1154CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
1155 SmallVectorImpl<llvm::Value *> &EltTys,
1156 llvm::DIType RecordTy) {
1157
1158 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1159 for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
1160 BE = RD->bases_end(); BI != BE; ++BI) {
1161 unsigned BFlags = 0;
1162 uint64_t BaseOffset;
Eric Christopher6537f082013-05-16 00:45:12 +00001163
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001164 const CXXRecordDecl *Base =
1165 cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl());
Eric Christopher6537f082013-05-16 00:45:12 +00001166
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001167 if (BI->isVirtual()) {
1168 // virtual base offset offset is -ve. The code generator emits dwarf
1169 // expression where it expects +ve number.
Eric Christopher6537f082013-05-16 00:45:12 +00001170 BaseOffset =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001171 0 - CGM.getVTableContext()
1172 .getVirtualBaseOffsetOffset(RD, Base).getQuantity();
1173 BFlags = llvm::DIDescriptor::FlagVirtual;
1174 } else
1175 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1176 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1177 // BI->isVirtual() and bits when not.
Eric Christopher6537f082013-05-16 00:45:12 +00001178
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001179 AccessSpecifier Access = BI->getAccessSpecifier();
1180 if (Access == clang::AS_private)
1181 BFlags |= llvm::DIDescriptor::FlagPrivate;
1182 else if (Access == clang::AS_protected)
1183 BFlags |= llvm::DIDescriptor::FlagProtected;
Eric Christopher6537f082013-05-16 00:45:12 +00001184
1185 llvm::DIType DTy =
1186 DBuilder.createInheritance(RecordTy,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001187 getOrCreateType(BI->getType(), Unit),
1188 BaseOffset, BFlags);
1189 EltTys.push_back(DTy);
1190 }
1191}
1192
1193/// CollectTemplateParams - A helper function to collect template parameters.
1194llvm::DIArray CGDebugInfo::
1195CollectTemplateParams(const TemplateParameterList *TPList,
1196 const TemplateArgumentList &TAList,
1197 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +00001198 SmallVector<llvm::Value *, 16> TemplateParams;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001199 for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1200 const TemplateArgument &TA = TAList[i];
1201 const NamedDecl *ND = TPList->getParam(i);
David Blaikie9dfd2432013-05-10 21:53:14 +00001202 switch (TA.getKind()) {
1203 case TemplateArgument::Type: {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001204 llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit);
1205 llvm::DITemplateTypeParameter TTP =
1206 DBuilder.createTemplateTypeParameter(TheCU, ND->getName(), TTy);
1207 TemplateParams.push_back(TTP);
David Blaikie9dfd2432013-05-10 21:53:14 +00001208 } break;
1209 case TemplateArgument::Integral: {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001210 llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit);
1211 llvm::DITemplateValueParameter TVP =
David Blaikie9dfd2432013-05-10 21:53:14 +00001212 DBuilder.createTemplateValueParameter(
1213 TheCU, ND->getName(), TTy,
1214 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral()));
1215 TemplateParams.push_back(TVP);
1216 } break;
1217 case TemplateArgument::Declaration: {
1218 const ValueDecl *D = TA.getAsDecl();
1219 bool InstanceMember = D->isCXXInstanceMember();
1220 QualType T = InstanceMember
1221 ? CGM.getContext().getMemberPointerType(
1222 D->getType(), cast<RecordDecl>(D->getDeclContext())
1223 ->getTypeForDecl())
1224 : CGM.getContext().getPointerType(D->getType());
1225 llvm::DIType TTy = getOrCreateType(T, Unit);
1226 llvm::Value *V = 0;
1227 // Variable pointer template parameters have a value that is the address
1228 // of the variable.
1229 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1230 V = CGM.GetAddrOfGlobalVar(VD);
1231 // Member function pointers have special support for building them, though
1232 // this is currently unsupported in LLVM CodeGen.
David Blaikief8aa1552013-05-13 06:57:50 +00001233 if (InstanceMember) {
David Blaikie9dfd2432013-05-10 21:53:14 +00001234 if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(D))
1235 V = CGM.getCXXABI().EmitMemberPointer(method);
David Blaikief8aa1552013-05-13 06:57:50 +00001236 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1237 V = CGM.GetAddrOfFunction(FD);
David Blaikie9dfd2432013-05-10 21:53:14 +00001238 // Member data pointers have special handling too to compute the fixed
1239 // offset within the object.
1240 if (isa<FieldDecl>(D)) {
1241 // These five lines (& possibly the above member function pointer
1242 // handling) might be able to be refactored to use similar code in
1243 // CodeGenModule::getMemberPointerConstant
1244 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
1245 CharUnits chars =
1246 CGM.getContext().toCharUnitsFromBits((int64_t) fieldOffset);
1247 V = CGM.getCXXABI().EmitMemberDataPointer(
1248 cast<MemberPointerType>(T.getTypePtr()), chars);
1249 }
1250 llvm::DITemplateValueParameter TVP =
1251 DBuilder.createTemplateValueParameter(TheCU, ND->getName(), TTy, V);
1252 TemplateParams.push_back(TVP);
1253 } break;
1254 case TemplateArgument::NullPtr: {
1255 QualType T = TA.getNullPtrType();
1256 llvm::DIType TTy = getOrCreateType(T, Unit);
1257 llvm::Value *V = 0;
1258 // Special case member data pointer null values since they're actually -1
1259 // instead of zero.
1260 if (const MemberPointerType *MPT =
1261 dyn_cast<MemberPointerType>(T.getTypePtr()))
1262 // But treat member function pointers as simple zero integers because
1263 // it's easier than having a special case in LLVM's CodeGen. If LLVM
1264 // CodeGen grows handling for values of non-null member function
1265 // pointers then perhaps we could remove this special case and rely on
1266 // EmitNullMemberPointer for member function pointers.
1267 if (MPT->isMemberDataPointer())
1268 V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1269 if (!V)
1270 V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
1271 llvm::DITemplateValueParameter TVP =
1272 DBuilder.createTemplateValueParameter(TheCU, ND->getName(), TTy, V);
1273 TemplateParams.push_back(TVP);
1274 } break;
1275 case TemplateArgument::Template:
1276 // We could support this with the GCC extension
1277 // DW_TAG_GNU_template_template_param
1278 break;
David Blaikie776a3642013-05-10 22:53:25 +00001279 case TemplateArgument::Pack:
1280 // And this with DW_TAG_GNU_template_parameter_pack
1281 break;
David Blaikiee8065122013-05-10 23:36:06 +00001282 // And the following should never occur:
David Blaikie9dfd2432013-05-10 21:53:14 +00001283 case TemplateArgument::Expression:
1284 case TemplateArgument::TemplateExpansion:
David Blaikie9dfd2432013-05-10 21:53:14 +00001285 case TemplateArgument::Null:
1286 llvm_unreachable(
1287 "These argument types shouldn't exist in concrete types");
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001288 }
1289 }
1290 return DBuilder.getOrCreateArray(TemplateParams);
1291}
1292
1293/// CollectFunctionTemplateParams - A helper function to collect debug
1294/// info for function template parameters.
1295llvm::DIArray CGDebugInfo::
1296CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) {
1297 if (FD->getTemplatedKind() ==
1298 FunctionDecl::TK_FunctionTemplateSpecialization) {
1299 const TemplateParameterList *TList =
1300 FD->getTemplateSpecializationInfo()->getTemplate()
1301 ->getTemplateParameters();
Eric Christopher6537f082013-05-16 00:45:12 +00001302 return
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001303 CollectTemplateParams(TList, *FD->getTemplateSpecializationArgs(), Unit);
1304 }
1305 return llvm::DIArray();
1306}
1307
1308/// CollectCXXTemplateParams - A helper function to collect debug info for
1309/// template parameters.
1310llvm::DIArray CGDebugInfo::
1311CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial,
1312 llvm::DIFile Unit) {
1313 llvm::PointerUnion<ClassTemplateDecl *,
1314 ClassTemplatePartialSpecializationDecl *>
1315 PU = TSpecial->getSpecializedTemplateOrPartial();
Eric Christopher6537f082013-05-16 00:45:12 +00001316
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001317 TemplateParameterList *TPList = PU.is<ClassTemplateDecl *>() ?
1318 PU.get<ClassTemplateDecl *>()->getTemplateParameters() :
1319 PU.get<ClassTemplatePartialSpecializationDecl *>()->getTemplateParameters();
1320 const TemplateArgumentList &TAList = TSpecial->getTemplateInstantiationArgs();
1321 return CollectTemplateParams(TPList, TAList, Unit);
1322}
1323
1324/// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
1325llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
1326 if (VTablePtrType.isValid())
1327 return VTablePtrType;
1328
1329 ASTContext &Context = CGM.getContext();
1330
1331 /* Function type */
1332 llvm::Value *STy = getOrCreateType(Context.IntTy, Unit);
1333 llvm::DIArray SElements = DBuilder.getOrCreateArray(STy);
1334 llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements);
1335 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1336 llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0,
1337 "__vtbl_ptr_type");
1338 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1339 return VTablePtrType;
1340}
1341
1342/// getVTableName - Get vtable name for the given Class.
1343StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
1344 // Construct gdb compatible name name.
1345 std::string Name = "_vptr$" + RD->getNameAsString();
1346
1347 // Copy this name on the side and use its reference.
1348 char *StrPtr = DebugInfoNames.Allocate<char>(Name.length());
1349 memcpy(StrPtr, Name.data(), Name.length());
1350 return StringRef(StrPtr, Name.length());
1351}
1352
1353
1354/// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
1355/// debug info entry in EltTys vector.
1356void CGDebugInfo::
1357CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
1358 SmallVectorImpl<llvm::Value *> &EltTys) {
1359 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1360
1361 // If there is a primary base then it will hold vtable info.
1362 if (RL.getPrimaryBase())
1363 return;
1364
1365 // If this class is not dynamic then there is not any vtable info to collect.
1366 if (!RD->isDynamicClass())
1367 return;
1368
1369 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1370 llvm::DIType VPTR
1371 = DBuilder.createMemberType(Unit, getVTableName(RD), Unit,
Eric Christopherf0890c42013-05-16 00:52:20 +00001372 0, Size, 0, 0,
1373 llvm::DIDescriptor::FlagArtificial,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001374 getOrCreateVTablePtrType(Unit));
1375 EltTys.push_back(VPTR);
1376}
1377
Eric Christopher6537f082013-05-16 00:45:12 +00001378/// getOrCreateRecordType - Emit record type's standalone debug info.
1379llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001380 SourceLocation Loc) {
Eric Christopher13c97672013-05-16 00:45:23 +00001381 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001382 llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc));
1383 return T;
1384}
1385
1386/// getOrCreateInterfaceType - Emit an objective c interface type standalone
1387/// debug info.
1388llvm::DIType CGDebugInfo::getOrCreateInterfaceType(QualType D,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001389 SourceLocation Loc) {
Eric Christopher13c97672013-05-16 00:45:23 +00001390 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001391 llvm::DIType T = getOrCreateType(D, getOrCreateFile(Loc));
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001392 RetainedTypes.push_back(D.getAsOpaquePtr());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001393 return T;
1394}
1395
1396/// CreateType - get structure or union type.
1397llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty) {
1398 RecordDecl *RD = Ty->getDecl();
1399
1400 // Get overall information about the record type for the debug info.
1401 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1402
1403 // Records and classes and unions can all be recursive. To handle them, we
1404 // first generate a debug descriptor for the struct as a forward declaration.
1405 // Then (if it is a definition) we go through and get debug info for all of
1406 // its members. Finally, we create a descriptor for the complete type (which
1407 // may refer to the forward decl if the struct is recursive) and replace all
1408 // uses of the forward declaration with the final definition.
1409
Eric Christopherf068c922013-04-02 22:59:11 +00001410 llvm::DICompositeType FwdDecl(
1411 getOrCreateLimitedType(QualType(Ty, 0), DefUnit));
1412 assert(FwdDecl.Verify() &&
David Blaikie9a845292013-05-22 23:22:42 +00001413 "The debug type of a RecordType should be a llvm::DICompositeType");
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001414
1415 if (FwdDecl.isForwardDecl())
1416 return FwdDecl;
1417
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001418 // Push the struct on region stack.
Eric Christopherf068c922013-04-02 22:59:11 +00001419 LexicalBlockStack.push_back(&*FwdDecl);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001420 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1421
Adrian Prantl4919de62013-03-06 22:03:30 +00001422 // Add this to the completed-type cache while we're completing it recursively.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001423 CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1424
1425 // Convert all the elements.
1426 SmallVector<llvm::Value *, 16> EltTys;
1427
1428 // Note: The split of CXXDecl information here is intentional, the
1429 // gdb tests will depend on a certain ordering at printout. The debug
1430 // information offsets are still correct if we merge them all together
1431 // though.
1432 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1433 if (CXXDecl) {
1434 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1435 CollectVTableInfo(CXXDecl, DefUnit, EltTys);
1436 }
1437
Eric Christopher0395de32013-01-16 01:22:32 +00001438 // Collect data fields (including static variables and any initializers).
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001439 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
1440 llvm::DIArray TParamsArray;
1441 if (CXXDecl) {
1442 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
1443 CollectCXXFriends(CXXDecl, DefUnit, EltTys, FwdDecl);
1444 if (const ClassTemplateSpecializationDecl *TSpecial
1445 = dyn_cast<ClassTemplateSpecializationDecl>(RD))
1446 TParamsArray = CollectCXXTemplateParams(TSpecial, DefUnit);
1447 }
1448
1449 LexicalBlockStack.pop_back();
1450 RegionMap.erase(Ty->getDecl());
1451
1452 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopherf068c922013-04-02 22:59:11 +00001453 FwdDecl.setTypeArray(Elements, TParamsArray);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001454
Eric Christopherf068c922013-04-02 22:59:11 +00001455 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1456 return FwdDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001457}
1458
1459/// CreateType - get objective-c object type.
1460llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1461 llvm::DIFile Unit) {
1462 // Ignore protocols.
1463 return getOrCreateType(Ty->getBaseType(), Unit);
1464}
1465
1466/// CreateType - get objective-c interface type.
1467llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1468 llvm::DIFile Unit) {
1469 ObjCInterfaceDecl *ID = Ty->getDecl();
1470 if (!ID)
1471 return llvm::DIType();
1472
1473 // Get overall information about the record type for the debug info.
1474 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1475 unsigned Line = getLineNumber(ID->getLocation());
1476 unsigned RuntimeLang = TheCU.getLanguage();
1477
1478 // If this is just a forward declaration return a special forward-declaration
1479 // debug type since we won't be able to lay out the entire type.
1480 ObjCInterfaceDecl *Def = ID->getDefinition();
1481 if (!Def) {
1482 llvm::DIType FwdDecl =
1483 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001484 ID->getName(), TheCU, DefUnit, Line,
1485 RuntimeLang);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001486 return FwdDecl;
1487 }
1488
1489 ID = Def;
1490
1491 // Bit size, align and offset of the type.
1492 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1493 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1494
1495 unsigned Flags = 0;
1496 if (ID->getImplementation())
1497 Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
1498
Eric Christopherf068c922013-04-02 22:59:11 +00001499 llvm::DICompositeType RealDecl =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001500 DBuilder.createStructType(Unit, ID->getName(), DefUnit,
1501 Line, Size, Align, Flags,
David Blaikiec1d0af12013-02-25 01:07:08 +00001502 llvm::DIType(), llvm::DIArray(), RuntimeLang);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001503
1504 // Otherwise, insert it into the CompletedTypeCache so that recursive uses
1505 // will find it and we're emitting the complete type.
Adrian Prantl4919de62013-03-06 22:03:30 +00001506 QualType QualTy = QualType(Ty, 0);
1507 CompletedTypeCache[QualTy.getAsOpaquePtr()] = RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001508 // Push the struct on region stack.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001509
Eric Christopherf068c922013-04-02 22:59:11 +00001510 LexicalBlockStack.push_back(static_cast<llvm::MDNode*>(RealDecl));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001511 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1512
1513 // Convert all the elements.
1514 SmallVector<llvm::Value *, 16> EltTys;
1515
1516 ObjCInterfaceDecl *SClass = ID->getSuperClass();
1517 if (SClass) {
1518 llvm::DIType SClassTy =
1519 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1520 if (!SClassTy.isValid())
1521 return llvm::DIType();
Eric Christopher6537f082013-05-16 00:45:12 +00001522
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001523 llvm::DIType InhTag =
1524 DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
1525 EltTys.push_back(InhTag);
1526 }
1527
1528 for (ObjCContainerDecl::prop_iterator I = ID->prop_begin(),
1529 E = ID->prop_end(); I != E; ++I) {
1530 const ObjCPropertyDecl *PD = *I;
1531 SourceLocation Loc = PD->getLocation();
1532 llvm::DIFile PUnit = getOrCreateFile(Loc);
1533 unsigned PLine = getLineNumber(Loc);
1534 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1535 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1536 llvm::MDNode *PropertyNode =
1537 DBuilder.createObjCProperty(PD->getName(),
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001538 PUnit, PLine,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001539 (Getter && Getter->isImplicit()) ? "" :
1540 getSelectorName(PD->getGetterName()),
1541 (Setter && Setter->isImplicit()) ? "" :
1542 getSelectorName(PD->getSetterName()),
1543 PD->getPropertyAttributes(),
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001544 getOrCreateType(PD->getType(), PUnit));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001545 EltTys.push_back(PropertyNode);
1546 }
1547
1548 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1549 unsigned FieldNo = 0;
1550 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1551 Field = Field->getNextIvar(), ++FieldNo) {
1552 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1553 if (!FieldTy.isValid())
1554 return llvm::DIType();
Eric Christopher6537f082013-05-16 00:45:12 +00001555
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001556 StringRef FieldName = Field->getName();
1557
1558 // Ignore unnamed fields.
1559 if (FieldName.empty())
1560 continue;
1561
1562 // Get the location for the field.
1563 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1564 unsigned FieldLine = getLineNumber(Field->getLocation());
1565 QualType FType = Field->getType();
1566 uint64_t FieldSize = 0;
1567 unsigned FieldAlign = 0;
1568
1569 if (!FType->isIncompleteArrayType()) {
1570
1571 // Bit size, align and offset of the type.
1572 FieldSize = Field->isBitField()
1573 ? Field->getBitWidthValue(CGM.getContext())
1574 : CGM.getContext().getTypeSize(FType);
1575 FieldAlign = CGM.getContext().getTypeAlign(FType);
1576 }
1577
1578 uint64_t FieldOffset;
1579 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1580 // We don't know the runtime offset of an ivar if we're using the
1581 // non-fragile ABI. For bitfields, use the bit offset into the first
1582 // byte of storage of the bitfield. For other fields, use zero.
1583 if (Field->isBitField()) {
1584 FieldOffset = CGM.getObjCRuntime().ComputeBitfieldBitOffset(
1585 CGM, ID, Field);
1586 FieldOffset %= CGM.getContext().getCharWidth();
1587 } else {
1588 FieldOffset = 0;
1589 }
1590 } else {
1591 FieldOffset = RL.getFieldOffset(FieldNo);
1592 }
1593
1594 unsigned Flags = 0;
1595 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1596 Flags = llvm::DIDescriptor::FlagProtected;
1597 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1598 Flags = llvm::DIDescriptor::FlagPrivate;
1599
1600 llvm::MDNode *PropertyNode = NULL;
1601 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
Eric Christopher6537f082013-05-16 00:45:12 +00001602 if (ObjCPropertyImplDecl *PImpD =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001603 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
1604 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001605 SourceLocation Loc = PD->getLocation();
1606 llvm::DIFile PUnit = getOrCreateFile(Loc);
1607 unsigned PLine = getLineNumber(Loc);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001608 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1609 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1610 PropertyNode =
1611 DBuilder.createObjCProperty(PD->getName(),
1612 PUnit, PLine,
1613 (Getter && Getter->isImplicit()) ? "" :
1614 getSelectorName(PD->getGetterName()),
1615 (Setter && Setter->isImplicit()) ? "" :
1616 getSelectorName(PD->getSetterName()),
1617 PD->getPropertyAttributes(),
1618 getOrCreateType(PD->getType(), PUnit));
1619 }
1620 }
1621 }
1622 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
1623 FieldLine, FieldSize, FieldAlign,
1624 FieldOffset, Flags, FieldTy,
1625 PropertyNode);
1626 EltTys.push_back(FieldTy);
1627 }
1628
1629 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopherf068c922013-04-02 22:59:11 +00001630 RealDecl.setTypeArray(Elements);
Adrian Prantl4919de62013-03-06 22:03:30 +00001631
1632 // If the implementation is not yet set, we do not want to mark it
1633 // as complete. An implementation may declare additional
1634 // private ivars that we would miss otherwise.
1635 if (ID->getImplementation() == 0)
1636 CompletedTypeCache.erase(QualTy.getAsOpaquePtr());
Eric Christopher6537f082013-05-16 00:45:12 +00001637
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001638 LexicalBlockStack.pop_back();
Eric Christopherf068c922013-04-02 22:59:11 +00001639 return RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001640}
1641
1642llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) {
1643 llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1644 int64_t Count = Ty->getNumElements();
1645 if (Count == 0)
1646 // If number of elements are not known then this is an unbounded array.
1647 // Use Count == -1 to express such arrays.
1648 Count = -1;
1649
1650 llvm::Value *Subscript = DBuilder.getOrCreateSubrange(0, Count);
1651 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1652
1653 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1654 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1655
1656 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1657}
1658
1659llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1660 llvm::DIFile Unit) {
1661 uint64_t Size;
1662 uint64_t Align;
1663
1664 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1665 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1666 Size = 0;
1667 Align =
1668 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1669 } else if (Ty->isIncompleteArrayType()) {
1670 Size = 0;
1671 if (Ty->getElementType()->isIncompleteType())
1672 Align = 0;
1673 else
1674 Align = CGM.getContext().getTypeAlign(Ty->getElementType());
David Blaikie089db2e2013-05-09 20:48:12 +00001675 } else if (Ty->isIncompleteType()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001676 Size = 0;
1677 Align = 0;
1678 } else {
1679 // Size and align of the whole array, not the element type.
1680 Size = CGM.getContext().getTypeSize(Ty);
1681 Align = CGM.getContext().getTypeAlign(Ty);
1682 }
1683
1684 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
1685 // interior arrays, do we care? Why aren't nested arrays represented the
1686 // obvious/recursive way?
1687 SmallVector<llvm::Value *, 8> Subscripts;
1688 QualType EltTy(Ty, 0);
1689 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1690 // If the number of elements is known, then count is that number. Otherwise,
1691 // it's -1. This allows us to represent a subrange with an array of 0
1692 // elements, like this:
1693 //
1694 // struct foo {
1695 // int x[0];
1696 // };
1697 int64_t Count = -1; // Count == -1 is an unbounded array.
1698 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1699 Count = CAT->getSize().getZExtValue();
Eric Christopher6537f082013-05-16 00:45:12 +00001700
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001701 // FIXME: Verify this is right for VLAs.
1702 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
1703 EltTy = Ty->getElementType();
1704 }
1705
1706 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1707
Eric Christopher6537f082013-05-16 00:45:12 +00001708 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001709 DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1710 SubscriptArray);
1711 return DbgTy;
1712}
1713
Eric Christopher6537f082013-05-16 00:45:12 +00001714llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001715 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +00001716 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001717 Ty, Ty->getPointeeType(), Unit);
1718}
1719
Eric Christopher6537f082013-05-16 00:45:12 +00001720llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001721 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +00001722 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001723 Ty, Ty->getPointeeType(), Unit);
1724}
1725
Eric Christopher6537f082013-05-16 00:45:12 +00001726llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001727 llvm::DIFile U) {
David Blaikiee8d75142013-01-19 19:20:56 +00001728 llvm::DIType ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
1729 if (!Ty->getPointeeType()->isFunctionType())
1730 return DBuilder.createMemberPointerType(
David Blaikieb0f77b02013-05-24 21:33:22 +00001731 getOrCreateTypeDeclaration(Ty->getPointeeType(), U), ClassType);
David Blaikiee8d75142013-01-19 19:20:56 +00001732 return DBuilder.createMemberPointerType(getOrCreateInstanceMethodType(
1733 CGM.getContext().getPointerType(
1734 QualType(Ty->getClass(), Ty->getPointeeType().getCVRQualifiers())),
1735 Ty->getPointeeType()->getAs<FunctionProtoType>(), U),
1736 ClassType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001737}
1738
Eric Christopher6537f082013-05-16 00:45:12 +00001739llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001740 llvm::DIFile U) {
1741 // Ignore the atomic wrapping
1742 // FIXME: What is the correct representation?
1743 return getOrCreateType(Ty->getValueType(), U);
1744}
1745
1746/// CreateEnumType - get enumeration type.
1747llvm::DIType CGDebugInfo::CreateEnumType(const EnumDecl *ED) {
1748 uint64_t Size = 0;
1749 uint64_t Align = 0;
1750 if (!ED->getTypeForDecl()->isIncompleteType()) {
1751 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1752 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1753 }
1754
1755 // If this is just a forward declaration, construct an appropriately
1756 // marked node and just return it.
1757 if (!ED->getDefinition()) {
1758 llvm::DIDescriptor EDContext;
1759 EDContext = getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1760 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1761 unsigned Line = getLineNumber(ED->getLocation());
1762 StringRef EDName = ED->getName();
1763 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_enumeration_type,
1764 EDName, EDContext, DefUnit, Line, 0,
1765 Size, Align);
1766 }
1767
1768 // Create DIEnumerator elements for each enumerator.
1769 SmallVector<llvm::Value *, 16> Enumerators;
1770 ED = ED->getDefinition();
1771 for (EnumDecl::enumerator_iterator
1772 Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
1773 Enum != EnumEnd; ++Enum) {
1774 Enumerators.push_back(
1775 DBuilder.createEnumerator(Enum->getName(),
1776 Enum->getInitVal().getZExtValue()));
1777 }
1778
1779 // Return a CompositeType for the enum itself.
1780 llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1781
1782 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1783 unsigned Line = getLineNumber(ED->getLocation());
Eric Christopher6537f082013-05-16 00:45:12 +00001784 llvm::DIDescriptor EnumContext =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001785 getContextDescriptor(cast<Decl>(ED->getDeclContext()));
Adrian Prantl59d6a712013-04-19 19:56:39 +00001786 llvm::DIType ClassTy = ED->isFixed() ?
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001787 getOrCreateType(ED->getIntegerType(), DefUnit) : llvm::DIType();
Eric Christopher6537f082013-05-16 00:45:12 +00001788 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001789 DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1790 Size, Align, EltArray,
1791 ClassTy);
1792 return DbgTy;
1793}
1794
David Blaikie4b12be62013-01-21 04:37:12 +00001795static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
1796 Qualifiers Quals;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001797 do {
David Blaikie4b12be62013-01-21 04:37:12 +00001798 Quals += T.getLocalQualifiers();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001799 QualType LastT = T;
1800 switch (T->getTypeClass()) {
1801 default:
David Blaikie4b12be62013-01-21 04:37:12 +00001802 return C.getQualifiedType(T.getTypePtr(), Quals);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001803 case Type::TemplateSpecialization:
1804 T = cast<TemplateSpecializationType>(T)->desugar();
1805 break;
1806 case Type::TypeOfExpr:
1807 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1808 break;
1809 case Type::TypeOf:
1810 T = cast<TypeOfType>(T)->getUnderlyingType();
1811 break;
1812 case Type::Decltype:
1813 T = cast<DecltypeType>(T)->getUnderlyingType();
1814 break;
1815 case Type::UnaryTransform:
1816 T = cast<UnaryTransformType>(T)->getUnderlyingType();
1817 break;
1818 case Type::Attributed:
1819 T = cast<AttributedType>(T)->getEquivalentType();
1820 break;
1821 case Type::Elaborated:
1822 T = cast<ElaboratedType>(T)->getNamedType();
1823 break;
1824 case Type::Paren:
1825 T = cast<ParenType>(T)->getInnerType();
1826 break;
David Blaikie4b12be62013-01-21 04:37:12 +00001827 case Type::SubstTemplateTypeParm:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001828 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001829 break;
1830 case Type::Auto:
David Blaikie91296482013-05-24 21:24:35 +00001831 QualType DT = cast<AutoType>(T)->getDeducedType();
1832 if (DT.isNull())
1833 return T;
1834 T = DT;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001835 break;
1836 }
Eric Christopher6537f082013-05-16 00:45:12 +00001837
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001838 assert(T != LastT && "Type unwrapping failed to unwrap!");
NAKAMURA Takumid24c9ab2013-01-21 10:51:28 +00001839 (void)LastT;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001840 } while (true);
1841}
1842
Eric Christopherf0890c42013-05-16 00:52:20 +00001843/// getType - Get the type from the cache or return null type if it doesn't
1844/// exist.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001845llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) {
1846
1847 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00001848 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Eric Christopher6537f082013-05-16 00:45:12 +00001849
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001850 // Check for existing entry.
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001851 if (Ty->getTypeClass() == Type::ObjCInterface) {
1852 llvm::Value *V = getCachedInterfaceTypeOrNull(Ty);
1853 if (V)
1854 return llvm::DIType(cast<llvm::MDNode>(V));
1855 else return llvm::DIType();
1856 }
1857
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001858 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1859 TypeCache.find(Ty.getAsOpaquePtr());
1860 if (it != TypeCache.end()) {
1861 // Verify that the debug info still exists.
1862 if (llvm::Value *V = it->second)
1863 return llvm::DIType(cast<llvm::MDNode>(V));
1864 }
1865
1866 return llvm::DIType();
1867}
1868
1869/// getCompletedTypeOrNull - Get the type from the cache or return null if it
1870/// doesn't exist.
1871llvm::DIType CGDebugInfo::getCompletedTypeOrNull(QualType Ty) {
1872
1873 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00001874 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001875
1876 // Check for existing entry.
Adrian Prantl4919de62013-03-06 22:03:30 +00001877 llvm::Value *V = 0;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001878 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1879 CompletedTypeCache.find(Ty.getAsOpaquePtr());
Adrian Prantl4919de62013-03-06 22:03:30 +00001880 if (it != CompletedTypeCache.end())
1881 V = it->second;
1882 else {
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001883 V = getCachedInterfaceTypeOrNull(Ty);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001884 }
1885
Adrian Prantl4919de62013-03-06 22:03:30 +00001886 // Verify that any cached debug info still exists.
1887 if (V != 0)
1888 return llvm::DIType(cast<llvm::MDNode>(V));
1889
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001890 return llvm::DIType();
1891}
1892
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001893/// getCachedInterfaceTypeOrNull - Get the type from the interface
1894/// cache, unless it needs to regenerated. Otherwise return null.
1895llvm::Value *CGDebugInfo::getCachedInterfaceTypeOrNull(QualType Ty) {
1896 // Is there a cached interface that hasn't changed?
1897 llvm::DenseMap<void *, std::pair<llvm::WeakVH, unsigned > >
1898 ::iterator it1 = ObjCInterfaceCache.find(Ty.getAsOpaquePtr());
1899
1900 if (it1 != ObjCInterfaceCache.end())
1901 if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty))
1902 if (Checksum(Decl) == it1->second.second)
1903 // Return cached forward declaration.
1904 return it1->second.first;
1905
1906 return 0;
1907}
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001908
1909/// getOrCreateType - Get the type from the cache or create a new
1910/// one if necessary.
1911llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit) {
1912 if (Ty.isNull())
1913 return llvm::DIType();
1914
1915 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00001916 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001917
1918 llvm::DIType T = getCompletedTypeOrNull(Ty);
1919
1920 if (T.Verify())
1921 return T;
1922
1923 // Otherwise create the type.
1924 llvm::DIType Res = CreateTypeNode(Ty, Unit);
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001925 void* TyPtr = Ty.getAsOpaquePtr();
1926
1927 // And update the type cache.
1928 TypeCache[TyPtr] = Res;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001929
1930 llvm::DIType TC = getTypeOrNull(Ty);
1931 if (TC.Verify() && TC.isForwardDecl())
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001932 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
1933 else if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty)) {
1934 // Interface types may have elements added to them by a
1935 // subsequent implementation or extension, so we keep them in
1936 // the ObjCInterfaceCache together with a checksum. Instead of
Adrian Prantlf06989b2013-05-08 23:37:22 +00001937 // the (possibly) incomplete interface type, we return a forward
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001938 // declaration that gets RAUW'd in CGDebugInfo::finalize().
David Blaikiee2eb89a2013-05-21 18:29:40 +00001939 std::pair<llvm::WeakVH, unsigned> &V = ObjCInterfaceCache[TyPtr];
1940 if (V.first)
1941 return llvm::DIType(cast<llvm::MDNode>(V.first));
1942 TC = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
1943 Decl->getName(), TheCU, Unit,
1944 getLineNumber(Decl->getLocation()),
1945 TheCU.getLanguage());
1946 // Store the forward declaration in the cache.
1947 V.first = TC;
1948 V.second = Checksum(Decl);
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001949
David Blaikiee2eb89a2013-05-21 18:29:40 +00001950 // Register the type for replacement in finalize().
1951 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
1952
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001953 return TC;
Adrian Prantl4919de62013-03-06 22:03:30 +00001954 }
1955
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001956 if (!Res.isForwardDecl())
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001957 CompletedTypeCache[TyPtr] = Res;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001958
1959 return Res;
1960}
1961
Adrian Prantl4919de62013-03-06 22:03:30 +00001962/// Currently the checksum merely consists of the number of ivars.
1963unsigned CGDebugInfo::Checksum(const ObjCInterfaceDecl
Adrian Prantl00df5ea2013-03-12 20:43:25 +00001964 *InterfaceDecl) {
Adrian Prantl4919de62013-03-06 22:03:30 +00001965 unsigned IvarNo = 0;
1966 for (const ObjCIvarDecl *Ivar = InterfaceDecl->all_declared_ivar_begin();
1967 Ivar != 0; Ivar = Ivar->getNextIvar()) ++IvarNo;
1968 return IvarNo;
1969}
1970
1971ObjCInterfaceDecl *CGDebugInfo::getObjCInterfaceDecl(QualType Ty) {
1972 switch (Ty->getTypeClass()) {
1973 case Type::ObjCObjectPointer:
Eric Christopherf0890c42013-05-16 00:52:20 +00001974 return getObjCInterfaceDecl(cast<ObjCObjectPointerType>(Ty)
1975 ->getPointeeType());
Adrian Prantl4919de62013-03-06 22:03:30 +00001976 case Type::ObjCInterface:
1977 return cast<ObjCInterfaceType>(Ty)->getDecl();
1978 default:
1979 return 0;
1980 }
1981}
1982
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001983/// CreateTypeNode - Create a new debug type node.
1984llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit) {
1985 // Handle qualifiers, which recursively handles what they refer to.
1986 if (Ty.hasLocalQualifiers())
1987 return CreateQualifiedType(Ty, Unit);
1988
1989 const char *Diag = 0;
Eric Christopher6537f082013-05-16 00:45:12 +00001990
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001991 // Work out details of type.
1992 switch (Ty->getTypeClass()) {
1993#define TYPE(Class, Base)
1994#define ABSTRACT_TYPE(Class, Base)
1995#define NON_CANONICAL_TYPE(Class, Base)
1996#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1997#include "clang/AST/TypeNodes.def"
1998 llvm_unreachable("Dependent types cannot show up in debug information");
1999
2000 case Type::ExtVector:
2001 case Type::Vector:
2002 return CreateType(cast<VectorType>(Ty), Unit);
2003 case Type::ObjCObjectPointer:
2004 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
2005 case Type::ObjCObject:
2006 return CreateType(cast<ObjCObjectType>(Ty), Unit);
2007 case Type::ObjCInterface:
2008 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
2009 case Type::Builtin:
2010 return CreateType(cast<BuiltinType>(Ty));
2011 case Type::Complex:
2012 return CreateType(cast<ComplexType>(Ty));
2013 case Type::Pointer:
2014 return CreateType(cast<PointerType>(Ty), Unit);
2015 case Type::BlockPointer:
2016 return CreateType(cast<BlockPointerType>(Ty), Unit);
2017 case Type::Typedef:
2018 return CreateType(cast<TypedefType>(Ty), Unit);
2019 case Type::Record:
2020 return CreateType(cast<RecordType>(Ty));
2021 case Type::Enum:
2022 return CreateEnumType(cast<EnumType>(Ty)->getDecl());
2023 case Type::FunctionProto:
2024 case Type::FunctionNoProto:
2025 return CreateType(cast<FunctionType>(Ty), Unit);
2026 case Type::ConstantArray:
2027 case Type::VariableArray:
2028 case Type::IncompleteArray:
2029 return CreateType(cast<ArrayType>(Ty), Unit);
2030
2031 case Type::LValueReference:
2032 return CreateType(cast<LValueReferenceType>(Ty), Unit);
2033 case Type::RValueReference:
2034 return CreateType(cast<RValueReferenceType>(Ty), Unit);
2035
2036 case Type::MemberPointer:
2037 return CreateType(cast<MemberPointerType>(Ty), Unit);
2038
2039 case Type::Atomic:
2040 return CreateType(cast<AtomicType>(Ty), Unit);
2041
2042 case Type::Attributed:
2043 case Type::TemplateSpecialization:
2044 case Type::Elaborated:
2045 case Type::Paren:
2046 case Type::SubstTemplateTypeParm:
2047 case Type::TypeOfExpr:
2048 case Type::TypeOf:
2049 case Type::Decltype:
2050 case Type::UnaryTransform:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002051 llvm_unreachable("type should have been unwrapped!");
David Blaikie91296482013-05-24 21:24:35 +00002052 case Type::Auto:
2053 Diag = "auto";
2054 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002055 }
Eric Christopher6537f082013-05-16 00:45:12 +00002056
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002057 assert(Diag && "Fall through without a diagnostic?");
2058 unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error,
2059 "debug information for %0 is not yet supported");
2060 CGM.getDiags().Report(DiagID)
2061 << Diag;
2062 return llvm::DIType();
2063}
2064
2065/// getOrCreateLimitedType - Get the type from the cache or create a new
2066/// limited type if necessary.
2067llvm::DIType CGDebugInfo::getOrCreateLimitedType(QualType Ty,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002068 llvm::DIFile Unit) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002069 if (Ty.isNull())
2070 return llvm::DIType();
2071
2072 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00002073 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002074
2075 llvm::DIType T = getTypeOrNull(Ty);
2076
2077 // We may have cached a forward decl when we could have created
2078 // a non-forward decl. Go ahead and create a non-forward decl
2079 // now.
2080 if (T.Verify() && !T.isForwardDecl()) return T;
2081
2082 // Otherwise create the type.
2083 llvm::DIType Res = CreateLimitedTypeNode(Ty, Unit);
2084
2085 if (T.Verify() && T.isForwardDecl())
2086 ReplaceMap.push_back(std::make_pair(Ty.getAsOpaquePtr(),
2087 static_cast<llvm::Value*>(T)));
2088
2089 // And update the type cache.
2090 TypeCache[Ty.getAsOpaquePtr()] = Res;
2091 return Res;
2092}
2093
2094// TODO: Currently used for context chains when limiting debug info.
2095llvm::DIType CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
2096 RecordDecl *RD = Ty->getDecl();
Eric Christopher6537f082013-05-16 00:45:12 +00002097
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002098 // Get overall information about the record type for the debug info.
2099 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
2100 unsigned Line = getLineNumber(RD->getLocation());
2101 StringRef RDName = getClassName(RD);
2102
2103 llvm::DIDescriptor RDContext;
Eric Christopher13c97672013-05-16 00:45:23 +00002104 if (DebugKind == CodeGenOptions::LimitedDebugInfo)
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002105 RDContext = createContextChain(cast<Decl>(RD->getDeclContext()));
2106 else
2107 RDContext = getContextDescriptor(cast<Decl>(RD->getDeclContext()));
2108
2109 // If this is just a forward declaration, construct an appropriately
2110 // marked node and just return it.
2111 if (!RD->getDefinition())
2112 return createRecordFwdDecl(RD, RDContext);
2113
2114 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2115 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
2116 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
David Blaikie2fcadbe2013-03-26 23:47:35 +00002117 llvm::DICompositeType RealDecl;
Eric Christopher6537f082013-05-16 00:45:12 +00002118
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002119 if (RD->isUnion())
2120 RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002121 Size, Align, 0, llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002122 else if (RD->isClass()) {
2123 // FIXME: This could be a struct type giving a default visibility different
2124 // than C++ class type, but needs llvm metadata changes first.
2125 RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002126 Size, Align, 0, 0, llvm::DIType(),
2127 llvm::DIArray(), llvm::DIType(),
2128 llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002129 } else
2130 RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line,
Eric Christopherf0890c42013-05-16 00:52:20 +00002131 Size, Align, 0, llvm::DIType(),
2132 llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002133
2134 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
David Blaikie2fcadbe2013-03-26 23:47:35 +00002135 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002136
2137 if (CXXDecl) {
2138 // A class's primary base or the class itself contains the vtable.
David Blaikie2fcadbe2013-03-26 23:47:35 +00002139 llvm::DICompositeType ContainingType;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002140 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2141 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
2142 // Seek non virtual primary base root.
2143 while (1) {
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002144 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
2145 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
2146 if (PBT && !BRL.isPrimaryBaseVirtual())
2147 PBase = PBT;
2148 else
2149 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002150 }
David Blaikie2fcadbe2013-03-26 23:47:35 +00002151 ContainingType = llvm::DICompositeType(
2152 getOrCreateType(QualType(PBase->getTypeForDecl(), 0), DefUnit));
2153 } else if (CXXDecl->isDynamicClass())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002154 ContainingType = RealDecl;
2155
David Blaikie2fcadbe2013-03-26 23:47:35 +00002156 RealDecl.setContainingType(ContainingType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002157 }
2158 return llvm::DIType(RealDecl);
2159}
2160
2161/// CreateLimitedTypeNode - Create a new debug type node, but only forward
2162/// declare composite types that haven't been processed yet.
2163llvm::DIType CGDebugInfo::CreateLimitedTypeNode(QualType Ty,llvm::DIFile Unit) {
2164
2165 // Work out details of type.
2166 switch (Ty->getTypeClass()) {
2167#define TYPE(Class, Base)
2168#define ABSTRACT_TYPE(Class, Base)
2169#define NON_CANONICAL_TYPE(Class, Base)
2170#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2171 #include "clang/AST/TypeNodes.def"
2172 llvm_unreachable("Dependent types cannot show up in debug information");
2173
2174 case Type::Record:
2175 return CreateLimitedType(cast<RecordType>(Ty));
2176 default:
2177 return CreateTypeNode(Ty, Unit);
2178 }
2179}
2180
2181/// CreateMemberType - Create new member and increase Offset by FType's size.
2182llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
2183 StringRef Name,
2184 uint64_t *Offset) {
2185 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2186 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
2187 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
2188 llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0,
2189 FieldSize, FieldAlign,
2190 *Offset, 0, FieldTy);
2191 *Offset += FieldSize;
2192 return Ty;
2193}
2194
David Blaikie9faebd22013-05-20 04:58:53 +00002195llvm::DIDescriptor CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
2196 // We only need a declaration (not a definition) of the type - so use whatever
2197 // we would otherwise do to get a type for a pointee. (forward declarations in
2198 // limited debug info, full definitions (if the type definition is available)
2199 // in unlimited debug info)
2200 if (const TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
2201 llvm::DIFile DefUnit = getOrCreateFile(TD->getLocation());
David Blaikieb0f77b02013-05-24 21:33:22 +00002202 return getOrCreateTypeDeclaration(CGM.getContext().getTypeDeclType(TD),
2203 DefUnit);
David Blaikie9faebd22013-05-20 04:58:53 +00002204 }
2205 // Otherwise fall back to a fairly rudimentary cache of existing declarations.
2206 // This doesn't handle providing declarations (for functions or variables) for
2207 // entities without definitions in this TU, nor when the definition proceeds
2208 // the call to this function.
2209 // FIXME: This should be split out into more specific maps with support for
2210 // emitting forward declarations and merging definitions with declarations,
2211 // the same way as we do for types.
2212 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator I =
2213 DeclCache.find(D->getCanonicalDecl());
2214 if (I == DeclCache.end())
2215 return llvm::DIDescriptor();
2216 llvm::Value *V = I->second;
2217 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
2218}
2219
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002220/// getFunctionDeclaration - Return debug info descriptor to describe method
2221/// declaration for the given method definition.
2222llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
2223 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
2224 if (!FD) return llvm::DISubprogram();
2225
2226 // Setup context.
2227 getContextDescriptor(cast<Decl>(D->getDeclContext()));
2228
2229 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2230 MI = SPCache.find(FD->getCanonicalDecl());
2231 if (MI != SPCache.end()) {
2232 llvm::Value *V = MI->second;
2233 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
2234 if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
2235 return SP;
2236 }
2237
2238 for (FunctionDecl::redecl_iterator I = FD->redecls_begin(),
2239 E = FD->redecls_end(); I != E; ++I) {
2240 const FunctionDecl *NextFD = *I;
2241 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2242 MI = SPCache.find(NextFD->getCanonicalDecl());
2243 if (MI != SPCache.end()) {
2244 llvm::Value *V = MI->second;
2245 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
2246 if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
2247 return SP;
2248 }
2249 }
2250 return llvm::DISubprogram();
2251}
2252
2253// getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
2254// implicit parameter "this".
David Blaikie9a845292013-05-22 23:22:42 +00002255llvm::DICompositeType CGDebugInfo::getOrCreateFunctionType(const Decl *D,
2256 QualType FnType,
2257 llvm::DIFile F) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002258
2259 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
2260 return getOrCreateMethodType(Method, F);
2261 if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
2262 // Add "self" and "_cmd"
2263 SmallVector<llvm::Value *, 16> Elts;
2264
2265 // First element is always return type. For 'void' functions it is NULL.
Adrian Prantl0cb00022013-05-22 21:37:49 +00002266 QualType ResultTy = OMethod->getResultType();
2267
2268 // Replace the instancetype keyword with the actual type.
2269 if (ResultTy == CGM.getContext().getObjCInstanceType())
2270 ResultTy = CGM.getContext().getPointerType(
2271 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
2272
Adrian Prantl566a9c32013-05-10 21:08:31 +00002273 Elts.push_back(getOrCreateType(ResultTy, F));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002274 // "self" pointer is always first argument.
Adrian Prantle86fcc42013-03-29 19:20:29 +00002275 QualType SelfDeclTy = OMethod->getSelfDecl()->getType();
2276 llvm::DIType SelfTy = getOrCreateType(SelfDeclTy, F);
2277 Elts.push_back(CreateSelfType(SelfDeclTy, SelfTy));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002278 // "_cmd" pointer is always second argument.
2279 llvm::DIType CmdTy = getOrCreateType(OMethod->getCmdDecl()->getType(), F);
2280 Elts.push_back(DBuilder.createArtificialType(CmdTy));
2281 // Get rest of the arguments.
Eric Christopher6537f082013-05-16 00:45:12 +00002282 for (ObjCMethodDecl::param_const_iterator PI = OMethod->param_begin(),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002283 PE = OMethod->param_end(); PI != PE; ++PI)
2284 Elts.push_back(getOrCreateType((*PI)->getType(), F));
2285
2286 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2287 return DBuilder.createSubroutineType(F, EltTypeArray);
2288 }
David Blaikie9a845292013-05-22 23:22:42 +00002289 return llvm::DICompositeType(getOrCreateType(FnType, F));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002290}
2291
2292/// EmitFunctionStart - Constructs the debug code for entering a function.
2293void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
2294 llvm::Function *Fn,
2295 CGBuilderTy &Builder) {
2296
2297 StringRef Name;
2298 StringRef LinkageName;
2299
2300 FnBeginRegionCount.push_back(LexicalBlockStack.size());
2301
2302 const Decl *D = GD.getDecl();
2303 // Function may lack declaration in source code if it is created by Clang
2304 // CodeGen (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
2305 bool HasDecl = (D != 0);
2306 // Use the location of the declaration.
2307 SourceLocation Loc;
2308 if (HasDecl)
2309 Loc = D->getLocation();
2310
2311 unsigned Flags = 0;
2312 llvm::DIFile Unit = getOrCreateFile(Loc);
2313 llvm::DIDescriptor FDContext(Unit);
2314 llvm::DIArray TParamsArray;
2315 if (!HasDecl) {
2316 // Use llvm function name.
2317 Name = Fn->getName();
2318 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2319 // If there is a DISubprogram for this function available then use it.
2320 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2321 FI = SPCache.find(FD->getCanonicalDecl());
2322 if (FI != SPCache.end()) {
2323 llvm::Value *V = FI->second;
2324 llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(V));
2325 if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
2326 llvm::MDNode *SPN = SP;
2327 LexicalBlockStack.push_back(SPN);
2328 RegionMap[D] = llvm::WeakVH(SP);
2329 return;
2330 }
2331 }
2332 Name = getFunctionName(FD);
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002333 // Use mangled name as linkage name for C/C++ functions.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002334 if (FD->hasPrototype()) {
2335 LinkageName = CGM.getMangledName(GD);
2336 Flags |= llvm::DIDescriptor::FlagPrototyped;
2337 }
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002338 // No need to replicate the linkage name if it isn't different from the
2339 // subprogram name, no need to have it at all unless coverage is enabled or
2340 // debug is set to more than just line tables.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002341 if (LinkageName == Name ||
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002342 (!CGM.getCodeGenOpts().EmitGcovArcs &&
2343 !CGM.getCodeGenOpts().EmitGcovNotes &&
Eric Christopher13c97672013-05-16 00:45:23 +00002344 DebugKind <= CodeGenOptions::DebugLineTablesOnly))
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002345 LinkageName = StringRef();
2346
Eric Christopher13c97672013-05-16 00:45:23 +00002347 if (DebugKind >= CodeGenOptions::LimitedDebugInfo) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002348 if (const NamespaceDecl *NSDecl =
2349 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
2350 FDContext = getOrCreateNameSpace(NSDecl);
2351 else if (const RecordDecl *RDecl =
2352 dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
2353 FDContext = getContextDescriptor(cast<Decl>(RDecl->getDeclContext()));
2354
2355 // Collect template parameters.
2356 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
2357 }
2358 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
2359 Name = getObjCMethodName(OMD);
2360 Flags |= llvm::DIDescriptor::FlagPrototyped;
2361 } else {
2362 // Use llvm function name.
2363 Name = Fn->getName();
2364 Flags |= llvm::DIDescriptor::FlagPrototyped;
2365 }
2366 if (!Name.empty() && Name[0] == '\01')
2367 Name = Name.substr(1);
2368
2369 unsigned LineNo = getLineNumber(Loc);
2370 if (!HasDecl || D->isImplicit())
2371 Flags |= llvm::DIDescriptor::FlagArtificial;
2372
David Blaikie9a845292013-05-22 23:22:42 +00002373 llvm::DICompositeType DIFnType;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002374 llvm::DISubprogram SPDecl;
2375 if (HasDecl &&
Eric Christopher13c97672013-05-16 00:45:23 +00002376 DebugKind >= CodeGenOptions::LimitedDebugInfo) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002377 DIFnType = getOrCreateFunctionType(D, FnType, Unit);
2378 SPDecl = getFunctionDeclaration(D);
2379 } else {
2380 // Create fake but valid subroutine type. Otherwise
2381 // llvm::DISubprogram::Verify() would return false, and
2382 // subprogram DIE will miss DW_AT_decl_file and
2383 // DW_AT_decl_line fields.
2384 SmallVector<llvm::Value*, 16> Elts;
2385 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2386 DIFnType = DBuilder.createSubroutineType(Unit, EltTypeArray);
2387 }
2388 llvm::DISubprogram SP;
2389 SP = DBuilder.createFunction(FDContext, Name, LinkageName, Unit,
2390 LineNo, DIFnType,
2391 Fn->hasInternalLinkage(), true/*definition*/,
2392 getLineNumber(CurLoc), Flags,
2393 CGM.getLangOpts().Optimize,
2394 Fn, TParamsArray, SPDecl);
David Blaikie9faebd22013-05-20 04:58:53 +00002395 if (HasDecl)
2396 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(SP)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002397
2398 // Push function on region stack.
2399 llvm::MDNode *SPN = SP;
2400 LexicalBlockStack.push_back(SPN);
2401 if (HasDecl)
2402 RegionMap[D] = llvm::WeakVH(SP);
2403}
2404
2405/// EmitLocation - Emit metadata to indicate a change in line/column
2406/// information in the source file.
Adrian Prantl00df5ea2013-03-12 20:43:25 +00002407void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc,
2408 bool ForceColumnInfo) {
Eric Christopher6537f082013-05-16 00:45:12 +00002409
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002410 // Update our current location
2411 setLocation(Loc);
2412
2413 if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
2414
2415 // Don't bother if things are the same as last time.
2416 SourceManager &SM = CGM.getContext().getSourceManager();
2417 if (CurLoc == PrevLoc ||
2418 SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc))
2419 // New Builder may not be in sync with CGDebugInfo.
David Blaikie0a0f93c2013-02-01 19:09:49 +00002420 if (!Builder.getCurrentDebugLocation().isUnknown() &&
2421 Builder.getCurrentDebugLocation().getScope(CGM.getLLVMContext()) ==
2422 LexicalBlockStack.back())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002423 return;
Eric Christopher6537f082013-05-16 00:45:12 +00002424
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002425 // Update last state.
2426 PrevLoc = CurLoc;
2427
2428 llvm::MDNode *Scope = LexicalBlockStack.back();
Adrian Prantl00df5ea2013-03-12 20:43:25 +00002429 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get
2430 (getLineNumber(CurLoc),
2431 getColumnNumber(CurLoc, ForceColumnInfo),
2432 Scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002433}
2434
2435/// CreateLexicalBlock - Creates a new lexical block node and pushes it on
2436/// the stack.
2437void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
2438 llvm::DIDescriptor D =
2439 DBuilder.createLexicalBlock(LexicalBlockStack.empty() ?
2440 llvm::DIDescriptor() :
2441 llvm::DIDescriptor(LexicalBlockStack.back()),
2442 getOrCreateFile(CurLoc),
2443 getLineNumber(CurLoc),
2444 getColumnNumber(CurLoc));
2445 llvm::MDNode *DN = D;
2446 LexicalBlockStack.push_back(DN);
2447}
2448
2449/// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
2450/// region - beginning of a DW_TAG_lexical_block.
Eric Christopherf0890c42013-05-16 00:52:20 +00002451void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
2452 SourceLocation Loc) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002453 // Set our current location.
2454 setLocation(Loc);
2455
2456 // Create a new lexical block and push it on the stack.
2457 CreateLexicalBlock(Loc);
2458
2459 // Emit a line table change for the current location inside the new scope.
2460 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc),
2461 getColumnNumber(Loc),
2462 LexicalBlockStack.back()));
2463}
2464
2465/// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative
2466/// region - end of a DW_TAG_lexical_block.
Eric Christopherf0890c42013-05-16 00:52:20 +00002467void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
2468 SourceLocation Loc) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002469 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2470
2471 // Provide an entry in the line table for the end of the block.
2472 EmitLocation(Builder, Loc);
2473
2474 LexicalBlockStack.pop_back();
2475}
2476
2477/// EmitFunctionEnd - Constructs the debug code for exiting a function.
2478void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
2479 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2480 unsigned RCount = FnBeginRegionCount.back();
2481 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
2482
2483 // Pop all regions for this function.
2484 while (LexicalBlockStack.size() != RCount)
2485 EmitLexicalBlockEnd(Builder, CurLoc);
2486 FnBeginRegionCount.pop_back();
2487}
2488
Eric Christopher6537f082013-05-16 00:45:12 +00002489// EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002490// See BuildByRefType.
2491llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
2492 uint64_t *XOffset) {
2493
2494 SmallVector<llvm::Value *, 5> EltTys;
2495 QualType FType;
2496 uint64_t FieldSize, FieldOffset;
2497 unsigned FieldAlign;
Eric Christopher6537f082013-05-16 00:45:12 +00002498
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002499 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
Eric Christopher6537f082013-05-16 00:45:12 +00002500 QualType Type = VD->getType();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002501
2502 FieldOffset = 0;
2503 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2504 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
2505 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
2506 FType = CGM.getContext().IntTy;
2507 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
2508 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
2509
2510 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
2511 if (HasCopyAndDispose) {
2512 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2513 EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
2514 &FieldOffset));
2515 EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
2516 &FieldOffset));
2517 }
2518 bool HasByrefExtendedLayout;
2519 Qualifiers::ObjCLifetime Lifetime;
2520 if (CGM.getContext().getByrefLifetime(Type,
2521 Lifetime, HasByrefExtendedLayout)
2522 && HasByrefExtendedLayout)
2523 EltTys.push_back(CreateMemberType(Unit, FType,
2524 "__byref_variable_layout",
2525 &FieldOffset));
Eric Christopher6537f082013-05-16 00:45:12 +00002526
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002527 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2528 if (Align > CGM.getContext().toCharUnitsFromBits(
John McCall64aa4b32013-04-16 22:48:15 +00002529 CGM.getTarget().getPointerAlign(0))) {
Eric Christopher6537f082013-05-16 00:45:12 +00002530 CharUnits FieldOffsetInBytes
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002531 = CGM.getContext().toCharUnitsFromBits(FieldOffset);
2532 CharUnits AlignedOffsetInBytes
2533 = FieldOffsetInBytes.RoundUpToAlignment(Align);
2534 CharUnits NumPaddingBytes
2535 = AlignedOffsetInBytes - FieldOffsetInBytes;
Eric Christopher6537f082013-05-16 00:45:12 +00002536
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002537 if (NumPaddingBytes.isPositive()) {
2538 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
2539 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
2540 pad, ArrayType::Normal, 0);
2541 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
2542 }
2543 }
Eric Christopher6537f082013-05-16 00:45:12 +00002544
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002545 FType = Type;
2546 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2547 FieldSize = CGM.getContext().getTypeSize(FType);
2548 FieldAlign = CGM.getContext().toBits(Align);
2549
Eric Christopher6537f082013-05-16 00:45:12 +00002550 *XOffset = FieldOffset;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002551 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit,
2552 0, FieldSize, FieldAlign,
2553 FieldOffset, 0, FieldTy);
2554 EltTys.push_back(FieldTy);
2555 FieldOffset += FieldSize;
Eric Christopher6537f082013-05-16 00:45:12 +00002556
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002557 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopher6537f082013-05-16 00:45:12 +00002558
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002559 unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
Eric Christopher6537f082013-05-16 00:45:12 +00002560
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002561 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
David Blaikiec1d0af12013-02-25 01:07:08 +00002562 llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002563}
2564
2565/// EmitDeclare - Emit local variable declaration debug info.
2566void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
Eric Christopher6537f082013-05-16 00:45:12 +00002567 llvm::Value *Storage,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002568 unsigned ArgNo, CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002569 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002570 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2571
2572 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2573 llvm::DIType Ty;
2574 uint64_t XOffset = 0;
2575 if (VD->hasAttr<BlocksAttr>())
2576 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopher6537f082013-05-16 00:45:12 +00002577 else
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002578 Ty = getOrCreateType(VD->getType(), Unit);
2579
2580 // If there is no debug info for this type then do not emit debug info
2581 // for this variable.
2582 if (!Ty)
2583 return;
2584
2585 if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage)) {
2586 // If Storage is an aggregate returned as 'sret' then let debugger know
2587 // about this.
2588 if (Arg->hasStructRetAttr())
2589 Ty = DBuilder.createReferenceType(llvm::dwarf::DW_TAG_reference_type, Ty);
2590 else if (CXXRecordDecl *Record = VD->getType()->getAsCXXRecordDecl()) {
2591 // If an aggregate variable has non trivial destructor or non trivial copy
2592 // constructor than it is pass indirectly. Let debug info know about this
2593 // by using reference of the aggregate type as a argument type.
2594 if (Record->hasNonTrivialCopyConstructor() ||
2595 !Record->hasTrivialDestructor())
Eric Christopherf0890c42013-05-16 00:52:20 +00002596 Ty = DBuilder.createReferenceType(llvm::dwarf::DW_TAG_reference_type,
2597 Ty);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002598 }
2599 }
Eric Christopher6537f082013-05-16 00:45:12 +00002600
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002601 // Get location information.
2602 unsigned Line = getLineNumber(VD->getLocation());
2603 unsigned Column = getColumnNumber(VD->getLocation());
2604 unsigned Flags = 0;
2605 if (VD->isImplicit())
2606 Flags |= llvm::DIDescriptor::FlagArtificial;
2607 // If this is the first argument and it is implicit then
2608 // give it an object pointer flag.
2609 // FIXME: There has to be a better way to do this, but for static
2610 // functions there won't be an implicit param at arg1 and
2611 // otherwise it is 'self' or 'this'.
2612 if (isa<ImplicitParamDecl>(VD) && ArgNo == 1)
2613 Flags |= llvm::DIDescriptor::FlagObjectPointer;
2614
2615 llvm::MDNode *Scope = LexicalBlockStack.back();
2616
2617 StringRef Name = VD->getName();
2618 if (!Name.empty()) {
2619 if (VD->hasAttr<BlocksAttr>()) {
2620 CharUnits offset = CharUnits::fromQuantity(32);
2621 SmallVector<llvm::Value *, 9> addr;
2622 llvm::Type *Int64Ty = CGM.Int64Ty;
2623 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2624 // offset of __forwarding field
2625 offset = CGM.getContext().toCharUnitsFromBits(
John McCall64aa4b32013-04-16 22:48:15 +00002626 CGM.getTarget().getPointerWidth(0));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002627 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2628 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2629 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2630 // offset of x field
2631 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2632 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2633
2634 // Create the descriptor for the variable.
2635 llvm::DIVariable D =
Eric Christopher6537f082013-05-16 00:45:12 +00002636 DBuilder.createComplexVariable(Tag,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002637 llvm::DIDescriptor(Scope),
2638 VD->getName(), Unit, Line, Ty,
2639 addr, ArgNo);
Eric Christopher6537f082013-05-16 00:45:12 +00002640
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002641 // Insert an llvm.dbg.declare into the current block.
2642 llvm::Instruction *Call =
2643 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2644 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2645 return;
Adrian Prantl230ea412013-04-30 22:45:09 +00002646 } else if (isa<VariableArrayType>(VD->getType())) {
2647 // These are "complex" variables in that they need an op_deref.
2648 // Create the descriptor for the variable.
2649 llvm::Value *Addr = llvm::ConstantInt::get(CGM.Int64Ty,
2650 llvm::DIBuilder::OpDeref);
2651 llvm::DIVariable D =
2652 DBuilder.createComplexVariable(Tag,
2653 llvm::DIDescriptor(Scope),
2654 Name, Unit, Line, Ty,
2655 Addr, ArgNo);
2656
2657 // Insert an llvm.dbg.declare into the current block.
2658 llvm::Instruction *Call =
2659 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2660 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2661 return;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002662 }
David Blaikie436653b2013-01-05 05:58:35 +00002663 } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2664 // If VD is an anonymous union then Storage represents value for
2665 // all union fields.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002666 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
David Blaikied8180cf2013-01-05 20:03:07 +00002667 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002668 for (RecordDecl::field_iterator I = RD->field_begin(),
2669 E = RD->field_end();
2670 I != E; ++I) {
2671 FieldDecl *Field = *I;
2672 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2673 StringRef FieldName = Field->getName();
Eric Christopher6537f082013-05-16 00:45:12 +00002674
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002675 // Ignore unnamed fields. Do not ignore unnamed records.
2676 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2677 continue;
Eric Christopher6537f082013-05-16 00:45:12 +00002678
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002679 // Use VarDecl's Tag, Scope and Line number.
2680 llvm::DIVariable D =
2681 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
Eric Christopher6537f082013-05-16 00:45:12 +00002682 FieldName, Unit, Line, FieldTy,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002683 CGM.getLangOpts().Optimize, Flags,
2684 ArgNo);
Eric Christopher6537f082013-05-16 00:45:12 +00002685
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002686 // Insert an llvm.dbg.declare into the current block.
2687 llvm::Instruction *Call =
2688 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2689 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2690 }
David Blaikied8180cf2013-01-05 20:03:07 +00002691 return;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002692 }
2693 }
David Blaikie436653b2013-01-05 05:58:35 +00002694
2695 // Create the descriptor for the variable.
2696 llvm::DIVariable D =
2697 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2698 Name, Unit, Line, Ty,
2699 CGM.getLangOpts().Optimize, Flags, ArgNo);
2700
2701 // Insert an llvm.dbg.declare into the current block.
2702 llvm::Instruction *Call =
2703 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2704 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002705}
2706
2707void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2708 llvm::Value *Storage,
2709 CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002710 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002711 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2712}
2713
Adrian Prantle86fcc42013-03-29 19:20:29 +00002714/// Look up the completed type for a self pointer in the TypeCache and
2715/// create a copy of it with the ObjectPointer and Artificial flags
2716/// set. If the type is not cached, a new one is created. This should
2717/// never happen though, since creating a type for the implicit self
2718/// argument implies that we already parsed the interface definition
2719/// and the ivar declarations in the implementation.
Eric Christopherf0890c42013-05-16 00:52:20 +00002720llvm::DIType CGDebugInfo::CreateSelfType(const QualType &QualTy,
2721 llvm::DIType Ty) {
Adrian Prantle86fcc42013-03-29 19:20:29 +00002722 llvm::DIType CachedTy = getTypeOrNull(QualTy);
2723 if (CachedTy.Verify()) Ty = CachedTy;
2724 else DEBUG(llvm::dbgs() << "No cached type for self.");
2725 return DBuilder.createObjectPointerType(Ty);
2726}
2727
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002728void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(const VarDecl *VD,
2729 llvm::Value *Storage,
2730 CGBuilderTy &Builder,
2731 const CGBlockInfo &blockInfo) {
Eric Christopher13c97672013-05-16 00:45:23 +00002732 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002733 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
Eric Christopher6537f082013-05-16 00:45:12 +00002734
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002735 if (Builder.GetInsertBlock() == 0)
2736 return;
Eric Christopher6537f082013-05-16 00:45:12 +00002737
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002738 bool isByRef = VD->hasAttr<BlocksAttr>();
Eric Christopher6537f082013-05-16 00:45:12 +00002739
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002740 uint64_t XOffset = 0;
2741 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2742 llvm::DIType Ty;
2743 if (isByRef)
2744 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopher6537f082013-05-16 00:45:12 +00002745 else
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002746 Ty = getOrCreateType(VD->getType(), Unit);
2747
2748 // Self is passed along as an implicit non-arg variable in a
2749 // block. Mark it as the object pointer.
2750 if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self")
Adrian Prantle86fcc42013-03-29 19:20:29 +00002751 Ty = CreateSelfType(VD->getType(), Ty);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002752
2753 // Get location information.
2754 unsigned Line = getLineNumber(VD->getLocation());
2755 unsigned Column = getColumnNumber(VD->getLocation());
2756
2757 const llvm::DataLayout &target = CGM.getDataLayout();
2758
2759 CharUnits offset = CharUnits::fromQuantity(
2760 target.getStructLayout(blockInfo.StructureType)
2761 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2762
2763 SmallVector<llvm::Value *, 9> addr;
2764 llvm::Type *Int64Ty = CGM.Int64Ty;
Adrian Prantl9b97adf2013-03-29 19:20:35 +00002765 if (isa<llvm::AllocaInst>(Storage))
2766 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002767 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2768 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2769 if (isByRef) {
2770 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2771 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2772 // offset of __forwarding field
2773 offset = CGM.getContext()
2774 .toCharUnitsFromBits(target.getPointerSizeInBits(0));
2775 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2776 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2777 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2778 // offset of x field
2779 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2780 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2781 }
2782
2783 // Create the descriptor for the variable.
2784 llvm::DIVariable D =
Eric Christopher6537f082013-05-16 00:45:12 +00002785 DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002786 llvm::DIDescriptor(LexicalBlockStack.back()),
2787 VD->getName(), Unit, Line, Ty, addr);
Adrian Prantl9b97adf2013-03-29 19:20:35 +00002788
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002789 // Insert an llvm.dbg.declare into the current block.
2790 llvm::Instruction *Call =
2791 DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
2792 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column,
2793 LexicalBlockStack.back()));
2794}
2795
2796/// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2797/// variable declaration.
2798void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2799 unsigned ArgNo,
2800 CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002801 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002802 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2803}
2804
2805namespace {
2806 struct BlockLayoutChunk {
2807 uint64_t OffsetInBits;
2808 const BlockDecl::Capture *Capture;
2809 };
2810 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2811 return l.OffsetInBits < r.OffsetInBits;
2812 }
2813}
2814
2815void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
Adrian Prantl836e7c92013-03-14 17:53:33 +00002816 llvm::Value *Arg,
2817 llvm::Value *LocalAddr,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002818 CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002819 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002820 ASTContext &C = CGM.getContext();
2821 const BlockDecl *blockDecl = block.getBlockDecl();
2822
2823 // Collect some general information about the block's location.
2824 SourceLocation loc = blockDecl->getCaretLocation();
2825 llvm::DIFile tunit = getOrCreateFile(loc);
2826 unsigned line = getLineNumber(loc);
2827 unsigned column = getColumnNumber(loc);
Eric Christopher6537f082013-05-16 00:45:12 +00002828
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002829 // Build the debug-info type for the block literal.
2830 getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
2831
2832 const llvm::StructLayout *blockLayout =
2833 CGM.getDataLayout().getStructLayout(block.StructureType);
2834
2835 SmallVector<llvm::Value*, 16> fields;
2836 fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
2837 blockLayout->getElementOffsetInBits(0),
2838 tunit, tunit));
2839 fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
2840 blockLayout->getElementOffsetInBits(1),
2841 tunit, tunit));
2842 fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
2843 blockLayout->getElementOffsetInBits(2),
2844 tunit, tunit));
2845 fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
2846 blockLayout->getElementOffsetInBits(3),
2847 tunit, tunit));
2848 fields.push_back(createFieldType("__descriptor",
2849 C.getPointerType(block.NeedsCopyDispose ?
2850 C.getBlockDescriptorExtendedType() :
2851 C.getBlockDescriptorType()),
2852 0, loc, AS_public,
2853 blockLayout->getElementOffsetInBits(4),
2854 tunit, tunit));
2855
2856 // We want to sort the captures by offset, not because DWARF
2857 // requires this, but because we're paranoid about debuggers.
2858 SmallVector<BlockLayoutChunk, 8> chunks;
2859
2860 // 'this' capture.
2861 if (blockDecl->capturesCXXThis()) {
2862 BlockLayoutChunk chunk;
2863 chunk.OffsetInBits =
2864 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
2865 chunk.Capture = 0;
2866 chunks.push_back(chunk);
2867 }
2868
2869 // Variable captures.
2870 for (BlockDecl::capture_const_iterator
2871 i = blockDecl->capture_begin(), e = blockDecl->capture_end();
2872 i != e; ++i) {
2873 const BlockDecl::Capture &capture = *i;
2874 const VarDecl *variable = capture.getVariable();
2875 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
2876
2877 // Ignore constant captures.
2878 if (captureInfo.isConstant())
2879 continue;
2880
2881 BlockLayoutChunk chunk;
2882 chunk.OffsetInBits =
2883 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
2884 chunk.Capture = &capture;
2885 chunks.push_back(chunk);
2886 }
2887
2888 // Sort by offset.
2889 llvm::array_pod_sort(chunks.begin(), chunks.end());
2890
2891 for (SmallVectorImpl<BlockLayoutChunk>::iterator
2892 i = chunks.begin(), e = chunks.end(); i != e; ++i) {
2893 uint64_t offsetInBits = i->OffsetInBits;
2894 const BlockDecl::Capture *capture = i->Capture;
2895
2896 // If we have a null capture, this must be the C++ 'this' capture.
2897 if (!capture) {
2898 const CXXMethodDecl *method =
2899 cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
2900 QualType type = method->getThisType(C);
2901
2902 fields.push_back(createFieldType("this", type, 0, loc, AS_public,
2903 offsetInBits, tunit, tunit));
2904 continue;
2905 }
2906
2907 const VarDecl *variable = capture->getVariable();
2908 StringRef name = variable->getName();
2909
2910 llvm::DIType fieldType;
2911 if (capture->isByRef()) {
2912 std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
2913
2914 // FIXME: this creates a second copy of this type!
2915 uint64_t xoffset;
2916 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
2917 fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
2918 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
2919 ptrInfo.first, ptrInfo.second,
2920 offsetInBits, 0, fieldType);
2921 } else {
2922 fieldType = createFieldType(name, variable->getType(), 0,
2923 loc, AS_public, offsetInBits, tunit, tunit);
2924 }
2925 fields.push_back(fieldType);
2926 }
2927
2928 SmallString<36> typeName;
2929 llvm::raw_svector_ostream(typeName)
2930 << "__block_literal_" << CGM.getUniqueBlockCount();
2931
2932 llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
2933
2934 llvm::DIType type =
2935 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
2936 CGM.getContext().toBits(block.BlockSize),
2937 CGM.getContext().toBits(block.BlockAlign),
David Blaikiec1d0af12013-02-25 01:07:08 +00002938 0, llvm::DIType(), fieldsArray);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002939 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
2940
2941 // Get overall information about the block.
2942 unsigned flags = llvm::DIDescriptor::FlagArtificial;
2943 llvm::MDNode *scope = LexicalBlockStack.back();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002944
2945 // Create the descriptor for the parameter.
2946 llvm::DIVariable debugVar =
2947 DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
Eric Christopher6537f082013-05-16 00:45:12 +00002948 llvm::DIDescriptor(scope),
Adrian Prantl836e7c92013-03-14 17:53:33 +00002949 Arg->getName(), tunit, line, type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002950 CGM.getLangOpts().Optimize, flags,
Adrian Prantl836e7c92013-03-14 17:53:33 +00002951 cast<llvm::Argument>(Arg)->getArgNo() + 1);
2952
Adrian Prantlbea407c2013-03-14 21:52:59 +00002953 if (LocalAddr) {
Adrian Prantl836e7c92013-03-14 17:53:33 +00002954 // Insert an llvm.dbg.value into the current block.
Adrian Prantlbea407c2013-03-14 21:52:59 +00002955 llvm::Instruction *DbgVal =
2956 DBuilder.insertDbgValueIntrinsic(LocalAddr, 0, debugVar,
Eric Christopherf068c922013-04-02 22:59:11 +00002957 Builder.GetInsertBlock());
Adrian Prantlbea407c2013-03-14 21:52:59 +00002958 DbgVal->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
2959 }
Adrian Prantl836e7c92013-03-14 17:53:33 +00002960
Adrian Prantlbea407c2013-03-14 21:52:59 +00002961 // Insert an llvm.dbg.declare into the current block.
2962 llvm::Instruction *DbgDecl =
2963 DBuilder.insertDeclare(Arg, debugVar, Builder.GetInsertBlock());
2964 DbgDecl->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002965}
2966
Eric Christopher0395de32013-01-16 01:22:32 +00002967/// getStaticDataMemberDeclaration - If D is an out-of-class definition of
2968/// a static data member of a class, find its corresponding in-class
2969/// declaration.
2970llvm::DIDerivedType CGDebugInfo::getStaticDataMemberDeclaration(const Decl *D) {
2971 if (cast<VarDecl>(D)->isStaticDataMember()) {
2972 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
2973 MI = StaticDataMemberCache.find(D->getCanonicalDecl());
2974 if (MI != StaticDataMemberCache.end())
2975 // Verify the info still exists.
2976 if (llvm::Value *V = MI->second)
2977 return llvm::DIDerivedType(cast<llvm::MDNode>(V));
2978 }
2979 return llvm::DIDerivedType();
2980}
2981
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002982/// EmitGlobalVariable - Emit information about a global variable.
2983void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
2984 const VarDecl *D) {
Eric Christopher13c97672013-05-16 00:45:23 +00002985 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002986 // Create global variable debug descriptor.
2987 llvm::DIFile Unit = getOrCreateFile(D->getLocation());
2988 unsigned LineNo = getLineNumber(D->getLocation());
2989
2990 setLocation(D->getLocation());
2991
2992 QualType T = D->getType();
2993 if (T->isIncompleteArrayType()) {
2994
2995 // CodeGen turns int[] into int[1] so we'll do the same here.
2996 llvm::APInt ConstVal(32, 1);
2997 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
2998
2999 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3000 ArrayType::Normal, 0);
3001 }
3002 StringRef DeclName = D->getName();
3003 StringRef LinkageName;
3004 if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext())
3005 && !isa<ObjCMethodDecl>(D->getDeclContext()))
3006 LinkageName = Var->getName();
3007 if (LinkageName == DeclName)
3008 LinkageName = StringRef();
Eric Christopher6537f082013-05-16 00:45:12 +00003009 llvm::DIDescriptor DContext =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003010 getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
David Blaikie9faebd22013-05-20 04:58:53 +00003011 llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(DContext, DeclName, LinkageName,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003012 Unit, LineNo, getOrCreateType(T, Unit),
Eric Christopher0395de32013-01-16 01:22:32 +00003013 Var->hasInternalLinkage(), Var,
3014 getStaticDataMemberDeclaration(D));
David Blaikie9faebd22013-05-20 04:58:53 +00003015 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(GV)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003016}
3017
3018/// EmitGlobalVariable - Emit information about an objective-c interface.
3019void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
3020 ObjCInterfaceDecl *ID) {
Eric Christopher13c97672013-05-16 00:45:23 +00003021 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003022 // Create global variable debug descriptor.
3023 llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
3024 unsigned LineNo = getLineNumber(ID->getLocation());
3025
3026 StringRef Name = ID->getName();
3027
3028 QualType T = CGM.getContext().getObjCInterfaceType(ID);
3029 if (T->isIncompleteArrayType()) {
3030
3031 // CodeGen turns int[] into int[1] so we'll do the same here.
3032 llvm::APInt ConstVal(32, 1);
3033 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3034
3035 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3036 ArrayType::Normal, 0);
3037 }
3038
3039 DBuilder.createGlobalVariable(Name, Unit, LineNo,
3040 getOrCreateType(T, Unit),
3041 Var->hasInternalLinkage(), Var);
3042}
3043
3044/// EmitGlobalVariable - Emit global variable's debug info.
Eric Christopher6537f082013-05-16 00:45:12 +00003045void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003046 llvm::Constant *Init) {
Eric Christopher13c97672013-05-16 00:45:23 +00003047 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003048 // Create the descriptor for the variable.
3049 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
3050 StringRef Name = VD->getName();
3051 llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
3052 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
3053 const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext());
3054 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
3055 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
3056 }
3057 // Do not use DIGlobalVariable for enums.
3058 if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
3059 return;
David Blaikie9faebd22013-05-20 04:58:53 +00003060 llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(Unit, Name, Name, Unit,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003061 getLineNumber(VD->getLocation()),
Eric Christopher0395de32013-01-16 01:22:32 +00003062 Ty, true, Init,
3063 getStaticDataMemberDeclaration(VD));
David Blaikie9faebd22013-05-20 04:58:53 +00003064 DeclCache.insert(std::make_pair(VD->getCanonicalDecl(), llvm::WeakVH(GV)));
3065}
3066
3067llvm::DIScope CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
3068 if (!LexicalBlockStack.empty())
3069 return llvm::DIScope(LexicalBlockStack.back());
3070 return getContextDescriptor(D);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003071}
3072
David Blaikie957dac52013-04-22 06:13:21 +00003073void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
David Blaikie9faebd22013-05-20 04:58:53 +00003074 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3075 return;
David Blaikie957dac52013-04-22 06:13:21 +00003076 DBuilder.createImportedModule(
David Blaikie9faebd22013-05-20 04:58:53 +00003077 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
3078 getOrCreateNameSpace(UD.getNominatedNamespace()),
David Blaikie957dac52013-04-22 06:13:21 +00003079 getLineNumber(UD.getLocation()));
3080}
3081
David Blaikie9faebd22013-05-20 04:58:53 +00003082void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
3083 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3084 return;
3085 assert(UD.shadow_size() &&
3086 "We shouldn't be codegening an invalid UsingDecl containing no decls");
3087 // Emitting one decl is sufficient - debuggers can detect that this is an
3088 // overloaded name & provide lookup for all the overloads.
3089 const UsingShadowDecl &USD = **UD.shadow_begin();
3090 if (llvm::DIDescriptor Target = getDeclarationOrDefinition(USD.getUnderlyingDecl()))
3091 DBuilder.createImportedDeclaration(
3092 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
3093 getLineNumber(USD.getLocation()));
3094}
3095
David Blaikiefc46ebc2013-05-20 22:50:41 +00003096llvm::DIImportedEntity
3097CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
3098 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3099 return llvm::DIImportedEntity(0);
3100 llvm::WeakVH &VH = NamespaceAliasCache[&NA];
3101 if (VH)
3102 return llvm::DIImportedEntity(cast<llvm::MDNode>(VH));
3103 llvm::DIImportedEntity R(0);
3104 if (const NamespaceAliasDecl *Underlying =
3105 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
3106 // This could cache & dedup here rather than relying on metadata deduping.
3107 R = DBuilder.createImportedModule(
3108 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3109 EmitNamespaceAlias(*Underlying), getLineNumber(NA.getLocation()),
3110 NA.getName());
3111 else
3112 R = DBuilder.createImportedModule(
3113 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3114 getOrCreateNameSpace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
3115 getLineNumber(NA.getLocation()), NA.getName());
3116 VH = R;
3117 return R;
3118}
3119
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003120/// getOrCreateNamesSpace - Return namespace descriptor for the given
3121/// namespace decl.
Eric Christopher6537f082013-05-16 00:45:12 +00003122llvm::DINameSpace
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003123CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
Eric Christopher6537f082013-05-16 00:45:12 +00003124 llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003125 NameSpaceCache.find(NSDecl);
3126 if (I != NameSpaceCache.end())
3127 return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
Eric Christopher6537f082013-05-16 00:45:12 +00003128
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003129 unsigned LineNo = getLineNumber(NSDecl->getLocation());
3130 llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
Eric Christopher6537f082013-05-16 00:45:12 +00003131 llvm::DIDescriptor Context =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003132 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
3133 llvm::DINameSpace NS =
3134 DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
3135 NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
3136 return NS;
3137}
3138
3139void CGDebugInfo::finalize() {
3140 for (std::vector<std::pair<void *, llvm::WeakVH> >::const_iterator VI
3141 = ReplaceMap.begin(), VE = ReplaceMap.end(); VI != VE; ++VI) {
3142 llvm::DIType Ty, RepTy;
3143 // Verify that the debug info still exists.
3144 if (llvm::Value *V = VI->second)
3145 Ty = llvm::DIType(cast<llvm::MDNode>(V));
Eric Christopher6537f082013-05-16 00:45:12 +00003146
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003147 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
3148 TypeCache.find(VI->first);
3149 if (it != TypeCache.end()) {
3150 // Verify that the debug info still exists.
3151 if (llvm::Value *V = it->second)
3152 RepTy = llvm::DIType(cast<llvm::MDNode>(V));
3153 }
Adrian Prantlebbd7e02013-03-11 18:33:46 +00003154
Adrian Prantl9b97adf2013-03-29 19:20:35 +00003155 if (Ty.Verify() && Ty.isForwardDecl() && RepTy.Verify())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003156 Ty.replaceAllUsesWith(RepTy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003157 }
Adrian Prantlebbd7e02013-03-11 18:33:46 +00003158
3159 // We keep our own list of retained types, because we need to look
3160 // up the final type in the type cache.
3161 for (std::vector<void *>::const_iterator RI = RetainedTypes.begin(),
3162 RE = RetainedTypes.end(); RI != RE; ++RI)
3163 DBuilder.retainType(llvm::DIType(cast<llvm::MDNode>(TypeCache[*RI])));
3164
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003165 DBuilder.finalize();
3166}