blob: dbae6e969920820fab30cadd4b22d4682fc2b73c [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)
44 : CGM(CGM), DBuilder(CGM.getModule()),
45 BlockLiteralGenericSet(false) {
46 CreateCompileUnit();
47}
48
49CGDebugInfo::~CGDebugInfo() {
50 assert(LexicalBlockStack.empty() &&
51 "Region stack mismatch, stack not empty!");
52}
53
54void CGDebugInfo::setLocation(SourceLocation Loc) {
55 // If the new location isn't valid return.
56 if (!Loc.isValid()) return;
57
58 CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc);
59
60 // If we've changed files in the middle of a lexical scope go ahead
61 // and create a new lexical scope with file node if it's different
62 // from the one in the scope.
63 if (LexicalBlockStack.empty()) return;
64
65 SourceManager &SM = CGM.getContext().getSourceManager();
66 PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
67 PresumedLoc PPLoc = SM.getPresumedLoc(PrevLoc);
68
69 if (PCLoc.isInvalid() || PPLoc.isInvalid() ||
70 !strcmp(PPLoc.getFilename(), PCLoc.getFilename()))
71 return;
72
73 llvm::MDNode *LB = LexicalBlockStack.back();
74 llvm::DIScope Scope = llvm::DIScope(LB);
75 if (Scope.isLexicalBlockFile()) {
76 llvm::DILexicalBlockFile LBF = llvm::DILexicalBlockFile(LB);
77 llvm::DIDescriptor D
78 = DBuilder.createLexicalBlockFile(LBF.getScope(),
79 getOrCreateFile(CurLoc));
80 llvm::MDNode *N = D;
81 LexicalBlockStack.pop_back();
82 LexicalBlockStack.push_back(N);
David Blaikiea6504852013-01-26 22:16:26 +000083 } else if (Scope.isLexicalBlock() || Scope.isSubprogram()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +000084 llvm::DIDescriptor D
85 = DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc));
86 llvm::MDNode *N = D;
87 LexicalBlockStack.pop_back();
88 LexicalBlockStack.push_back(N);
89 }
90}
91
92/// getContextDescriptor - Get context info for the decl.
David Blaikiebb000792013-04-19 06:56:38 +000093llvm::DIScope CGDebugInfo::getContextDescriptor(const Decl *Context) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +000094 if (!Context)
95 return TheCU;
96
97 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
98 I = RegionMap.find(Context);
99 if (I != RegionMap.end()) {
100 llvm::Value *V = I->second;
David Blaikiebb000792013-04-19 06:56:38 +0000101 return llvm::DIScope(dyn_cast_or_null<llvm::MDNode>(V));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000102 }
103
104 // Check namespace.
105 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
David Blaikiebb000792013-04-19 06:56:38 +0000106 return getOrCreateNameSpace(NSDecl);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000107
David Blaikiebb000792013-04-19 06:56:38 +0000108 if (const RecordDecl *RDecl = dyn_cast<RecordDecl>(Context))
109 if (!RDecl->isDependentType())
110 return getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000111 getOrCreateMainFile());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000112 return TheCU;
113}
114
115/// getFunctionName - Get function name for the given FunctionDecl. If the
116/// name is constructred on demand (e.g. C++ destructor) then the name
117/// is stored on the side.
118StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
119 assert (FD && "Invalid FunctionDecl!");
120 IdentifierInfo *FII = FD->getIdentifier();
121 FunctionTemplateSpecializationInfo *Info
122 = FD->getTemplateSpecializationInfo();
123 if (!Info && FII)
124 return FII->getName();
125
126 // Otherwise construct human readable name for debug info.
Benjamin Kramer5eada842013-02-22 15:46:01 +0000127 SmallString<128> NS;
128 llvm::raw_svector_ostream OS(NS);
129 FD->printName(OS);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000130
131 // Add any template specialization args.
132 if (Info) {
133 const TemplateArgumentList *TArgs = Info->TemplateArguments;
134 const TemplateArgument *Args = TArgs->data();
135 unsigned NumArgs = TArgs->size();
136 PrintingPolicy Policy(CGM.getLangOpts());
Benjamin Kramer5eada842013-02-22 15:46:01 +0000137 TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs,
138 Policy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000139 }
140
141 // Copy this name on the side and use its reference.
Benjamin Kramer5eada842013-02-22 15:46:01 +0000142 OS.flush();
143 char *StrPtr = DebugInfoNames.Allocate<char>(NS.size());
144 memcpy(StrPtr, NS.data(), NS.size());
145 return StringRef(StrPtr, NS.size());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000146}
147
148StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
149 SmallString<256> MethodName;
150 llvm::raw_svector_ostream OS(MethodName);
151 OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
152 const DeclContext *DC = OMD->getDeclContext();
153 if (const ObjCImplementationDecl *OID =
154 dyn_cast<const ObjCImplementationDecl>(DC)) {
155 OS << OID->getName();
156 } else if (const ObjCInterfaceDecl *OID =
157 dyn_cast<const ObjCInterfaceDecl>(DC)) {
158 OS << OID->getName();
159 } else if (const ObjCCategoryImplDecl *OCD =
160 dyn_cast<const ObjCCategoryImplDecl>(DC)){
161 OS << ((const NamedDecl *)OCD)->getIdentifier()->getNameStart() << '(' <<
162 OCD->getIdentifier()->getNameStart() << ')';
163 }
164 OS << ' ' << OMD->getSelector().getAsString() << ']';
165
166 char *StrPtr = DebugInfoNames.Allocate<char>(OS.tell());
167 memcpy(StrPtr, MethodName.begin(), OS.tell());
168 return StringRef(StrPtr, OS.tell());
169}
170
171/// getSelectorName - Return selector name. This is used for debugging
172/// info.
173StringRef CGDebugInfo::getSelectorName(Selector S) {
174 const std::string &SName = S.getAsString();
175 char *StrPtr = DebugInfoNames.Allocate<char>(SName.size());
176 memcpy(StrPtr, SName.data(), SName.size());
177 return StringRef(StrPtr, SName.size());
178}
179
180/// getClassName - Get class name including template argument list.
181StringRef
182CGDebugInfo::getClassName(const RecordDecl *RD) {
183 const ClassTemplateSpecializationDecl *Spec
184 = dyn_cast<ClassTemplateSpecializationDecl>(RD);
185 if (!Spec)
186 return RD->getName();
187
188 const TemplateArgument *Args;
189 unsigned NumArgs;
190 if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) {
191 const TemplateSpecializationType *TST =
192 cast<TemplateSpecializationType>(TAW->getType());
193 Args = TST->getArgs();
194 NumArgs = TST->getNumArgs();
195 } else {
196 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
197 Args = TemplateArgs.data();
198 NumArgs = TemplateArgs.size();
199 }
200 StringRef Name = RD->getIdentifier()->getName();
201 PrintingPolicy Policy(CGM.getLangOpts());
Benjamin Kramer5eada842013-02-22 15:46:01 +0000202 SmallString<128> TemplateArgList;
203 {
204 llvm::raw_svector_ostream OS(TemplateArgList);
205 TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs,
206 Policy);
207 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000208
209 // Copy this name on the side and use its reference.
210 size_t Length = Name.size() + TemplateArgList.size();
211 char *StrPtr = DebugInfoNames.Allocate<char>(Length);
212 memcpy(StrPtr, Name.data(), Name.size());
213 memcpy(StrPtr + Name.size(), TemplateArgList.data(), TemplateArgList.size());
214 return StringRef(StrPtr, Length);
215}
216
217/// getOrCreateFile - Get the file debug info descriptor for the input location.
218llvm::DIFile CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
219 if (!Loc.isValid())
220 // If Location is not valid then use main input file.
221 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
222
223 SourceManager &SM = CGM.getContext().getSourceManager();
224 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
225
226 if (PLoc.isInvalid() || StringRef(PLoc.getFilename()).empty())
227 // If the location is not valid then use main input file.
228 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
229
230 // Cache the results.
231 const char *fname = PLoc.getFilename();
232 llvm::DenseMap<const char *, llvm::WeakVH>::iterator it =
233 DIFileCache.find(fname);
234
235 if (it != DIFileCache.end()) {
236 // Verify that the information still exists.
237 if (llvm::Value *V = it->second)
238 return llvm::DIFile(cast<llvm::MDNode>(V));
239 }
240
241 llvm::DIFile F = DBuilder.createFile(PLoc.getFilename(), getCurrentDirname());
242
243 DIFileCache[fname] = F;
244 return F;
245}
246
247/// getOrCreateMainFile - Get the file info for main compile unit.
248llvm::DIFile CGDebugInfo::getOrCreateMainFile() {
249 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
250}
251
252/// getLineNumber - Get line number for the location. If location is invalid
253/// then use current location.
254unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
255 if (Loc.isInvalid() && CurLoc.isInvalid())
256 return 0;
257 SourceManager &SM = CGM.getContext().getSourceManager();
258 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
259 return PLoc.isValid()? PLoc.getLine() : 0;
260}
261
262/// getColumnNumber - Get column number for the location.
Adrian Prantl00df5ea2013-03-12 20:43:25 +0000263unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000264 // We may not want column information at all.
Adrian Prantl00df5ea2013-03-12 20:43:25 +0000265 if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000266 return 0;
267
268 // If the location is invalid then use the current column.
269 if (Loc.isInvalid() && CurLoc.isInvalid())
270 return 0;
271 SourceManager &SM = CGM.getContext().getSourceManager();
272 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
273 return PLoc.isValid()? PLoc.getColumn() : 0;
274}
275
276StringRef CGDebugInfo::getCurrentDirname() {
277 if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
278 return CGM.getCodeGenOpts().DebugCompilationDir;
279
280 if (!CWDName.empty())
281 return CWDName;
282 SmallString<256> CWD;
283 llvm::sys::fs::current_path(CWD);
284 char *CompDirnamePtr = DebugInfoNames.Allocate<char>(CWD.size());
285 memcpy(CompDirnamePtr, CWD.data(), CWD.size());
286 return CWDName = StringRef(CompDirnamePtr, CWD.size());
287}
288
289/// CreateCompileUnit - Create new compile unit.
290void CGDebugInfo::CreateCompileUnit() {
291
292 // Get absolute path name.
293 SourceManager &SM = CGM.getContext().getSourceManager();
294 std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
295 if (MainFileName.empty())
296 MainFileName = "<unknown>";
297
298 // The main file name provided via the "-main-file-name" option contains just
299 // the file name itself with no path information. This file name may have had
300 // a relative path, so we look into the actual file entry for the main
301 // file to determine the real absolute path for the file.
302 std::string MainFileDir;
303 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
304 MainFileDir = MainFile->getDir()->getName();
305 if (MainFileDir != ".")
306 MainFileName = MainFileDir + "/" + MainFileName;
307 }
308
309 // Save filename string.
310 char *FilenamePtr = DebugInfoNames.Allocate<char>(MainFileName.length());
311 memcpy(FilenamePtr, MainFileName.c_str(), MainFileName.length());
312 StringRef Filename(FilenamePtr, MainFileName.length());
Eric Christopherff971d72013-02-22 23:50:16 +0000313
314 // Save split dwarf file string.
315 std::string SplitDwarfFile = CGM.getCodeGenOpts().SplitDwarfFile;
316 char *SplitDwarfPtr = DebugInfoNames.Allocate<char>(SplitDwarfFile.length());
317 memcpy(SplitDwarfPtr, SplitDwarfFile.c_str(), SplitDwarfFile.length());
318 StringRef SplitDwarfFilename(SplitDwarfPtr, SplitDwarfFile.length());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000319
320 unsigned LangTag;
321 const LangOptions &LO = CGM.getLangOpts();
322 if (LO.CPlusPlus) {
323 if (LO.ObjC1)
324 LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
325 else
326 LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
327 } else if (LO.ObjC1) {
328 LangTag = llvm::dwarf::DW_LANG_ObjC;
329 } else if (LO.C99) {
330 LangTag = llvm::dwarf::DW_LANG_C99;
331 } else {
332 LangTag = llvm::dwarf::DW_LANG_C89;
333 }
334
335 std::string Producer = getClangFullVersion();
336
337 // Figure out which version of the ObjC runtime we have.
338 unsigned RuntimeVers = 0;
339 if (LO.ObjC1)
340 RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
341
342 // Create new compile unit.
Eric Christopherbe5f1be2013-02-21 22:35:08 +0000343 DBuilder.createCompileUnit(LangTag, Filename, getCurrentDirname(),
344 Producer, LO.Optimize,
Eric Christopherff971d72013-02-22 23:50:16 +0000345 CGM.getCodeGenOpts().DwarfDebugFlags,
346 RuntimeVers, SplitDwarfFilename);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000347 // FIXME - Eliminate TheCU.
348 TheCU = llvm::DICompileUnit(DBuilder.getCU());
349}
350
351/// CreateType - Get the Basic type from the cache or create a new
352/// one if necessary.
353llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT) {
354 unsigned Encoding = 0;
355 StringRef BTName;
356 switch (BT->getKind()) {
357#define BUILTIN_TYPE(Id, SingletonId)
358#define PLACEHOLDER_TYPE(Id, SingletonId) \
359 case BuiltinType::Id:
360#include "clang/AST/BuiltinTypes.def"
361 case BuiltinType::Dependent:
362 llvm_unreachable("Unexpected builtin type");
363 case BuiltinType::NullPtr:
364 return DBuilder.
365 createNullPtrType(BT->getName(CGM.getLangOpts()));
366 case BuiltinType::Void:
367 return llvm::DIType();
368 case BuiltinType::ObjCClass:
369 if (ClassTy.Verify())
370 return ClassTy;
371 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
372 "objc_class", TheCU,
373 getOrCreateMainFile(), 0);
374 return ClassTy;
375 case BuiltinType::ObjCId: {
376 // typedef struct objc_class *Class;
377 // typedef struct objc_object {
378 // Class isa;
379 // } *id;
380
381 if (ObjTy.Verify())
382 return ObjTy;
383
384 if (!ClassTy.Verify())
385 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
386 "objc_class", TheCU,
387 getOrCreateMainFile(), 0);
388
389 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
390
391 llvm::DIType ISATy = DBuilder.createPointerType(ClassTy, Size);
392
Eric Christopherf068c922013-04-02 22:59:11 +0000393 ObjTy =
David Blaikiec1d0af12013-02-25 01:07:08 +0000394 DBuilder.createStructType(TheCU, "objc_object", getOrCreateMainFile(),
395 0, 0, 0, 0, llvm::DIType(), llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000396
Eric Christopherf068c922013-04-02 22:59:11 +0000397 ObjTy.setTypeArray(DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
398 ObjTy, "isa", getOrCreateMainFile(), 0, Size, 0, 0, 0, ISATy)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000399 return ObjTy;
400 }
401 case BuiltinType::ObjCSel: {
402 if (SelTy.Verify())
403 return SelTy;
404 SelTy =
405 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
406 "objc_selector", TheCU, getOrCreateMainFile(),
407 0);
408 return SelTy;
409 }
Guy Benyeib13621d2012-12-18 14:38:23 +0000410
411 case BuiltinType::OCLImage1d:
412 return getOrCreateStructPtrType("opencl_image1d_t",
413 OCLImage1dDITy);
414 case BuiltinType::OCLImage1dArray:
415 return getOrCreateStructPtrType("opencl_image1d_array_t",
416 OCLImage1dArrayDITy);
417 case BuiltinType::OCLImage1dBuffer:
418 return getOrCreateStructPtrType("opencl_image1d_buffer_t",
419 OCLImage1dBufferDITy);
420 case BuiltinType::OCLImage2d:
421 return getOrCreateStructPtrType("opencl_image2d_t",
422 OCLImage2dDITy);
423 case BuiltinType::OCLImage2dArray:
424 return getOrCreateStructPtrType("opencl_image2d_array_t",
425 OCLImage2dArrayDITy);
426 case BuiltinType::OCLImage3d:
427 return getOrCreateStructPtrType("opencl_image3d_t",
428 OCLImage3dDITy);
Guy Benyei21f18c42013-02-07 10:55:47 +0000429 case BuiltinType::OCLSampler:
430 return DBuilder.createBasicType("opencl_sampler_t",
431 CGM.getContext().getTypeSize(BT),
432 CGM.getContext().getTypeAlign(BT),
433 llvm::dwarf::DW_ATE_unsigned);
Guy Benyeie6b9d802013-01-20 12:31:11 +0000434 case BuiltinType::OCLEvent:
435 return getOrCreateStructPtrType("opencl_event_t",
436 OCLEventDITy);
Guy Benyeib13621d2012-12-18 14:38:23 +0000437
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000438 case BuiltinType::UChar:
439 case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
440 case BuiltinType::Char_S:
441 case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
442 case BuiltinType::Char16:
443 case BuiltinType::Char32: Encoding = llvm::dwarf::DW_ATE_UTF; break;
444 case BuiltinType::UShort:
445 case BuiltinType::UInt:
446 case BuiltinType::UInt128:
447 case BuiltinType::ULong:
448 case BuiltinType::WChar_U:
449 case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
450 case BuiltinType::Short:
451 case BuiltinType::Int:
452 case BuiltinType::Int128:
453 case BuiltinType::Long:
454 case BuiltinType::WChar_S:
455 case BuiltinType::LongLong: Encoding = llvm::dwarf::DW_ATE_signed; break;
456 case BuiltinType::Bool: Encoding = llvm::dwarf::DW_ATE_boolean; break;
457 case BuiltinType::Half:
458 case BuiltinType::Float:
459 case BuiltinType::LongDouble:
460 case BuiltinType::Double: Encoding = llvm::dwarf::DW_ATE_float; break;
461 }
462
463 switch (BT->getKind()) {
464 case BuiltinType::Long: BTName = "long int"; break;
465 case BuiltinType::LongLong: BTName = "long long int"; break;
466 case BuiltinType::ULong: BTName = "long unsigned int"; break;
467 case BuiltinType::ULongLong: BTName = "long long unsigned int"; break;
468 default:
469 BTName = BT->getName(CGM.getLangOpts());
470 break;
471 }
472 // Bit size, align and offset of the type.
473 uint64_t Size = CGM.getContext().getTypeSize(BT);
474 uint64_t Align = CGM.getContext().getTypeAlign(BT);
475 llvm::DIType DbgTy =
476 DBuilder.createBasicType(BTName, Size, Align, Encoding);
477 return DbgTy;
478}
479
480llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty) {
481 // Bit size, align and offset of the type.
482 unsigned Encoding = llvm::dwarf::DW_ATE_complex_float;
483 if (Ty->isComplexIntegerType())
484 Encoding = llvm::dwarf::DW_ATE_lo_user;
485
486 uint64_t Size = CGM.getContext().getTypeSize(Ty);
487 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
488 llvm::DIType DbgTy =
489 DBuilder.createBasicType("complex", Size, Align, Encoding);
490
491 return DbgTy;
492}
493
494/// CreateCVRType - Get the qualified type from the cache or create
495/// a new one if necessary.
496llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit) {
497 QualifierCollector Qc;
498 const Type *T = Qc.strip(Ty);
499
500 // Ignore these qualifiers for now.
501 Qc.removeObjCGCAttr();
502 Qc.removeAddressSpace();
503 Qc.removeObjCLifetime();
504
505 // We will create one Derived type for one qualifier and recurse to handle any
506 // additional ones.
507 unsigned Tag;
508 if (Qc.hasConst()) {
509 Tag = llvm::dwarf::DW_TAG_const_type;
510 Qc.removeConst();
511 } else if (Qc.hasVolatile()) {
512 Tag = llvm::dwarf::DW_TAG_volatile_type;
513 Qc.removeVolatile();
514 } else if (Qc.hasRestrict()) {
515 Tag = llvm::dwarf::DW_TAG_restrict_type;
516 Qc.removeRestrict();
517 } else {
518 assert(Qc.empty() && "Unknown type qualifier for debug info");
519 return getOrCreateType(QualType(T, 0), Unit);
520 }
521
522 llvm::DIType FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
523
524 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
525 // CVR derived types.
526 llvm::DIType DbgTy = DBuilder.createQualifiedType(Tag, FromTy);
527
528 return DbgTy;
529}
530
531llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
532 llvm::DIFile Unit) {
Fariborz Jahanian05f8ff12013-02-21 20:42:11 +0000533
534 // The frontend treats 'id' as a typedef to an ObjCObjectType,
535 // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
536 // debug info, we want to emit 'id' in both cases.
537 if (Ty->isObjCQualifiedIdType())
538 return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
539
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000540 llvm::DIType DbgTy =
541 CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
542 Ty->getPointeeType(), Unit);
543 return DbgTy;
544}
545
546llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
547 llvm::DIFile Unit) {
548 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
549 Ty->getPointeeType(), Unit);
550}
551
552// Creates a forward declaration for a RecordDecl in the given context.
553llvm::DIType CGDebugInfo::createRecordFwdDecl(const RecordDecl *RD,
554 llvm::DIDescriptor Ctx) {
555 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
556 unsigned Line = getLineNumber(RD->getLocation());
557 StringRef RDName = getClassName(RD);
558
559 unsigned Tag = 0;
560 if (RD->isStruct() || RD->isInterface())
561 Tag = llvm::dwarf::DW_TAG_structure_type;
562 else if (RD->isUnion())
563 Tag = llvm::dwarf::DW_TAG_union_type;
564 else {
565 assert(RD->isClass());
566 Tag = llvm::dwarf::DW_TAG_class_type;
567 }
568
569 // Create the type.
570 return DBuilder.createForwardDecl(Tag, RDName, Ctx, DefUnit, Line);
571}
572
573// Walk up the context chain and create forward decls for record decls,
574// and normal descriptors for namespaces.
575llvm::DIDescriptor CGDebugInfo::createContextChain(const Decl *Context) {
576 if (!Context)
577 return TheCU;
578
579 // See if we already have the parent.
580 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
581 I = RegionMap.find(Context);
582 if (I != RegionMap.end()) {
583 llvm::Value *V = I->second;
584 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
585 }
586
587 // Check namespace.
588 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
589 return llvm::DIDescriptor(getOrCreateNameSpace(NSDecl));
590
591 if (const RecordDecl *RD = dyn_cast<RecordDecl>(Context)) {
592 if (!RD->isDependentType()) {
593 llvm::DIType Ty = getOrCreateLimitedType(CGM.getContext().getTypeDeclType(RD),
Eric Christopherbe5f1be2013-02-21 22:35:08 +0000594 getOrCreateMainFile());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000595 return llvm::DIDescriptor(Ty);
596 }
597 }
598 return TheCU;
599}
600
601/// CreatePointeeType - Create Pointee type. If Pointee is a record
602/// then emit record's fwd if debug info size reduction is enabled.
603llvm::DIType CGDebugInfo::CreatePointeeType(QualType PointeeTy,
604 llvm::DIFile Unit) {
605 if (CGM.getCodeGenOpts().getDebugInfo() != CodeGenOptions::LimitedDebugInfo)
606 return getOrCreateType(PointeeTy, Unit);
607
608 // Limit debug info for the pointee type.
609
610 // If we have an existing type, use that, it's still smaller than creating
611 // a new type.
612 llvm::DIType Ty = getTypeOrNull(PointeeTy);
613 if (Ty.Verify()) return Ty;
614
615 // Handle qualifiers.
616 if (PointeeTy.hasLocalQualifiers())
617 return CreateQualifiedType(PointeeTy, Unit);
618
619 if (const RecordType *RTy = dyn_cast<RecordType>(PointeeTy)) {
620 RecordDecl *RD = RTy->getDecl();
621 llvm::DIDescriptor FDContext =
622 getContextDescriptor(cast<Decl>(RD->getDeclContext()));
623 llvm::DIType RetTy = createRecordFwdDecl(RD, FDContext);
624 TypeCache[QualType(RTy, 0).getAsOpaquePtr()] = RetTy;
625 return RetTy;
626 }
627 return getOrCreateType(PointeeTy, Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000628}
629
630llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag,
631 const Type *Ty,
632 QualType PointeeTy,
633 llvm::DIFile Unit) {
634 if (Tag == llvm::dwarf::DW_TAG_reference_type ||
635 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
636 return DBuilder.createReferenceType(Tag,
637 CreatePointeeType(PointeeTy, Unit));
Fariborz Jahanian05f8ff12013-02-21 20:42:11 +0000638
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000639 // Bit size, align and offset of the type.
640 // Size is always the size of a pointer. We can't use getTypeSize here
641 // because that does not return the correct value for references.
642 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCall64aa4b32013-04-16 22:48:15 +0000643 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000644 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
645
646 return DBuilder.createPointerType(CreatePointeeType(PointeeTy, Unit),
647 Size, Align);
648}
649
Guy Benyeib13621d2012-12-18 14:38:23 +0000650llvm::DIType CGDebugInfo::getOrCreateStructPtrType(StringRef Name, llvm::DIType &Cache) {
651 if (Cache.Verify())
652 return Cache;
653 Cache =
654 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
655 Name, TheCU, getOrCreateMainFile(),
656 0);
657 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
658 Cache = DBuilder.createPointerType(Cache, Size);
659 return Cache;
660}
661
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000662llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
663 llvm::DIFile Unit) {
664 if (BlockLiteralGenericSet)
665 return BlockLiteralGeneric;
666
667 SmallVector<llvm::Value *, 8> EltTys;
668 llvm::DIType FieldTy;
669 QualType FType;
670 uint64_t FieldSize, FieldOffset;
671 unsigned FieldAlign;
672 llvm::DIArray Elements;
673 llvm::DIType EltTy, DescTy;
674
675 FieldOffset = 0;
676 FType = CGM.getContext().UnsignedLongTy;
677 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
678 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
679
680 Elements = DBuilder.getOrCreateArray(EltTys);
681 EltTys.clear();
682
683 unsigned Flags = llvm::DIDescriptor::FlagAppleBlock;
684 unsigned LineNo = getLineNumber(CurLoc);
685
686 EltTy = DBuilder.createStructType(Unit, "__block_descriptor",
687 Unit, LineNo, FieldOffset, 0,
David Blaikiec1d0af12013-02-25 01:07:08 +0000688 Flags, llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000689
690 // Bit size, align and offset of the type.
691 uint64_t Size = CGM.getContext().getTypeSize(Ty);
692
693 DescTy = DBuilder.createPointerType(EltTy, Size);
694
695 FieldOffset = 0;
696 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
697 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
698 FType = CGM.getContext().IntTy;
699 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
700 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
701 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
702 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
703
704 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
705 FieldTy = DescTy;
706 FieldSize = CGM.getContext().getTypeSize(Ty);
707 FieldAlign = CGM.getContext().getTypeAlign(Ty);
708 FieldTy = DBuilder.createMemberType(Unit, "__descriptor", Unit,
709 LineNo, FieldSize, FieldAlign,
710 FieldOffset, 0, FieldTy);
711 EltTys.push_back(FieldTy);
712
713 FieldOffset += FieldSize;
714 Elements = DBuilder.getOrCreateArray(EltTys);
715
716 EltTy = DBuilder.createStructType(Unit, "__block_literal_generic",
717 Unit, LineNo, FieldOffset, 0,
David Blaikiec1d0af12013-02-25 01:07:08 +0000718 Flags, llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000719
720 BlockLiteralGenericSet = true;
721 BlockLiteralGeneric = DBuilder.createPointerType(EltTy, Size);
722 return BlockLiteralGeneric;
723}
724
725llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty, llvm::DIFile Unit) {
726 // Typedefs are derived from some other type. If we have a typedef of a
727 // typedef, make sure to emit the whole chain.
728 llvm::DIType Src = getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
729 if (!Src.Verify())
730 return llvm::DIType();
731 // We don't set size information, but do specify where the typedef was
732 // declared.
733 unsigned Line = getLineNumber(Ty->getDecl()->getLocation());
734 const TypedefNameDecl *TyDecl = Ty->getDecl();
735
736 llvm::DIDescriptor TypedefContext =
737 getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext()));
738
739 return
740 DBuilder.createTypedef(Src, TyDecl->getName(), Unit, Line, TypedefContext);
741}
742
743llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
744 llvm::DIFile Unit) {
745 SmallVector<llvm::Value *, 16> EltTys;
746
747 // Add the result type at least.
748 EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit));
749
750 // Set up remainder of arguments if there is a prototype.
751 // FIXME: IF NOT, HOW IS THIS REPRESENTED? llvm-gcc doesn't represent '...'!
752 if (isa<FunctionNoProtoType>(Ty))
753 EltTys.push_back(DBuilder.createUnspecifiedParameter());
754 else if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Ty)) {
755 for (unsigned i = 0, e = FPT->getNumArgs(); i != e; ++i)
756 EltTys.push_back(getOrCreateType(FPT->getArgType(i), Unit));
757 }
758
759 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
760 return DBuilder.createSubroutineType(Unit, EltTypeArray);
761}
762
763
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000764llvm::DIType CGDebugInfo::createFieldType(StringRef name,
765 QualType type,
766 uint64_t sizeInBitsOverride,
767 SourceLocation loc,
768 AccessSpecifier AS,
769 uint64_t offsetInBits,
770 llvm::DIFile tunit,
771 llvm::DIDescriptor scope) {
772 llvm::DIType debugType = getOrCreateType(type, tunit);
773
774 // Get the location for the field.
775 llvm::DIFile file = getOrCreateFile(loc);
776 unsigned line = getLineNumber(loc);
777
778 uint64_t sizeInBits = 0;
779 unsigned alignInBits = 0;
780 if (!type->isIncompleteArrayType()) {
781 llvm::tie(sizeInBits, alignInBits) = CGM.getContext().getTypeInfo(type);
782
783 if (sizeInBitsOverride)
784 sizeInBits = sizeInBitsOverride;
785 }
786
787 unsigned flags = 0;
788 if (AS == clang::AS_private)
789 flags |= llvm::DIDescriptor::FlagPrivate;
790 else if (AS == clang::AS_protected)
791 flags |= llvm::DIDescriptor::FlagProtected;
792
793 return DBuilder.createMemberType(scope, name, file, line, sizeInBits,
794 alignInBits, offsetInBits, flags, debugType);
795}
796
Eric Christopher0395de32013-01-16 01:22:32 +0000797/// CollectRecordLambdaFields - Helper for CollectRecordFields.
798void CGDebugInfo::
799CollectRecordLambdaFields(const CXXRecordDecl *CXXDecl,
800 SmallVectorImpl<llvm::Value *> &elements,
801 llvm::DIType RecordTy) {
802 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
803 // has the name and the location of the variable so we should iterate over
804 // both concurrently.
805 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
806 RecordDecl::field_iterator Field = CXXDecl->field_begin();
807 unsigned fieldno = 0;
808 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
809 E = CXXDecl->captures_end(); I != E; ++I, ++Field, ++fieldno) {
810 const LambdaExpr::Capture C = *I;
811 if (C.capturesVariable()) {
812 VarDecl *V = C.getCapturedVar();
813 llvm::DIFile VUnit = getOrCreateFile(C.getLocation());
814 StringRef VName = V->getName();
815 uint64_t SizeInBitsOverride = 0;
816 if (Field->isBitField()) {
817 SizeInBitsOverride = Field->getBitWidthValue(CGM.getContext());
818 assert(SizeInBitsOverride && "found named 0-width bitfield");
819 }
820 llvm::DIType fieldType
821 = createFieldType(VName, Field->getType(), SizeInBitsOverride,
822 C.getLocation(), Field->getAccess(),
823 layout.getFieldOffset(fieldno), VUnit, RecordTy);
824 elements.push_back(fieldType);
825 } else {
826 // TODO: Need to handle 'this' in some way by probably renaming the
827 // this of the lambda class and having a field member of 'this' or
828 // by using AT_object_pointer for the function and having that be
829 // used as 'this' for semantic references.
830 assert(C.capturesThis() && "Field that isn't captured and isn't this?");
831 FieldDecl *f = *Field;
832 llvm::DIFile VUnit = getOrCreateFile(f->getLocation());
833 QualType type = f->getType();
834 llvm::DIType fieldType
835 = createFieldType("this", type, 0, f->getLocation(), f->getAccess(),
836 layout.getFieldOffset(fieldno), VUnit, RecordTy);
837
838 elements.push_back(fieldType);
839 }
840 }
841}
842
843/// CollectRecordStaticField - Helper for CollectRecordFields.
844void CGDebugInfo::
845CollectRecordStaticField(const VarDecl *Var,
846 SmallVectorImpl<llvm::Value *> &elements,
847 llvm::DIType RecordTy) {
848 // Create the descriptor for the static variable, with or without
849 // constant initializers.
850 llvm::DIFile VUnit = getOrCreateFile(Var->getLocation());
851 llvm::DIType VTy = getOrCreateType(Var->getType(), VUnit);
852
853 // Do not describe enums as static members.
854 if (VTy.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
855 return;
856
857 unsigned LineNumber = getLineNumber(Var->getLocation());
858 StringRef VName = Var->getName();
David Blaikiea89701b2013-01-20 01:19:17 +0000859 llvm::Constant *C = NULL;
Eric Christopher0395de32013-01-16 01:22:32 +0000860 if (Var->getInit()) {
861 const APValue *Value = Var->evaluateValue();
David Blaikiea89701b2013-01-20 01:19:17 +0000862 if (Value) {
863 if (Value->isInt())
864 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
865 if (Value->isFloat())
866 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
867 }
Eric Christopher0395de32013-01-16 01:22:32 +0000868 }
869
870 unsigned Flags = 0;
871 AccessSpecifier Access = Var->getAccess();
872 if (Access == clang::AS_private)
873 Flags |= llvm::DIDescriptor::FlagPrivate;
874 else if (Access == clang::AS_protected)
875 Flags |= llvm::DIDescriptor::FlagProtected;
876
877 llvm::DIType GV = DBuilder.createStaticMemberType(RecordTy, VName, VUnit,
David Blaikiea89701b2013-01-20 01:19:17 +0000878 LineNumber, VTy, Flags, C);
Eric Christopher0395de32013-01-16 01:22:32 +0000879 elements.push_back(GV);
880 StaticDataMemberCache[Var->getCanonicalDecl()] = llvm::WeakVH(GV);
881}
882
883/// CollectRecordNormalField - Helper for CollectRecordFields.
884void CGDebugInfo::
885CollectRecordNormalField(const FieldDecl *field, uint64_t OffsetInBits,
886 llvm::DIFile tunit,
887 SmallVectorImpl<llvm::Value *> &elements,
888 llvm::DIType RecordTy) {
889 StringRef name = field->getName();
890 QualType type = field->getType();
891
892 // Ignore unnamed fields unless they're anonymous structs/unions.
893 if (name.empty() && !type->isRecordType())
894 return;
895
896 uint64_t SizeInBitsOverride = 0;
897 if (field->isBitField()) {
898 SizeInBitsOverride = field->getBitWidthValue(CGM.getContext());
899 assert(SizeInBitsOverride && "found named 0-width bitfield");
900 }
901
902 llvm::DIType fieldType
903 = createFieldType(name, type, SizeInBitsOverride,
904 field->getLocation(), field->getAccess(),
905 OffsetInBits, tunit, RecordTy);
906
907 elements.push_back(fieldType);
908}
909
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000910/// CollectRecordFields - A helper function to collect debug info for
911/// record fields. This is used while creating debug info entry for a Record.
912void CGDebugInfo::
913CollectRecordFields(const RecordDecl *record, llvm::DIFile tunit,
914 SmallVectorImpl<llvm::Value *> &elements,
915 llvm::DIType RecordTy) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000916 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(record);
917
Eric Christopher0395de32013-01-16 01:22:32 +0000918 if (CXXDecl && CXXDecl->isLambda())
919 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
920 else {
921 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000922
Eric Christopher0395de32013-01-16 01:22:32 +0000923 // Field number for non-static fields.
Eric Christopherfd5ac0d2013-01-04 17:59:07 +0000924 unsigned fieldNo = 0;
Eric Christopher0395de32013-01-16 01:22:32 +0000925
926 // Bookkeeping for an ms struct, which ignores certain fields.
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000927 bool IsMsStruct = record->isMsStruct(CGM.getContext());
928 const FieldDecl *LastFD = 0;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000929
Eric Christopher0395de32013-01-16 01:22:32 +0000930 // Static and non-static members should appear in the same order as
931 // the corresponding declarations in the source program.
932 for (RecordDecl::decl_iterator I = record->decls_begin(),
933 E = record->decls_end(); I != E; ++I)
934 if (const VarDecl *V = dyn_cast<VarDecl>(*I))
935 CollectRecordStaticField(V, elements, RecordTy);
936 else if (FieldDecl *field = dyn_cast<FieldDecl>(*I)) {
937 if (IsMsStruct) {
938 // Zero-length bitfields following non-bitfield members are
939 // completely ignored; we don't even count them.
940 if (CGM.getContext().ZeroBitfieldFollowsNonBitfield((field), LastFD))
941 continue;
942 LastFD = field;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000943 }
Eric Christopher0395de32013-01-16 01:22:32 +0000944 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo),
945 tunit, elements, RecordTy);
946
947 // Bump field number for next field.
948 ++fieldNo;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000949 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000950 }
951}
952
953/// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
954/// function type is not updated to include implicit "this" pointer. Use this
955/// routine to get a method type which includes "this" pointer.
956llvm::DIType
957CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
958 llvm::DIFile Unit) {
David Blaikie9c78f9b2013-01-07 23:06:35 +0000959 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
David Blaikie67f8b5e2013-01-07 22:24:59 +0000960 if (Method->isStatic())
David Blaikie9c78f9b2013-01-07 23:06:35 +0000961 return getOrCreateType(QualType(Func, 0), Unit);
962 return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()),
963 Func, Unit);
964}
David Blaikie67f8b5e2013-01-07 22:24:59 +0000965
David Blaikie9c78f9b2013-01-07 23:06:35 +0000966llvm::DIType CGDebugInfo::getOrCreateInstanceMethodType(
967 QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile Unit) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000968 // Add "this" pointer.
David Blaikie9c78f9b2013-01-07 23:06:35 +0000969 llvm::DIArray Args = llvm::DICompositeType(
970 getOrCreateType(QualType(Func, 0), Unit)).getTypeArray();
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000971 assert (Args.getNumElements() && "Invalid number of arguments!");
972
973 SmallVector<llvm::Value *, 16> Elts;
974
975 // First element is always return type. For 'void' functions it is NULL.
976 Elts.push_back(Args.getElement(0));
977
David Blaikie67f8b5e2013-01-07 22:24:59 +0000978 // "this" pointer is always first argument.
David Blaikie9c78f9b2013-01-07 23:06:35 +0000979 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
David Blaikie67f8b5e2013-01-07 22:24:59 +0000980 if (isa<ClassTemplateSpecializationDecl>(RD)) {
981 // Create pointer type directly in this case.
982 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
983 QualType PointeeTy = ThisPtrTy->getPointeeType();
984 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCall64aa4b32013-04-16 22:48:15 +0000985 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
David Blaikie67f8b5e2013-01-07 22:24:59 +0000986 uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy);
987 llvm::DIType PointeeType = getOrCreateType(PointeeTy, Unit);
988 llvm::DIType ThisPtrType = DBuilder.createPointerType(PointeeType, Size, Align);
989 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
990 // TODO: This and the artificial type below are misleading, the
991 // types aren't artificial the argument is, but the current
992 // metadata doesn't represent that.
993 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
994 Elts.push_back(ThisPtrType);
995 } else {
996 llvm::DIType ThisPtrType = getOrCreateType(ThisPtr, Unit);
997 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
998 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
999 Elts.push_back(ThisPtrType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001000 }
1001
1002 // Copy rest of the arguments.
1003 for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
1004 Elts.push_back(Args.getElement(i));
1005
1006 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
1007
1008 return DBuilder.createSubroutineType(Unit, EltTypeArray);
1009}
1010
1011/// isFunctionLocalClass - Return true if CXXRecordDecl is defined
1012/// inside a function.
1013static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
1014 if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
1015 return isFunctionLocalClass(NRD);
1016 if (isa<FunctionDecl>(RD->getDeclContext()))
1017 return true;
1018 return false;
1019}
1020
1021/// CreateCXXMemberFunction - A helper function to create a DISubprogram for
1022/// a single member function GlobalDecl.
1023llvm::DISubprogram
1024CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
1025 llvm::DIFile Unit,
1026 llvm::DIType RecordTy) {
1027 bool IsCtorOrDtor =
1028 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
1029
1030 StringRef MethodName = getFunctionName(Method);
1031 llvm::DIType MethodTy = getOrCreateMethodType(Method, Unit);
1032
1033 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1034 // make sense to give a single ctor/dtor a linkage name.
1035 StringRef MethodLinkageName;
1036 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1037 MethodLinkageName = CGM.getMangledName(Method);
1038
1039 // Get the location for the method.
1040 llvm::DIFile MethodDefUnit = getOrCreateFile(Method->getLocation());
1041 unsigned MethodLine = getLineNumber(Method->getLocation());
1042
1043 // Collect virtual method info.
1044 llvm::DIType ContainingType;
1045 unsigned Virtuality = 0;
1046 unsigned VIndex = 0;
1047
1048 if (Method->isVirtual()) {
1049 if (Method->isPure())
1050 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
1051 else
1052 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
1053
1054 // It doesn't make sense to give a virtual destructor a vtable index,
1055 // since a single destructor has two entries in the vtable.
1056 if (!isa<CXXDestructorDecl>(Method))
1057 VIndex = CGM.getVTableContext().getMethodVTableIndex(Method);
1058 ContainingType = RecordTy;
1059 }
1060
1061 unsigned Flags = 0;
1062 if (Method->isImplicit())
1063 Flags |= llvm::DIDescriptor::FlagArtificial;
1064 AccessSpecifier Access = Method->getAccess();
1065 if (Access == clang::AS_private)
1066 Flags |= llvm::DIDescriptor::FlagPrivate;
1067 else if (Access == clang::AS_protected)
1068 Flags |= llvm::DIDescriptor::FlagProtected;
1069 if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1070 if (CXXC->isExplicit())
1071 Flags |= llvm::DIDescriptor::FlagExplicit;
1072 } else if (const CXXConversionDecl *CXXC =
1073 dyn_cast<CXXConversionDecl>(Method)) {
1074 if (CXXC->isExplicit())
1075 Flags |= llvm::DIDescriptor::FlagExplicit;
1076 }
1077 if (Method->hasPrototype())
1078 Flags |= llvm::DIDescriptor::FlagPrototyped;
1079
1080 llvm::DIArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1081 llvm::DISubprogram SP =
1082 DBuilder.createMethod(RecordTy, MethodName, MethodLinkageName,
1083 MethodDefUnit, MethodLine,
1084 MethodTy, /*isLocalToUnit=*/false,
1085 /* isDefinition=*/ false,
1086 Virtuality, VIndex, ContainingType,
1087 Flags, CGM.getLangOpts().Optimize, NULL,
1088 TParamsArray);
1089
1090 SPCache[Method->getCanonicalDecl()] = llvm::WeakVH(SP);
1091
1092 return SP;
1093}
1094
1095/// CollectCXXMemberFunctions - A helper function to collect debug info for
1096/// C++ member functions. This is used while creating debug info entry for
1097/// a Record.
1098void CGDebugInfo::
1099CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
1100 SmallVectorImpl<llvm::Value *> &EltTys,
1101 llvm::DIType RecordTy) {
1102
1103 // Since we want more than just the individual member decls if we
1104 // have templated functions iterate over every declaration to gather
1105 // the functions.
1106 for(DeclContext::decl_iterator I = RD->decls_begin(),
1107 E = RD->decls_end(); I != E; ++I) {
1108 Decl *D = *I;
1109 if (D->isImplicit() && !D->isUsed())
1110 continue;
1111
1112 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1113 EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
1114 else if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
1115 for (FunctionTemplateDecl::spec_iterator SI = FTD->spec_begin(),
1116 SE = FTD->spec_end(); SI != SE; ++SI)
1117 EltTys.push_back(CreateCXXMemberFunction(cast<CXXMethodDecl>(*SI), Unit,
1118 RecordTy));
1119 }
1120}
1121
1122/// CollectCXXFriends - A helper function to collect debug info for
1123/// C++ base classes. This is used while creating debug info entry for
1124/// a Record.
1125void CGDebugInfo::
1126CollectCXXFriends(const CXXRecordDecl *RD, llvm::DIFile Unit,
1127 SmallVectorImpl<llvm::Value *> &EltTys,
1128 llvm::DIType RecordTy) {
1129 for (CXXRecordDecl::friend_iterator BI = RD->friend_begin(),
1130 BE = RD->friend_end(); BI != BE; ++BI) {
1131 if ((*BI)->isUnsupportedFriend())
1132 continue;
1133 if (TypeSourceInfo *TInfo = (*BI)->getFriendType())
1134 EltTys.push_back(DBuilder.createFriend(RecordTy,
1135 getOrCreateType(TInfo->getType(),
1136 Unit)));
1137 }
1138}
1139
1140/// CollectCXXBases - A helper function to collect debug info for
1141/// C++ base classes. This is used while creating debug info entry for
1142/// a Record.
1143void CGDebugInfo::
1144CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
1145 SmallVectorImpl<llvm::Value *> &EltTys,
1146 llvm::DIType RecordTy) {
1147
1148 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1149 for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
1150 BE = RD->bases_end(); BI != BE; ++BI) {
1151 unsigned BFlags = 0;
1152 uint64_t BaseOffset;
1153
1154 const CXXRecordDecl *Base =
1155 cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl());
1156
1157 if (BI->isVirtual()) {
1158 // virtual base offset offset is -ve. The code generator emits dwarf
1159 // expression where it expects +ve number.
1160 BaseOffset =
1161 0 - CGM.getVTableContext()
1162 .getVirtualBaseOffsetOffset(RD, Base).getQuantity();
1163 BFlags = llvm::DIDescriptor::FlagVirtual;
1164 } else
1165 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1166 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1167 // BI->isVirtual() and bits when not.
1168
1169 AccessSpecifier Access = BI->getAccessSpecifier();
1170 if (Access == clang::AS_private)
1171 BFlags |= llvm::DIDescriptor::FlagPrivate;
1172 else if (Access == clang::AS_protected)
1173 BFlags |= llvm::DIDescriptor::FlagProtected;
1174
1175 llvm::DIType DTy =
1176 DBuilder.createInheritance(RecordTy,
1177 getOrCreateType(BI->getType(), Unit),
1178 BaseOffset, BFlags);
1179 EltTys.push_back(DTy);
1180 }
1181}
1182
1183/// CollectTemplateParams - A helper function to collect template parameters.
1184llvm::DIArray CGDebugInfo::
1185CollectTemplateParams(const TemplateParameterList *TPList,
1186 const TemplateArgumentList &TAList,
1187 llvm::DIFile Unit) {
1188 SmallVector<llvm::Value *, 16> TemplateParams;
1189 for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1190 const TemplateArgument &TA = TAList[i];
1191 const NamedDecl *ND = TPList->getParam(i);
David Blaikie9dfd2432013-05-10 21:53:14 +00001192 switch (TA.getKind()) {
1193 case TemplateArgument::Type: {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001194 llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit);
1195 llvm::DITemplateTypeParameter TTP =
1196 DBuilder.createTemplateTypeParameter(TheCU, ND->getName(), TTy);
1197 TemplateParams.push_back(TTP);
David Blaikie9dfd2432013-05-10 21:53:14 +00001198 } break;
1199 case TemplateArgument::Integral: {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001200 llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit);
1201 llvm::DITemplateValueParameter TVP =
David Blaikie9dfd2432013-05-10 21:53:14 +00001202 DBuilder.createTemplateValueParameter(
1203 TheCU, ND->getName(), TTy,
1204 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral()));
1205 TemplateParams.push_back(TVP);
1206 } break;
1207 case TemplateArgument::Declaration: {
1208 const ValueDecl *D = TA.getAsDecl();
1209 bool InstanceMember = D->isCXXInstanceMember();
1210 QualType T = InstanceMember
1211 ? CGM.getContext().getMemberPointerType(
1212 D->getType(), cast<RecordDecl>(D->getDeclContext())
1213 ->getTypeForDecl())
1214 : CGM.getContext().getPointerType(D->getType());
1215 llvm::DIType TTy = getOrCreateType(T, Unit);
1216 llvm::Value *V = 0;
1217 // Variable pointer template parameters have a value that is the address
1218 // of the variable.
1219 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1220 V = CGM.GetAddrOfGlobalVar(VD);
1221 // Member function pointers have special support for building them, though
1222 // this is currently unsupported in LLVM CodeGen.
1223 if (InstanceMember)
1224 if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(D))
1225 V = CGM.getCXXABI().EmitMemberPointer(method);
1226 // Member data pointers have special handling too to compute the fixed
1227 // offset within the object.
1228 if (isa<FieldDecl>(D)) {
1229 // These five lines (& possibly the above member function pointer
1230 // handling) might be able to be refactored to use similar code in
1231 // CodeGenModule::getMemberPointerConstant
1232 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
1233 CharUnits chars =
1234 CGM.getContext().toCharUnitsFromBits((int64_t) fieldOffset);
1235 V = CGM.getCXXABI().EmitMemberDataPointer(
1236 cast<MemberPointerType>(T.getTypePtr()), chars);
1237 }
1238 llvm::DITemplateValueParameter TVP =
1239 DBuilder.createTemplateValueParameter(TheCU, ND->getName(), TTy, V);
1240 TemplateParams.push_back(TVP);
1241 } break;
1242 case TemplateArgument::NullPtr: {
1243 QualType T = TA.getNullPtrType();
1244 llvm::DIType TTy = getOrCreateType(T, Unit);
1245 llvm::Value *V = 0;
1246 // Special case member data pointer null values since they're actually -1
1247 // instead of zero.
1248 if (const MemberPointerType *MPT =
1249 dyn_cast<MemberPointerType>(T.getTypePtr()))
1250 // But treat member function pointers as simple zero integers because
1251 // it's easier than having a special case in LLVM's CodeGen. If LLVM
1252 // CodeGen grows handling for values of non-null member function
1253 // pointers then perhaps we could remove this special case and rely on
1254 // EmitNullMemberPointer for member function pointers.
1255 if (MPT->isMemberDataPointer())
1256 V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1257 if (!V)
1258 V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
1259 llvm::DITemplateValueParameter TVP =
1260 DBuilder.createTemplateValueParameter(TheCU, ND->getName(), TTy, V);
1261 TemplateParams.push_back(TVP);
1262 } break;
1263 case TemplateArgument::Template:
1264 // We could support this with the GCC extension
1265 // DW_TAG_GNU_template_template_param
1266 break;
David Blaikie776a3642013-05-10 22:53:25 +00001267 case TemplateArgument::Pack:
1268 // And this with DW_TAG_GNU_template_parameter_pack
1269 break;
David Blaikie9dfd2432013-05-10 21:53:14 +00001270 // these next 4 should never occur
1271 case TemplateArgument::Expression:
1272 case TemplateArgument::TemplateExpansion:
David Blaikie9dfd2432013-05-10 21:53:14 +00001273 case TemplateArgument::Null:
1274 llvm_unreachable(
1275 "These argument types shouldn't exist in concrete types");
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001276 }
1277 }
1278 return DBuilder.getOrCreateArray(TemplateParams);
1279}
1280
1281/// CollectFunctionTemplateParams - A helper function to collect debug
1282/// info for function template parameters.
1283llvm::DIArray CGDebugInfo::
1284CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) {
1285 if (FD->getTemplatedKind() ==
1286 FunctionDecl::TK_FunctionTemplateSpecialization) {
1287 const TemplateParameterList *TList =
1288 FD->getTemplateSpecializationInfo()->getTemplate()
1289 ->getTemplateParameters();
1290 return
1291 CollectTemplateParams(TList, *FD->getTemplateSpecializationArgs(), Unit);
1292 }
1293 return llvm::DIArray();
1294}
1295
1296/// CollectCXXTemplateParams - A helper function to collect debug info for
1297/// template parameters.
1298llvm::DIArray CGDebugInfo::
1299CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial,
1300 llvm::DIFile Unit) {
1301 llvm::PointerUnion<ClassTemplateDecl *,
1302 ClassTemplatePartialSpecializationDecl *>
1303 PU = TSpecial->getSpecializedTemplateOrPartial();
1304
1305 TemplateParameterList *TPList = PU.is<ClassTemplateDecl *>() ?
1306 PU.get<ClassTemplateDecl *>()->getTemplateParameters() :
1307 PU.get<ClassTemplatePartialSpecializationDecl *>()->getTemplateParameters();
1308 const TemplateArgumentList &TAList = TSpecial->getTemplateInstantiationArgs();
1309 return CollectTemplateParams(TPList, TAList, Unit);
1310}
1311
1312/// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
1313llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
1314 if (VTablePtrType.isValid())
1315 return VTablePtrType;
1316
1317 ASTContext &Context = CGM.getContext();
1318
1319 /* Function type */
1320 llvm::Value *STy = getOrCreateType(Context.IntTy, Unit);
1321 llvm::DIArray SElements = DBuilder.getOrCreateArray(STy);
1322 llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements);
1323 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1324 llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0,
1325 "__vtbl_ptr_type");
1326 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1327 return VTablePtrType;
1328}
1329
1330/// getVTableName - Get vtable name for the given Class.
1331StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
1332 // Construct gdb compatible name name.
1333 std::string Name = "_vptr$" + RD->getNameAsString();
1334
1335 // Copy this name on the side and use its reference.
1336 char *StrPtr = DebugInfoNames.Allocate<char>(Name.length());
1337 memcpy(StrPtr, Name.data(), Name.length());
1338 return StringRef(StrPtr, Name.length());
1339}
1340
1341
1342/// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
1343/// debug info entry in EltTys vector.
1344void CGDebugInfo::
1345CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
1346 SmallVectorImpl<llvm::Value *> &EltTys) {
1347 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1348
1349 // If there is a primary base then it will hold vtable info.
1350 if (RL.getPrimaryBase())
1351 return;
1352
1353 // If this class is not dynamic then there is not any vtable info to collect.
1354 if (!RD->isDynamicClass())
1355 return;
1356
1357 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1358 llvm::DIType VPTR
1359 = DBuilder.createMemberType(Unit, getVTableName(RD), Unit,
1360 0, Size, 0, 0, llvm::DIDescriptor::FlagArtificial,
1361 getOrCreateVTablePtrType(Unit));
1362 EltTys.push_back(VPTR);
1363}
1364
1365/// getOrCreateRecordType - Emit record type's standalone debug info.
1366llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy,
1367 SourceLocation Loc) {
1368 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
1369 llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc));
1370 return T;
1371}
1372
1373/// getOrCreateInterfaceType - Emit an objective c interface type standalone
1374/// debug info.
1375llvm::DIType CGDebugInfo::getOrCreateInterfaceType(QualType D,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001376 SourceLocation Loc) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001377 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
1378 llvm::DIType T = getOrCreateType(D, getOrCreateFile(Loc));
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001379 RetainedTypes.push_back(D.getAsOpaquePtr());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001380 return T;
1381}
1382
1383/// CreateType - get structure or union type.
1384llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty) {
1385 RecordDecl *RD = Ty->getDecl();
1386
1387 // Get overall information about the record type for the debug info.
1388 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1389
1390 // Records and classes and unions can all be recursive. To handle them, we
1391 // first generate a debug descriptor for the struct as a forward declaration.
1392 // Then (if it is a definition) we go through and get debug info for all of
1393 // its members. Finally, we create a descriptor for the complete type (which
1394 // may refer to the forward decl if the struct is recursive) and replace all
1395 // uses of the forward declaration with the final definition.
1396
Eric Christopherf068c922013-04-02 22:59:11 +00001397 llvm::DICompositeType FwdDecl(
1398 getOrCreateLimitedType(QualType(Ty, 0), DefUnit));
1399 assert(FwdDecl.Verify() &&
1400 "The debug type of a RecordType should be a DICompositeType");
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001401
1402 if (FwdDecl.isForwardDecl())
1403 return FwdDecl;
1404
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001405 // Push the struct on region stack.
Eric Christopherf068c922013-04-02 22:59:11 +00001406 LexicalBlockStack.push_back(&*FwdDecl);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001407 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1408
Adrian Prantl4919de62013-03-06 22:03:30 +00001409 // Add this to the completed-type cache while we're completing it recursively.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001410 CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1411
1412 // Convert all the elements.
1413 SmallVector<llvm::Value *, 16> EltTys;
1414
1415 // Note: The split of CXXDecl information here is intentional, the
1416 // gdb tests will depend on a certain ordering at printout. The debug
1417 // information offsets are still correct if we merge them all together
1418 // though.
1419 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1420 if (CXXDecl) {
1421 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1422 CollectVTableInfo(CXXDecl, DefUnit, EltTys);
1423 }
1424
Eric Christopher0395de32013-01-16 01:22:32 +00001425 // Collect data fields (including static variables and any initializers).
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001426 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
1427 llvm::DIArray TParamsArray;
1428 if (CXXDecl) {
1429 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
1430 CollectCXXFriends(CXXDecl, DefUnit, EltTys, FwdDecl);
1431 if (const ClassTemplateSpecializationDecl *TSpecial
1432 = dyn_cast<ClassTemplateSpecializationDecl>(RD))
1433 TParamsArray = CollectCXXTemplateParams(TSpecial, DefUnit);
1434 }
1435
1436 LexicalBlockStack.pop_back();
1437 RegionMap.erase(Ty->getDecl());
1438
1439 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopherf068c922013-04-02 22:59:11 +00001440 FwdDecl.setTypeArray(Elements, TParamsArray);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001441
Eric Christopherf068c922013-04-02 22:59:11 +00001442 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1443 return FwdDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001444}
1445
1446/// CreateType - get objective-c object type.
1447llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1448 llvm::DIFile Unit) {
1449 // Ignore protocols.
1450 return getOrCreateType(Ty->getBaseType(), Unit);
1451}
1452
1453/// CreateType - get objective-c interface type.
1454llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1455 llvm::DIFile Unit) {
1456 ObjCInterfaceDecl *ID = Ty->getDecl();
1457 if (!ID)
1458 return llvm::DIType();
1459
1460 // Get overall information about the record type for the debug info.
1461 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1462 unsigned Line = getLineNumber(ID->getLocation());
1463 unsigned RuntimeLang = TheCU.getLanguage();
1464
1465 // If this is just a forward declaration return a special forward-declaration
1466 // debug type since we won't be able to lay out the entire type.
1467 ObjCInterfaceDecl *Def = ID->getDefinition();
1468 if (!Def) {
1469 llvm::DIType FwdDecl =
1470 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001471 ID->getName(), TheCU, DefUnit, Line,
1472 RuntimeLang);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001473 return FwdDecl;
1474 }
1475
1476 ID = Def;
1477
1478 // Bit size, align and offset of the type.
1479 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1480 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1481
1482 unsigned Flags = 0;
1483 if (ID->getImplementation())
1484 Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
1485
Eric Christopherf068c922013-04-02 22:59:11 +00001486 llvm::DICompositeType RealDecl =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001487 DBuilder.createStructType(Unit, ID->getName(), DefUnit,
1488 Line, Size, Align, Flags,
David Blaikiec1d0af12013-02-25 01:07:08 +00001489 llvm::DIType(), llvm::DIArray(), RuntimeLang);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001490
1491 // Otherwise, insert it into the CompletedTypeCache so that recursive uses
1492 // will find it and we're emitting the complete type.
Adrian Prantl4919de62013-03-06 22:03:30 +00001493 QualType QualTy = QualType(Ty, 0);
1494 CompletedTypeCache[QualTy.getAsOpaquePtr()] = RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001495 // Push the struct on region stack.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001496
Eric Christopherf068c922013-04-02 22:59:11 +00001497 LexicalBlockStack.push_back(static_cast<llvm::MDNode*>(RealDecl));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001498 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1499
1500 // Convert all the elements.
1501 SmallVector<llvm::Value *, 16> EltTys;
1502
1503 ObjCInterfaceDecl *SClass = ID->getSuperClass();
1504 if (SClass) {
1505 llvm::DIType SClassTy =
1506 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1507 if (!SClassTy.isValid())
1508 return llvm::DIType();
1509
1510 llvm::DIType InhTag =
1511 DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
1512 EltTys.push_back(InhTag);
1513 }
1514
1515 for (ObjCContainerDecl::prop_iterator I = ID->prop_begin(),
1516 E = ID->prop_end(); I != E; ++I) {
1517 const ObjCPropertyDecl *PD = *I;
1518 SourceLocation Loc = PD->getLocation();
1519 llvm::DIFile PUnit = getOrCreateFile(Loc);
1520 unsigned PLine = getLineNumber(Loc);
1521 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1522 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1523 llvm::MDNode *PropertyNode =
1524 DBuilder.createObjCProperty(PD->getName(),
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001525 PUnit, PLine,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001526 (Getter && Getter->isImplicit()) ? "" :
1527 getSelectorName(PD->getGetterName()),
1528 (Setter && Setter->isImplicit()) ? "" :
1529 getSelectorName(PD->getSetterName()),
1530 PD->getPropertyAttributes(),
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001531 getOrCreateType(PD->getType(), PUnit));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001532 EltTys.push_back(PropertyNode);
1533 }
1534
1535 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1536 unsigned FieldNo = 0;
1537 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1538 Field = Field->getNextIvar(), ++FieldNo) {
1539 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1540 if (!FieldTy.isValid())
1541 return llvm::DIType();
1542
1543 StringRef FieldName = Field->getName();
1544
1545 // Ignore unnamed fields.
1546 if (FieldName.empty())
1547 continue;
1548
1549 // Get the location for the field.
1550 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1551 unsigned FieldLine = getLineNumber(Field->getLocation());
1552 QualType FType = Field->getType();
1553 uint64_t FieldSize = 0;
1554 unsigned FieldAlign = 0;
1555
1556 if (!FType->isIncompleteArrayType()) {
1557
1558 // Bit size, align and offset of the type.
1559 FieldSize = Field->isBitField()
1560 ? Field->getBitWidthValue(CGM.getContext())
1561 : CGM.getContext().getTypeSize(FType);
1562 FieldAlign = CGM.getContext().getTypeAlign(FType);
1563 }
1564
1565 uint64_t FieldOffset;
1566 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1567 // We don't know the runtime offset of an ivar if we're using the
1568 // non-fragile ABI. For bitfields, use the bit offset into the first
1569 // byte of storage of the bitfield. For other fields, use zero.
1570 if (Field->isBitField()) {
1571 FieldOffset = CGM.getObjCRuntime().ComputeBitfieldBitOffset(
1572 CGM, ID, Field);
1573 FieldOffset %= CGM.getContext().getCharWidth();
1574 } else {
1575 FieldOffset = 0;
1576 }
1577 } else {
1578 FieldOffset = RL.getFieldOffset(FieldNo);
1579 }
1580
1581 unsigned Flags = 0;
1582 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1583 Flags = llvm::DIDescriptor::FlagProtected;
1584 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1585 Flags = llvm::DIDescriptor::FlagPrivate;
1586
1587 llvm::MDNode *PropertyNode = NULL;
1588 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
1589 if (ObjCPropertyImplDecl *PImpD =
1590 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
1591 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001592 SourceLocation Loc = PD->getLocation();
1593 llvm::DIFile PUnit = getOrCreateFile(Loc);
1594 unsigned PLine = getLineNumber(Loc);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001595 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1596 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1597 PropertyNode =
1598 DBuilder.createObjCProperty(PD->getName(),
1599 PUnit, PLine,
1600 (Getter && Getter->isImplicit()) ? "" :
1601 getSelectorName(PD->getGetterName()),
1602 (Setter && Setter->isImplicit()) ? "" :
1603 getSelectorName(PD->getSetterName()),
1604 PD->getPropertyAttributes(),
1605 getOrCreateType(PD->getType(), PUnit));
1606 }
1607 }
1608 }
1609 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
1610 FieldLine, FieldSize, FieldAlign,
1611 FieldOffset, Flags, FieldTy,
1612 PropertyNode);
1613 EltTys.push_back(FieldTy);
1614 }
1615
1616 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopherf068c922013-04-02 22:59:11 +00001617 RealDecl.setTypeArray(Elements);
Adrian Prantl4919de62013-03-06 22:03:30 +00001618
1619 // If the implementation is not yet set, we do not want to mark it
1620 // as complete. An implementation may declare additional
1621 // private ivars that we would miss otherwise.
1622 if (ID->getImplementation() == 0)
1623 CompletedTypeCache.erase(QualTy.getAsOpaquePtr());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001624
1625 LexicalBlockStack.pop_back();
Eric Christopherf068c922013-04-02 22:59:11 +00001626 return RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001627}
1628
1629llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) {
1630 llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1631 int64_t Count = Ty->getNumElements();
1632 if (Count == 0)
1633 // If number of elements are not known then this is an unbounded array.
1634 // Use Count == -1 to express such arrays.
1635 Count = -1;
1636
1637 llvm::Value *Subscript = DBuilder.getOrCreateSubrange(0, Count);
1638 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1639
1640 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1641 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1642
1643 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1644}
1645
1646llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1647 llvm::DIFile Unit) {
1648 uint64_t Size;
1649 uint64_t Align;
1650
1651 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1652 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1653 Size = 0;
1654 Align =
1655 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1656 } else if (Ty->isIncompleteArrayType()) {
1657 Size = 0;
1658 if (Ty->getElementType()->isIncompleteType())
1659 Align = 0;
1660 else
1661 Align = CGM.getContext().getTypeAlign(Ty->getElementType());
David Blaikie089db2e2013-05-09 20:48:12 +00001662 } else if (Ty->isIncompleteType()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001663 Size = 0;
1664 Align = 0;
1665 } else {
1666 // Size and align of the whole array, not the element type.
1667 Size = CGM.getContext().getTypeSize(Ty);
1668 Align = CGM.getContext().getTypeAlign(Ty);
1669 }
1670
1671 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
1672 // interior arrays, do we care? Why aren't nested arrays represented the
1673 // obvious/recursive way?
1674 SmallVector<llvm::Value *, 8> Subscripts;
1675 QualType EltTy(Ty, 0);
1676 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1677 // If the number of elements is known, then count is that number. Otherwise,
1678 // it's -1. This allows us to represent a subrange with an array of 0
1679 // elements, like this:
1680 //
1681 // struct foo {
1682 // int x[0];
1683 // };
1684 int64_t Count = -1; // Count == -1 is an unbounded array.
1685 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1686 Count = CAT->getSize().getZExtValue();
1687
1688 // FIXME: Verify this is right for VLAs.
1689 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
1690 EltTy = Ty->getElementType();
1691 }
1692
1693 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1694
1695 llvm::DIType DbgTy =
1696 DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1697 SubscriptArray);
1698 return DbgTy;
1699}
1700
1701llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
1702 llvm::DIFile Unit) {
1703 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
1704 Ty, Ty->getPointeeType(), Unit);
1705}
1706
1707llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
1708 llvm::DIFile Unit) {
1709 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
1710 Ty, Ty->getPointeeType(), Unit);
1711}
1712
1713llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
1714 llvm::DIFile U) {
David Blaikiee8d75142013-01-19 19:20:56 +00001715 llvm::DIType ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
1716 if (!Ty->getPointeeType()->isFunctionType())
1717 return DBuilder.createMemberPointerType(
1718 CreatePointeeType(Ty->getPointeeType(), U), ClassType);
1719 return DBuilder.createMemberPointerType(getOrCreateInstanceMethodType(
1720 CGM.getContext().getPointerType(
1721 QualType(Ty->getClass(), Ty->getPointeeType().getCVRQualifiers())),
1722 Ty->getPointeeType()->getAs<FunctionProtoType>(), U),
1723 ClassType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001724}
1725
1726llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty,
1727 llvm::DIFile U) {
1728 // Ignore the atomic wrapping
1729 // FIXME: What is the correct representation?
1730 return getOrCreateType(Ty->getValueType(), U);
1731}
1732
1733/// CreateEnumType - get enumeration type.
1734llvm::DIType CGDebugInfo::CreateEnumType(const EnumDecl *ED) {
1735 uint64_t Size = 0;
1736 uint64_t Align = 0;
1737 if (!ED->getTypeForDecl()->isIncompleteType()) {
1738 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1739 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1740 }
1741
1742 // If this is just a forward declaration, construct an appropriately
1743 // marked node and just return it.
1744 if (!ED->getDefinition()) {
1745 llvm::DIDescriptor EDContext;
1746 EDContext = getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1747 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1748 unsigned Line = getLineNumber(ED->getLocation());
1749 StringRef EDName = ED->getName();
1750 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_enumeration_type,
1751 EDName, EDContext, DefUnit, Line, 0,
1752 Size, Align);
1753 }
1754
1755 // Create DIEnumerator elements for each enumerator.
1756 SmallVector<llvm::Value *, 16> Enumerators;
1757 ED = ED->getDefinition();
1758 for (EnumDecl::enumerator_iterator
1759 Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
1760 Enum != EnumEnd; ++Enum) {
1761 Enumerators.push_back(
1762 DBuilder.createEnumerator(Enum->getName(),
1763 Enum->getInitVal().getZExtValue()));
1764 }
1765
1766 // Return a CompositeType for the enum itself.
1767 llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1768
1769 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1770 unsigned Line = getLineNumber(ED->getLocation());
1771 llvm::DIDescriptor EnumContext =
1772 getContextDescriptor(cast<Decl>(ED->getDeclContext()));
Adrian Prantl59d6a712013-04-19 19:56:39 +00001773 llvm::DIType ClassTy = ED->isFixed() ?
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001774 getOrCreateType(ED->getIntegerType(), DefUnit) : llvm::DIType();
1775 llvm::DIType DbgTy =
1776 DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1777 Size, Align, EltArray,
1778 ClassTy);
1779 return DbgTy;
1780}
1781
David Blaikie4b12be62013-01-21 04:37:12 +00001782static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
1783 Qualifiers Quals;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001784 do {
David Blaikie4b12be62013-01-21 04:37:12 +00001785 Quals += T.getLocalQualifiers();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001786 QualType LastT = T;
1787 switch (T->getTypeClass()) {
1788 default:
David Blaikie4b12be62013-01-21 04:37:12 +00001789 return C.getQualifiedType(T.getTypePtr(), Quals);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001790 case Type::TemplateSpecialization:
1791 T = cast<TemplateSpecializationType>(T)->desugar();
1792 break;
1793 case Type::TypeOfExpr:
1794 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1795 break;
1796 case Type::TypeOf:
1797 T = cast<TypeOfType>(T)->getUnderlyingType();
1798 break;
1799 case Type::Decltype:
1800 T = cast<DecltypeType>(T)->getUnderlyingType();
1801 break;
1802 case Type::UnaryTransform:
1803 T = cast<UnaryTransformType>(T)->getUnderlyingType();
1804 break;
1805 case Type::Attributed:
1806 T = cast<AttributedType>(T)->getEquivalentType();
1807 break;
1808 case Type::Elaborated:
1809 T = cast<ElaboratedType>(T)->getNamedType();
1810 break;
1811 case Type::Paren:
1812 T = cast<ParenType>(T)->getInnerType();
1813 break;
David Blaikie4b12be62013-01-21 04:37:12 +00001814 case Type::SubstTemplateTypeParm:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001815 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001816 break;
1817 case Type::Auto:
1818 T = cast<AutoType>(T)->getDeducedType();
1819 break;
1820 }
1821
1822 assert(T != LastT && "Type unwrapping failed to unwrap!");
NAKAMURA Takumid24c9ab2013-01-21 10:51:28 +00001823 (void)LastT;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001824 } while (true);
1825}
1826
1827/// getType - Get the type from the cache or return null type if it doesn't exist.
1828llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) {
1829
1830 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00001831 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001832
1833 // Check for existing entry.
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001834 if (Ty->getTypeClass() == Type::ObjCInterface) {
1835 llvm::Value *V = getCachedInterfaceTypeOrNull(Ty);
1836 if (V)
1837 return llvm::DIType(cast<llvm::MDNode>(V));
1838 else return llvm::DIType();
1839 }
1840
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001841 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1842 TypeCache.find(Ty.getAsOpaquePtr());
1843 if (it != TypeCache.end()) {
1844 // Verify that the debug info still exists.
1845 if (llvm::Value *V = it->second)
1846 return llvm::DIType(cast<llvm::MDNode>(V));
1847 }
1848
1849 return llvm::DIType();
1850}
1851
1852/// getCompletedTypeOrNull - Get the type from the cache or return null if it
1853/// doesn't exist.
1854llvm::DIType CGDebugInfo::getCompletedTypeOrNull(QualType Ty) {
1855
1856 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00001857 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001858
1859 // Check for existing entry.
Adrian Prantl4919de62013-03-06 22:03:30 +00001860 llvm::Value *V = 0;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001861 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1862 CompletedTypeCache.find(Ty.getAsOpaquePtr());
Adrian Prantl4919de62013-03-06 22:03:30 +00001863 if (it != CompletedTypeCache.end())
1864 V = it->second;
1865 else {
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001866 V = getCachedInterfaceTypeOrNull(Ty);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001867 }
1868
Adrian Prantl4919de62013-03-06 22:03:30 +00001869 // Verify that any cached debug info still exists.
1870 if (V != 0)
1871 return llvm::DIType(cast<llvm::MDNode>(V));
1872
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001873 return llvm::DIType();
1874}
1875
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001876/// getCachedInterfaceTypeOrNull - Get the type from the interface
1877/// cache, unless it needs to regenerated. Otherwise return null.
1878llvm::Value *CGDebugInfo::getCachedInterfaceTypeOrNull(QualType Ty) {
1879 // Is there a cached interface that hasn't changed?
1880 llvm::DenseMap<void *, std::pair<llvm::WeakVH, unsigned > >
1881 ::iterator it1 = ObjCInterfaceCache.find(Ty.getAsOpaquePtr());
1882
1883 if (it1 != ObjCInterfaceCache.end())
1884 if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty))
1885 if (Checksum(Decl) == it1->second.second)
1886 // Return cached forward declaration.
1887 return it1->second.first;
1888
1889 return 0;
1890}
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001891
1892/// getOrCreateType - Get the type from the cache or create a new
1893/// one if necessary.
1894llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit) {
1895 if (Ty.isNull())
1896 return llvm::DIType();
1897
1898 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00001899 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001900
1901 llvm::DIType T = getCompletedTypeOrNull(Ty);
1902
1903 if (T.Verify())
1904 return T;
1905
1906 // Otherwise create the type.
1907 llvm::DIType Res = CreateTypeNode(Ty, Unit);
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001908 void* TyPtr = Ty.getAsOpaquePtr();
1909
1910 // And update the type cache.
1911 TypeCache[TyPtr] = Res;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001912
1913 llvm::DIType TC = getTypeOrNull(Ty);
1914 if (TC.Verify() && TC.isForwardDecl())
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001915 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
1916 else if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty)) {
1917 // Interface types may have elements added to them by a
1918 // subsequent implementation or extension, so we keep them in
1919 // the ObjCInterfaceCache together with a checksum. Instead of
Adrian Prantlf06989b2013-05-08 23:37:22 +00001920 // the (possibly) incomplete interface type, we return a forward
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001921 // declaration that gets RAUW'd in CGDebugInfo::finalize().
1922 llvm::DenseMap<void *, std::pair<llvm::WeakVH, unsigned > >
1923 ::iterator it = ObjCInterfaceCache.find(TyPtr);
1924 if (it != ObjCInterfaceCache.end())
1925 TC = llvm::DIType(cast<llvm::MDNode>(it->second.first));
1926 else
1927 TC = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
Adrian Prantl00df5ea2013-03-12 20:43:25 +00001928 Decl->getName(), TheCU, Unit,
1929 getLineNumber(Decl->getLocation()),
1930 TheCU.getLanguage());
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001931 // Store the forward declaration in the cache.
1932 ObjCInterfaceCache[TyPtr] = std::make_pair(TC, Checksum(Decl));
1933
1934 // Register the type for replacement in finalize().
1935 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
1936 return TC;
Adrian Prantl4919de62013-03-06 22:03:30 +00001937 }
1938
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001939 if (!Res.isForwardDecl())
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001940 CompletedTypeCache[TyPtr] = Res;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001941
1942 return Res;
1943}
1944
Adrian Prantl4919de62013-03-06 22:03:30 +00001945/// Currently the checksum merely consists of the number of ivars.
1946unsigned CGDebugInfo::Checksum(const ObjCInterfaceDecl
Adrian Prantl00df5ea2013-03-12 20:43:25 +00001947 *InterfaceDecl) {
Adrian Prantl4919de62013-03-06 22:03:30 +00001948 unsigned IvarNo = 0;
1949 for (const ObjCIvarDecl *Ivar = InterfaceDecl->all_declared_ivar_begin();
1950 Ivar != 0; Ivar = Ivar->getNextIvar()) ++IvarNo;
1951 return IvarNo;
1952}
1953
1954ObjCInterfaceDecl *CGDebugInfo::getObjCInterfaceDecl(QualType Ty) {
1955 switch (Ty->getTypeClass()) {
1956 case Type::ObjCObjectPointer:
1957 return getObjCInterfaceDecl(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
1958 case Type::ObjCInterface:
1959 return cast<ObjCInterfaceType>(Ty)->getDecl();
1960 default:
1961 return 0;
1962 }
1963}
1964
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001965/// CreateTypeNode - Create a new debug type node.
1966llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit) {
1967 // Handle qualifiers, which recursively handles what they refer to.
1968 if (Ty.hasLocalQualifiers())
1969 return CreateQualifiedType(Ty, Unit);
1970
1971 const char *Diag = 0;
1972
1973 // Work out details of type.
1974 switch (Ty->getTypeClass()) {
1975#define TYPE(Class, Base)
1976#define ABSTRACT_TYPE(Class, Base)
1977#define NON_CANONICAL_TYPE(Class, Base)
1978#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1979#include "clang/AST/TypeNodes.def"
1980 llvm_unreachable("Dependent types cannot show up in debug information");
1981
1982 case Type::ExtVector:
1983 case Type::Vector:
1984 return CreateType(cast<VectorType>(Ty), Unit);
1985 case Type::ObjCObjectPointer:
1986 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
1987 case Type::ObjCObject:
1988 return CreateType(cast<ObjCObjectType>(Ty), Unit);
1989 case Type::ObjCInterface:
1990 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
1991 case Type::Builtin:
1992 return CreateType(cast<BuiltinType>(Ty));
1993 case Type::Complex:
1994 return CreateType(cast<ComplexType>(Ty));
1995 case Type::Pointer:
1996 return CreateType(cast<PointerType>(Ty), Unit);
1997 case Type::BlockPointer:
1998 return CreateType(cast<BlockPointerType>(Ty), Unit);
1999 case Type::Typedef:
2000 return CreateType(cast<TypedefType>(Ty), Unit);
2001 case Type::Record:
2002 return CreateType(cast<RecordType>(Ty));
2003 case Type::Enum:
2004 return CreateEnumType(cast<EnumType>(Ty)->getDecl());
2005 case Type::FunctionProto:
2006 case Type::FunctionNoProto:
2007 return CreateType(cast<FunctionType>(Ty), Unit);
2008 case Type::ConstantArray:
2009 case Type::VariableArray:
2010 case Type::IncompleteArray:
2011 return CreateType(cast<ArrayType>(Ty), Unit);
2012
2013 case Type::LValueReference:
2014 return CreateType(cast<LValueReferenceType>(Ty), Unit);
2015 case Type::RValueReference:
2016 return CreateType(cast<RValueReferenceType>(Ty), Unit);
2017
2018 case Type::MemberPointer:
2019 return CreateType(cast<MemberPointerType>(Ty), Unit);
2020
2021 case Type::Atomic:
2022 return CreateType(cast<AtomicType>(Ty), Unit);
2023
2024 case Type::Attributed:
2025 case Type::TemplateSpecialization:
2026 case Type::Elaborated:
2027 case Type::Paren:
2028 case Type::SubstTemplateTypeParm:
2029 case Type::TypeOfExpr:
2030 case Type::TypeOf:
2031 case Type::Decltype:
2032 case Type::UnaryTransform:
2033 case Type::Auto:
2034 llvm_unreachable("type should have been unwrapped!");
2035 }
2036
2037 assert(Diag && "Fall through without a diagnostic?");
2038 unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error,
2039 "debug information for %0 is not yet supported");
2040 CGM.getDiags().Report(DiagID)
2041 << Diag;
2042 return llvm::DIType();
2043}
2044
2045/// getOrCreateLimitedType - Get the type from the cache or create a new
2046/// limited type if necessary.
2047llvm::DIType CGDebugInfo::getOrCreateLimitedType(QualType Ty,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002048 llvm::DIFile Unit) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002049 if (Ty.isNull())
2050 return llvm::DIType();
2051
2052 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00002053 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002054
2055 llvm::DIType T = getTypeOrNull(Ty);
2056
2057 // We may have cached a forward decl when we could have created
2058 // a non-forward decl. Go ahead and create a non-forward decl
2059 // now.
2060 if (T.Verify() && !T.isForwardDecl()) return T;
2061
2062 // Otherwise create the type.
2063 llvm::DIType Res = CreateLimitedTypeNode(Ty, Unit);
2064
2065 if (T.Verify() && T.isForwardDecl())
2066 ReplaceMap.push_back(std::make_pair(Ty.getAsOpaquePtr(),
2067 static_cast<llvm::Value*>(T)));
2068
2069 // And update the type cache.
2070 TypeCache[Ty.getAsOpaquePtr()] = Res;
2071 return Res;
2072}
2073
2074// TODO: Currently used for context chains when limiting debug info.
2075llvm::DIType CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
2076 RecordDecl *RD = Ty->getDecl();
2077
2078 // Get overall information about the record type for the debug info.
2079 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
2080 unsigned Line = getLineNumber(RD->getLocation());
2081 StringRef RDName = getClassName(RD);
2082
2083 llvm::DIDescriptor RDContext;
2084 if (CGM.getCodeGenOpts().getDebugInfo() == CodeGenOptions::LimitedDebugInfo)
2085 RDContext = createContextChain(cast<Decl>(RD->getDeclContext()));
2086 else
2087 RDContext = getContextDescriptor(cast<Decl>(RD->getDeclContext()));
2088
2089 // If this is just a forward declaration, construct an appropriately
2090 // marked node and just return it.
2091 if (!RD->getDefinition())
2092 return createRecordFwdDecl(RD, RDContext);
2093
2094 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2095 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
2096 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
David Blaikie2fcadbe2013-03-26 23:47:35 +00002097 llvm::DICompositeType RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002098
2099 if (RD->isUnion())
2100 RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002101 Size, Align, 0, llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002102 else if (RD->isClass()) {
2103 // FIXME: This could be a struct type giving a default visibility different
2104 // than C++ class type, but needs llvm metadata changes first.
2105 RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002106 Size, Align, 0, 0, llvm::DIType(),
2107 llvm::DIArray(), llvm::DIType(),
2108 llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002109 } else
2110 RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line,
Adrian Prantl00df5ea2013-03-12 20:43:25 +00002111 Size, Align, 0, llvm::DIType(), llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002112
2113 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
David Blaikie2fcadbe2013-03-26 23:47:35 +00002114 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002115
2116 if (CXXDecl) {
2117 // A class's primary base or the class itself contains the vtable.
David Blaikie2fcadbe2013-03-26 23:47:35 +00002118 llvm::DICompositeType ContainingType;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002119 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2120 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
2121 // Seek non virtual primary base root.
2122 while (1) {
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002123 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
2124 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
2125 if (PBT && !BRL.isPrimaryBaseVirtual())
2126 PBase = PBT;
2127 else
2128 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002129 }
David Blaikie2fcadbe2013-03-26 23:47:35 +00002130 ContainingType = llvm::DICompositeType(
2131 getOrCreateType(QualType(PBase->getTypeForDecl(), 0), DefUnit));
2132 } else if (CXXDecl->isDynamicClass())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002133 ContainingType = RealDecl;
2134
David Blaikie2fcadbe2013-03-26 23:47:35 +00002135 RealDecl.setContainingType(ContainingType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002136 }
2137 return llvm::DIType(RealDecl);
2138}
2139
2140/// CreateLimitedTypeNode - Create a new debug type node, but only forward
2141/// declare composite types that haven't been processed yet.
2142llvm::DIType CGDebugInfo::CreateLimitedTypeNode(QualType Ty,llvm::DIFile Unit) {
2143
2144 // Work out details of type.
2145 switch (Ty->getTypeClass()) {
2146#define TYPE(Class, Base)
2147#define ABSTRACT_TYPE(Class, Base)
2148#define NON_CANONICAL_TYPE(Class, Base)
2149#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2150 #include "clang/AST/TypeNodes.def"
2151 llvm_unreachable("Dependent types cannot show up in debug information");
2152
2153 case Type::Record:
2154 return CreateLimitedType(cast<RecordType>(Ty));
2155 default:
2156 return CreateTypeNode(Ty, Unit);
2157 }
2158}
2159
2160/// CreateMemberType - Create new member and increase Offset by FType's size.
2161llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
2162 StringRef Name,
2163 uint64_t *Offset) {
2164 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2165 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
2166 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
2167 llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0,
2168 FieldSize, FieldAlign,
2169 *Offset, 0, FieldTy);
2170 *Offset += FieldSize;
2171 return Ty;
2172}
2173
David Blaikie3923d6a2013-05-08 06:01:46 +00002174llvm::DIDescriptor CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
2175 if (const TypeDecl *RD = dyn_cast<TypeDecl>(D))
2176 return CreatePointeeType(QualType(RD->getTypeForDecl(), 0), llvm::DIFile());
2177 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator I =
2178 DeclCache.find(D->getCanonicalDecl());
2179 if (I == DeclCache.end())
2180 return llvm::DIDescriptor();
2181 llvm::Value *V = I->second;
2182 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
2183}
2184
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002185/// getFunctionDeclaration - Return debug info descriptor to describe method
2186/// declaration for the given method definition.
2187llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
2188 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
2189 if (!FD) return llvm::DISubprogram();
2190
2191 // Setup context.
2192 getContextDescriptor(cast<Decl>(D->getDeclContext()));
2193
2194 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2195 MI = SPCache.find(FD->getCanonicalDecl());
2196 if (MI != SPCache.end()) {
2197 llvm::Value *V = MI->second;
2198 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
2199 if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
2200 return SP;
2201 }
2202
2203 for (FunctionDecl::redecl_iterator I = FD->redecls_begin(),
2204 E = FD->redecls_end(); I != E; ++I) {
2205 const FunctionDecl *NextFD = *I;
2206 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2207 MI = SPCache.find(NextFD->getCanonicalDecl());
2208 if (MI != SPCache.end()) {
2209 llvm::Value *V = MI->second;
2210 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
2211 if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
2212 return SP;
2213 }
2214 }
2215 return llvm::DISubprogram();
2216}
2217
2218// getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
2219// implicit parameter "this".
2220llvm::DIType CGDebugInfo::getOrCreateFunctionType(const Decl *D,
2221 QualType FnType,
2222 llvm::DIFile F) {
2223
2224 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
2225 return getOrCreateMethodType(Method, F);
2226 if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
2227 // Add "self" and "_cmd"
2228 SmallVector<llvm::Value *, 16> Elts;
2229
2230 // First element is always return type. For 'void' functions it is NULL.
Adrian Prantl566a9c32013-05-10 21:08:31 +00002231 QualType ResultTy = OMethod->hasRelatedResultType()
2232 ? QualType(OMethod->getClassInterface()->getTypeForDecl(), 0)
2233 : OMethod->getResultType();
2234 Elts.push_back(getOrCreateType(ResultTy, F));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002235 // "self" pointer is always first argument.
Adrian Prantle86fcc42013-03-29 19:20:29 +00002236 QualType SelfDeclTy = OMethod->getSelfDecl()->getType();
2237 llvm::DIType SelfTy = getOrCreateType(SelfDeclTy, F);
2238 Elts.push_back(CreateSelfType(SelfDeclTy, SelfTy));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002239 // "_cmd" pointer is always second argument.
2240 llvm::DIType CmdTy = getOrCreateType(OMethod->getCmdDecl()->getType(), F);
2241 Elts.push_back(DBuilder.createArtificialType(CmdTy));
2242 // Get rest of the arguments.
2243 for (ObjCMethodDecl::param_const_iterator PI = OMethod->param_begin(),
2244 PE = OMethod->param_end(); PI != PE; ++PI)
2245 Elts.push_back(getOrCreateType((*PI)->getType(), F));
2246
2247 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2248 return DBuilder.createSubroutineType(F, EltTypeArray);
2249 }
2250 return getOrCreateType(FnType, F);
2251}
2252
2253/// EmitFunctionStart - Constructs the debug code for entering a function.
2254void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
2255 llvm::Function *Fn,
2256 CGBuilderTy &Builder) {
2257
2258 StringRef Name;
2259 StringRef LinkageName;
2260
2261 FnBeginRegionCount.push_back(LexicalBlockStack.size());
2262
2263 const Decl *D = GD.getDecl();
2264 // Function may lack declaration in source code if it is created by Clang
2265 // CodeGen (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
2266 bool HasDecl = (D != 0);
2267 // Use the location of the declaration.
2268 SourceLocation Loc;
2269 if (HasDecl)
2270 Loc = D->getLocation();
2271
2272 unsigned Flags = 0;
2273 llvm::DIFile Unit = getOrCreateFile(Loc);
2274 llvm::DIDescriptor FDContext(Unit);
2275 llvm::DIArray TParamsArray;
2276 if (!HasDecl) {
2277 // Use llvm function name.
2278 Name = Fn->getName();
2279 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2280 // If there is a DISubprogram for this function available then use it.
2281 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2282 FI = SPCache.find(FD->getCanonicalDecl());
2283 if (FI != SPCache.end()) {
2284 llvm::Value *V = FI->second;
2285 llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(V));
2286 if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
2287 llvm::MDNode *SPN = SP;
2288 LexicalBlockStack.push_back(SPN);
2289 RegionMap[D] = llvm::WeakVH(SP);
2290 return;
2291 }
2292 }
2293 Name = getFunctionName(FD);
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002294 // Use mangled name as linkage name for C/C++ functions.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002295 if (FD->hasPrototype()) {
2296 LinkageName = CGM.getMangledName(GD);
2297 Flags |= llvm::DIDescriptor::FlagPrototyped;
2298 }
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002299 // No need to replicate the linkage name if it isn't different from the
2300 // subprogram name, no need to have it at all unless coverage is enabled or
2301 // debug is set to more than just line tables.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002302 if (LinkageName == Name ||
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002303 (!CGM.getCodeGenOpts().EmitGcovArcs &&
2304 !CGM.getCodeGenOpts().EmitGcovNotes &&
2305 CGM.getCodeGenOpts().getDebugInfo() <= CodeGenOptions::DebugLineTablesOnly))
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002306 LinkageName = StringRef();
2307
2308 if (CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
2309 if (const NamespaceDecl *NSDecl =
2310 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
2311 FDContext = getOrCreateNameSpace(NSDecl);
2312 else if (const RecordDecl *RDecl =
2313 dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
2314 FDContext = getContextDescriptor(cast<Decl>(RDecl->getDeclContext()));
2315
2316 // Collect template parameters.
2317 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
2318 }
2319 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
2320 Name = getObjCMethodName(OMD);
2321 Flags |= llvm::DIDescriptor::FlagPrototyped;
2322 } else {
2323 // Use llvm function name.
2324 Name = Fn->getName();
2325 Flags |= llvm::DIDescriptor::FlagPrototyped;
2326 }
2327 if (!Name.empty() && Name[0] == '\01')
2328 Name = Name.substr(1);
2329
2330 unsigned LineNo = getLineNumber(Loc);
2331 if (!HasDecl || D->isImplicit())
2332 Flags |= llvm::DIDescriptor::FlagArtificial;
2333
2334 llvm::DIType DIFnType;
2335 llvm::DISubprogram SPDecl;
2336 if (HasDecl &&
2337 CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
2338 DIFnType = getOrCreateFunctionType(D, FnType, Unit);
2339 SPDecl = getFunctionDeclaration(D);
2340 } else {
2341 // Create fake but valid subroutine type. Otherwise
2342 // llvm::DISubprogram::Verify() would return false, and
2343 // subprogram DIE will miss DW_AT_decl_file and
2344 // DW_AT_decl_line fields.
2345 SmallVector<llvm::Value*, 16> Elts;
2346 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2347 DIFnType = DBuilder.createSubroutineType(Unit, EltTypeArray);
2348 }
2349 llvm::DISubprogram SP;
2350 SP = DBuilder.createFunction(FDContext, Name, LinkageName, Unit,
2351 LineNo, DIFnType,
2352 Fn->hasInternalLinkage(), true/*definition*/,
2353 getLineNumber(CurLoc), Flags,
2354 CGM.getLangOpts().Optimize,
2355 Fn, TParamsArray, SPDecl);
David Blaikie3923d6a2013-05-08 06:01:46 +00002356 if (HasDecl)
2357 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(SP)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002358
2359 // Push function on region stack.
2360 llvm::MDNode *SPN = SP;
2361 LexicalBlockStack.push_back(SPN);
2362 if (HasDecl)
2363 RegionMap[D] = llvm::WeakVH(SP);
2364}
2365
2366/// EmitLocation - Emit metadata to indicate a change in line/column
2367/// information in the source file.
Adrian Prantl00df5ea2013-03-12 20:43:25 +00002368void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc,
2369 bool ForceColumnInfo) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002370
2371 // Update our current location
2372 setLocation(Loc);
2373
2374 if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
2375
2376 // Don't bother if things are the same as last time.
2377 SourceManager &SM = CGM.getContext().getSourceManager();
2378 if (CurLoc == PrevLoc ||
2379 SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc))
2380 // New Builder may not be in sync with CGDebugInfo.
David Blaikie0a0f93c2013-02-01 19:09:49 +00002381 if (!Builder.getCurrentDebugLocation().isUnknown() &&
2382 Builder.getCurrentDebugLocation().getScope(CGM.getLLVMContext()) ==
2383 LexicalBlockStack.back())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002384 return;
2385
2386 // Update last state.
2387 PrevLoc = CurLoc;
2388
2389 llvm::MDNode *Scope = LexicalBlockStack.back();
Adrian Prantl00df5ea2013-03-12 20:43:25 +00002390 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get
2391 (getLineNumber(CurLoc),
2392 getColumnNumber(CurLoc, ForceColumnInfo),
2393 Scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002394}
2395
2396/// CreateLexicalBlock - Creates a new lexical block node and pushes it on
2397/// the stack.
2398void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
2399 llvm::DIDescriptor D =
2400 DBuilder.createLexicalBlock(LexicalBlockStack.empty() ?
2401 llvm::DIDescriptor() :
2402 llvm::DIDescriptor(LexicalBlockStack.back()),
2403 getOrCreateFile(CurLoc),
2404 getLineNumber(CurLoc),
2405 getColumnNumber(CurLoc));
2406 llvm::MDNode *DN = D;
2407 LexicalBlockStack.push_back(DN);
2408}
2409
2410/// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
2411/// region - beginning of a DW_TAG_lexical_block.
2412void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder, SourceLocation Loc) {
2413 // Set our current location.
2414 setLocation(Loc);
2415
2416 // Create a new lexical block and push it on the stack.
2417 CreateLexicalBlock(Loc);
2418
2419 // Emit a line table change for the current location inside the new scope.
2420 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc),
2421 getColumnNumber(Loc),
2422 LexicalBlockStack.back()));
2423}
2424
2425/// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative
2426/// region - end of a DW_TAG_lexical_block.
2427void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder, SourceLocation Loc) {
2428 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2429
2430 // Provide an entry in the line table for the end of the block.
2431 EmitLocation(Builder, Loc);
2432
2433 LexicalBlockStack.pop_back();
2434}
2435
2436/// EmitFunctionEnd - Constructs the debug code for exiting a function.
2437void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
2438 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2439 unsigned RCount = FnBeginRegionCount.back();
2440 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
2441
2442 // Pop all regions for this function.
2443 while (LexicalBlockStack.size() != RCount)
2444 EmitLexicalBlockEnd(Builder, CurLoc);
2445 FnBeginRegionCount.pop_back();
2446}
2447
2448// EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
2449// See BuildByRefType.
2450llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
2451 uint64_t *XOffset) {
2452
2453 SmallVector<llvm::Value *, 5> EltTys;
2454 QualType FType;
2455 uint64_t FieldSize, FieldOffset;
2456 unsigned FieldAlign;
2457
2458 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2459 QualType Type = VD->getType();
2460
2461 FieldOffset = 0;
2462 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2463 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
2464 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
2465 FType = CGM.getContext().IntTy;
2466 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
2467 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
2468
2469 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
2470 if (HasCopyAndDispose) {
2471 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2472 EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
2473 &FieldOffset));
2474 EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
2475 &FieldOffset));
2476 }
2477 bool HasByrefExtendedLayout;
2478 Qualifiers::ObjCLifetime Lifetime;
2479 if (CGM.getContext().getByrefLifetime(Type,
2480 Lifetime, HasByrefExtendedLayout)
2481 && HasByrefExtendedLayout)
2482 EltTys.push_back(CreateMemberType(Unit, FType,
2483 "__byref_variable_layout",
2484 &FieldOffset));
2485
2486 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2487 if (Align > CGM.getContext().toCharUnitsFromBits(
John McCall64aa4b32013-04-16 22:48:15 +00002488 CGM.getTarget().getPointerAlign(0))) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002489 CharUnits FieldOffsetInBytes
2490 = CGM.getContext().toCharUnitsFromBits(FieldOffset);
2491 CharUnits AlignedOffsetInBytes
2492 = FieldOffsetInBytes.RoundUpToAlignment(Align);
2493 CharUnits NumPaddingBytes
2494 = AlignedOffsetInBytes - FieldOffsetInBytes;
2495
2496 if (NumPaddingBytes.isPositive()) {
2497 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
2498 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
2499 pad, ArrayType::Normal, 0);
2500 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
2501 }
2502 }
2503
2504 FType = Type;
2505 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2506 FieldSize = CGM.getContext().getTypeSize(FType);
2507 FieldAlign = CGM.getContext().toBits(Align);
2508
2509 *XOffset = FieldOffset;
2510 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit,
2511 0, FieldSize, FieldAlign,
2512 FieldOffset, 0, FieldTy);
2513 EltTys.push_back(FieldTy);
2514 FieldOffset += FieldSize;
2515
2516 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
2517
2518 unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
2519
2520 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
David Blaikiec1d0af12013-02-25 01:07:08 +00002521 llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002522}
2523
2524/// EmitDeclare - Emit local variable declaration debug info.
2525void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
2526 llvm::Value *Storage,
2527 unsigned ArgNo, CGBuilderTy &Builder) {
2528 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2529 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2530
2531 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2532 llvm::DIType Ty;
2533 uint64_t XOffset = 0;
2534 if (VD->hasAttr<BlocksAttr>())
2535 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
2536 else
2537 Ty = getOrCreateType(VD->getType(), Unit);
2538
2539 // If there is no debug info for this type then do not emit debug info
2540 // for this variable.
2541 if (!Ty)
2542 return;
2543
2544 if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage)) {
2545 // If Storage is an aggregate returned as 'sret' then let debugger know
2546 // about this.
2547 if (Arg->hasStructRetAttr())
2548 Ty = DBuilder.createReferenceType(llvm::dwarf::DW_TAG_reference_type, Ty);
2549 else if (CXXRecordDecl *Record = VD->getType()->getAsCXXRecordDecl()) {
2550 // If an aggregate variable has non trivial destructor or non trivial copy
2551 // constructor than it is pass indirectly. Let debug info know about this
2552 // by using reference of the aggregate type as a argument type.
2553 if (Record->hasNonTrivialCopyConstructor() ||
2554 !Record->hasTrivialDestructor())
2555 Ty = DBuilder.createReferenceType(llvm::dwarf::DW_TAG_reference_type, Ty);
2556 }
2557 }
2558
2559 // Get location information.
2560 unsigned Line = getLineNumber(VD->getLocation());
2561 unsigned Column = getColumnNumber(VD->getLocation());
2562 unsigned Flags = 0;
2563 if (VD->isImplicit())
2564 Flags |= llvm::DIDescriptor::FlagArtificial;
2565 // If this is the first argument and it is implicit then
2566 // give it an object pointer flag.
2567 // FIXME: There has to be a better way to do this, but for static
2568 // functions there won't be an implicit param at arg1 and
2569 // otherwise it is 'self' or 'this'.
2570 if (isa<ImplicitParamDecl>(VD) && ArgNo == 1)
2571 Flags |= llvm::DIDescriptor::FlagObjectPointer;
2572
2573 llvm::MDNode *Scope = LexicalBlockStack.back();
2574
2575 StringRef Name = VD->getName();
2576 if (!Name.empty()) {
2577 if (VD->hasAttr<BlocksAttr>()) {
2578 CharUnits offset = CharUnits::fromQuantity(32);
2579 SmallVector<llvm::Value *, 9> addr;
2580 llvm::Type *Int64Ty = CGM.Int64Ty;
2581 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2582 // offset of __forwarding field
2583 offset = CGM.getContext().toCharUnitsFromBits(
John McCall64aa4b32013-04-16 22:48:15 +00002584 CGM.getTarget().getPointerWidth(0));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002585 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2586 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2587 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2588 // offset of x field
2589 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2590 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2591
2592 // Create the descriptor for the variable.
2593 llvm::DIVariable D =
2594 DBuilder.createComplexVariable(Tag,
2595 llvm::DIDescriptor(Scope),
2596 VD->getName(), Unit, Line, Ty,
2597 addr, ArgNo);
2598
2599 // Insert an llvm.dbg.declare into the current block.
2600 llvm::Instruction *Call =
2601 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2602 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2603 return;
Adrian Prantl230ea412013-04-30 22:45:09 +00002604 } else if (isa<VariableArrayType>(VD->getType())) {
2605 // These are "complex" variables in that they need an op_deref.
2606 // Create the descriptor for the variable.
2607 llvm::Value *Addr = llvm::ConstantInt::get(CGM.Int64Ty,
2608 llvm::DIBuilder::OpDeref);
2609 llvm::DIVariable D =
2610 DBuilder.createComplexVariable(Tag,
2611 llvm::DIDescriptor(Scope),
2612 Name, Unit, Line, Ty,
2613 Addr, ArgNo);
2614
2615 // Insert an llvm.dbg.declare into the current block.
2616 llvm::Instruction *Call =
2617 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2618 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2619 return;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002620 }
David Blaikie436653b2013-01-05 05:58:35 +00002621 } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2622 // If VD is an anonymous union then Storage represents value for
2623 // all union fields.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002624 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
David Blaikied8180cf2013-01-05 20:03:07 +00002625 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002626 for (RecordDecl::field_iterator I = RD->field_begin(),
2627 E = RD->field_end();
2628 I != E; ++I) {
2629 FieldDecl *Field = *I;
2630 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2631 StringRef FieldName = Field->getName();
2632
2633 // Ignore unnamed fields. Do not ignore unnamed records.
2634 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2635 continue;
2636
2637 // Use VarDecl's Tag, Scope and Line number.
2638 llvm::DIVariable D =
2639 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2640 FieldName, Unit, Line, FieldTy,
2641 CGM.getLangOpts().Optimize, Flags,
2642 ArgNo);
2643
2644 // Insert an llvm.dbg.declare into the current block.
2645 llvm::Instruction *Call =
2646 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2647 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2648 }
David Blaikied8180cf2013-01-05 20:03:07 +00002649 return;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002650 }
2651 }
David Blaikie436653b2013-01-05 05:58:35 +00002652
2653 // Create the descriptor for the variable.
2654 llvm::DIVariable D =
2655 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2656 Name, Unit, Line, Ty,
2657 CGM.getLangOpts().Optimize, Flags, ArgNo);
2658
2659 // Insert an llvm.dbg.declare into the current block.
2660 llvm::Instruction *Call =
2661 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2662 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002663}
2664
2665void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2666 llvm::Value *Storage,
2667 CGBuilderTy &Builder) {
2668 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2669 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2670}
2671
Adrian Prantle86fcc42013-03-29 19:20:29 +00002672/// Look up the completed type for a self pointer in the TypeCache and
2673/// create a copy of it with the ObjectPointer and Artificial flags
2674/// set. If the type is not cached, a new one is created. This should
2675/// never happen though, since creating a type for the implicit self
2676/// argument implies that we already parsed the interface definition
2677/// and the ivar declarations in the implementation.
2678llvm::DIType CGDebugInfo::CreateSelfType(const QualType &QualTy, llvm::DIType Ty) {
2679 llvm::DIType CachedTy = getTypeOrNull(QualTy);
2680 if (CachedTy.Verify()) Ty = CachedTy;
2681 else DEBUG(llvm::dbgs() << "No cached type for self.");
2682 return DBuilder.createObjectPointerType(Ty);
2683}
2684
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002685void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(const VarDecl *VD,
2686 llvm::Value *Storage,
2687 CGBuilderTy &Builder,
2688 const CGBlockInfo &blockInfo) {
2689 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2690 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2691
2692 if (Builder.GetInsertBlock() == 0)
2693 return;
2694
2695 bool isByRef = VD->hasAttr<BlocksAttr>();
2696
2697 uint64_t XOffset = 0;
2698 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2699 llvm::DIType Ty;
2700 if (isByRef)
2701 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
2702 else
2703 Ty = getOrCreateType(VD->getType(), Unit);
2704
2705 // Self is passed along as an implicit non-arg variable in a
2706 // block. Mark it as the object pointer.
2707 if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self")
Adrian Prantle86fcc42013-03-29 19:20:29 +00002708 Ty = CreateSelfType(VD->getType(), Ty);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002709
2710 // Get location information.
2711 unsigned Line = getLineNumber(VD->getLocation());
2712 unsigned Column = getColumnNumber(VD->getLocation());
2713
2714 const llvm::DataLayout &target = CGM.getDataLayout();
2715
2716 CharUnits offset = CharUnits::fromQuantity(
2717 target.getStructLayout(blockInfo.StructureType)
2718 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2719
2720 SmallVector<llvm::Value *, 9> addr;
2721 llvm::Type *Int64Ty = CGM.Int64Ty;
Adrian Prantl9b97adf2013-03-29 19:20:35 +00002722 if (isa<llvm::AllocaInst>(Storage))
2723 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002724 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2725 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2726 if (isByRef) {
2727 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2728 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2729 // offset of __forwarding field
2730 offset = CGM.getContext()
2731 .toCharUnitsFromBits(target.getPointerSizeInBits(0));
2732 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2733 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2734 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2735 // offset of x field
2736 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2737 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2738 }
2739
2740 // Create the descriptor for the variable.
2741 llvm::DIVariable D =
2742 DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable,
2743 llvm::DIDescriptor(LexicalBlockStack.back()),
2744 VD->getName(), Unit, Line, Ty, addr);
Adrian Prantl9b97adf2013-03-29 19:20:35 +00002745
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002746 // Insert an llvm.dbg.declare into the current block.
2747 llvm::Instruction *Call =
2748 DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
2749 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column,
2750 LexicalBlockStack.back()));
2751}
2752
2753/// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2754/// variable declaration.
2755void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2756 unsigned ArgNo,
2757 CGBuilderTy &Builder) {
2758 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2759 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2760}
2761
2762namespace {
2763 struct BlockLayoutChunk {
2764 uint64_t OffsetInBits;
2765 const BlockDecl::Capture *Capture;
2766 };
2767 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2768 return l.OffsetInBits < r.OffsetInBits;
2769 }
2770}
2771
2772void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
Adrian Prantl836e7c92013-03-14 17:53:33 +00002773 llvm::Value *Arg,
2774 llvm::Value *LocalAddr,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002775 CGBuilderTy &Builder) {
2776 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2777 ASTContext &C = CGM.getContext();
2778 const BlockDecl *blockDecl = block.getBlockDecl();
2779
2780 // Collect some general information about the block's location.
2781 SourceLocation loc = blockDecl->getCaretLocation();
2782 llvm::DIFile tunit = getOrCreateFile(loc);
2783 unsigned line = getLineNumber(loc);
2784 unsigned column = getColumnNumber(loc);
2785
2786 // Build the debug-info type for the block literal.
2787 getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
2788
2789 const llvm::StructLayout *blockLayout =
2790 CGM.getDataLayout().getStructLayout(block.StructureType);
2791
2792 SmallVector<llvm::Value*, 16> fields;
2793 fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
2794 blockLayout->getElementOffsetInBits(0),
2795 tunit, tunit));
2796 fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
2797 blockLayout->getElementOffsetInBits(1),
2798 tunit, tunit));
2799 fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
2800 blockLayout->getElementOffsetInBits(2),
2801 tunit, tunit));
2802 fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
2803 blockLayout->getElementOffsetInBits(3),
2804 tunit, tunit));
2805 fields.push_back(createFieldType("__descriptor",
2806 C.getPointerType(block.NeedsCopyDispose ?
2807 C.getBlockDescriptorExtendedType() :
2808 C.getBlockDescriptorType()),
2809 0, loc, AS_public,
2810 blockLayout->getElementOffsetInBits(4),
2811 tunit, tunit));
2812
2813 // We want to sort the captures by offset, not because DWARF
2814 // requires this, but because we're paranoid about debuggers.
2815 SmallVector<BlockLayoutChunk, 8> chunks;
2816
2817 // 'this' capture.
2818 if (blockDecl->capturesCXXThis()) {
2819 BlockLayoutChunk chunk;
2820 chunk.OffsetInBits =
2821 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
2822 chunk.Capture = 0;
2823 chunks.push_back(chunk);
2824 }
2825
2826 // Variable captures.
2827 for (BlockDecl::capture_const_iterator
2828 i = blockDecl->capture_begin(), e = blockDecl->capture_end();
2829 i != e; ++i) {
2830 const BlockDecl::Capture &capture = *i;
2831 const VarDecl *variable = capture.getVariable();
2832 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
2833
2834 // Ignore constant captures.
2835 if (captureInfo.isConstant())
2836 continue;
2837
2838 BlockLayoutChunk chunk;
2839 chunk.OffsetInBits =
2840 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
2841 chunk.Capture = &capture;
2842 chunks.push_back(chunk);
2843 }
2844
2845 // Sort by offset.
2846 llvm::array_pod_sort(chunks.begin(), chunks.end());
2847
2848 for (SmallVectorImpl<BlockLayoutChunk>::iterator
2849 i = chunks.begin(), e = chunks.end(); i != e; ++i) {
2850 uint64_t offsetInBits = i->OffsetInBits;
2851 const BlockDecl::Capture *capture = i->Capture;
2852
2853 // If we have a null capture, this must be the C++ 'this' capture.
2854 if (!capture) {
2855 const CXXMethodDecl *method =
2856 cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
2857 QualType type = method->getThisType(C);
2858
2859 fields.push_back(createFieldType("this", type, 0, loc, AS_public,
2860 offsetInBits, tunit, tunit));
2861 continue;
2862 }
2863
2864 const VarDecl *variable = capture->getVariable();
2865 StringRef name = variable->getName();
2866
2867 llvm::DIType fieldType;
2868 if (capture->isByRef()) {
2869 std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
2870
2871 // FIXME: this creates a second copy of this type!
2872 uint64_t xoffset;
2873 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
2874 fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
2875 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
2876 ptrInfo.first, ptrInfo.second,
2877 offsetInBits, 0, fieldType);
2878 } else {
2879 fieldType = createFieldType(name, variable->getType(), 0,
2880 loc, AS_public, offsetInBits, tunit, tunit);
2881 }
2882 fields.push_back(fieldType);
2883 }
2884
2885 SmallString<36> typeName;
2886 llvm::raw_svector_ostream(typeName)
2887 << "__block_literal_" << CGM.getUniqueBlockCount();
2888
2889 llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
2890
2891 llvm::DIType type =
2892 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
2893 CGM.getContext().toBits(block.BlockSize),
2894 CGM.getContext().toBits(block.BlockAlign),
David Blaikiec1d0af12013-02-25 01:07:08 +00002895 0, llvm::DIType(), fieldsArray);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002896 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
2897
2898 // Get overall information about the block.
2899 unsigned flags = llvm::DIDescriptor::FlagArtificial;
2900 llvm::MDNode *scope = LexicalBlockStack.back();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002901
2902 // Create the descriptor for the parameter.
2903 llvm::DIVariable debugVar =
2904 DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
2905 llvm::DIDescriptor(scope),
Adrian Prantl836e7c92013-03-14 17:53:33 +00002906 Arg->getName(), tunit, line, type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002907 CGM.getLangOpts().Optimize, flags,
Adrian Prantl836e7c92013-03-14 17:53:33 +00002908 cast<llvm::Argument>(Arg)->getArgNo() + 1);
2909
Adrian Prantlbea407c2013-03-14 21:52:59 +00002910 if (LocalAddr) {
Adrian Prantl836e7c92013-03-14 17:53:33 +00002911 // Insert an llvm.dbg.value into the current block.
Adrian Prantlbea407c2013-03-14 21:52:59 +00002912 llvm::Instruction *DbgVal =
2913 DBuilder.insertDbgValueIntrinsic(LocalAddr, 0, debugVar,
Eric Christopherf068c922013-04-02 22:59:11 +00002914 Builder.GetInsertBlock());
Adrian Prantlbea407c2013-03-14 21:52:59 +00002915 DbgVal->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
2916 }
Adrian Prantl836e7c92013-03-14 17:53:33 +00002917
Adrian Prantlbea407c2013-03-14 21:52:59 +00002918 // Insert an llvm.dbg.declare into the current block.
2919 llvm::Instruction *DbgDecl =
2920 DBuilder.insertDeclare(Arg, debugVar, Builder.GetInsertBlock());
2921 DbgDecl->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002922}
2923
Eric Christopher0395de32013-01-16 01:22:32 +00002924/// getStaticDataMemberDeclaration - If D is an out-of-class definition of
2925/// a static data member of a class, find its corresponding in-class
2926/// declaration.
2927llvm::DIDerivedType CGDebugInfo::getStaticDataMemberDeclaration(const Decl *D) {
2928 if (cast<VarDecl>(D)->isStaticDataMember()) {
2929 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
2930 MI = StaticDataMemberCache.find(D->getCanonicalDecl());
2931 if (MI != StaticDataMemberCache.end())
2932 // Verify the info still exists.
2933 if (llvm::Value *V = MI->second)
2934 return llvm::DIDerivedType(cast<llvm::MDNode>(V));
2935 }
2936 return llvm::DIDerivedType();
2937}
2938
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002939/// EmitGlobalVariable - Emit information about a global variable.
2940void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
2941 const VarDecl *D) {
2942 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2943 // Create global variable debug descriptor.
2944 llvm::DIFile Unit = getOrCreateFile(D->getLocation());
2945 unsigned LineNo = getLineNumber(D->getLocation());
2946
2947 setLocation(D->getLocation());
2948
2949 QualType T = D->getType();
2950 if (T->isIncompleteArrayType()) {
2951
2952 // CodeGen turns int[] into int[1] so we'll do the same here.
2953 llvm::APInt ConstVal(32, 1);
2954 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
2955
2956 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
2957 ArrayType::Normal, 0);
2958 }
2959 StringRef DeclName = D->getName();
2960 StringRef LinkageName;
2961 if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext())
2962 && !isa<ObjCMethodDecl>(D->getDeclContext()))
2963 LinkageName = Var->getName();
2964 if (LinkageName == DeclName)
2965 LinkageName = StringRef();
2966 llvm::DIDescriptor DContext =
2967 getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
David Blaikie3923d6a2013-05-08 06:01:46 +00002968 llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(DContext, DeclName, LinkageName,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002969 Unit, LineNo, getOrCreateType(T, Unit),
Eric Christopher0395de32013-01-16 01:22:32 +00002970 Var->hasInternalLinkage(), Var,
2971 getStaticDataMemberDeclaration(D));
David Blaikie3923d6a2013-05-08 06:01:46 +00002972 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(GV)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002973}
2974
2975/// EmitGlobalVariable - Emit information about an objective-c interface.
2976void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
2977 ObjCInterfaceDecl *ID) {
2978 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2979 // Create global variable debug descriptor.
2980 llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
2981 unsigned LineNo = getLineNumber(ID->getLocation());
2982
2983 StringRef Name = ID->getName();
2984
2985 QualType T = CGM.getContext().getObjCInterfaceType(ID);
2986 if (T->isIncompleteArrayType()) {
2987
2988 // CodeGen turns int[] into int[1] so we'll do the same here.
2989 llvm::APInt ConstVal(32, 1);
2990 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
2991
2992 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
2993 ArrayType::Normal, 0);
2994 }
2995
2996 DBuilder.createGlobalVariable(Name, Unit, LineNo,
2997 getOrCreateType(T, Unit),
2998 Var->hasInternalLinkage(), Var);
2999}
3000
3001/// EmitGlobalVariable - Emit global variable's debug info.
3002void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
3003 llvm::Constant *Init) {
3004 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
3005 // Create the descriptor for the variable.
3006 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
3007 StringRef Name = VD->getName();
3008 llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
3009 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
3010 const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext());
3011 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
3012 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
3013 }
3014 // Do not use DIGlobalVariable for enums.
3015 if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
3016 return;
David Blaikie3923d6a2013-05-08 06:01:46 +00003017 llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(Unit, Name, Name, Unit,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003018 getLineNumber(VD->getLocation()),
Eric Christopher0395de32013-01-16 01:22:32 +00003019 Ty, true, Init,
3020 getStaticDataMemberDeclaration(VD));
David Blaikie3923d6a2013-05-08 06:01:46 +00003021 DeclCache.insert(std::make_pair(VD->getCanonicalDecl(), llvm::WeakVH(GV)));
3022}
3023
3024llvm::DIScope CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
3025 if (!LexicalBlockStack.empty())
3026 return llvm::DIScope(LexicalBlockStack.back());
3027 return getContextDescriptor(D);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003028}
3029
David Blaikie957dac52013-04-22 06:13:21 +00003030void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
3031 DBuilder.createImportedModule(
David Blaikie3923d6a2013-05-08 06:01:46 +00003032 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
3033 getOrCreateNameSpace(UD.getNominatedNamespace()),
David Blaikie957dac52013-04-22 06:13:21 +00003034 getLineNumber(UD.getLocation()));
3035}
3036
David Blaikie3923d6a2013-05-08 06:01:46 +00003037void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
3038 assert(UD.shadow_size() &&
3039 "We shouldn't be codegening an invalid UsingDecl containing no decls");
3040 // Emitting one decl is sufficient - debuggers can detect that this is an
3041 // overloaded name & provide lookup for all the overloads.
3042 const UsingShadowDecl &USD = **UD.shadow_begin();
3043 if (llvm::DIDescriptor Target = getDeclarationOrDefinition(USD.getUnderlyingDecl()))
3044 DBuilder.createImportedDeclaration(
3045 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
3046 getLineNumber(USD.getLocation()));
3047}
3048
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003049/// getOrCreateNamesSpace - Return namespace descriptor for the given
3050/// namespace decl.
3051llvm::DINameSpace
3052CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
3053 llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
3054 NameSpaceCache.find(NSDecl);
3055 if (I != NameSpaceCache.end())
3056 return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
3057
3058 unsigned LineNo = getLineNumber(NSDecl->getLocation());
3059 llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
3060 llvm::DIDescriptor Context =
3061 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
3062 llvm::DINameSpace NS =
3063 DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
3064 NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
3065 return NS;
3066}
3067
3068void CGDebugInfo::finalize() {
3069 for (std::vector<std::pair<void *, llvm::WeakVH> >::const_iterator VI
3070 = ReplaceMap.begin(), VE = ReplaceMap.end(); VI != VE; ++VI) {
3071 llvm::DIType Ty, RepTy;
3072 // Verify that the debug info still exists.
3073 if (llvm::Value *V = VI->second)
3074 Ty = llvm::DIType(cast<llvm::MDNode>(V));
3075
3076 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
3077 TypeCache.find(VI->first);
3078 if (it != TypeCache.end()) {
3079 // Verify that the debug info still exists.
3080 if (llvm::Value *V = it->second)
3081 RepTy = llvm::DIType(cast<llvm::MDNode>(V));
3082 }
Adrian Prantlebbd7e02013-03-11 18:33:46 +00003083
Adrian Prantl9b97adf2013-03-29 19:20:35 +00003084 if (Ty.Verify() && Ty.isForwardDecl() && RepTy.Verify())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003085 Ty.replaceAllUsesWith(RepTy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003086 }
Adrian Prantlebbd7e02013-03-11 18:33:46 +00003087
3088 // We keep our own list of retained types, because we need to look
3089 // up the final type in the type cache.
3090 for (std::vector<void *>::const_iterator RI = RetainedTypes.begin(),
3091 RE = RetainedTypes.end(); RI != RE; ++RI)
3092 DBuilder.retainType(llvm::DIType(cast<llvm::MDNode>(TypeCache[*RI])));
3093
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003094 DBuilder.finalize();
3095}