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