blob: 2dd1741d832e43e3c227a405efd5e0c4b317f27f [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.
David Blaikief8aa1552013-05-13 06:57:50 +00001223 if (InstanceMember) {
David Blaikie9dfd2432013-05-10 21:53:14 +00001224 if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(D))
1225 V = CGM.getCXXABI().EmitMemberPointer(method);
David Blaikief8aa1552013-05-13 06:57:50 +00001226 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1227 V = CGM.GetAddrOfFunction(FD);
David Blaikie9dfd2432013-05-10 21:53:14 +00001228 // Member data pointers have special handling too to compute the fixed
1229 // offset within the object.
1230 if (isa<FieldDecl>(D)) {
1231 // These five lines (& possibly the above member function pointer
1232 // handling) might be able to be refactored to use similar code in
1233 // CodeGenModule::getMemberPointerConstant
1234 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
1235 CharUnits chars =
1236 CGM.getContext().toCharUnitsFromBits((int64_t) fieldOffset);
1237 V = CGM.getCXXABI().EmitMemberDataPointer(
1238 cast<MemberPointerType>(T.getTypePtr()), chars);
1239 }
1240 llvm::DITemplateValueParameter TVP =
1241 DBuilder.createTemplateValueParameter(TheCU, ND->getName(), TTy, V);
1242 TemplateParams.push_back(TVP);
1243 } break;
1244 case TemplateArgument::NullPtr: {
1245 QualType T = TA.getNullPtrType();
1246 llvm::DIType TTy = getOrCreateType(T, Unit);
1247 llvm::Value *V = 0;
1248 // Special case member data pointer null values since they're actually -1
1249 // instead of zero.
1250 if (const MemberPointerType *MPT =
1251 dyn_cast<MemberPointerType>(T.getTypePtr()))
1252 // But treat member function pointers as simple zero integers because
1253 // it's easier than having a special case in LLVM's CodeGen. If LLVM
1254 // CodeGen grows handling for values of non-null member function
1255 // pointers then perhaps we could remove this special case and rely on
1256 // EmitNullMemberPointer for member function pointers.
1257 if (MPT->isMemberDataPointer())
1258 V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1259 if (!V)
1260 V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
1261 llvm::DITemplateValueParameter TVP =
1262 DBuilder.createTemplateValueParameter(TheCU, ND->getName(), TTy, V);
1263 TemplateParams.push_back(TVP);
1264 } break;
1265 case TemplateArgument::Template:
1266 // We could support this with the GCC extension
1267 // DW_TAG_GNU_template_template_param
1268 break;
David Blaikie776a3642013-05-10 22:53:25 +00001269 case TemplateArgument::Pack:
1270 // And this with DW_TAG_GNU_template_parameter_pack
1271 break;
David Blaikiee8065122013-05-10 23:36:06 +00001272 // And the following should never occur:
David Blaikie9dfd2432013-05-10 21:53:14 +00001273 case TemplateArgument::Expression:
1274 case TemplateArgument::TemplateExpansion:
David Blaikie9dfd2432013-05-10 21:53:14 +00001275 case TemplateArgument::Null:
1276 llvm_unreachable(
1277 "These argument types shouldn't exist in concrete types");
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001278 }
1279 }
1280 return DBuilder.getOrCreateArray(TemplateParams);
1281}
1282
1283/// CollectFunctionTemplateParams - A helper function to collect debug
1284/// info for function template parameters.
1285llvm::DIArray CGDebugInfo::
1286CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) {
1287 if (FD->getTemplatedKind() ==
1288 FunctionDecl::TK_FunctionTemplateSpecialization) {
1289 const TemplateParameterList *TList =
1290 FD->getTemplateSpecializationInfo()->getTemplate()
1291 ->getTemplateParameters();
1292 return
1293 CollectTemplateParams(TList, *FD->getTemplateSpecializationArgs(), Unit);
1294 }
1295 return llvm::DIArray();
1296}
1297
1298/// CollectCXXTemplateParams - A helper function to collect debug info for
1299/// template parameters.
1300llvm::DIArray CGDebugInfo::
1301CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial,
1302 llvm::DIFile Unit) {
1303 llvm::PointerUnion<ClassTemplateDecl *,
1304 ClassTemplatePartialSpecializationDecl *>
1305 PU = TSpecial->getSpecializedTemplateOrPartial();
1306
1307 TemplateParameterList *TPList = PU.is<ClassTemplateDecl *>() ?
1308 PU.get<ClassTemplateDecl *>()->getTemplateParameters() :
1309 PU.get<ClassTemplatePartialSpecializationDecl *>()->getTemplateParameters();
1310 const TemplateArgumentList &TAList = TSpecial->getTemplateInstantiationArgs();
1311 return CollectTemplateParams(TPList, TAList, Unit);
1312}
1313
1314/// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
1315llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
1316 if (VTablePtrType.isValid())
1317 return VTablePtrType;
1318
1319 ASTContext &Context = CGM.getContext();
1320
1321 /* Function type */
1322 llvm::Value *STy = getOrCreateType(Context.IntTy, Unit);
1323 llvm::DIArray SElements = DBuilder.getOrCreateArray(STy);
1324 llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements);
1325 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1326 llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0,
1327 "__vtbl_ptr_type");
1328 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1329 return VTablePtrType;
1330}
1331
1332/// getVTableName - Get vtable name for the given Class.
1333StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
1334 // Construct gdb compatible name name.
1335 std::string Name = "_vptr$" + RD->getNameAsString();
1336
1337 // Copy this name on the side and use its reference.
1338 char *StrPtr = DebugInfoNames.Allocate<char>(Name.length());
1339 memcpy(StrPtr, Name.data(), Name.length());
1340 return StringRef(StrPtr, Name.length());
1341}
1342
1343
1344/// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
1345/// debug info entry in EltTys vector.
1346void CGDebugInfo::
1347CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
1348 SmallVectorImpl<llvm::Value *> &EltTys) {
1349 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1350
1351 // If there is a primary base then it will hold vtable info.
1352 if (RL.getPrimaryBase())
1353 return;
1354
1355 // If this class is not dynamic then there is not any vtable info to collect.
1356 if (!RD->isDynamicClass())
1357 return;
1358
1359 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1360 llvm::DIType VPTR
1361 = DBuilder.createMemberType(Unit, getVTableName(RD), Unit,
1362 0, Size, 0, 0, llvm::DIDescriptor::FlagArtificial,
1363 getOrCreateVTablePtrType(Unit));
1364 EltTys.push_back(VPTR);
1365}
1366
1367/// getOrCreateRecordType - Emit record type's standalone debug info.
1368llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy,
1369 SourceLocation Loc) {
1370 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
1371 llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc));
1372 return T;
1373}
1374
1375/// getOrCreateInterfaceType - Emit an objective c interface type standalone
1376/// debug info.
1377llvm::DIType CGDebugInfo::getOrCreateInterfaceType(QualType D,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001378 SourceLocation Loc) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001379 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
1380 llvm::DIType T = getOrCreateType(D, getOrCreateFile(Loc));
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001381 RetainedTypes.push_back(D.getAsOpaquePtr());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001382 return T;
1383}
1384
1385/// CreateType - get structure or union type.
1386llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty) {
1387 RecordDecl *RD = Ty->getDecl();
1388
1389 // Get overall information about the record type for the debug info.
1390 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1391
1392 // Records and classes and unions can all be recursive. To handle them, we
1393 // first generate a debug descriptor for the struct as a forward declaration.
1394 // Then (if it is a definition) we go through and get debug info for all of
1395 // its members. Finally, we create a descriptor for the complete type (which
1396 // may refer to the forward decl if the struct is recursive) and replace all
1397 // uses of the forward declaration with the final definition.
1398
Eric Christopherf068c922013-04-02 22:59:11 +00001399 llvm::DICompositeType FwdDecl(
1400 getOrCreateLimitedType(QualType(Ty, 0), DefUnit));
1401 assert(FwdDecl.Verify() &&
1402 "The debug type of a RecordType should be a DICompositeType");
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001403
1404 if (FwdDecl.isForwardDecl())
1405 return FwdDecl;
1406
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001407 // Push the struct on region stack.
Eric Christopherf068c922013-04-02 22:59:11 +00001408 LexicalBlockStack.push_back(&*FwdDecl);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001409 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1410
Adrian Prantl4919de62013-03-06 22:03:30 +00001411 // Add this to the completed-type cache while we're completing it recursively.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001412 CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1413
1414 // Convert all the elements.
1415 SmallVector<llvm::Value *, 16> EltTys;
1416
1417 // Note: The split of CXXDecl information here is intentional, the
1418 // gdb tests will depend on a certain ordering at printout. The debug
1419 // information offsets are still correct if we merge them all together
1420 // though.
1421 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1422 if (CXXDecl) {
1423 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1424 CollectVTableInfo(CXXDecl, DefUnit, EltTys);
1425 }
1426
Eric Christopher0395de32013-01-16 01:22:32 +00001427 // Collect data fields (including static variables and any initializers).
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001428 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
1429 llvm::DIArray TParamsArray;
1430 if (CXXDecl) {
1431 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
1432 CollectCXXFriends(CXXDecl, DefUnit, EltTys, FwdDecl);
1433 if (const ClassTemplateSpecializationDecl *TSpecial
1434 = dyn_cast<ClassTemplateSpecializationDecl>(RD))
1435 TParamsArray = CollectCXXTemplateParams(TSpecial, DefUnit);
1436 }
1437
1438 LexicalBlockStack.pop_back();
1439 RegionMap.erase(Ty->getDecl());
1440
1441 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopherf068c922013-04-02 22:59:11 +00001442 FwdDecl.setTypeArray(Elements, TParamsArray);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001443
Eric Christopherf068c922013-04-02 22:59:11 +00001444 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1445 return FwdDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001446}
1447
1448/// CreateType - get objective-c object type.
1449llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1450 llvm::DIFile Unit) {
1451 // Ignore protocols.
1452 return getOrCreateType(Ty->getBaseType(), Unit);
1453}
1454
1455/// CreateType - get objective-c interface type.
1456llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1457 llvm::DIFile Unit) {
1458 ObjCInterfaceDecl *ID = Ty->getDecl();
1459 if (!ID)
1460 return llvm::DIType();
1461
1462 // Get overall information about the record type for the debug info.
1463 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1464 unsigned Line = getLineNumber(ID->getLocation());
1465 unsigned RuntimeLang = TheCU.getLanguage();
1466
1467 // If this is just a forward declaration return a special forward-declaration
1468 // debug type since we won't be able to lay out the entire type.
1469 ObjCInterfaceDecl *Def = ID->getDefinition();
1470 if (!Def) {
1471 llvm::DIType FwdDecl =
1472 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001473 ID->getName(), TheCU, DefUnit, Line,
1474 RuntimeLang);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001475 return FwdDecl;
1476 }
1477
1478 ID = Def;
1479
1480 // Bit size, align and offset of the type.
1481 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1482 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1483
1484 unsigned Flags = 0;
1485 if (ID->getImplementation())
1486 Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
1487
Eric Christopherf068c922013-04-02 22:59:11 +00001488 llvm::DICompositeType RealDecl =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001489 DBuilder.createStructType(Unit, ID->getName(), DefUnit,
1490 Line, Size, Align, Flags,
David Blaikiec1d0af12013-02-25 01:07:08 +00001491 llvm::DIType(), llvm::DIArray(), RuntimeLang);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001492
1493 // Otherwise, insert it into the CompletedTypeCache so that recursive uses
1494 // will find it and we're emitting the complete type.
Adrian Prantl4919de62013-03-06 22:03:30 +00001495 QualType QualTy = QualType(Ty, 0);
1496 CompletedTypeCache[QualTy.getAsOpaquePtr()] = RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001497 // Push the struct on region stack.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001498
Eric Christopherf068c922013-04-02 22:59:11 +00001499 LexicalBlockStack.push_back(static_cast<llvm::MDNode*>(RealDecl));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001500 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1501
1502 // Convert all the elements.
1503 SmallVector<llvm::Value *, 16> EltTys;
1504
1505 ObjCInterfaceDecl *SClass = ID->getSuperClass();
1506 if (SClass) {
1507 llvm::DIType SClassTy =
1508 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1509 if (!SClassTy.isValid())
1510 return llvm::DIType();
1511
1512 llvm::DIType InhTag =
1513 DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
1514 EltTys.push_back(InhTag);
1515 }
1516
1517 for (ObjCContainerDecl::prop_iterator I = ID->prop_begin(),
1518 E = ID->prop_end(); I != E; ++I) {
1519 const ObjCPropertyDecl *PD = *I;
1520 SourceLocation Loc = PD->getLocation();
1521 llvm::DIFile PUnit = getOrCreateFile(Loc);
1522 unsigned PLine = getLineNumber(Loc);
1523 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1524 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1525 llvm::MDNode *PropertyNode =
1526 DBuilder.createObjCProperty(PD->getName(),
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001527 PUnit, PLine,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001528 (Getter && Getter->isImplicit()) ? "" :
1529 getSelectorName(PD->getGetterName()),
1530 (Setter && Setter->isImplicit()) ? "" :
1531 getSelectorName(PD->getSetterName()),
1532 PD->getPropertyAttributes(),
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001533 getOrCreateType(PD->getType(), PUnit));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001534 EltTys.push_back(PropertyNode);
1535 }
1536
1537 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1538 unsigned FieldNo = 0;
1539 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1540 Field = Field->getNextIvar(), ++FieldNo) {
1541 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1542 if (!FieldTy.isValid())
1543 return llvm::DIType();
1544
1545 StringRef FieldName = Field->getName();
1546
1547 // Ignore unnamed fields.
1548 if (FieldName.empty())
1549 continue;
1550
1551 // Get the location for the field.
1552 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1553 unsigned FieldLine = getLineNumber(Field->getLocation());
1554 QualType FType = Field->getType();
1555 uint64_t FieldSize = 0;
1556 unsigned FieldAlign = 0;
1557
1558 if (!FType->isIncompleteArrayType()) {
1559
1560 // Bit size, align and offset of the type.
1561 FieldSize = Field->isBitField()
1562 ? Field->getBitWidthValue(CGM.getContext())
1563 : CGM.getContext().getTypeSize(FType);
1564 FieldAlign = CGM.getContext().getTypeAlign(FType);
1565 }
1566
1567 uint64_t FieldOffset;
1568 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1569 // We don't know the runtime offset of an ivar if we're using the
1570 // non-fragile ABI. For bitfields, use the bit offset into the first
1571 // byte of storage of the bitfield. For other fields, use zero.
1572 if (Field->isBitField()) {
1573 FieldOffset = CGM.getObjCRuntime().ComputeBitfieldBitOffset(
1574 CGM, ID, Field);
1575 FieldOffset %= CGM.getContext().getCharWidth();
1576 } else {
1577 FieldOffset = 0;
1578 }
1579 } else {
1580 FieldOffset = RL.getFieldOffset(FieldNo);
1581 }
1582
1583 unsigned Flags = 0;
1584 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1585 Flags = llvm::DIDescriptor::FlagProtected;
1586 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1587 Flags = llvm::DIDescriptor::FlagPrivate;
1588
1589 llvm::MDNode *PropertyNode = NULL;
1590 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
1591 if (ObjCPropertyImplDecl *PImpD =
1592 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
1593 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001594 SourceLocation Loc = PD->getLocation();
1595 llvm::DIFile PUnit = getOrCreateFile(Loc);
1596 unsigned PLine = getLineNumber(Loc);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001597 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1598 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1599 PropertyNode =
1600 DBuilder.createObjCProperty(PD->getName(),
1601 PUnit, PLine,
1602 (Getter && Getter->isImplicit()) ? "" :
1603 getSelectorName(PD->getGetterName()),
1604 (Setter && Setter->isImplicit()) ? "" :
1605 getSelectorName(PD->getSetterName()),
1606 PD->getPropertyAttributes(),
1607 getOrCreateType(PD->getType(), PUnit));
1608 }
1609 }
1610 }
1611 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
1612 FieldLine, FieldSize, FieldAlign,
1613 FieldOffset, Flags, FieldTy,
1614 PropertyNode);
1615 EltTys.push_back(FieldTy);
1616 }
1617
1618 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopherf068c922013-04-02 22:59:11 +00001619 RealDecl.setTypeArray(Elements);
Adrian Prantl4919de62013-03-06 22:03:30 +00001620
1621 // If the implementation is not yet set, we do not want to mark it
1622 // as complete. An implementation may declare additional
1623 // private ivars that we would miss otherwise.
1624 if (ID->getImplementation() == 0)
1625 CompletedTypeCache.erase(QualTy.getAsOpaquePtr());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001626
1627 LexicalBlockStack.pop_back();
Eric Christopherf068c922013-04-02 22:59:11 +00001628 return RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001629}
1630
1631llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) {
1632 llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1633 int64_t Count = Ty->getNumElements();
1634 if (Count == 0)
1635 // If number of elements are not known then this is an unbounded array.
1636 // Use Count == -1 to express such arrays.
1637 Count = -1;
1638
1639 llvm::Value *Subscript = DBuilder.getOrCreateSubrange(0, Count);
1640 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1641
1642 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1643 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1644
1645 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1646}
1647
1648llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1649 llvm::DIFile Unit) {
1650 uint64_t Size;
1651 uint64_t Align;
1652
1653 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1654 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1655 Size = 0;
1656 Align =
1657 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1658 } else if (Ty->isIncompleteArrayType()) {
1659 Size = 0;
1660 if (Ty->getElementType()->isIncompleteType())
1661 Align = 0;
1662 else
1663 Align = CGM.getContext().getTypeAlign(Ty->getElementType());
David Blaikie089db2e2013-05-09 20:48:12 +00001664 } else if (Ty->isIncompleteType()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001665 Size = 0;
1666 Align = 0;
1667 } else {
1668 // Size and align of the whole array, not the element type.
1669 Size = CGM.getContext().getTypeSize(Ty);
1670 Align = CGM.getContext().getTypeAlign(Ty);
1671 }
1672
1673 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
1674 // interior arrays, do we care? Why aren't nested arrays represented the
1675 // obvious/recursive way?
1676 SmallVector<llvm::Value *, 8> Subscripts;
1677 QualType EltTy(Ty, 0);
1678 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1679 // If the number of elements is known, then count is that number. Otherwise,
1680 // it's -1. This allows us to represent a subrange with an array of 0
1681 // elements, like this:
1682 //
1683 // struct foo {
1684 // int x[0];
1685 // };
1686 int64_t Count = -1; // Count == -1 is an unbounded array.
1687 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1688 Count = CAT->getSize().getZExtValue();
1689
1690 // FIXME: Verify this is right for VLAs.
1691 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
1692 EltTy = Ty->getElementType();
1693 }
1694
1695 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1696
1697 llvm::DIType DbgTy =
1698 DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1699 SubscriptArray);
1700 return DbgTy;
1701}
1702
1703llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
1704 llvm::DIFile Unit) {
1705 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
1706 Ty, Ty->getPointeeType(), Unit);
1707}
1708
1709llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
1710 llvm::DIFile Unit) {
1711 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
1712 Ty, Ty->getPointeeType(), Unit);
1713}
1714
1715llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
1716 llvm::DIFile U) {
David Blaikiee8d75142013-01-19 19:20:56 +00001717 llvm::DIType ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
1718 if (!Ty->getPointeeType()->isFunctionType())
1719 return DBuilder.createMemberPointerType(
1720 CreatePointeeType(Ty->getPointeeType(), U), ClassType);
1721 return DBuilder.createMemberPointerType(getOrCreateInstanceMethodType(
1722 CGM.getContext().getPointerType(
1723 QualType(Ty->getClass(), Ty->getPointeeType().getCVRQualifiers())),
1724 Ty->getPointeeType()->getAs<FunctionProtoType>(), U),
1725 ClassType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001726}
1727
1728llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty,
1729 llvm::DIFile U) {
1730 // Ignore the atomic wrapping
1731 // FIXME: What is the correct representation?
1732 return getOrCreateType(Ty->getValueType(), U);
1733}
1734
1735/// CreateEnumType - get enumeration type.
1736llvm::DIType CGDebugInfo::CreateEnumType(const EnumDecl *ED) {
1737 uint64_t Size = 0;
1738 uint64_t Align = 0;
1739 if (!ED->getTypeForDecl()->isIncompleteType()) {
1740 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1741 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1742 }
1743
1744 // If this is just a forward declaration, construct an appropriately
1745 // marked node and just return it.
1746 if (!ED->getDefinition()) {
1747 llvm::DIDescriptor EDContext;
1748 EDContext = getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1749 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1750 unsigned Line = getLineNumber(ED->getLocation());
1751 StringRef EDName = ED->getName();
1752 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_enumeration_type,
1753 EDName, EDContext, DefUnit, Line, 0,
1754 Size, Align);
1755 }
1756
1757 // Create DIEnumerator elements for each enumerator.
1758 SmallVector<llvm::Value *, 16> Enumerators;
1759 ED = ED->getDefinition();
1760 for (EnumDecl::enumerator_iterator
1761 Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
1762 Enum != EnumEnd; ++Enum) {
1763 Enumerators.push_back(
1764 DBuilder.createEnumerator(Enum->getName(),
1765 Enum->getInitVal().getZExtValue()));
1766 }
1767
1768 // Return a CompositeType for the enum itself.
1769 llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1770
1771 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1772 unsigned Line = getLineNumber(ED->getLocation());
1773 llvm::DIDescriptor EnumContext =
1774 getContextDescriptor(cast<Decl>(ED->getDeclContext()));
Adrian Prantl59d6a712013-04-19 19:56:39 +00001775 llvm::DIType ClassTy = ED->isFixed() ?
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001776 getOrCreateType(ED->getIntegerType(), DefUnit) : llvm::DIType();
1777 llvm::DIType DbgTy =
1778 DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1779 Size, Align, EltArray,
1780 ClassTy);
1781 return DbgTy;
1782}
1783
David Blaikie4b12be62013-01-21 04:37:12 +00001784static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
1785 Qualifiers Quals;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001786 do {
David Blaikie4b12be62013-01-21 04:37:12 +00001787 Quals += T.getLocalQualifiers();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001788 QualType LastT = T;
1789 switch (T->getTypeClass()) {
1790 default:
David Blaikie4b12be62013-01-21 04:37:12 +00001791 return C.getQualifiedType(T.getTypePtr(), Quals);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001792 case Type::TemplateSpecialization:
1793 T = cast<TemplateSpecializationType>(T)->desugar();
1794 break;
1795 case Type::TypeOfExpr:
1796 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1797 break;
1798 case Type::TypeOf:
1799 T = cast<TypeOfType>(T)->getUnderlyingType();
1800 break;
1801 case Type::Decltype:
1802 T = cast<DecltypeType>(T)->getUnderlyingType();
1803 break;
1804 case Type::UnaryTransform:
1805 T = cast<UnaryTransformType>(T)->getUnderlyingType();
1806 break;
1807 case Type::Attributed:
1808 T = cast<AttributedType>(T)->getEquivalentType();
1809 break;
1810 case Type::Elaborated:
1811 T = cast<ElaboratedType>(T)->getNamedType();
1812 break;
1813 case Type::Paren:
1814 T = cast<ParenType>(T)->getInnerType();
1815 break;
David Blaikie4b12be62013-01-21 04:37:12 +00001816 case Type::SubstTemplateTypeParm:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001817 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001818 break;
1819 case Type::Auto:
1820 T = cast<AutoType>(T)->getDeducedType();
1821 break;
1822 }
1823
1824 assert(T != LastT && "Type unwrapping failed to unwrap!");
NAKAMURA Takumid24c9ab2013-01-21 10:51:28 +00001825 (void)LastT;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001826 } while (true);
1827}
1828
1829/// getType - Get the type from the cache or return null type if it doesn't exist.
1830llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) {
1831
1832 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00001833 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001834
1835 // Check for existing entry.
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001836 if (Ty->getTypeClass() == Type::ObjCInterface) {
1837 llvm::Value *V = getCachedInterfaceTypeOrNull(Ty);
1838 if (V)
1839 return llvm::DIType(cast<llvm::MDNode>(V));
1840 else return llvm::DIType();
1841 }
1842
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001843 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1844 TypeCache.find(Ty.getAsOpaquePtr());
1845 if (it != TypeCache.end()) {
1846 // Verify that the debug info still exists.
1847 if (llvm::Value *V = it->second)
1848 return llvm::DIType(cast<llvm::MDNode>(V));
1849 }
1850
1851 return llvm::DIType();
1852}
1853
1854/// getCompletedTypeOrNull - Get the type from the cache or return null if it
1855/// doesn't exist.
1856llvm::DIType CGDebugInfo::getCompletedTypeOrNull(QualType Ty) {
1857
1858 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00001859 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001860
1861 // Check for existing entry.
Adrian Prantl4919de62013-03-06 22:03:30 +00001862 llvm::Value *V = 0;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001863 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1864 CompletedTypeCache.find(Ty.getAsOpaquePtr());
Adrian Prantl4919de62013-03-06 22:03:30 +00001865 if (it != CompletedTypeCache.end())
1866 V = it->second;
1867 else {
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001868 V = getCachedInterfaceTypeOrNull(Ty);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001869 }
1870
Adrian Prantl4919de62013-03-06 22:03:30 +00001871 // Verify that any cached debug info still exists.
1872 if (V != 0)
1873 return llvm::DIType(cast<llvm::MDNode>(V));
1874
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001875 return llvm::DIType();
1876}
1877
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001878/// getCachedInterfaceTypeOrNull - Get the type from the interface
1879/// cache, unless it needs to regenerated. Otherwise return null.
1880llvm::Value *CGDebugInfo::getCachedInterfaceTypeOrNull(QualType Ty) {
1881 // Is there a cached interface that hasn't changed?
1882 llvm::DenseMap<void *, std::pair<llvm::WeakVH, unsigned > >
1883 ::iterator it1 = ObjCInterfaceCache.find(Ty.getAsOpaquePtr());
1884
1885 if (it1 != ObjCInterfaceCache.end())
1886 if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty))
1887 if (Checksum(Decl) == it1->second.second)
1888 // Return cached forward declaration.
1889 return it1->second.first;
1890
1891 return 0;
1892}
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001893
1894/// getOrCreateType - Get the type from the cache or create a new
1895/// one if necessary.
1896llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit) {
1897 if (Ty.isNull())
1898 return llvm::DIType();
1899
1900 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00001901 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001902
1903 llvm::DIType T = getCompletedTypeOrNull(Ty);
1904
1905 if (T.Verify())
1906 return T;
1907
1908 // Otherwise create the type.
1909 llvm::DIType Res = CreateTypeNode(Ty, Unit);
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001910 void* TyPtr = Ty.getAsOpaquePtr();
1911
1912 // And update the type cache.
1913 TypeCache[TyPtr] = Res;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001914
1915 llvm::DIType TC = getTypeOrNull(Ty);
1916 if (TC.Verify() && TC.isForwardDecl())
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001917 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
1918 else if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty)) {
1919 // Interface types may have elements added to them by a
1920 // subsequent implementation or extension, so we keep them in
1921 // the ObjCInterfaceCache together with a checksum. Instead of
Adrian Prantlf06989b2013-05-08 23:37:22 +00001922 // the (possibly) incomplete interface type, we return a forward
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001923 // declaration that gets RAUW'd in CGDebugInfo::finalize().
1924 llvm::DenseMap<void *, std::pair<llvm::WeakVH, unsigned > >
1925 ::iterator it = ObjCInterfaceCache.find(TyPtr);
1926 if (it != ObjCInterfaceCache.end())
1927 TC = llvm::DIType(cast<llvm::MDNode>(it->second.first));
1928 else
1929 TC = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
Adrian Prantl00df5ea2013-03-12 20:43:25 +00001930 Decl->getName(), TheCU, Unit,
1931 getLineNumber(Decl->getLocation()),
1932 TheCU.getLanguage());
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001933 // Store the forward declaration in the cache.
1934 ObjCInterfaceCache[TyPtr] = std::make_pair(TC, Checksum(Decl));
1935
1936 // Register the type for replacement in finalize().
1937 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
1938 return TC;
Adrian Prantl4919de62013-03-06 22:03:30 +00001939 }
1940
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001941 if (!Res.isForwardDecl())
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001942 CompletedTypeCache[TyPtr] = Res;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001943
1944 return Res;
1945}
1946
Adrian Prantl4919de62013-03-06 22:03:30 +00001947/// Currently the checksum merely consists of the number of ivars.
1948unsigned CGDebugInfo::Checksum(const ObjCInterfaceDecl
Adrian Prantl00df5ea2013-03-12 20:43:25 +00001949 *InterfaceDecl) {
Adrian Prantl4919de62013-03-06 22:03:30 +00001950 unsigned IvarNo = 0;
1951 for (const ObjCIvarDecl *Ivar = InterfaceDecl->all_declared_ivar_begin();
1952 Ivar != 0; Ivar = Ivar->getNextIvar()) ++IvarNo;
1953 return IvarNo;
1954}
1955
1956ObjCInterfaceDecl *CGDebugInfo::getObjCInterfaceDecl(QualType Ty) {
1957 switch (Ty->getTypeClass()) {
1958 case Type::ObjCObjectPointer:
1959 return getObjCInterfaceDecl(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
1960 case Type::ObjCInterface:
1961 return cast<ObjCInterfaceType>(Ty)->getDecl();
1962 default:
1963 return 0;
1964 }
1965}
1966
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001967/// CreateTypeNode - Create a new debug type node.
1968llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit) {
1969 // Handle qualifiers, which recursively handles what they refer to.
1970 if (Ty.hasLocalQualifiers())
1971 return CreateQualifiedType(Ty, Unit);
1972
1973 const char *Diag = 0;
1974
1975 // Work out details of type.
1976 switch (Ty->getTypeClass()) {
1977#define TYPE(Class, Base)
1978#define ABSTRACT_TYPE(Class, Base)
1979#define NON_CANONICAL_TYPE(Class, Base)
1980#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1981#include "clang/AST/TypeNodes.def"
1982 llvm_unreachable("Dependent types cannot show up in debug information");
1983
1984 case Type::ExtVector:
1985 case Type::Vector:
1986 return CreateType(cast<VectorType>(Ty), Unit);
1987 case Type::ObjCObjectPointer:
1988 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
1989 case Type::ObjCObject:
1990 return CreateType(cast<ObjCObjectType>(Ty), Unit);
1991 case Type::ObjCInterface:
1992 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
1993 case Type::Builtin:
1994 return CreateType(cast<BuiltinType>(Ty));
1995 case Type::Complex:
1996 return CreateType(cast<ComplexType>(Ty));
1997 case Type::Pointer:
1998 return CreateType(cast<PointerType>(Ty), Unit);
1999 case Type::BlockPointer:
2000 return CreateType(cast<BlockPointerType>(Ty), Unit);
2001 case Type::Typedef:
2002 return CreateType(cast<TypedefType>(Ty), Unit);
2003 case Type::Record:
2004 return CreateType(cast<RecordType>(Ty));
2005 case Type::Enum:
2006 return CreateEnumType(cast<EnumType>(Ty)->getDecl());
2007 case Type::FunctionProto:
2008 case Type::FunctionNoProto:
2009 return CreateType(cast<FunctionType>(Ty), Unit);
2010 case Type::ConstantArray:
2011 case Type::VariableArray:
2012 case Type::IncompleteArray:
2013 return CreateType(cast<ArrayType>(Ty), Unit);
2014
2015 case Type::LValueReference:
2016 return CreateType(cast<LValueReferenceType>(Ty), Unit);
2017 case Type::RValueReference:
2018 return CreateType(cast<RValueReferenceType>(Ty), Unit);
2019
2020 case Type::MemberPointer:
2021 return CreateType(cast<MemberPointerType>(Ty), Unit);
2022
2023 case Type::Atomic:
2024 return CreateType(cast<AtomicType>(Ty), Unit);
2025
2026 case Type::Attributed:
2027 case Type::TemplateSpecialization:
2028 case Type::Elaborated:
2029 case Type::Paren:
2030 case Type::SubstTemplateTypeParm:
2031 case Type::TypeOfExpr:
2032 case Type::TypeOf:
2033 case Type::Decltype:
2034 case Type::UnaryTransform:
2035 case Type::Auto:
2036 llvm_unreachable("type should have been unwrapped!");
2037 }
2038
2039 assert(Diag && "Fall through without a diagnostic?");
2040 unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error,
2041 "debug information for %0 is not yet supported");
2042 CGM.getDiags().Report(DiagID)
2043 << Diag;
2044 return llvm::DIType();
2045}
2046
2047/// getOrCreateLimitedType - Get the type from the cache or create a new
2048/// limited type if necessary.
2049llvm::DIType CGDebugInfo::getOrCreateLimitedType(QualType Ty,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002050 llvm::DIFile Unit) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002051 if (Ty.isNull())
2052 return llvm::DIType();
2053
2054 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00002055 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002056
2057 llvm::DIType T = getTypeOrNull(Ty);
2058
2059 // We may have cached a forward decl when we could have created
2060 // a non-forward decl. Go ahead and create a non-forward decl
2061 // now.
2062 if (T.Verify() && !T.isForwardDecl()) return T;
2063
2064 // Otherwise create the type.
2065 llvm::DIType Res = CreateLimitedTypeNode(Ty, Unit);
2066
2067 if (T.Verify() && T.isForwardDecl())
2068 ReplaceMap.push_back(std::make_pair(Ty.getAsOpaquePtr(),
2069 static_cast<llvm::Value*>(T)));
2070
2071 // And update the type cache.
2072 TypeCache[Ty.getAsOpaquePtr()] = Res;
2073 return Res;
2074}
2075
2076// TODO: Currently used for context chains when limiting debug info.
2077llvm::DIType CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
2078 RecordDecl *RD = Ty->getDecl();
2079
2080 // Get overall information about the record type for the debug info.
2081 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
2082 unsigned Line = getLineNumber(RD->getLocation());
2083 StringRef RDName = getClassName(RD);
2084
2085 llvm::DIDescriptor RDContext;
2086 if (CGM.getCodeGenOpts().getDebugInfo() == CodeGenOptions::LimitedDebugInfo)
2087 RDContext = createContextChain(cast<Decl>(RD->getDeclContext()));
2088 else
2089 RDContext = getContextDescriptor(cast<Decl>(RD->getDeclContext()));
2090
2091 // If this is just a forward declaration, construct an appropriately
2092 // marked node and just return it.
2093 if (!RD->getDefinition())
2094 return createRecordFwdDecl(RD, RDContext);
2095
2096 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2097 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
2098 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
David Blaikie2fcadbe2013-03-26 23:47:35 +00002099 llvm::DICompositeType RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002100
2101 if (RD->isUnion())
2102 RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002103 Size, Align, 0, llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002104 else if (RD->isClass()) {
2105 // FIXME: This could be a struct type giving a default visibility different
2106 // than C++ class type, but needs llvm metadata changes first.
2107 RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002108 Size, Align, 0, 0, llvm::DIType(),
2109 llvm::DIArray(), llvm::DIType(),
2110 llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002111 } else
2112 RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line,
Adrian Prantl00df5ea2013-03-12 20:43:25 +00002113 Size, Align, 0, llvm::DIType(), llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002114
2115 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
David Blaikie2fcadbe2013-03-26 23:47:35 +00002116 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002117
2118 if (CXXDecl) {
2119 // A class's primary base or the class itself contains the vtable.
David Blaikie2fcadbe2013-03-26 23:47:35 +00002120 llvm::DICompositeType ContainingType;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002121 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2122 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
2123 // Seek non virtual primary base root.
2124 while (1) {
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002125 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
2126 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
2127 if (PBT && !BRL.isPrimaryBaseVirtual())
2128 PBase = PBT;
2129 else
2130 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002131 }
David Blaikie2fcadbe2013-03-26 23:47:35 +00002132 ContainingType = llvm::DICompositeType(
2133 getOrCreateType(QualType(PBase->getTypeForDecl(), 0), DefUnit));
2134 } else if (CXXDecl->isDynamicClass())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002135 ContainingType = RealDecl;
2136
David Blaikie2fcadbe2013-03-26 23:47:35 +00002137 RealDecl.setContainingType(ContainingType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002138 }
2139 return llvm::DIType(RealDecl);
2140}
2141
2142/// CreateLimitedTypeNode - Create a new debug type node, but only forward
2143/// declare composite types that haven't been processed yet.
2144llvm::DIType CGDebugInfo::CreateLimitedTypeNode(QualType Ty,llvm::DIFile Unit) {
2145
2146 // Work out details of type.
2147 switch (Ty->getTypeClass()) {
2148#define TYPE(Class, Base)
2149#define ABSTRACT_TYPE(Class, Base)
2150#define NON_CANONICAL_TYPE(Class, Base)
2151#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2152 #include "clang/AST/TypeNodes.def"
2153 llvm_unreachable("Dependent types cannot show up in debug information");
2154
2155 case Type::Record:
2156 return CreateLimitedType(cast<RecordType>(Ty));
2157 default:
2158 return CreateTypeNode(Ty, Unit);
2159 }
2160}
2161
2162/// CreateMemberType - Create new member and increase Offset by FType's size.
2163llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
2164 StringRef Name,
2165 uint64_t *Offset) {
2166 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2167 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
2168 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
2169 llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0,
2170 FieldSize, FieldAlign,
2171 *Offset, 0, FieldTy);
2172 *Offset += FieldSize;
2173 return Ty;
2174}
2175
2176/// getFunctionDeclaration - Return debug info descriptor to describe method
2177/// declaration for the given method definition.
2178llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
2179 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
2180 if (!FD) return llvm::DISubprogram();
2181
2182 // Setup context.
2183 getContextDescriptor(cast<Decl>(D->getDeclContext()));
2184
2185 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2186 MI = SPCache.find(FD->getCanonicalDecl());
2187 if (MI != SPCache.end()) {
2188 llvm::Value *V = MI->second;
2189 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
2190 if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
2191 return SP;
2192 }
2193
2194 for (FunctionDecl::redecl_iterator I = FD->redecls_begin(),
2195 E = FD->redecls_end(); I != E; ++I) {
2196 const FunctionDecl *NextFD = *I;
2197 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2198 MI = SPCache.find(NextFD->getCanonicalDecl());
2199 if (MI != SPCache.end()) {
2200 llvm::Value *V = MI->second;
2201 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
2202 if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
2203 return SP;
2204 }
2205 }
2206 return llvm::DISubprogram();
2207}
2208
2209// getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
2210// implicit parameter "this".
2211llvm::DIType CGDebugInfo::getOrCreateFunctionType(const Decl *D,
2212 QualType FnType,
2213 llvm::DIFile F) {
2214
2215 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
2216 return getOrCreateMethodType(Method, F);
2217 if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
2218 // Add "self" and "_cmd"
2219 SmallVector<llvm::Value *, 16> Elts;
2220
2221 // First element is always return type. For 'void' functions it is NULL.
Adrian Prantl566a9c32013-05-10 21:08:31 +00002222 QualType ResultTy = OMethod->hasRelatedResultType()
2223 ? QualType(OMethod->getClassInterface()->getTypeForDecl(), 0)
2224 : OMethod->getResultType();
2225 Elts.push_back(getOrCreateType(ResultTy, F));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002226 // "self" pointer is always first argument.
Adrian Prantle86fcc42013-03-29 19:20:29 +00002227 QualType SelfDeclTy = OMethod->getSelfDecl()->getType();
2228 llvm::DIType SelfTy = getOrCreateType(SelfDeclTy, F);
2229 Elts.push_back(CreateSelfType(SelfDeclTy, SelfTy));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002230 // "_cmd" pointer is always second argument.
2231 llvm::DIType CmdTy = getOrCreateType(OMethod->getCmdDecl()->getType(), F);
2232 Elts.push_back(DBuilder.createArtificialType(CmdTy));
2233 // Get rest of the arguments.
2234 for (ObjCMethodDecl::param_const_iterator PI = OMethod->param_begin(),
2235 PE = OMethod->param_end(); PI != PE; ++PI)
2236 Elts.push_back(getOrCreateType((*PI)->getType(), F));
2237
2238 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2239 return DBuilder.createSubroutineType(F, EltTypeArray);
2240 }
2241 return getOrCreateType(FnType, F);
2242}
2243
2244/// EmitFunctionStart - Constructs the debug code for entering a function.
2245void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
2246 llvm::Function *Fn,
2247 CGBuilderTy &Builder) {
2248
2249 StringRef Name;
2250 StringRef LinkageName;
2251
2252 FnBeginRegionCount.push_back(LexicalBlockStack.size());
2253
2254 const Decl *D = GD.getDecl();
2255 // Function may lack declaration in source code if it is created by Clang
2256 // CodeGen (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
2257 bool HasDecl = (D != 0);
2258 // Use the location of the declaration.
2259 SourceLocation Loc;
2260 if (HasDecl)
2261 Loc = D->getLocation();
2262
2263 unsigned Flags = 0;
2264 llvm::DIFile Unit = getOrCreateFile(Loc);
2265 llvm::DIDescriptor FDContext(Unit);
2266 llvm::DIArray TParamsArray;
2267 if (!HasDecl) {
2268 // Use llvm function name.
2269 Name = Fn->getName();
2270 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2271 // If there is a DISubprogram for this function available then use it.
2272 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2273 FI = SPCache.find(FD->getCanonicalDecl());
2274 if (FI != SPCache.end()) {
2275 llvm::Value *V = FI->second;
2276 llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(V));
2277 if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
2278 llvm::MDNode *SPN = SP;
2279 LexicalBlockStack.push_back(SPN);
2280 RegionMap[D] = llvm::WeakVH(SP);
2281 return;
2282 }
2283 }
2284 Name = getFunctionName(FD);
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002285 // Use mangled name as linkage name for C/C++ functions.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002286 if (FD->hasPrototype()) {
2287 LinkageName = CGM.getMangledName(GD);
2288 Flags |= llvm::DIDescriptor::FlagPrototyped;
2289 }
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002290 // No need to replicate the linkage name if it isn't different from the
2291 // subprogram name, no need to have it at all unless coverage is enabled or
2292 // debug is set to more than just line tables.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002293 if (LinkageName == Name ||
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002294 (!CGM.getCodeGenOpts().EmitGcovArcs &&
2295 !CGM.getCodeGenOpts().EmitGcovNotes &&
2296 CGM.getCodeGenOpts().getDebugInfo() <= CodeGenOptions::DebugLineTablesOnly))
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002297 LinkageName = StringRef();
2298
2299 if (CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
2300 if (const NamespaceDecl *NSDecl =
2301 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
2302 FDContext = getOrCreateNameSpace(NSDecl);
2303 else if (const RecordDecl *RDecl =
2304 dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
2305 FDContext = getContextDescriptor(cast<Decl>(RDecl->getDeclContext()));
2306
2307 // Collect template parameters.
2308 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
2309 }
2310 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
2311 Name = getObjCMethodName(OMD);
2312 Flags |= llvm::DIDescriptor::FlagPrototyped;
2313 } else {
2314 // Use llvm function name.
2315 Name = Fn->getName();
2316 Flags |= llvm::DIDescriptor::FlagPrototyped;
2317 }
2318 if (!Name.empty() && Name[0] == '\01')
2319 Name = Name.substr(1);
2320
2321 unsigned LineNo = getLineNumber(Loc);
2322 if (!HasDecl || D->isImplicit())
2323 Flags |= llvm::DIDescriptor::FlagArtificial;
2324
2325 llvm::DIType DIFnType;
2326 llvm::DISubprogram SPDecl;
2327 if (HasDecl &&
2328 CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
2329 DIFnType = getOrCreateFunctionType(D, FnType, Unit);
2330 SPDecl = getFunctionDeclaration(D);
2331 } else {
2332 // Create fake but valid subroutine type. Otherwise
2333 // llvm::DISubprogram::Verify() would return false, and
2334 // subprogram DIE will miss DW_AT_decl_file and
2335 // DW_AT_decl_line fields.
2336 SmallVector<llvm::Value*, 16> Elts;
2337 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2338 DIFnType = DBuilder.createSubroutineType(Unit, EltTypeArray);
2339 }
2340 llvm::DISubprogram SP;
2341 SP = DBuilder.createFunction(FDContext, Name, LinkageName, Unit,
2342 LineNo, DIFnType,
2343 Fn->hasInternalLinkage(), true/*definition*/,
2344 getLineNumber(CurLoc), Flags,
2345 CGM.getLangOpts().Optimize,
2346 Fn, TParamsArray, SPDecl);
2347
2348 // Push function on region stack.
2349 llvm::MDNode *SPN = SP;
2350 LexicalBlockStack.push_back(SPN);
2351 if (HasDecl)
2352 RegionMap[D] = llvm::WeakVH(SP);
2353}
2354
2355/// EmitLocation - Emit metadata to indicate a change in line/column
2356/// information in the source file.
Adrian Prantl00df5ea2013-03-12 20:43:25 +00002357void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc,
2358 bool ForceColumnInfo) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002359
2360 // Update our current location
2361 setLocation(Loc);
2362
2363 if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
2364
2365 // Don't bother if things are the same as last time.
2366 SourceManager &SM = CGM.getContext().getSourceManager();
2367 if (CurLoc == PrevLoc ||
2368 SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc))
2369 // New Builder may not be in sync with CGDebugInfo.
David Blaikie0a0f93c2013-02-01 19:09:49 +00002370 if (!Builder.getCurrentDebugLocation().isUnknown() &&
2371 Builder.getCurrentDebugLocation().getScope(CGM.getLLVMContext()) ==
2372 LexicalBlockStack.back())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002373 return;
2374
2375 // Update last state.
2376 PrevLoc = CurLoc;
2377
2378 llvm::MDNode *Scope = LexicalBlockStack.back();
Adrian Prantl00df5ea2013-03-12 20:43:25 +00002379 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get
2380 (getLineNumber(CurLoc),
2381 getColumnNumber(CurLoc, ForceColumnInfo),
2382 Scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002383}
2384
2385/// CreateLexicalBlock - Creates a new lexical block node and pushes it on
2386/// the stack.
2387void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
2388 llvm::DIDescriptor D =
2389 DBuilder.createLexicalBlock(LexicalBlockStack.empty() ?
2390 llvm::DIDescriptor() :
2391 llvm::DIDescriptor(LexicalBlockStack.back()),
2392 getOrCreateFile(CurLoc),
2393 getLineNumber(CurLoc),
2394 getColumnNumber(CurLoc));
2395 llvm::MDNode *DN = D;
2396 LexicalBlockStack.push_back(DN);
2397}
2398
2399/// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
2400/// region - beginning of a DW_TAG_lexical_block.
2401void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder, SourceLocation Loc) {
2402 // Set our current location.
2403 setLocation(Loc);
2404
2405 // Create a new lexical block and push it on the stack.
2406 CreateLexicalBlock(Loc);
2407
2408 // Emit a line table change for the current location inside the new scope.
2409 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc),
2410 getColumnNumber(Loc),
2411 LexicalBlockStack.back()));
2412}
2413
2414/// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative
2415/// region - end of a DW_TAG_lexical_block.
2416void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder, SourceLocation Loc) {
2417 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2418
2419 // Provide an entry in the line table for the end of the block.
2420 EmitLocation(Builder, Loc);
2421
2422 LexicalBlockStack.pop_back();
2423}
2424
2425/// EmitFunctionEnd - Constructs the debug code for exiting a function.
2426void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
2427 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2428 unsigned RCount = FnBeginRegionCount.back();
2429 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
2430
2431 // Pop all regions for this function.
2432 while (LexicalBlockStack.size() != RCount)
2433 EmitLexicalBlockEnd(Builder, CurLoc);
2434 FnBeginRegionCount.pop_back();
2435}
2436
2437// EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
2438// See BuildByRefType.
2439llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
2440 uint64_t *XOffset) {
2441
2442 SmallVector<llvm::Value *, 5> EltTys;
2443 QualType FType;
2444 uint64_t FieldSize, FieldOffset;
2445 unsigned FieldAlign;
2446
2447 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2448 QualType Type = VD->getType();
2449
2450 FieldOffset = 0;
2451 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2452 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
2453 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
2454 FType = CGM.getContext().IntTy;
2455 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
2456 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
2457
2458 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
2459 if (HasCopyAndDispose) {
2460 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2461 EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
2462 &FieldOffset));
2463 EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
2464 &FieldOffset));
2465 }
2466 bool HasByrefExtendedLayout;
2467 Qualifiers::ObjCLifetime Lifetime;
2468 if (CGM.getContext().getByrefLifetime(Type,
2469 Lifetime, HasByrefExtendedLayout)
2470 && HasByrefExtendedLayout)
2471 EltTys.push_back(CreateMemberType(Unit, FType,
2472 "__byref_variable_layout",
2473 &FieldOffset));
2474
2475 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2476 if (Align > CGM.getContext().toCharUnitsFromBits(
John McCall64aa4b32013-04-16 22:48:15 +00002477 CGM.getTarget().getPointerAlign(0))) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002478 CharUnits FieldOffsetInBytes
2479 = CGM.getContext().toCharUnitsFromBits(FieldOffset);
2480 CharUnits AlignedOffsetInBytes
2481 = FieldOffsetInBytes.RoundUpToAlignment(Align);
2482 CharUnits NumPaddingBytes
2483 = AlignedOffsetInBytes - FieldOffsetInBytes;
2484
2485 if (NumPaddingBytes.isPositive()) {
2486 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
2487 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
2488 pad, ArrayType::Normal, 0);
2489 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
2490 }
2491 }
2492
2493 FType = Type;
2494 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2495 FieldSize = CGM.getContext().getTypeSize(FType);
2496 FieldAlign = CGM.getContext().toBits(Align);
2497
2498 *XOffset = FieldOffset;
2499 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit,
2500 0, FieldSize, FieldAlign,
2501 FieldOffset, 0, FieldTy);
2502 EltTys.push_back(FieldTy);
2503 FieldOffset += FieldSize;
2504
2505 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
2506
2507 unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
2508
2509 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
David Blaikiec1d0af12013-02-25 01:07:08 +00002510 llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002511}
2512
2513/// EmitDeclare - Emit local variable declaration debug info.
2514void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
2515 llvm::Value *Storage,
2516 unsigned ArgNo, CGBuilderTy &Builder) {
2517 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2518 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2519
2520 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2521 llvm::DIType Ty;
2522 uint64_t XOffset = 0;
2523 if (VD->hasAttr<BlocksAttr>())
2524 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
2525 else
2526 Ty = getOrCreateType(VD->getType(), Unit);
2527
2528 // If there is no debug info for this type then do not emit debug info
2529 // for this variable.
2530 if (!Ty)
2531 return;
2532
2533 if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage)) {
2534 // If Storage is an aggregate returned as 'sret' then let debugger know
2535 // about this.
2536 if (Arg->hasStructRetAttr())
2537 Ty = DBuilder.createReferenceType(llvm::dwarf::DW_TAG_reference_type, Ty);
2538 else if (CXXRecordDecl *Record = VD->getType()->getAsCXXRecordDecl()) {
2539 // If an aggregate variable has non trivial destructor or non trivial copy
2540 // constructor than it is pass indirectly. Let debug info know about this
2541 // by using reference of the aggregate type as a argument type.
2542 if (Record->hasNonTrivialCopyConstructor() ||
2543 !Record->hasTrivialDestructor())
2544 Ty = DBuilder.createReferenceType(llvm::dwarf::DW_TAG_reference_type, Ty);
2545 }
2546 }
2547
2548 // Get location information.
2549 unsigned Line = getLineNumber(VD->getLocation());
2550 unsigned Column = getColumnNumber(VD->getLocation());
2551 unsigned Flags = 0;
2552 if (VD->isImplicit())
2553 Flags |= llvm::DIDescriptor::FlagArtificial;
2554 // If this is the first argument and it is implicit then
2555 // give it an object pointer flag.
2556 // FIXME: There has to be a better way to do this, but for static
2557 // functions there won't be an implicit param at arg1 and
2558 // otherwise it is 'self' or 'this'.
2559 if (isa<ImplicitParamDecl>(VD) && ArgNo == 1)
2560 Flags |= llvm::DIDescriptor::FlagObjectPointer;
2561
2562 llvm::MDNode *Scope = LexicalBlockStack.back();
2563
2564 StringRef Name = VD->getName();
2565 if (!Name.empty()) {
2566 if (VD->hasAttr<BlocksAttr>()) {
2567 CharUnits offset = CharUnits::fromQuantity(32);
2568 SmallVector<llvm::Value *, 9> addr;
2569 llvm::Type *Int64Ty = CGM.Int64Ty;
2570 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2571 // offset of __forwarding field
2572 offset = CGM.getContext().toCharUnitsFromBits(
John McCall64aa4b32013-04-16 22:48:15 +00002573 CGM.getTarget().getPointerWidth(0));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002574 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2575 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2576 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2577 // offset of x field
2578 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2579 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2580
2581 // Create the descriptor for the variable.
2582 llvm::DIVariable D =
2583 DBuilder.createComplexVariable(Tag,
2584 llvm::DIDescriptor(Scope),
2585 VD->getName(), Unit, Line, Ty,
2586 addr, ArgNo);
2587
2588 // Insert an llvm.dbg.declare into the current block.
2589 llvm::Instruction *Call =
2590 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2591 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2592 return;
Adrian Prantl230ea412013-04-30 22:45:09 +00002593 } else if (isa<VariableArrayType>(VD->getType())) {
2594 // These are "complex" variables in that they need an op_deref.
2595 // Create the descriptor for the variable.
2596 llvm::Value *Addr = llvm::ConstantInt::get(CGM.Int64Ty,
2597 llvm::DIBuilder::OpDeref);
2598 llvm::DIVariable D =
2599 DBuilder.createComplexVariable(Tag,
2600 llvm::DIDescriptor(Scope),
2601 Name, Unit, Line, Ty,
2602 Addr, ArgNo);
2603
2604 // Insert an llvm.dbg.declare into the current block.
2605 llvm::Instruction *Call =
2606 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2607 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2608 return;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002609 }
David Blaikie436653b2013-01-05 05:58:35 +00002610 } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2611 // If VD is an anonymous union then Storage represents value for
2612 // all union fields.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002613 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
David Blaikied8180cf2013-01-05 20:03:07 +00002614 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002615 for (RecordDecl::field_iterator I = RD->field_begin(),
2616 E = RD->field_end();
2617 I != E; ++I) {
2618 FieldDecl *Field = *I;
2619 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2620 StringRef FieldName = Field->getName();
2621
2622 // Ignore unnamed fields. Do not ignore unnamed records.
2623 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2624 continue;
2625
2626 // Use VarDecl's Tag, Scope and Line number.
2627 llvm::DIVariable D =
2628 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2629 FieldName, Unit, Line, FieldTy,
2630 CGM.getLangOpts().Optimize, Flags,
2631 ArgNo);
2632
2633 // Insert an llvm.dbg.declare into the current block.
2634 llvm::Instruction *Call =
2635 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2636 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2637 }
David Blaikied8180cf2013-01-05 20:03:07 +00002638 return;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002639 }
2640 }
David Blaikie436653b2013-01-05 05:58:35 +00002641
2642 // Create the descriptor for the variable.
2643 llvm::DIVariable D =
2644 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2645 Name, Unit, Line, Ty,
2646 CGM.getLangOpts().Optimize, Flags, ArgNo);
2647
2648 // Insert an llvm.dbg.declare into the current block.
2649 llvm::Instruction *Call =
2650 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2651 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002652}
2653
2654void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2655 llvm::Value *Storage,
2656 CGBuilderTy &Builder) {
2657 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2658 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2659}
2660
Adrian Prantle86fcc42013-03-29 19:20:29 +00002661/// Look up the completed type for a self pointer in the TypeCache and
2662/// create a copy of it with the ObjectPointer and Artificial flags
2663/// set. If the type is not cached, a new one is created. This should
2664/// never happen though, since creating a type for the implicit self
2665/// argument implies that we already parsed the interface definition
2666/// and the ivar declarations in the implementation.
2667llvm::DIType CGDebugInfo::CreateSelfType(const QualType &QualTy, llvm::DIType Ty) {
2668 llvm::DIType CachedTy = getTypeOrNull(QualTy);
2669 if (CachedTy.Verify()) Ty = CachedTy;
2670 else DEBUG(llvm::dbgs() << "No cached type for self.");
2671 return DBuilder.createObjectPointerType(Ty);
2672}
2673
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002674void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(const VarDecl *VD,
2675 llvm::Value *Storage,
2676 CGBuilderTy &Builder,
2677 const CGBlockInfo &blockInfo) {
2678 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2679 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2680
2681 if (Builder.GetInsertBlock() == 0)
2682 return;
2683
2684 bool isByRef = VD->hasAttr<BlocksAttr>();
2685
2686 uint64_t XOffset = 0;
2687 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2688 llvm::DIType Ty;
2689 if (isByRef)
2690 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
2691 else
2692 Ty = getOrCreateType(VD->getType(), Unit);
2693
2694 // Self is passed along as an implicit non-arg variable in a
2695 // block. Mark it as the object pointer.
2696 if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self")
Adrian Prantle86fcc42013-03-29 19:20:29 +00002697 Ty = CreateSelfType(VD->getType(), Ty);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002698
2699 // Get location information.
2700 unsigned Line = getLineNumber(VD->getLocation());
2701 unsigned Column = getColumnNumber(VD->getLocation());
2702
2703 const llvm::DataLayout &target = CGM.getDataLayout();
2704
2705 CharUnits offset = CharUnits::fromQuantity(
2706 target.getStructLayout(blockInfo.StructureType)
2707 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2708
2709 SmallVector<llvm::Value *, 9> addr;
2710 llvm::Type *Int64Ty = CGM.Int64Ty;
Adrian Prantl9b97adf2013-03-29 19:20:35 +00002711 if (isa<llvm::AllocaInst>(Storage))
2712 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002713 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2714 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2715 if (isByRef) {
2716 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2717 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2718 // offset of __forwarding field
2719 offset = CGM.getContext()
2720 .toCharUnitsFromBits(target.getPointerSizeInBits(0));
2721 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2722 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2723 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2724 // offset of x field
2725 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2726 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2727 }
2728
2729 // Create the descriptor for the variable.
2730 llvm::DIVariable D =
2731 DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable,
2732 llvm::DIDescriptor(LexicalBlockStack.back()),
2733 VD->getName(), Unit, Line, Ty, addr);
Adrian Prantl9b97adf2013-03-29 19:20:35 +00002734
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002735 // Insert an llvm.dbg.declare into the current block.
2736 llvm::Instruction *Call =
2737 DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
2738 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column,
2739 LexicalBlockStack.back()));
2740}
2741
2742/// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2743/// variable declaration.
2744void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2745 unsigned ArgNo,
2746 CGBuilderTy &Builder) {
2747 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2748 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2749}
2750
2751namespace {
2752 struct BlockLayoutChunk {
2753 uint64_t OffsetInBits;
2754 const BlockDecl::Capture *Capture;
2755 };
2756 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2757 return l.OffsetInBits < r.OffsetInBits;
2758 }
2759}
2760
2761void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
Adrian Prantl836e7c92013-03-14 17:53:33 +00002762 llvm::Value *Arg,
2763 llvm::Value *LocalAddr,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002764 CGBuilderTy &Builder) {
2765 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2766 ASTContext &C = CGM.getContext();
2767 const BlockDecl *blockDecl = block.getBlockDecl();
2768
2769 // Collect some general information about the block's location.
2770 SourceLocation loc = blockDecl->getCaretLocation();
2771 llvm::DIFile tunit = getOrCreateFile(loc);
2772 unsigned line = getLineNumber(loc);
2773 unsigned column = getColumnNumber(loc);
2774
2775 // Build the debug-info type for the block literal.
2776 getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
2777
2778 const llvm::StructLayout *blockLayout =
2779 CGM.getDataLayout().getStructLayout(block.StructureType);
2780
2781 SmallVector<llvm::Value*, 16> fields;
2782 fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
2783 blockLayout->getElementOffsetInBits(0),
2784 tunit, tunit));
2785 fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
2786 blockLayout->getElementOffsetInBits(1),
2787 tunit, tunit));
2788 fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
2789 blockLayout->getElementOffsetInBits(2),
2790 tunit, tunit));
2791 fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
2792 blockLayout->getElementOffsetInBits(3),
2793 tunit, tunit));
2794 fields.push_back(createFieldType("__descriptor",
2795 C.getPointerType(block.NeedsCopyDispose ?
2796 C.getBlockDescriptorExtendedType() :
2797 C.getBlockDescriptorType()),
2798 0, loc, AS_public,
2799 blockLayout->getElementOffsetInBits(4),
2800 tunit, tunit));
2801
2802 // We want to sort the captures by offset, not because DWARF
2803 // requires this, but because we're paranoid about debuggers.
2804 SmallVector<BlockLayoutChunk, 8> chunks;
2805
2806 // 'this' capture.
2807 if (blockDecl->capturesCXXThis()) {
2808 BlockLayoutChunk chunk;
2809 chunk.OffsetInBits =
2810 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
2811 chunk.Capture = 0;
2812 chunks.push_back(chunk);
2813 }
2814
2815 // Variable captures.
2816 for (BlockDecl::capture_const_iterator
2817 i = blockDecl->capture_begin(), e = blockDecl->capture_end();
2818 i != e; ++i) {
2819 const BlockDecl::Capture &capture = *i;
2820 const VarDecl *variable = capture.getVariable();
2821 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
2822
2823 // Ignore constant captures.
2824 if (captureInfo.isConstant())
2825 continue;
2826
2827 BlockLayoutChunk chunk;
2828 chunk.OffsetInBits =
2829 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
2830 chunk.Capture = &capture;
2831 chunks.push_back(chunk);
2832 }
2833
2834 // Sort by offset.
2835 llvm::array_pod_sort(chunks.begin(), chunks.end());
2836
2837 for (SmallVectorImpl<BlockLayoutChunk>::iterator
2838 i = chunks.begin(), e = chunks.end(); i != e; ++i) {
2839 uint64_t offsetInBits = i->OffsetInBits;
2840 const BlockDecl::Capture *capture = i->Capture;
2841
2842 // If we have a null capture, this must be the C++ 'this' capture.
2843 if (!capture) {
2844 const CXXMethodDecl *method =
2845 cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
2846 QualType type = method->getThisType(C);
2847
2848 fields.push_back(createFieldType("this", type, 0, loc, AS_public,
2849 offsetInBits, tunit, tunit));
2850 continue;
2851 }
2852
2853 const VarDecl *variable = capture->getVariable();
2854 StringRef name = variable->getName();
2855
2856 llvm::DIType fieldType;
2857 if (capture->isByRef()) {
2858 std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
2859
2860 // FIXME: this creates a second copy of this type!
2861 uint64_t xoffset;
2862 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
2863 fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
2864 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
2865 ptrInfo.first, ptrInfo.second,
2866 offsetInBits, 0, fieldType);
2867 } else {
2868 fieldType = createFieldType(name, variable->getType(), 0,
2869 loc, AS_public, offsetInBits, tunit, tunit);
2870 }
2871 fields.push_back(fieldType);
2872 }
2873
2874 SmallString<36> typeName;
2875 llvm::raw_svector_ostream(typeName)
2876 << "__block_literal_" << CGM.getUniqueBlockCount();
2877
2878 llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
2879
2880 llvm::DIType type =
2881 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
2882 CGM.getContext().toBits(block.BlockSize),
2883 CGM.getContext().toBits(block.BlockAlign),
David Blaikiec1d0af12013-02-25 01:07:08 +00002884 0, llvm::DIType(), fieldsArray);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002885 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
2886
2887 // Get overall information about the block.
2888 unsigned flags = llvm::DIDescriptor::FlagArtificial;
2889 llvm::MDNode *scope = LexicalBlockStack.back();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002890
2891 // Create the descriptor for the parameter.
2892 llvm::DIVariable debugVar =
2893 DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
2894 llvm::DIDescriptor(scope),
Adrian Prantl836e7c92013-03-14 17:53:33 +00002895 Arg->getName(), tunit, line, type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002896 CGM.getLangOpts().Optimize, flags,
Adrian Prantl836e7c92013-03-14 17:53:33 +00002897 cast<llvm::Argument>(Arg)->getArgNo() + 1);
2898
Adrian Prantlbea407c2013-03-14 21:52:59 +00002899 if (LocalAddr) {
Adrian Prantl836e7c92013-03-14 17:53:33 +00002900 // Insert an llvm.dbg.value into the current block.
Adrian Prantlbea407c2013-03-14 21:52:59 +00002901 llvm::Instruction *DbgVal =
2902 DBuilder.insertDbgValueIntrinsic(LocalAddr, 0, debugVar,
Eric Christopherf068c922013-04-02 22:59:11 +00002903 Builder.GetInsertBlock());
Adrian Prantlbea407c2013-03-14 21:52:59 +00002904 DbgVal->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
2905 }
Adrian Prantl836e7c92013-03-14 17:53:33 +00002906
Adrian Prantlbea407c2013-03-14 21:52:59 +00002907 // Insert an llvm.dbg.declare into the current block.
2908 llvm::Instruction *DbgDecl =
2909 DBuilder.insertDeclare(Arg, debugVar, Builder.GetInsertBlock());
2910 DbgDecl->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002911}
2912
Eric Christopher0395de32013-01-16 01:22:32 +00002913/// getStaticDataMemberDeclaration - If D is an out-of-class definition of
2914/// a static data member of a class, find its corresponding in-class
2915/// declaration.
2916llvm::DIDerivedType CGDebugInfo::getStaticDataMemberDeclaration(const Decl *D) {
2917 if (cast<VarDecl>(D)->isStaticDataMember()) {
2918 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
2919 MI = StaticDataMemberCache.find(D->getCanonicalDecl());
2920 if (MI != StaticDataMemberCache.end())
2921 // Verify the info still exists.
2922 if (llvm::Value *V = MI->second)
2923 return llvm::DIDerivedType(cast<llvm::MDNode>(V));
2924 }
2925 return llvm::DIDerivedType();
2926}
2927
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002928/// EmitGlobalVariable - Emit information about a global variable.
2929void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
2930 const VarDecl *D) {
2931 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2932 // Create global variable debug descriptor.
2933 llvm::DIFile Unit = getOrCreateFile(D->getLocation());
2934 unsigned LineNo = getLineNumber(D->getLocation());
2935
2936 setLocation(D->getLocation());
2937
2938 QualType T = D->getType();
2939 if (T->isIncompleteArrayType()) {
2940
2941 // CodeGen turns int[] into int[1] so we'll do the same here.
2942 llvm::APInt ConstVal(32, 1);
2943 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
2944
2945 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
2946 ArrayType::Normal, 0);
2947 }
2948 StringRef DeclName = D->getName();
2949 StringRef LinkageName;
2950 if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext())
2951 && !isa<ObjCMethodDecl>(D->getDeclContext()))
2952 LinkageName = Var->getName();
2953 if (LinkageName == DeclName)
2954 LinkageName = StringRef();
2955 llvm::DIDescriptor DContext =
2956 getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
David Blaikie214c3d62013-05-15 23:46:19 +00002957 DBuilder.createStaticVariable(DContext, DeclName, LinkageName,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002958 Unit, LineNo, getOrCreateType(T, Unit),
Eric Christopher0395de32013-01-16 01:22:32 +00002959 Var->hasInternalLinkage(), Var,
2960 getStaticDataMemberDeclaration(D));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002961}
2962
2963/// EmitGlobalVariable - Emit information about an objective-c interface.
2964void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
2965 ObjCInterfaceDecl *ID) {
2966 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2967 // Create global variable debug descriptor.
2968 llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
2969 unsigned LineNo = getLineNumber(ID->getLocation());
2970
2971 StringRef Name = ID->getName();
2972
2973 QualType T = CGM.getContext().getObjCInterfaceType(ID);
2974 if (T->isIncompleteArrayType()) {
2975
2976 // CodeGen turns int[] into int[1] so we'll do the same here.
2977 llvm::APInt ConstVal(32, 1);
2978 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
2979
2980 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
2981 ArrayType::Normal, 0);
2982 }
2983
2984 DBuilder.createGlobalVariable(Name, Unit, LineNo,
2985 getOrCreateType(T, Unit),
2986 Var->hasInternalLinkage(), Var);
2987}
2988
2989/// EmitGlobalVariable - Emit global variable's debug info.
2990void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
2991 llvm::Constant *Init) {
2992 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2993 // Create the descriptor for the variable.
2994 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2995 StringRef Name = VD->getName();
2996 llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
2997 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
2998 const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext());
2999 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
3000 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
3001 }
3002 // Do not use DIGlobalVariable for enums.
3003 if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
3004 return;
David Blaikie214c3d62013-05-15 23:46:19 +00003005 DBuilder.createStaticVariable(Unit, Name, Name, Unit,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003006 getLineNumber(VD->getLocation()),
Eric Christopher0395de32013-01-16 01:22:32 +00003007 Ty, true, Init,
3008 getStaticDataMemberDeclaration(VD));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003009}
3010
David Blaikie957dac52013-04-22 06:13:21 +00003011void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
David Blaikie214c3d62013-05-15 23:46:19 +00003012 llvm::DIScope Scope =
3013 LexicalBlockStack.empty()
3014 ? getContextDescriptor(cast<Decl>(UD.getDeclContext()))
3015 : llvm::DIScope(LexicalBlockStack.back());
David Blaikie957dac52013-04-22 06:13:21 +00003016 DBuilder.createImportedModule(
David Blaikie214c3d62013-05-15 23:46:19 +00003017 Scope, getOrCreateNameSpace(UD.getNominatedNamespace()),
David Blaikie957dac52013-04-22 06:13:21 +00003018 getLineNumber(UD.getLocation()));
3019}
3020
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003021/// getOrCreateNamesSpace - Return namespace descriptor for the given
3022/// namespace decl.
3023llvm::DINameSpace
3024CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
3025 llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
3026 NameSpaceCache.find(NSDecl);
3027 if (I != NameSpaceCache.end())
3028 return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
3029
3030 unsigned LineNo = getLineNumber(NSDecl->getLocation());
3031 llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
3032 llvm::DIDescriptor Context =
3033 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
3034 llvm::DINameSpace NS =
3035 DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
3036 NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
3037 return NS;
3038}
3039
3040void CGDebugInfo::finalize() {
3041 for (std::vector<std::pair<void *, llvm::WeakVH> >::const_iterator VI
3042 = ReplaceMap.begin(), VE = ReplaceMap.end(); VI != VE; ++VI) {
3043 llvm::DIType Ty, RepTy;
3044 // Verify that the debug info still exists.
3045 if (llvm::Value *V = VI->second)
3046 Ty = llvm::DIType(cast<llvm::MDNode>(V));
3047
3048 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
3049 TypeCache.find(VI->first);
3050 if (it != TypeCache.end()) {
3051 // Verify that the debug info still exists.
3052 if (llvm::Value *V = it->second)
3053 RepTy = llvm::DIType(cast<llvm::MDNode>(V));
3054 }
Adrian Prantlebbd7e02013-03-11 18:33:46 +00003055
Adrian Prantl9b97adf2013-03-29 19:20:35 +00003056 if (Ty.Verify() && Ty.isForwardDecl() && RepTy.Verify())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003057 Ty.replaceAllUsesWith(RepTy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003058 }
Adrian Prantlebbd7e02013-03-11 18:33:46 +00003059
3060 // We keep our own list of retained types, because we need to look
3061 // up the final type in the type cache.
3062 for (std::vector<void *>::const_iterator RI = RetainedTypes.begin(),
3063 RE = RetainedTypes.end(); RI != RE; ++RI)
3064 DBuilder.retainType(llvm::DIType(cast<llvm::MDNode>(TypeCache[*RI])));
3065
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003066 DBuilder.finalize();
3067}