blob: 53fa4a4e8f1eb45f84074af1eb5e24fc8548f7bb [file] [log] [blame]
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001//===--- CGDebugInfo.cpp - Emit Debug Information for a Module ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the debug information generation while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGDebugInfo.h"
15#include "CGBlocks.h"
David Blaikie9dfd2432013-05-10 21:53:14 +000016#include "CGCXXABI.h"
Guy Benyei7f92f2d2012-12-18 14:30:41 +000017#include "CGObjCRuntime.h"
18#include "CodeGenFunction.h"
19#include "CodeGenModule.h"
20#include "clang/AST/ASTContext.h"
21#include "clang/AST/DeclFriend.h"
22#include "clang/AST/DeclObjC.h"
23#include "clang/AST/DeclTemplate.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/RecordLayout.h"
26#include "clang/Basic/FileManager.h"
27#include "clang/Basic/SourceManager.h"
28#include "clang/Basic/Version.h"
29#include "clang/Frontend/CodeGenOptions.h"
30#include "llvm/ADT/SmallVector.h"
31#include "llvm/ADT/StringExtras.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000032#include "llvm/IR/Constants.h"
33#include "llvm/IR/DataLayout.h"
34#include "llvm/IR/DerivedTypes.h"
35#include "llvm/IR/Instructions.h"
36#include "llvm/IR/Intrinsics.h"
37#include "llvm/IR/Module.h"
Guy Benyei7f92f2d2012-12-18 14:30:41 +000038#include "llvm/Support/Dwarf.h"
39#include "llvm/Support/FileSystem.h"
40using namespace clang;
41using namespace clang::CodeGen;
42
43CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
Eric Christopher13c97672013-05-16 00:45:23 +000044 : CGM(CGM), DebugKind(CGM.getCodeGenOpts().getDebugInfo()),
45 DBuilder(CGM.getModule()),
Guy Benyei7f92f2d2012-12-18 14:30:41 +000046 BlockLiteralGenericSet(false) {
47 CreateCompileUnit();
48}
49
50CGDebugInfo::~CGDebugInfo() {
51 assert(LexicalBlockStack.empty() &&
52 "Region stack mismatch, stack not empty!");
53}
54
55void CGDebugInfo::setLocation(SourceLocation Loc) {
56 // If the new location isn't valid return.
57 if (!Loc.isValid()) return;
58
59 CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc);
60
61 // If we've changed files in the middle of a lexical scope go ahead
62 // and create a new lexical scope with file node if it's different
63 // from the one in the scope.
64 if (LexicalBlockStack.empty()) return;
65
66 SourceManager &SM = CGM.getContext().getSourceManager();
67 PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
68 PresumedLoc PPLoc = SM.getPresumedLoc(PrevLoc);
69
70 if (PCLoc.isInvalid() || PPLoc.isInvalid() ||
71 !strcmp(PPLoc.getFilename(), PCLoc.getFilename()))
72 return;
73
74 llvm::MDNode *LB = LexicalBlockStack.back();
75 llvm::DIScope Scope = llvm::DIScope(LB);
76 if (Scope.isLexicalBlockFile()) {
77 llvm::DILexicalBlockFile LBF = llvm::DILexicalBlockFile(LB);
78 llvm::DIDescriptor D
79 = DBuilder.createLexicalBlockFile(LBF.getScope(),
80 getOrCreateFile(CurLoc));
81 llvm::MDNode *N = D;
82 LexicalBlockStack.pop_back();
83 LexicalBlockStack.push_back(N);
David Blaikiea6504852013-01-26 22:16:26 +000084 } else if (Scope.isLexicalBlock() || Scope.isSubprogram()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +000085 llvm::DIDescriptor D
86 = DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc));
87 llvm::MDNode *N = D;
88 LexicalBlockStack.pop_back();
89 LexicalBlockStack.push_back(N);
90 }
91}
92
93/// getContextDescriptor - Get context info for the decl.
David Blaikiebb000792013-04-19 06:56:38 +000094llvm::DIScope CGDebugInfo::getContextDescriptor(const Decl *Context) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +000095 if (!Context)
96 return TheCU;
97
98 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
99 I = RegionMap.find(Context);
100 if (I != RegionMap.end()) {
101 llvm::Value *V = I->second;
David Blaikiebb000792013-04-19 06:56:38 +0000102 return llvm::DIScope(dyn_cast_or_null<llvm::MDNode>(V));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000103 }
104
105 // Check namespace.
106 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
David Blaikiebb000792013-04-19 06:56:38 +0000107 return getOrCreateNameSpace(NSDecl);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000108
David Blaikiebb000792013-04-19 06:56:38 +0000109 if (const RecordDecl *RDecl = dyn_cast<RecordDecl>(Context))
110 if (!RDecl->isDependentType())
111 return getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000112 getOrCreateMainFile());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000113 return TheCU;
114}
115
116/// getFunctionName - Get function name for the given FunctionDecl. If the
117/// name is constructred on demand (e.g. C++ destructor) then the name
118/// is stored on the side.
119StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
120 assert (FD && "Invalid FunctionDecl!");
121 IdentifierInfo *FII = FD->getIdentifier();
122 FunctionTemplateSpecializationInfo *Info
123 = FD->getTemplateSpecializationInfo();
124 if (!Info && FII)
125 return FII->getName();
126
127 // Otherwise construct human readable name for debug info.
Benjamin Kramer5eada842013-02-22 15:46:01 +0000128 SmallString<128> NS;
129 llvm::raw_svector_ostream OS(NS);
130 FD->printName(OS);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000131
132 // Add any template specialization args.
133 if (Info) {
134 const TemplateArgumentList *TArgs = Info->TemplateArguments;
135 const TemplateArgument *Args = TArgs->data();
136 unsigned NumArgs = TArgs->size();
137 PrintingPolicy Policy(CGM.getLangOpts());
Benjamin Kramer5eada842013-02-22 15:46:01 +0000138 TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs,
139 Policy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000140 }
141
142 // Copy this name on the side and use its reference.
Benjamin Kramer5eada842013-02-22 15:46:01 +0000143 OS.flush();
144 char *StrPtr = DebugInfoNames.Allocate<char>(NS.size());
145 memcpy(StrPtr, NS.data(), NS.size());
146 return StringRef(StrPtr, NS.size());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000147}
148
149StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
150 SmallString<256> MethodName;
151 llvm::raw_svector_ostream OS(MethodName);
152 OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
153 const DeclContext *DC = OMD->getDeclContext();
Eric Christopher6537f082013-05-16 00:45:12 +0000154 if (const ObjCImplementationDecl *OID =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000155 dyn_cast<const ObjCImplementationDecl>(DC)) {
156 OS << OID->getName();
Eric Christopher6537f082013-05-16 00:45:12 +0000157 } else if (const ObjCInterfaceDecl *OID =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000158 dyn_cast<const ObjCInterfaceDecl>(DC)) {
159 OS << OID->getName();
Eric Christopher6537f082013-05-16 00:45:12 +0000160 } else if (const ObjCCategoryImplDecl *OCD =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000161 dyn_cast<const ObjCCategoryImplDecl>(DC)){
162 OS << ((const NamedDecl *)OCD)->getIdentifier()->getNameStart() << '(' <<
163 OCD->getIdentifier()->getNameStart() << ')';
Adrian Prantlb5092242013-05-17 23:58:45 +0000164 } else if (isa<ObjCProtocolDecl>(DC)) {
Adrian Prantl687ecae2013-05-17 23:49:10 +0000165 // We can extract the type of the class from the self pointer.
166 if (ImplicitParamDecl* SelfDecl = OMD->getSelfDecl()) {
167 QualType ClassTy =
168 cast<ObjCObjectPointerType>(SelfDecl->getType())->getPointeeType();
169 ClassTy.print(OS, PrintingPolicy(LangOptions()));
170 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000171 }
172 OS << ' ' << OMD->getSelector().getAsString() << ']';
173
174 char *StrPtr = DebugInfoNames.Allocate<char>(OS.tell());
175 memcpy(StrPtr, MethodName.begin(), OS.tell());
176 return StringRef(StrPtr, OS.tell());
177}
178
179/// getSelectorName - Return selector name. This is used for debugging
180/// info.
181StringRef CGDebugInfo::getSelectorName(Selector S) {
182 const std::string &SName = S.getAsString();
183 char *StrPtr = DebugInfoNames.Allocate<char>(SName.size());
184 memcpy(StrPtr, SName.data(), SName.size());
185 return StringRef(StrPtr, SName.size());
186}
187
188/// getClassName - Get class name including template argument list.
Eric Christopher6537f082013-05-16 00:45:12 +0000189StringRef
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000190CGDebugInfo::getClassName(const RecordDecl *RD) {
191 const ClassTemplateSpecializationDecl *Spec
192 = dyn_cast<ClassTemplateSpecializationDecl>(RD);
193 if (!Spec)
194 return RD->getName();
195
196 const TemplateArgument *Args;
197 unsigned NumArgs;
198 if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) {
199 const TemplateSpecializationType *TST =
200 cast<TemplateSpecializationType>(TAW->getType());
201 Args = TST->getArgs();
202 NumArgs = TST->getNumArgs();
203 } else {
204 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
205 Args = TemplateArgs.data();
206 NumArgs = TemplateArgs.size();
207 }
208 StringRef Name = RD->getIdentifier()->getName();
209 PrintingPolicy Policy(CGM.getLangOpts());
Benjamin Kramer5eada842013-02-22 15:46:01 +0000210 SmallString<128> TemplateArgList;
211 {
212 llvm::raw_svector_ostream OS(TemplateArgList);
213 TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs,
214 Policy);
215 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000216
217 // Copy this name on the side and use its reference.
218 size_t Length = Name.size() + TemplateArgList.size();
219 char *StrPtr = DebugInfoNames.Allocate<char>(Length);
220 memcpy(StrPtr, Name.data(), Name.size());
221 memcpy(StrPtr + Name.size(), TemplateArgList.data(), TemplateArgList.size());
222 return StringRef(StrPtr, Length);
223}
224
225/// getOrCreateFile - Get the file debug info descriptor for the input location.
226llvm::DIFile CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
227 if (!Loc.isValid())
228 // If Location is not valid then use main input file.
229 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
230
231 SourceManager &SM = CGM.getContext().getSourceManager();
232 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
233
234 if (PLoc.isInvalid() || StringRef(PLoc.getFilename()).empty())
235 // If the location is not valid then use main input file.
236 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
237
238 // Cache the results.
239 const char *fname = PLoc.getFilename();
240 llvm::DenseMap<const char *, llvm::WeakVH>::iterator it =
241 DIFileCache.find(fname);
242
243 if (it != DIFileCache.end()) {
244 // Verify that the information still exists.
245 if (llvm::Value *V = it->second)
246 return llvm::DIFile(cast<llvm::MDNode>(V));
247 }
248
249 llvm::DIFile F = DBuilder.createFile(PLoc.getFilename(), getCurrentDirname());
250
251 DIFileCache[fname] = F;
252 return F;
253}
254
255/// getOrCreateMainFile - Get the file info for main compile unit.
256llvm::DIFile CGDebugInfo::getOrCreateMainFile() {
257 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
258}
259
260/// getLineNumber - Get line number for the location. If location is invalid
261/// then use current location.
262unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
263 if (Loc.isInvalid() && CurLoc.isInvalid())
264 return 0;
265 SourceManager &SM = CGM.getContext().getSourceManager();
266 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
267 return PLoc.isValid()? PLoc.getLine() : 0;
268}
269
270/// getColumnNumber - Get column number for the location.
Adrian Prantl00df5ea2013-03-12 20:43:25 +0000271unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000272 // We may not want column information at all.
Adrian Prantl00df5ea2013-03-12 20:43:25 +0000273 if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000274 return 0;
275
276 // If the location is invalid then use the current column.
277 if (Loc.isInvalid() && CurLoc.isInvalid())
278 return 0;
279 SourceManager &SM = CGM.getContext().getSourceManager();
280 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
281 return PLoc.isValid()? PLoc.getColumn() : 0;
282}
283
284StringRef CGDebugInfo::getCurrentDirname() {
285 if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
286 return CGM.getCodeGenOpts().DebugCompilationDir;
287
288 if (!CWDName.empty())
289 return CWDName;
290 SmallString<256> CWD;
291 llvm::sys::fs::current_path(CWD);
292 char *CompDirnamePtr = DebugInfoNames.Allocate<char>(CWD.size());
293 memcpy(CompDirnamePtr, CWD.data(), CWD.size());
294 return CWDName = StringRef(CompDirnamePtr, CWD.size());
295}
296
297/// CreateCompileUnit - Create new compile unit.
298void CGDebugInfo::CreateCompileUnit() {
299
300 // Get absolute path name.
301 SourceManager &SM = CGM.getContext().getSourceManager();
302 std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
303 if (MainFileName.empty())
304 MainFileName = "<unknown>";
305
306 // The main file name provided via the "-main-file-name" option contains just
307 // the file name itself with no path information. This file name may have had
308 // a relative path, so we look into the actual file entry for the main
309 // file to determine the real absolute path for the file.
310 std::string MainFileDir;
311 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
312 MainFileDir = MainFile->getDir()->getName();
313 if (MainFileDir != ".")
314 MainFileName = MainFileDir + "/" + MainFileName;
315 }
316
317 // Save filename string.
318 char *FilenamePtr = DebugInfoNames.Allocate<char>(MainFileName.length());
319 memcpy(FilenamePtr, MainFileName.c_str(), MainFileName.length());
320 StringRef Filename(FilenamePtr, MainFileName.length());
Eric Christopherff971d72013-02-22 23:50:16 +0000321
322 // Save split dwarf file string.
323 std::string SplitDwarfFile = CGM.getCodeGenOpts().SplitDwarfFile;
324 char *SplitDwarfPtr = DebugInfoNames.Allocate<char>(SplitDwarfFile.length());
325 memcpy(SplitDwarfPtr, SplitDwarfFile.c_str(), SplitDwarfFile.length());
326 StringRef SplitDwarfFilename(SplitDwarfPtr, SplitDwarfFile.length());
Eric Christopher6537f082013-05-16 00:45:12 +0000327
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000328 unsigned LangTag;
329 const LangOptions &LO = CGM.getLangOpts();
330 if (LO.CPlusPlus) {
331 if (LO.ObjC1)
332 LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
333 else
334 LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
335 } else if (LO.ObjC1) {
336 LangTag = llvm::dwarf::DW_LANG_ObjC;
337 } else if (LO.C99) {
338 LangTag = llvm::dwarf::DW_LANG_C99;
339 } else {
340 LangTag = llvm::dwarf::DW_LANG_C89;
341 }
342
343 std::string Producer = getClangFullVersion();
344
345 // Figure out which version of the ObjC runtime we have.
346 unsigned RuntimeVers = 0;
347 if (LO.ObjC1)
348 RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
349
350 // Create new compile unit.
Eric Christopherbe5f1be2013-02-21 22:35:08 +0000351 DBuilder.createCompileUnit(LangTag, Filename, getCurrentDirname(),
352 Producer, LO.Optimize,
Eric Christopherff971d72013-02-22 23:50:16 +0000353 CGM.getCodeGenOpts().DwarfDebugFlags,
354 RuntimeVers, SplitDwarfFilename);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000355 // FIXME - Eliminate TheCU.
356 TheCU = llvm::DICompileUnit(DBuilder.getCU());
357}
358
359/// CreateType - Get the Basic type from the cache or create a new
360/// one if necessary.
361llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT) {
362 unsigned Encoding = 0;
363 StringRef BTName;
364 switch (BT->getKind()) {
365#define BUILTIN_TYPE(Id, SingletonId)
366#define PLACEHOLDER_TYPE(Id, SingletonId) \
367 case BuiltinType::Id:
368#include "clang/AST/BuiltinTypes.def"
369 case BuiltinType::Dependent:
370 llvm_unreachable("Unexpected builtin type");
371 case BuiltinType::NullPtr:
Peter Collingbourne24118f52013-06-27 22:51:01 +0000372 return DBuilder.createNullPtrType();
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000373 case BuiltinType::Void:
374 return llvm::DIType();
375 case BuiltinType::ObjCClass:
376 if (ClassTy.Verify())
377 return ClassTy;
378 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
379 "objc_class", TheCU,
380 getOrCreateMainFile(), 0);
381 return ClassTy;
382 case BuiltinType::ObjCId: {
383 // typedef struct objc_class *Class;
384 // typedef struct objc_object {
385 // Class isa;
386 // } *id;
387
388 if (ObjTy.Verify())
389 return ObjTy;
390
391 if (!ClassTy.Verify())
392 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
393 "objc_class", TheCU,
394 getOrCreateMainFile(), 0);
395
396 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
Eric Christopher6537f082013-05-16 00:45:12 +0000397
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000398 llvm::DIType ISATy = DBuilder.createPointerType(ClassTy, Size);
399
Eric Christopherf068c922013-04-02 22:59:11 +0000400 ObjTy =
David Blaikiec1d0af12013-02-25 01:07:08 +0000401 DBuilder.createStructType(TheCU, "objc_object", getOrCreateMainFile(),
402 0, 0, 0, 0, llvm::DIType(), llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000403
Eric Christopherf068c922013-04-02 22:59:11 +0000404 ObjTy.setTypeArray(DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
405 ObjTy, "isa", getOrCreateMainFile(), 0, Size, 0, 0, 0, ISATy)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000406 return ObjTy;
407 }
408 case BuiltinType::ObjCSel: {
409 if (SelTy.Verify())
410 return SelTy;
411 SelTy =
412 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
413 "objc_selector", TheCU, getOrCreateMainFile(),
414 0);
415 return SelTy;
416 }
Guy Benyeib13621d2012-12-18 14:38:23 +0000417
418 case BuiltinType::OCLImage1d:
419 return getOrCreateStructPtrType("opencl_image1d_t",
420 OCLImage1dDITy);
421 case BuiltinType::OCLImage1dArray:
Eric Christopher6537f082013-05-16 00:45:12 +0000422 return getOrCreateStructPtrType("opencl_image1d_array_t",
Guy Benyeib13621d2012-12-18 14:38:23 +0000423 OCLImage1dArrayDITy);
424 case BuiltinType::OCLImage1dBuffer:
425 return getOrCreateStructPtrType("opencl_image1d_buffer_t",
426 OCLImage1dBufferDITy);
427 case BuiltinType::OCLImage2d:
428 return getOrCreateStructPtrType("opencl_image2d_t",
429 OCLImage2dDITy);
430 case BuiltinType::OCLImage2dArray:
431 return getOrCreateStructPtrType("opencl_image2d_array_t",
432 OCLImage2dArrayDITy);
433 case BuiltinType::OCLImage3d:
434 return getOrCreateStructPtrType("opencl_image3d_t",
435 OCLImage3dDITy);
Guy Benyei21f18c42013-02-07 10:55:47 +0000436 case BuiltinType::OCLSampler:
437 return DBuilder.createBasicType("opencl_sampler_t",
438 CGM.getContext().getTypeSize(BT),
439 CGM.getContext().getTypeAlign(BT),
440 llvm::dwarf::DW_ATE_unsigned);
Guy Benyeie6b9d802013-01-20 12:31:11 +0000441 case BuiltinType::OCLEvent:
442 return getOrCreateStructPtrType("opencl_event_t",
443 OCLEventDITy);
Guy Benyeib13621d2012-12-18 14:38:23 +0000444
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000445 case BuiltinType::UChar:
446 case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
447 case BuiltinType::Char_S:
448 case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
449 case BuiltinType::Char16:
450 case BuiltinType::Char32: Encoding = llvm::dwarf::DW_ATE_UTF; break;
451 case BuiltinType::UShort:
452 case BuiltinType::UInt:
453 case BuiltinType::UInt128:
454 case BuiltinType::ULong:
455 case BuiltinType::WChar_U:
456 case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
457 case BuiltinType::Short:
458 case BuiltinType::Int:
459 case BuiltinType::Int128:
460 case BuiltinType::Long:
461 case BuiltinType::WChar_S:
462 case BuiltinType::LongLong: Encoding = llvm::dwarf::DW_ATE_signed; break;
463 case BuiltinType::Bool: Encoding = llvm::dwarf::DW_ATE_boolean; break;
464 case BuiltinType::Half:
465 case BuiltinType::Float:
466 case BuiltinType::LongDouble:
467 case BuiltinType::Double: Encoding = llvm::dwarf::DW_ATE_float; break;
468 }
469
470 switch (BT->getKind()) {
471 case BuiltinType::Long: BTName = "long int"; break;
472 case BuiltinType::LongLong: BTName = "long long int"; break;
473 case BuiltinType::ULong: BTName = "long unsigned int"; break;
474 case BuiltinType::ULongLong: BTName = "long long unsigned int"; break;
475 default:
476 BTName = BT->getName(CGM.getLangOpts());
477 break;
478 }
479 // Bit size, align and offset of the type.
480 uint64_t Size = CGM.getContext().getTypeSize(BT);
481 uint64_t Align = CGM.getContext().getTypeAlign(BT);
Eric Christopher6537f082013-05-16 00:45:12 +0000482 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000483 DBuilder.createBasicType(BTName, Size, Align, Encoding);
484 return DbgTy;
485}
486
487llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty) {
488 // Bit size, align and offset of the type.
489 unsigned Encoding = llvm::dwarf::DW_ATE_complex_float;
490 if (Ty->isComplexIntegerType())
491 Encoding = llvm::dwarf::DW_ATE_lo_user;
492
493 uint64_t Size = CGM.getContext().getTypeSize(Ty);
494 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
Eric Christopher6537f082013-05-16 00:45:12 +0000495 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000496 DBuilder.createBasicType("complex", Size, Align, Encoding);
497
498 return DbgTy;
499}
500
501/// CreateCVRType - Get the qualified type from the cache or create
502/// a new one if necessary.
Eric Christopher56b108a2013-06-07 22:54:39 +0000503llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit,
504 bool Declaration) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000505 QualifierCollector Qc;
506 const Type *T = Qc.strip(Ty);
507
508 // Ignore these qualifiers for now.
509 Qc.removeObjCGCAttr();
510 Qc.removeAddressSpace();
511 Qc.removeObjCLifetime();
512
513 // We will create one Derived type for one qualifier and recurse to handle any
514 // additional ones.
515 unsigned Tag;
516 if (Qc.hasConst()) {
517 Tag = llvm::dwarf::DW_TAG_const_type;
518 Qc.removeConst();
519 } else if (Qc.hasVolatile()) {
520 Tag = llvm::dwarf::DW_TAG_volatile_type;
521 Qc.removeVolatile();
522 } else if (Qc.hasRestrict()) {
523 Tag = llvm::dwarf::DW_TAG_restrict_type;
524 Qc.removeRestrict();
525 } else {
526 assert(Qc.empty() && "Unknown type qualifier for debug info");
527 return getOrCreateType(QualType(T, 0), Unit);
528 }
529
Eric Christopher56b108a2013-06-07 22:54:39 +0000530 llvm::DIType FromTy =
531 getOrCreateType(Qc.apply(CGM.getContext(), T), Unit, Declaration);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000532
533 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
534 // CVR derived types.
535 llvm::DIType DbgTy = DBuilder.createQualifiedType(Tag, FromTy);
Eric Christopher6537f082013-05-16 00:45:12 +0000536
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000537 return DbgTy;
538}
539
540llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
541 llvm::DIFile Unit) {
Fariborz Jahanian05f8ff12013-02-21 20:42:11 +0000542
543 // The frontend treats 'id' as a typedef to an ObjCObjectType,
544 // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
545 // debug info, we want to emit 'id' in both cases.
546 if (Ty->isObjCQualifiedIdType())
547 return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
548
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000549 llvm::DIType DbgTy =
Eric Christopher6537f082013-05-16 00:45:12 +0000550 CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000551 Ty->getPointeeType(), Unit);
552 return DbgTy;
553}
554
555llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
556 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +0000557 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000558 Ty->getPointeeType(), Unit);
559}
560
561// Creates a forward declaration for a RecordDecl in the given context.
562llvm::DIType CGDebugInfo::createRecordFwdDecl(const RecordDecl *RD,
563 llvm::DIDescriptor Ctx) {
564 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
565 unsigned Line = getLineNumber(RD->getLocation());
566 StringRef RDName = getClassName(RD);
567
568 unsigned Tag = 0;
569 if (RD->isStruct() || RD->isInterface())
570 Tag = llvm::dwarf::DW_TAG_structure_type;
571 else if (RD->isUnion())
572 Tag = llvm::dwarf::DW_TAG_union_type;
573 else {
574 assert(RD->isClass());
575 Tag = llvm::dwarf::DW_TAG_class_type;
576 }
577
578 // Create the type.
579 return DBuilder.createForwardDecl(Tag, RDName, Ctx, DefUnit, Line);
580}
581
582// Walk up the context chain and create forward decls for record decls,
583// and normal descriptors for namespaces.
584llvm::DIDescriptor CGDebugInfo::createContextChain(const Decl *Context) {
585 if (!Context)
586 return TheCU;
587
588 // See if we already have the parent.
589 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
590 I = RegionMap.find(Context);
591 if (I != RegionMap.end()) {
592 llvm::Value *V = I->second;
593 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
594 }
Eric Christopher6537f082013-05-16 00:45:12 +0000595
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000596 // Check namespace.
597 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
598 return llvm::DIDescriptor(getOrCreateNameSpace(NSDecl));
599
600 if (const RecordDecl *RD = dyn_cast<RecordDecl>(Context)) {
601 if (!RD->isDependentType()) {
Eric Christopherf0890c42013-05-16 00:52:20 +0000602 llvm::DIType Ty =
603 getOrCreateLimitedType(CGM.getContext().getTypeDeclType(RD),
604 getOrCreateMainFile());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000605 return llvm::DIDescriptor(Ty);
606 }
607 }
608 return TheCU;
609}
610
David Blaikieb0f77b02013-05-24 21:33:22 +0000611/// getOrCreateTypeDeclaration - Create Pointee type. If Pointee is a record
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000612/// then emit record's fwd if debug info size reduction is enabled.
David Blaikieb0f77b02013-05-24 21:33:22 +0000613llvm::DIType CGDebugInfo::getOrCreateTypeDeclaration(QualType PointeeTy,
614 llvm::DIFile Unit) {
David Blaikie9faebd22013-05-20 04:58:53 +0000615 if (DebugKind > CodeGenOptions::LimitedDebugInfo)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000616 return getOrCreateType(PointeeTy, Unit);
David Blaikie5f6e2f42013-06-05 05:32:23 +0000617 return getOrCreateType(PointeeTy, Unit, true);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000618}
619
620llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag,
Eric Christopher6537f082013-05-16 00:45:12 +0000621 const Type *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000622 QualType PointeeTy,
623 llvm::DIFile Unit) {
624 if (Tag == llvm::dwarf::DW_TAG_reference_type ||
625 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
David Blaikieb0f77b02013-05-24 21:33:22 +0000626 return DBuilder.createReferenceType(
627 Tag, getOrCreateTypeDeclaration(PointeeTy, Unit));
Fariborz Jahanian05f8ff12013-02-21 20:42:11 +0000628
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000629 // Bit size, align and offset of the type.
630 // Size is always the size of a pointer. We can't use getTypeSize here
631 // because that does not return the correct value for references.
632 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCall64aa4b32013-04-16 22:48:15 +0000633 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000634 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
635
David Blaikieb0f77b02013-05-24 21:33:22 +0000636 return DBuilder.createPointerType(getOrCreateTypeDeclaration(PointeeTy, Unit),
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000637 Size, Align);
638}
639
Eric Christopherf0890c42013-05-16 00:52:20 +0000640llvm::DIType CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
641 llvm::DIType &Cache) {
David Blaikie1e97c1e2013-05-21 17:58:54 +0000642 if (Cache.Verify())
Guy Benyeib13621d2012-12-18 14:38:23 +0000643 return Cache;
David Blaikie1e97c1e2013-05-21 17:58:54 +0000644 Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
645 TheCU, getOrCreateMainFile(), 0);
646 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
647 Cache = DBuilder.createPointerType(Cache, Size);
648 return Cache;
Guy Benyeib13621d2012-12-18 14:38:23 +0000649}
650
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000651llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
652 llvm::DIFile Unit) {
653 if (BlockLiteralGenericSet)
654 return BlockLiteralGeneric;
655
656 SmallVector<llvm::Value *, 8> EltTys;
657 llvm::DIType FieldTy;
658 QualType FType;
659 uint64_t FieldSize, FieldOffset;
660 unsigned FieldAlign;
661 llvm::DIArray Elements;
662 llvm::DIType EltTy, DescTy;
663
664 FieldOffset = 0;
665 FType = CGM.getContext().UnsignedLongTy;
666 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
667 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
668
669 Elements = DBuilder.getOrCreateArray(EltTys);
670 EltTys.clear();
671
672 unsigned Flags = llvm::DIDescriptor::FlagAppleBlock;
673 unsigned LineNo = getLineNumber(CurLoc);
674
675 EltTy = DBuilder.createStructType(Unit, "__block_descriptor",
676 Unit, LineNo, FieldOffset, 0,
David Blaikiec1d0af12013-02-25 01:07:08 +0000677 Flags, llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000678
679 // Bit size, align and offset of the type.
680 uint64_t Size = CGM.getContext().getTypeSize(Ty);
681
682 DescTy = DBuilder.createPointerType(EltTy, Size);
683
684 FieldOffset = 0;
685 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
686 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
687 FType = CGM.getContext().IntTy;
688 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
689 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
690 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
691 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
692
693 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
694 FieldTy = DescTy;
695 FieldSize = CGM.getContext().getTypeSize(Ty);
696 FieldAlign = CGM.getContext().getTypeAlign(Ty);
697 FieldTy = DBuilder.createMemberType(Unit, "__descriptor", Unit,
698 LineNo, FieldSize, FieldAlign,
699 FieldOffset, 0, FieldTy);
700 EltTys.push_back(FieldTy);
701
702 FieldOffset += FieldSize;
703 Elements = DBuilder.getOrCreateArray(EltTys);
704
705 EltTy = DBuilder.createStructType(Unit, "__block_literal_generic",
706 Unit, LineNo, FieldOffset, 0,
David Blaikiec1d0af12013-02-25 01:07:08 +0000707 Flags, llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000708
709 BlockLiteralGenericSet = true;
710 BlockLiteralGeneric = DBuilder.createPointerType(EltTy, Size);
711 return BlockLiteralGeneric;
712}
713
David Blaikie5f6e2f42013-06-05 05:32:23 +0000714llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty, llvm::DIFile Unit,
715 bool Declaration) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000716 // Typedefs are derived from some other type. If we have a typedef of a
717 // typedef, make sure to emit the whole chain.
David Blaikieb0f77b02013-05-24 21:33:22 +0000718 llvm::DIType Src =
David Blaikie5f6e2f42013-06-05 05:32:23 +0000719 getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit, Declaration);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000720 if (!Src.Verify())
721 return llvm::DIType();
722 // We don't set size information, but do specify where the typedef was
723 // declared.
724 unsigned Line = getLineNumber(Ty->getDecl()->getLocation());
725 const TypedefNameDecl *TyDecl = Ty->getDecl();
Eric Christopher6537f082013-05-16 00:45:12 +0000726
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000727 llvm::DIDescriptor TypedefContext =
728 getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext()));
Eric Christopher6537f082013-05-16 00:45:12 +0000729
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000730 return
731 DBuilder.createTypedef(Src, TyDecl->getName(), Unit, Line, TypedefContext);
732}
733
734llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
735 llvm::DIFile Unit) {
736 SmallVector<llvm::Value *, 16> EltTys;
737
738 // Add the result type at least.
739 EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit));
740
741 // Set up remainder of arguments if there is a prototype.
742 // FIXME: IF NOT, HOW IS THIS REPRESENTED? llvm-gcc doesn't represent '...'!
743 if (isa<FunctionNoProtoType>(Ty))
744 EltTys.push_back(DBuilder.createUnspecifiedParameter());
745 else if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Ty)) {
746 for (unsigned i = 0, e = FPT->getNumArgs(); i != e; ++i)
747 EltTys.push_back(getOrCreateType(FPT->getArgType(i), Unit));
748 }
749
750 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
751 return DBuilder.createSubroutineType(Unit, EltTypeArray);
752}
753
754
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000755llvm::DIType CGDebugInfo::createFieldType(StringRef name,
756 QualType type,
757 uint64_t sizeInBitsOverride,
758 SourceLocation loc,
759 AccessSpecifier AS,
760 uint64_t offsetInBits,
761 llvm::DIFile tunit,
762 llvm::DIDescriptor scope) {
763 llvm::DIType debugType = getOrCreateType(type, tunit);
764
765 // Get the location for the field.
766 llvm::DIFile file = getOrCreateFile(loc);
767 unsigned line = getLineNumber(loc);
768
769 uint64_t sizeInBits = 0;
770 unsigned alignInBits = 0;
771 if (!type->isIncompleteArrayType()) {
772 llvm::tie(sizeInBits, alignInBits) = CGM.getContext().getTypeInfo(type);
773
774 if (sizeInBitsOverride)
775 sizeInBits = sizeInBitsOverride;
776 }
777
778 unsigned flags = 0;
779 if (AS == clang::AS_private)
780 flags |= llvm::DIDescriptor::FlagPrivate;
781 else if (AS == clang::AS_protected)
782 flags |= llvm::DIDescriptor::FlagProtected;
783
784 return DBuilder.createMemberType(scope, name, file, line, sizeInBits,
785 alignInBits, offsetInBits, flags, debugType);
786}
787
Eric Christopher0395de32013-01-16 01:22:32 +0000788/// CollectRecordLambdaFields - Helper for CollectRecordFields.
789void CGDebugInfo::
790CollectRecordLambdaFields(const CXXRecordDecl *CXXDecl,
791 SmallVectorImpl<llvm::Value *> &elements,
792 llvm::DIType RecordTy) {
793 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
794 // has the name and the location of the variable so we should iterate over
795 // both concurrently.
796 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
797 RecordDecl::field_iterator Field = CXXDecl->field_begin();
798 unsigned fieldno = 0;
799 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
800 E = CXXDecl->captures_end(); I != E; ++I, ++Field, ++fieldno) {
801 const LambdaExpr::Capture C = *I;
802 if (C.capturesVariable()) {
803 VarDecl *V = C.getCapturedVar();
804 llvm::DIFile VUnit = getOrCreateFile(C.getLocation());
805 StringRef VName = V->getName();
806 uint64_t SizeInBitsOverride = 0;
807 if (Field->isBitField()) {
808 SizeInBitsOverride = Field->getBitWidthValue(CGM.getContext());
809 assert(SizeInBitsOverride && "found named 0-width bitfield");
810 }
811 llvm::DIType fieldType
812 = createFieldType(VName, Field->getType(), SizeInBitsOverride,
813 C.getLocation(), Field->getAccess(),
814 layout.getFieldOffset(fieldno), VUnit, RecordTy);
815 elements.push_back(fieldType);
816 } else {
817 // TODO: Need to handle 'this' in some way by probably renaming the
818 // this of the lambda class and having a field member of 'this' or
819 // by using AT_object_pointer for the function and having that be
820 // used as 'this' for semantic references.
821 assert(C.capturesThis() && "Field that isn't captured and isn't this?");
822 FieldDecl *f = *Field;
823 llvm::DIFile VUnit = getOrCreateFile(f->getLocation());
824 QualType type = f->getType();
825 llvm::DIType fieldType
826 = createFieldType("this", type, 0, f->getLocation(), f->getAccess(),
827 layout.getFieldOffset(fieldno), VUnit, RecordTy);
828
829 elements.push_back(fieldType);
830 }
831 }
832}
833
834/// CollectRecordStaticField - Helper for CollectRecordFields.
835void CGDebugInfo::
836CollectRecordStaticField(const VarDecl *Var,
837 SmallVectorImpl<llvm::Value *> &elements,
838 llvm::DIType RecordTy) {
839 // Create the descriptor for the static variable, with or without
840 // constant initializers.
841 llvm::DIFile VUnit = getOrCreateFile(Var->getLocation());
842 llvm::DIType VTy = getOrCreateType(Var->getType(), VUnit);
843
844 // Do not describe enums as static members.
845 if (VTy.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
846 return;
847
848 unsigned LineNumber = getLineNumber(Var->getLocation());
849 StringRef VName = Var->getName();
David Blaikiea89701b2013-01-20 01:19:17 +0000850 llvm::Constant *C = NULL;
Eric Christopher0395de32013-01-16 01:22:32 +0000851 if (Var->getInit()) {
852 const APValue *Value = Var->evaluateValue();
David Blaikiea89701b2013-01-20 01:19:17 +0000853 if (Value) {
854 if (Value->isInt())
855 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
856 if (Value->isFloat())
857 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
858 }
Eric Christopher0395de32013-01-16 01:22:32 +0000859 }
860
861 unsigned Flags = 0;
862 AccessSpecifier Access = Var->getAccess();
863 if (Access == clang::AS_private)
864 Flags |= llvm::DIDescriptor::FlagPrivate;
865 else if (Access == clang::AS_protected)
866 Flags |= llvm::DIDescriptor::FlagProtected;
867
868 llvm::DIType GV = DBuilder.createStaticMemberType(RecordTy, VName, VUnit,
David Blaikiea89701b2013-01-20 01:19:17 +0000869 LineNumber, VTy, Flags, C);
Eric Christopher0395de32013-01-16 01:22:32 +0000870 elements.push_back(GV);
871 StaticDataMemberCache[Var->getCanonicalDecl()] = llvm::WeakVH(GV);
872}
873
874/// CollectRecordNormalField - Helper for CollectRecordFields.
875void CGDebugInfo::
876CollectRecordNormalField(const FieldDecl *field, uint64_t OffsetInBits,
877 llvm::DIFile tunit,
878 SmallVectorImpl<llvm::Value *> &elements,
879 llvm::DIType RecordTy) {
880 StringRef name = field->getName();
881 QualType type = field->getType();
882
883 // Ignore unnamed fields unless they're anonymous structs/unions.
884 if (name.empty() && !type->isRecordType())
885 return;
886
887 uint64_t SizeInBitsOverride = 0;
888 if (field->isBitField()) {
889 SizeInBitsOverride = field->getBitWidthValue(CGM.getContext());
890 assert(SizeInBitsOverride && "found named 0-width bitfield");
891 }
892
893 llvm::DIType fieldType
894 = createFieldType(name, type, SizeInBitsOverride,
895 field->getLocation(), field->getAccess(),
896 OffsetInBits, tunit, RecordTy);
897
898 elements.push_back(fieldType);
899}
900
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000901/// CollectRecordFields - A helper function to collect debug info for
902/// record fields. This is used while creating debug info entry for a Record.
903void CGDebugInfo::
904CollectRecordFields(const RecordDecl *record, llvm::DIFile tunit,
905 SmallVectorImpl<llvm::Value *> &elements,
906 llvm::DIType RecordTy) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000907 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(record);
908
Eric Christopher0395de32013-01-16 01:22:32 +0000909 if (CXXDecl && CXXDecl->isLambda())
910 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
911 else {
912 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000913
Eric Christopher0395de32013-01-16 01:22:32 +0000914 // Field number for non-static fields.
Eric Christopherfd5ac0d2013-01-04 17:59:07 +0000915 unsigned fieldNo = 0;
Eric Christopher0395de32013-01-16 01:22:32 +0000916
Eric Christopher0395de32013-01-16 01:22:32 +0000917 // Static and non-static members should appear in the same order as
918 // the corresponding declarations in the source program.
919 for (RecordDecl::decl_iterator I = record->decls_begin(),
920 E = record->decls_end(); I != E; ++I)
921 if (const VarDecl *V = dyn_cast<VarDecl>(*I))
922 CollectRecordStaticField(V, elements, RecordTy);
923 else if (FieldDecl *field = dyn_cast<FieldDecl>(*I)) {
Eric Christopher0395de32013-01-16 01:22:32 +0000924 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo),
925 tunit, elements, RecordTy);
926
927 // Bump field number for next field.
928 ++fieldNo;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000929 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000930 }
931}
932
933/// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
934/// function type is not updated to include implicit "this" pointer. Use this
935/// routine to get a method type which includes "this" pointer.
David Blaikie9a845292013-05-22 23:22:42 +0000936llvm::DICompositeType
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000937CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
938 llvm::DIFile Unit) {
David Blaikie9c78f9b2013-01-07 23:06:35 +0000939 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
David Blaikie67f8b5e2013-01-07 22:24:59 +0000940 if (Method->isStatic())
David Blaikie9a845292013-05-22 23:22:42 +0000941 return llvm::DICompositeType(getOrCreateType(QualType(Func, 0), Unit));
David Blaikie9c78f9b2013-01-07 23:06:35 +0000942 return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()),
943 Func, Unit);
944}
David Blaikie67f8b5e2013-01-07 22:24:59 +0000945
David Blaikie9a845292013-05-22 23:22:42 +0000946llvm::DICompositeType CGDebugInfo::getOrCreateInstanceMethodType(
David Blaikie9c78f9b2013-01-07 23:06:35 +0000947 QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile Unit) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000948 // Add "this" pointer.
David Blaikie9c78f9b2013-01-07 23:06:35 +0000949 llvm::DIArray Args = llvm::DICompositeType(
950 getOrCreateType(QualType(Func, 0), Unit)).getTypeArray();
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000951 assert (Args.getNumElements() && "Invalid number of arguments!");
952
953 SmallVector<llvm::Value *, 16> Elts;
954
955 // First element is always return type. For 'void' functions it is NULL.
956 Elts.push_back(Args.getElement(0));
957
David Blaikie67f8b5e2013-01-07 22:24:59 +0000958 // "this" pointer is always first argument.
David Blaikie9c78f9b2013-01-07 23:06:35 +0000959 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
David Blaikie67f8b5e2013-01-07 22:24:59 +0000960 if (isa<ClassTemplateSpecializationDecl>(RD)) {
961 // Create pointer type directly in this case.
962 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
963 QualType PointeeTy = ThisPtrTy->getPointeeType();
964 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCall64aa4b32013-04-16 22:48:15 +0000965 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
David Blaikie67f8b5e2013-01-07 22:24:59 +0000966 uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy);
967 llvm::DIType PointeeType = getOrCreateType(PointeeTy, Unit);
Eric Christopherf0890c42013-05-16 00:52:20 +0000968 llvm::DIType ThisPtrType =
969 DBuilder.createPointerType(PointeeType, Size, Align);
David Blaikie67f8b5e2013-01-07 22:24:59 +0000970 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
971 // TODO: This and the artificial type below are misleading, the
972 // types aren't artificial the argument is, but the current
973 // metadata doesn't represent that.
974 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
975 Elts.push_back(ThisPtrType);
976 } else {
977 llvm::DIType ThisPtrType = getOrCreateType(ThisPtr, Unit);
978 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
979 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
980 Elts.push_back(ThisPtrType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000981 }
982
983 // Copy rest of the arguments.
984 for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
985 Elts.push_back(Args.getElement(i));
986
987 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
988
989 return DBuilder.createSubroutineType(Unit, EltTypeArray);
990}
991
Eric Christopher6537f082013-05-16 00:45:12 +0000992/// isFunctionLocalClass - Return true if CXXRecordDecl is defined
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000993/// inside a function.
994static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
995 if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
996 return isFunctionLocalClass(NRD);
997 if (isa<FunctionDecl>(RD->getDeclContext()))
998 return true;
999 return false;
1000}
1001
1002/// CreateCXXMemberFunction - A helper function to create a DISubprogram for
1003/// a single member function GlobalDecl.
1004llvm::DISubprogram
1005CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
1006 llvm::DIFile Unit,
1007 llvm::DIType RecordTy) {
Eric Christopher6537f082013-05-16 00:45:12 +00001008 bool IsCtorOrDtor =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001009 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
Eric Christopher6537f082013-05-16 00:45:12 +00001010
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001011 StringRef MethodName = getFunctionName(Method);
David Blaikie9a845292013-05-22 23:22:42 +00001012 llvm::DICompositeType MethodTy = getOrCreateMethodType(Method, Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001013
1014 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1015 // make sense to give a single ctor/dtor a linkage name.
1016 StringRef MethodLinkageName;
1017 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1018 MethodLinkageName = CGM.getMangledName(Method);
1019
1020 // Get the location for the method.
1021 llvm::DIFile MethodDefUnit = getOrCreateFile(Method->getLocation());
1022 unsigned MethodLine = getLineNumber(Method->getLocation());
1023
1024 // Collect virtual method info.
1025 llvm::DIType ContainingType;
Eric Christopher6537f082013-05-16 00:45:12 +00001026 unsigned Virtuality = 0;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001027 unsigned VIndex = 0;
Eric Christopher6537f082013-05-16 00:45:12 +00001028
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001029 if (Method->isVirtual()) {
1030 if (Method->isPure())
1031 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
1032 else
1033 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
Eric Christopher6537f082013-05-16 00:45:12 +00001034
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001035 // It doesn't make sense to give a virtual destructor a vtable index,
1036 // since a single destructor has two entries in the vtable.
1037 if (!isa<CXXDestructorDecl>(Method))
1038 VIndex = CGM.getVTableContext().getMethodVTableIndex(Method);
1039 ContainingType = RecordTy;
1040 }
1041
1042 unsigned Flags = 0;
1043 if (Method->isImplicit())
1044 Flags |= llvm::DIDescriptor::FlagArtificial;
1045 AccessSpecifier Access = Method->getAccess();
1046 if (Access == clang::AS_private)
1047 Flags |= llvm::DIDescriptor::FlagPrivate;
1048 else if (Access == clang::AS_protected)
1049 Flags |= llvm::DIDescriptor::FlagProtected;
1050 if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1051 if (CXXC->isExplicit())
1052 Flags |= llvm::DIDescriptor::FlagExplicit;
Eric Christopher6537f082013-05-16 00:45:12 +00001053 } else if (const CXXConversionDecl *CXXC =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001054 dyn_cast<CXXConversionDecl>(Method)) {
1055 if (CXXC->isExplicit())
1056 Flags |= llvm::DIDescriptor::FlagExplicit;
1057 }
1058 if (Method->hasPrototype())
1059 Flags |= llvm::DIDescriptor::FlagPrototyped;
1060
1061 llvm::DIArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1062 llvm::DISubprogram SP =
Eric Christopher6537f082013-05-16 00:45:12 +00001063 DBuilder.createMethod(RecordTy, MethodName, MethodLinkageName,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001064 MethodDefUnit, MethodLine,
Eric Christopher6537f082013-05-16 00:45:12 +00001065 MethodTy, /*isLocalToUnit=*/false,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001066 /* isDefinition=*/ false,
1067 Virtuality, VIndex, ContainingType,
1068 Flags, CGM.getLangOpts().Optimize, NULL,
1069 TParamsArray);
Eric Christopher6537f082013-05-16 00:45:12 +00001070
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001071 SPCache[Method->getCanonicalDecl()] = llvm::WeakVH(SP);
1072
1073 return SP;
1074}
1075
1076/// CollectCXXMemberFunctions - A helper function to collect debug info for
Eric Christopher6537f082013-05-16 00:45:12 +00001077/// C++ member functions. This is used while creating debug info entry for
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001078/// a Record.
1079void CGDebugInfo::
1080CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
1081 SmallVectorImpl<llvm::Value *> &EltTys,
1082 llvm::DIType RecordTy) {
1083
1084 // Since we want more than just the individual member decls if we
1085 // have templated functions iterate over every declaration to gather
1086 // the functions.
1087 for(DeclContext::decl_iterator I = RD->decls_begin(),
1088 E = RD->decls_end(); I != E; ++I) {
1089 Decl *D = *I;
1090 if (D->isImplicit() && !D->isUsed())
1091 continue;
1092
1093 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1094 EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
1095 else if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
1096 for (FunctionTemplateDecl::spec_iterator SI = FTD->spec_begin(),
1097 SE = FTD->spec_end(); SI != SE; ++SI)
1098 EltTys.push_back(CreateCXXMemberFunction(cast<CXXMethodDecl>(*SI), Unit,
1099 RecordTy));
1100 }
Eric Christopher6537f082013-05-16 00:45:12 +00001101}
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001102
1103/// CollectCXXFriends - A helper function to collect debug info for
1104/// C++ base classes. This is used while creating debug info entry for
1105/// a Record.
1106void CGDebugInfo::
1107CollectCXXFriends(const CXXRecordDecl *RD, llvm::DIFile Unit,
1108 SmallVectorImpl<llvm::Value *> &EltTys,
1109 llvm::DIType RecordTy) {
1110 for (CXXRecordDecl::friend_iterator BI = RD->friend_begin(),
1111 BE = RD->friend_end(); BI != BE; ++BI) {
1112 if ((*BI)->isUnsupportedFriend())
1113 continue;
1114 if (TypeSourceInfo *TInfo = (*BI)->getFriendType())
Eric Christopher6537f082013-05-16 00:45:12 +00001115 EltTys.push_back(DBuilder.createFriend(RecordTy,
1116 getOrCreateType(TInfo->getType(),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001117 Unit)));
1118 }
1119}
1120
1121/// CollectCXXBases - A helper function to collect debug info for
Eric Christopher6537f082013-05-16 00:45:12 +00001122/// C++ base classes. This is used while creating debug info entry for
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001123/// a Record.
1124void CGDebugInfo::
1125CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
1126 SmallVectorImpl<llvm::Value *> &EltTys,
1127 llvm::DIType RecordTy) {
1128
1129 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1130 for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
1131 BE = RD->bases_end(); BI != BE; ++BI) {
1132 unsigned BFlags = 0;
1133 uint64_t BaseOffset;
Eric Christopher6537f082013-05-16 00:45:12 +00001134
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001135 const CXXRecordDecl *Base =
1136 cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl());
Eric Christopher6537f082013-05-16 00:45:12 +00001137
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001138 if (BI->isVirtual()) {
1139 // virtual base offset offset is -ve. The code generator emits dwarf
1140 // expression where it expects +ve number.
Eric Christopher6537f082013-05-16 00:45:12 +00001141 BaseOffset =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001142 0 - CGM.getVTableContext()
1143 .getVirtualBaseOffsetOffset(RD, Base).getQuantity();
1144 BFlags = llvm::DIDescriptor::FlagVirtual;
1145 } else
1146 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1147 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1148 // BI->isVirtual() and bits when not.
Eric Christopher6537f082013-05-16 00:45:12 +00001149
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001150 AccessSpecifier Access = BI->getAccessSpecifier();
1151 if (Access == clang::AS_private)
1152 BFlags |= llvm::DIDescriptor::FlagPrivate;
1153 else if (Access == clang::AS_protected)
1154 BFlags |= llvm::DIDescriptor::FlagProtected;
Eric Christopher6537f082013-05-16 00:45:12 +00001155
1156 llvm::DIType DTy =
1157 DBuilder.createInheritance(RecordTy,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001158 getOrCreateType(BI->getType(), Unit),
1159 BaseOffset, BFlags);
1160 EltTys.push_back(DTy);
1161 }
1162}
1163
1164/// CollectTemplateParams - A helper function to collect template parameters.
1165llvm::DIArray CGDebugInfo::
1166CollectTemplateParams(const TemplateParameterList *TPList,
David Blaikie35178dc2013-06-22 18:59:18 +00001167 ArrayRef<TemplateArgument> TAList,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001168 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +00001169 SmallVector<llvm::Value *, 16> TemplateParams;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001170 for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1171 const TemplateArgument &TA = TAList[i];
David Blaikie35178dc2013-06-22 18:59:18 +00001172 StringRef Name;
1173 if (TPList)
1174 Name = TPList->getParam(i)->getName();
David Blaikie9dfd2432013-05-10 21:53:14 +00001175 switch (TA.getKind()) {
1176 case TemplateArgument::Type: {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001177 llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit);
1178 llvm::DITemplateTypeParameter TTP =
David Blaikie35178dc2013-06-22 18:59:18 +00001179 DBuilder.createTemplateTypeParameter(TheCU, Name, TTy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001180 TemplateParams.push_back(TTP);
David Blaikie9dfd2432013-05-10 21:53:14 +00001181 } break;
1182 case TemplateArgument::Integral: {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001183 llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit);
1184 llvm::DITemplateValueParameter TVP =
David Blaikie9dfd2432013-05-10 21:53:14 +00001185 DBuilder.createTemplateValueParameter(
David Blaikie35178dc2013-06-22 18:59:18 +00001186 TheCU, Name, TTy,
David Blaikie9dfd2432013-05-10 21:53:14 +00001187 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral()));
1188 TemplateParams.push_back(TVP);
1189 } break;
1190 case TemplateArgument::Declaration: {
1191 const ValueDecl *D = TA.getAsDecl();
1192 bool InstanceMember = D->isCXXInstanceMember();
1193 QualType T = InstanceMember
1194 ? CGM.getContext().getMemberPointerType(
1195 D->getType(), cast<RecordDecl>(D->getDeclContext())
1196 ->getTypeForDecl())
1197 : CGM.getContext().getPointerType(D->getType());
1198 llvm::DIType TTy = getOrCreateType(T, Unit);
1199 llvm::Value *V = 0;
1200 // Variable pointer template parameters have a value that is the address
1201 // of the variable.
1202 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1203 V = CGM.GetAddrOfGlobalVar(VD);
1204 // Member function pointers have special support for building them, though
1205 // this is currently unsupported in LLVM CodeGen.
David Blaikief8aa1552013-05-13 06:57:50 +00001206 if (InstanceMember) {
David Blaikie9dfd2432013-05-10 21:53:14 +00001207 if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(D))
1208 V = CGM.getCXXABI().EmitMemberPointer(method);
David Blaikief8aa1552013-05-13 06:57:50 +00001209 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1210 V = CGM.GetAddrOfFunction(FD);
David Blaikie9dfd2432013-05-10 21:53:14 +00001211 // Member data pointers have special handling too to compute the fixed
1212 // offset within the object.
1213 if (isa<FieldDecl>(D)) {
1214 // These five lines (& possibly the above member function pointer
1215 // handling) might be able to be refactored to use similar code in
1216 // CodeGenModule::getMemberPointerConstant
1217 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
1218 CharUnits chars =
1219 CGM.getContext().toCharUnitsFromBits((int64_t) fieldOffset);
1220 V = CGM.getCXXABI().EmitMemberDataPointer(
1221 cast<MemberPointerType>(T.getTypePtr()), chars);
1222 }
1223 llvm::DITemplateValueParameter TVP =
David Blaikie35178dc2013-06-22 18:59:18 +00001224 DBuilder.createTemplateValueParameter(TheCU, Name, TTy, V);
David Blaikie9dfd2432013-05-10 21:53:14 +00001225 TemplateParams.push_back(TVP);
1226 } break;
1227 case TemplateArgument::NullPtr: {
1228 QualType T = TA.getNullPtrType();
1229 llvm::DIType TTy = getOrCreateType(T, Unit);
1230 llvm::Value *V = 0;
1231 // Special case member data pointer null values since they're actually -1
1232 // instead of zero.
1233 if (const MemberPointerType *MPT =
1234 dyn_cast<MemberPointerType>(T.getTypePtr()))
1235 // But treat member function pointers as simple zero integers because
1236 // it's easier than having a special case in LLVM's CodeGen. If LLVM
1237 // CodeGen grows handling for values of non-null member function
1238 // pointers then perhaps we could remove this special case and rely on
1239 // EmitNullMemberPointer for member function pointers.
1240 if (MPT->isMemberDataPointer())
1241 V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1242 if (!V)
1243 V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
1244 llvm::DITemplateValueParameter TVP =
David Blaikie35178dc2013-06-22 18:59:18 +00001245 DBuilder.createTemplateValueParameter(TheCU, Name, TTy, V);
David Blaikie9dfd2432013-05-10 21:53:14 +00001246 TemplateParams.push_back(TVP);
1247 } break;
David Blaikie35178dc2013-06-22 18:59:18 +00001248 case TemplateArgument::Template: {
1249 llvm::DITemplateValueParameter TVP =
1250 DBuilder.createTemplateTemplateParameter(
1251 TheCU, Name, llvm::DIType(),
1252 TA.getAsTemplate().getAsTemplateDecl()
1253 ->getQualifiedNameAsString());
1254 TemplateParams.push_back(TVP);
1255 } break;
1256 case TemplateArgument::Pack: {
1257 llvm::DITemplateValueParameter TVP =
1258 DBuilder.createTemplateParameterPack(
1259 TheCU, Name, llvm::DIType(),
1260 CollectTemplateParams(NULL, TA.getPackAsArray(), Unit));
1261 TemplateParams.push_back(TVP);
1262 } break;
David Blaikiee8065122013-05-10 23:36:06 +00001263 // And the following should never occur:
David Blaikie9dfd2432013-05-10 21:53:14 +00001264 case TemplateArgument::Expression:
1265 case TemplateArgument::TemplateExpansion:
David Blaikie9dfd2432013-05-10 21:53:14 +00001266 case TemplateArgument::Null:
1267 llvm_unreachable(
1268 "These argument types shouldn't exist in concrete types");
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001269 }
1270 }
1271 return DBuilder.getOrCreateArray(TemplateParams);
1272}
1273
1274/// CollectFunctionTemplateParams - A helper function to collect debug
1275/// info for function template parameters.
1276llvm::DIArray CGDebugInfo::
1277CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) {
1278 if (FD->getTemplatedKind() ==
1279 FunctionDecl::TK_FunctionTemplateSpecialization) {
1280 const TemplateParameterList *TList =
1281 FD->getTemplateSpecializationInfo()->getTemplate()
1282 ->getTemplateParameters();
David Blaikie35178dc2013-06-22 18:59:18 +00001283 return CollectTemplateParams(
1284 TList, FD->getTemplateSpecializationArgs()->asArray(), Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001285 }
1286 return llvm::DIArray();
1287}
1288
1289/// CollectCXXTemplateParams - A helper function to collect debug info for
1290/// template parameters.
1291llvm::DIArray CGDebugInfo::
1292CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial,
1293 llvm::DIFile Unit) {
1294 llvm::PointerUnion<ClassTemplateDecl *,
1295 ClassTemplatePartialSpecializationDecl *>
1296 PU = TSpecial->getSpecializedTemplateOrPartial();
Eric Christopher6537f082013-05-16 00:45:12 +00001297
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001298 TemplateParameterList *TPList = PU.is<ClassTemplateDecl *>() ?
1299 PU.get<ClassTemplateDecl *>()->getTemplateParameters() :
1300 PU.get<ClassTemplatePartialSpecializationDecl *>()->getTemplateParameters();
1301 const TemplateArgumentList &TAList = TSpecial->getTemplateInstantiationArgs();
David Blaikie35178dc2013-06-22 18:59:18 +00001302 return CollectTemplateParams(TPList, TAList.asArray(), Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001303}
1304
1305/// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
1306llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
1307 if (VTablePtrType.isValid())
1308 return VTablePtrType;
1309
1310 ASTContext &Context = CGM.getContext();
1311
1312 /* Function type */
1313 llvm::Value *STy = getOrCreateType(Context.IntTy, Unit);
1314 llvm::DIArray SElements = DBuilder.getOrCreateArray(STy);
1315 llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements);
1316 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1317 llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0,
1318 "__vtbl_ptr_type");
1319 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1320 return VTablePtrType;
1321}
1322
1323/// getVTableName - Get vtable name for the given Class.
1324StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
1325 // Construct gdb compatible name name.
1326 std::string Name = "_vptr$" + RD->getNameAsString();
1327
1328 // Copy this name on the side and use its reference.
1329 char *StrPtr = DebugInfoNames.Allocate<char>(Name.length());
1330 memcpy(StrPtr, Name.data(), Name.length());
1331 return StringRef(StrPtr, Name.length());
1332}
1333
1334
1335/// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
1336/// debug info entry in EltTys vector.
1337void CGDebugInfo::
1338CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
1339 SmallVectorImpl<llvm::Value *> &EltTys) {
1340 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1341
1342 // If there is a primary base then it will hold vtable info.
1343 if (RL.getPrimaryBase())
1344 return;
1345
1346 // If this class is not dynamic then there is not any vtable info to collect.
1347 if (!RD->isDynamicClass())
1348 return;
1349
1350 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1351 llvm::DIType VPTR
1352 = DBuilder.createMemberType(Unit, getVTableName(RD), Unit,
Eric Christopherf0890c42013-05-16 00:52:20 +00001353 0, Size, 0, 0,
1354 llvm::DIDescriptor::FlagArtificial,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001355 getOrCreateVTablePtrType(Unit));
1356 EltTys.push_back(VPTR);
1357}
1358
Eric Christopher6537f082013-05-16 00:45:12 +00001359/// getOrCreateRecordType - Emit record type's standalone debug info.
1360llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001361 SourceLocation Loc) {
Eric Christopher13c97672013-05-16 00:45:23 +00001362 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001363 llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc));
1364 return T;
1365}
1366
1367/// getOrCreateInterfaceType - Emit an objective c interface type standalone
1368/// debug info.
1369llvm::DIType CGDebugInfo::getOrCreateInterfaceType(QualType D,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001370 SourceLocation Loc) {
Eric Christopher13c97672013-05-16 00:45:23 +00001371 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001372 llvm::DIType T = getOrCreateType(D, getOrCreateFile(Loc));
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001373 RetainedTypes.push_back(D.getAsOpaquePtr());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001374 return T;
1375}
1376
1377/// CreateType - get structure or union type.
David Blaikie5f6e2f42013-06-05 05:32:23 +00001378llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty, bool Declaration) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001379 RecordDecl *RD = Ty->getDecl();
Adrian Prantl776bfa12013-06-18 23:32:21 +00001380 // Limited debug info should only remove struct definitions that can
1381 // safely be replaced by a forward declaration in the source code.
Adrian Prantl14c1a132013-06-18 23:01:56 +00001382 if (DebugKind <= CodeGenOptions::LimitedDebugInfo && Declaration) {
Adrian Prantl776bfa12013-06-18 23:32:21 +00001383 // FIXME: This implementation is problematic; there are some test
1384 // cases where we violate the above principle, such as
1385 // test/CodeGen/debug-info-records.c .
David Blaikie5f6e2f42013-06-05 05:32:23 +00001386 llvm::DIDescriptor FDContext =
1387 getContextDescriptor(cast<Decl>(RD->getDeclContext()));
1388 llvm::DIType RetTy = createRecordFwdDecl(RD, FDContext);
1389 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RetTy;
1390 return RetTy;
1391 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001392
1393 // Get overall information about the record type for the debug info.
1394 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1395
1396 // Records and classes and unions can all be recursive. To handle them, we
1397 // first generate a debug descriptor for the struct as a forward declaration.
1398 // Then (if it is a definition) we go through and get debug info for all of
1399 // its members. Finally, we create a descriptor for the complete type (which
1400 // may refer to the forward decl if the struct is recursive) and replace all
1401 // uses of the forward declaration with the final definition.
1402
Eric Christopherf068c922013-04-02 22:59:11 +00001403 llvm::DICompositeType FwdDecl(
1404 getOrCreateLimitedType(QualType(Ty, 0), DefUnit));
1405 assert(FwdDecl.Verify() &&
David Blaikie9a845292013-05-22 23:22:42 +00001406 "The debug type of a RecordType should be a llvm::DICompositeType");
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001407
1408 if (FwdDecl.isForwardDecl())
1409 return FwdDecl;
1410
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001411 // Push the struct on region stack.
Eric Christopherf068c922013-04-02 22:59:11 +00001412 LexicalBlockStack.push_back(&*FwdDecl);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001413 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1414
Adrian Prantl4919de62013-03-06 22:03:30 +00001415 // Add this to the completed-type cache while we're completing it recursively.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001416 CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1417
1418 // Convert all the elements.
1419 SmallVector<llvm::Value *, 16> EltTys;
1420
1421 // Note: The split of CXXDecl information here is intentional, the
1422 // gdb tests will depend on a certain ordering at printout. The debug
1423 // information offsets are still correct if we merge them all together
1424 // though.
1425 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1426 if (CXXDecl) {
1427 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1428 CollectVTableInfo(CXXDecl, DefUnit, EltTys);
1429 }
1430
Eric Christopher0395de32013-01-16 01:22:32 +00001431 // Collect data fields (including static variables and any initializers).
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001432 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
1433 llvm::DIArray TParamsArray;
1434 if (CXXDecl) {
1435 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
1436 CollectCXXFriends(CXXDecl, DefUnit, EltTys, FwdDecl);
1437 if (const ClassTemplateSpecializationDecl *TSpecial
1438 = dyn_cast<ClassTemplateSpecializationDecl>(RD))
1439 TParamsArray = CollectCXXTemplateParams(TSpecial, DefUnit);
1440 }
1441
1442 LexicalBlockStack.pop_back();
1443 RegionMap.erase(Ty->getDecl());
1444
1445 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopherf068c922013-04-02 22:59:11 +00001446 FwdDecl.setTypeArray(Elements, TParamsArray);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001447
Eric Christopherf068c922013-04-02 22:59:11 +00001448 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1449 return FwdDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001450}
1451
1452/// CreateType - get objective-c object type.
1453llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1454 llvm::DIFile Unit) {
1455 // Ignore protocols.
1456 return getOrCreateType(Ty->getBaseType(), Unit);
1457}
1458
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001459
1460/// \return true if Getter has the default name for the property PD.
1461static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
1462 const ObjCMethodDecl *Getter) {
1463 assert(PD);
1464 if (!Getter)
1465 return true;
1466
1467 assert(Getter->getDeclName().isObjCZeroArgSelector());
1468 return PD->getName() ==
1469 Getter->getDeclName().getObjCSelector().getNameForSlot(0);
1470}
1471
1472/// \return true if Setter has the default name for the property PD.
1473static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
1474 const ObjCMethodDecl *Setter) {
1475 assert(PD);
1476 if (!Setter)
1477 return true;
1478
1479 assert(Setter->getDeclName().isObjCOneArgSelector());
Adrian Prantl80e8ea92013-06-07 22:29:12 +00001480 return SelectorTable::constructSetterName(PD->getName()) ==
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001481 Setter->getDeclName().getObjCSelector().getNameForSlot(0);
1482}
1483
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001484/// CreateType - get objective-c interface type.
1485llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1486 llvm::DIFile Unit) {
1487 ObjCInterfaceDecl *ID = Ty->getDecl();
1488 if (!ID)
1489 return llvm::DIType();
1490
1491 // Get overall information about the record type for the debug info.
1492 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1493 unsigned Line = getLineNumber(ID->getLocation());
1494 unsigned RuntimeLang = TheCU.getLanguage();
1495
1496 // If this is just a forward declaration return a special forward-declaration
1497 // debug type since we won't be able to lay out the entire type.
1498 ObjCInterfaceDecl *Def = ID->getDefinition();
1499 if (!Def) {
1500 llvm::DIType FwdDecl =
1501 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001502 ID->getName(), TheCU, DefUnit, Line,
1503 RuntimeLang);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001504 return FwdDecl;
1505 }
1506
1507 ID = Def;
1508
1509 // Bit size, align and offset of the type.
1510 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1511 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1512
1513 unsigned Flags = 0;
1514 if (ID->getImplementation())
1515 Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
1516
Eric Christopherf068c922013-04-02 22:59:11 +00001517 llvm::DICompositeType RealDecl =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001518 DBuilder.createStructType(Unit, ID->getName(), DefUnit,
1519 Line, Size, Align, Flags,
David Blaikiec1d0af12013-02-25 01:07:08 +00001520 llvm::DIType(), llvm::DIArray(), RuntimeLang);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001521
1522 // Otherwise, insert it into the CompletedTypeCache so that recursive uses
1523 // will find it and we're emitting the complete type.
Adrian Prantl4919de62013-03-06 22:03:30 +00001524 QualType QualTy = QualType(Ty, 0);
1525 CompletedTypeCache[QualTy.getAsOpaquePtr()] = RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001526 // Push the struct on region stack.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001527
Eric Christopherf068c922013-04-02 22:59:11 +00001528 LexicalBlockStack.push_back(static_cast<llvm::MDNode*>(RealDecl));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001529 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1530
1531 // Convert all the elements.
1532 SmallVector<llvm::Value *, 16> EltTys;
1533
1534 ObjCInterfaceDecl *SClass = ID->getSuperClass();
1535 if (SClass) {
1536 llvm::DIType SClassTy =
1537 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1538 if (!SClassTy.isValid())
1539 return llvm::DIType();
Eric Christopher6537f082013-05-16 00:45:12 +00001540
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001541 llvm::DIType InhTag =
1542 DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
1543 EltTys.push_back(InhTag);
1544 }
1545
1546 for (ObjCContainerDecl::prop_iterator I = ID->prop_begin(),
1547 E = ID->prop_end(); I != E; ++I) {
1548 const ObjCPropertyDecl *PD = *I;
1549 SourceLocation Loc = PD->getLocation();
1550 llvm::DIFile PUnit = getOrCreateFile(Loc);
1551 unsigned PLine = getLineNumber(Loc);
1552 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1553 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1554 llvm::MDNode *PropertyNode =
1555 DBuilder.createObjCProperty(PD->getName(),
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001556 PUnit, PLine,
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001557 hasDefaultGetterName(PD, Getter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001558 getSelectorName(PD->getGetterName()),
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001559 hasDefaultSetterName(PD, Setter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001560 getSelectorName(PD->getSetterName()),
1561 PD->getPropertyAttributes(),
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001562 getOrCreateType(PD->getType(), PUnit));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001563 EltTys.push_back(PropertyNode);
1564 }
1565
1566 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1567 unsigned FieldNo = 0;
1568 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1569 Field = Field->getNextIvar(), ++FieldNo) {
1570 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1571 if (!FieldTy.isValid())
1572 return llvm::DIType();
Eric Christopher6537f082013-05-16 00:45:12 +00001573
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001574 StringRef FieldName = Field->getName();
1575
1576 // Ignore unnamed fields.
1577 if (FieldName.empty())
1578 continue;
1579
1580 // Get the location for the field.
1581 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1582 unsigned FieldLine = getLineNumber(Field->getLocation());
1583 QualType FType = Field->getType();
1584 uint64_t FieldSize = 0;
1585 unsigned FieldAlign = 0;
1586
1587 if (!FType->isIncompleteArrayType()) {
1588
1589 // Bit size, align and offset of the type.
1590 FieldSize = Field->isBitField()
1591 ? Field->getBitWidthValue(CGM.getContext())
1592 : CGM.getContext().getTypeSize(FType);
1593 FieldAlign = CGM.getContext().getTypeAlign(FType);
1594 }
1595
1596 uint64_t FieldOffset;
1597 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1598 // We don't know the runtime offset of an ivar if we're using the
1599 // non-fragile ABI. For bitfields, use the bit offset into the first
1600 // byte of storage of the bitfield. For other fields, use zero.
1601 if (Field->isBitField()) {
1602 FieldOffset = CGM.getObjCRuntime().ComputeBitfieldBitOffset(
1603 CGM, ID, Field);
1604 FieldOffset %= CGM.getContext().getCharWidth();
1605 } else {
1606 FieldOffset = 0;
1607 }
1608 } else {
1609 FieldOffset = RL.getFieldOffset(FieldNo);
1610 }
1611
1612 unsigned Flags = 0;
1613 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1614 Flags = llvm::DIDescriptor::FlagProtected;
1615 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1616 Flags = llvm::DIDescriptor::FlagPrivate;
1617
1618 llvm::MDNode *PropertyNode = NULL;
1619 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
Eric Christopher6537f082013-05-16 00:45:12 +00001620 if (ObjCPropertyImplDecl *PImpD =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001621 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
1622 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001623 SourceLocation Loc = PD->getLocation();
1624 llvm::DIFile PUnit = getOrCreateFile(Loc);
1625 unsigned PLine = getLineNumber(Loc);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001626 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1627 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1628 PropertyNode =
1629 DBuilder.createObjCProperty(PD->getName(),
1630 PUnit, PLine,
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001631 hasDefaultGetterName(PD, Getter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001632 getSelectorName(PD->getGetterName()),
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001633 hasDefaultSetterName(PD, Setter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001634 getSelectorName(PD->getSetterName()),
1635 PD->getPropertyAttributes(),
1636 getOrCreateType(PD->getType(), PUnit));
1637 }
1638 }
1639 }
1640 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
1641 FieldLine, FieldSize, FieldAlign,
1642 FieldOffset, Flags, FieldTy,
1643 PropertyNode);
1644 EltTys.push_back(FieldTy);
1645 }
1646
1647 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopherf068c922013-04-02 22:59:11 +00001648 RealDecl.setTypeArray(Elements);
Adrian Prantl4919de62013-03-06 22:03:30 +00001649
1650 // If the implementation is not yet set, we do not want to mark it
1651 // as complete. An implementation may declare additional
1652 // private ivars that we would miss otherwise.
1653 if (ID->getImplementation() == 0)
1654 CompletedTypeCache.erase(QualTy.getAsOpaquePtr());
Eric Christopher6537f082013-05-16 00:45:12 +00001655
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001656 LexicalBlockStack.pop_back();
Eric Christopherf068c922013-04-02 22:59:11 +00001657 return RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001658}
1659
1660llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) {
1661 llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1662 int64_t Count = Ty->getNumElements();
1663 if (Count == 0)
1664 // If number of elements are not known then this is an unbounded array.
1665 // Use Count == -1 to express such arrays.
1666 Count = -1;
1667
1668 llvm::Value *Subscript = DBuilder.getOrCreateSubrange(0, Count);
1669 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1670
1671 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1672 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1673
1674 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1675}
1676
1677llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1678 llvm::DIFile Unit) {
1679 uint64_t Size;
1680 uint64_t Align;
1681
1682 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1683 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1684 Size = 0;
1685 Align =
1686 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1687 } else if (Ty->isIncompleteArrayType()) {
1688 Size = 0;
1689 if (Ty->getElementType()->isIncompleteType())
1690 Align = 0;
1691 else
1692 Align = CGM.getContext().getTypeAlign(Ty->getElementType());
David Blaikie089db2e2013-05-09 20:48:12 +00001693 } else if (Ty->isIncompleteType()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001694 Size = 0;
1695 Align = 0;
1696 } else {
1697 // Size and align of the whole array, not the element type.
1698 Size = CGM.getContext().getTypeSize(Ty);
1699 Align = CGM.getContext().getTypeAlign(Ty);
1700 }
1701
1702 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
1703 // interior arrays, do we care? Why aren't nested arrays represented the
1704 // obvious/recursive way?
1705 SmallVector<llvm::Value *, 8> Subscripts;
1706 QualType EltTy(Ty, 0);
1707 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1708 // If the number of elements is known, then count is that number. Otherwise,
1709 // it's -1. This allows us to represent a subrange with an array of 0
1710 // elements, like this:
1711 //
1712 // struct foo {
1713 // int x[0];
1714 // };
1715 int64_t Count = -1; // Count == -1 is an unbounded array.
1716 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1717 Count = CAT->getSize().getZExtValue();
Eric Christopher6537f082013-05-16 00:45:12 +00001718
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001719 // FIXME: Verify this is right for VLAs.
1720 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
1721 EltTy = Ty->getElementType();
1722 }
1723
1724 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1725
Eric Christopher6537f082013-05-16 00:45:12 +00001726 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001727 DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1728 SubscriptArray);
1729 return DbgTy;
1730}
1731
Eric Christopher6537f082013-05-16 00:45:12 +00001732llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001733 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +00001734 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001735 Ty, Ty->getPointeeType(), Unit);
1736}
1737
Eric Christopher6537f082013-05-16 00:45:12 +00001738llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001739 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +00001740 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001741 Ty, Ty->getPointeeType(), Unit);
1742}
1743
Eric Christopher6537f082013-05-16 00:45:12 +00001744llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001745 llvm::DIFile U) {
David Blaikiee8d75142013-01-19 19:20:56 +00001746 llvm::DIType ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
1747 if (!Ty->getPointeeType()->isFunctionType())
1748 return DBuilder.createMemberPointerType(
David Blaikieb0f77b02013-05-24 21:33:22 +00001749 getOrCreateTypeDeclaration(Ty->getPointeeType(), U), ClassType);
David Blaikiee8d75142013-01-19 19:20:56 +00001750 return DBuilder.createMemberPointerType(getOrCreateInstanceMethodType(
1751 CGM.getContext().getPointerType(
1752 QualType(Ty->getClass(), Ty->getPointeeType().getCVRQualifiers())),
1753 Ty->getPointeeType()->getAs<FunctionProtoType>(), U),
1754 ClassType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001755}
1756
Eric Christopher6537f082013-05-16 00:45:12 +00001757llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001758 llvm::DIFile U) {
1759 // Ignore the atomic wrapping
1760 // FIXME: What is the correct representation?
1761 return getOrCreateType(Ty->getValueType(), U);
1762}
1763
1764/// CreateEnumType - get enumeration type.
1765llvm::DIType CGDebugInfo::CreateEnumType(const EnumDecl *ED) {
1766 uint64_t Size = 0;
1767 uint64_t Align = 0;
1768 if (!ED->getTypeForDecl()->isIncompleteType()) {
1769 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1770 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1771 }
1772
1773 // If this is just a forward declaration, construct an appropriately
1774 // marked node and just return it.
1775 if (!ED->getDefinition()) {
1776 llvm::DIDescriptor EDContext;
1777 EDContext = getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1778 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1779 unsigned Line = getLineNumber(ED->getLocation());
1780 StringRef EDName = ED->getName();
1781 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_enumeration_type,
1782 EDName, EDContext, DefUnit, Line, 0,
1783 Size, Align);
1784 }
1785
1786 // Create DIEnumerator elements for each enumerator.
1787 SmallVector<llvm::Value *, 16> Enumerators;
1788 ED = ED->getDefinition();
1789 for (EnumDecl::enumerator_iterator
1790 Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
1791 Enum != EnumEnd; ++Enum) {
1792 Enumerators.push_back(
1793 DBuilder.createEnumerator(Enum->getName(),
David Blaikieac8f43c2013-06-24 07:13:13 +00001794 Enum->getInitVal().getSExtValue()));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001795 }
1796
1797 // Return a CompositeType for the enum itself.
1798 llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1799
1800 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1801 unsigned Line = getLineNumber(ED->getLocation());
Eric Christopher6537f082013-05-16 00:45:12 +00001802 llvm::DIDescriptor EnumContext =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001803 getContextDescriptor(cast<Decl>(ED->getDeclContext()));
Adrian Prantl59d6a712013-04-19 19:56:39 +00001804 llvm::DIType ClassTy = ED->isFixed() ?
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001805 getOrCreateType(ED->getIntegerType(), DefUnit) : llvm::DIType();
Eric Christopher6537f082013-05-16 00:45:12 +00001806 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001807 DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1808 Size, Align, EltArray,
1809 ClassTy);
1810 return DbgTy;
1811}
1812
David Blaikie4b12be62013-01-21 04:37:12 +00001813static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
1814 Qualifiers Quals;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001815 do {
David Blaikie4b12be62013-01-21 04:37:12 +00001816 Quals += T.getLocalQualifiers();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001817 QualType LastT = T;
1818 switch (T->getTypeClass()) {
1819 default:
David Blaikie4b12be62013-01-21 04:37:12 +00001820 return C.getQualifiedType(T.getTypePtr(), Quals);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001821 case Type::TemplateSpecialization:
1822 T = cast<TemplateSpecializationType>(T)->desugar();
1823 break;
1824 case Type::TypeOfExpr:
1825 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1826 break;
1827 case Type::TypeOf:
1828 T = cast<TypeOfType>(T)->getUnderlyingType();
1829 break;
1830 case Type::Decltype:
1831 T = cast<DecltypeType>(T)->getUnderlyingType();
1832 break;
1833 case Type::UnaryTransform:
1834 T = cast<UnaryTransformType>(T)->getUnderlyingType();
1835 break;
1836 case Type::Attributed:
1837 T = cast<AttributedType>(T)->getEquivalentType();
1838 break;
1839 case Type::Elaborated:
1840 T = cast<ElaboratedType>(T)->getNamedType();
1841 break;
1842 case Type::Paren:
1843 T = cast<ParenType>(T)->getInnerType();
1844 break;
David Blaikie4b12be62013-01-21 04:37:12 +00001845 case Type::SubstTemplateTypeParm:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001846 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001847 break;
1848 case Type::Auto:
David Blaikie91296482013-05-24 21:24:35 +00001849 QualType DT = cast<AutoType>(T)->getDeducedType();
1850 if (DT.isNull())
1851 return T;
1852 T = DT;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001853 break;
1854 }
Eric Christopher6537f082013-05-16 00:45:12 +00001855
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001856 assert(T != LastT && "Type unwrapping failed to unwrap!");
NAKAMURA Takumid24c9ab2013-01-21 10:51:28 +00001857 (void)LastT;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001858 } while (true);
1859}
1860
Eric Christopherf0890c42013-05-16 00:52:20 +00001861/// getType - Get the type from the cache or return null type if it doesn't
1862/// exist.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001863llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) {
1864
1865 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00001866 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Eric Christopher6537f082013-05-16 00:45:12 +00001867
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001868 // Check for existing entry.
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001869 if (Ty->getTypeClass() == Type::ObjCInterface) {
1870 llvm::Value *V = getCachedInterfaceTypeOrNull(Ty);
1871 if (V)
1872 return llvm::DIType(cast<llvm::MDNode>(V));
1873 else return llvm::DIType();
1874 }
1875
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001876 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1877 TypeCache.find(Ty.getAsOpaquePtr());
1878 if (it != TypeCache.end()) {
1879 // Verify that the debug info still exists.
1880 if (llvm::Value *V = it->second)
1881 return llvm::DIType(cast<llvm::MDNode>(V));
1882 }
1883
1884 return llvm::DIType();
1885}
1886
1887/// getCompletedTypeOrNull - Get the type from the cache or return null if it
1888/// doesn't exist.
1889llvm::DIType CGDebugInfo::getCompletedTypeOrNull(QualType Ty) {
1890
1891 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00001892 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001893
1894 // Check for existing entry.
Adrian Prantl4919de62013-03-06 22:03:30 +00001895 llvm::Value *V = 0;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001896 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1897 CompletedTypeCache.find(Ty.getAsOpaquePtr());
Adrian Prantl4919de62013-03-06 22:03:30 +00001898 if (it != CompletedTypeCache.end())
1899 V = it->second;
1900 else {
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001901 V = getCachedInterfaceTypeOrNull(Ty);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001902 }
1903
Adrian Prantl4919de62013-03-06 22:03:30 +00001904 // Verify that any cached debug info still exists.
David Blaikieeab6a362013-06-21 00:40:50 +00001905 if (V != 0)
1906 return llvm::DIType(cast<llvm::MDNode>(V));
Adrian Prantl4919de62013-03-06 22:03:30 +00001907
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001908 return llvm::DIType();
1909}
1910
David Blaikieeab6a362013-06-21 00:40:50 +00001911void CGDebugInfo::completeFwdDecl(const RecordDecl &RD) {
1912 // In limited debug info we only want to do this if the complete type was
1913 // required.
1914 if (DebugKind <= CodeGenOptions::LimitedDebugInfo)
1915 return;
1916
David Blaikie076f51f2013-06-21 00:59:44 +00001917 QualType QTy = CGM.getContext().getRecordType(&RD);
1918 llvm::DIType T = getTypeOrNull(QTy);
David Blaikieeab6a362013-06-21 00:40:50 +00001919
1920 if (T.Verify() && T.isForwardDecl())
David Blaikie076f51f2013-06-21 00:59:44 +00001921 getOrCreateType(QTy, getOrCreateFile(RD.getLocation()));
David Blaikieeab6a362013-06-21 00:40:50 +00001922}
1923
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001924/// getCachedInterfaceTypeOrNull - Get the type from the interface
1925/// cache, unless it needs to regenerated. Otherwise return null.
1926llvm::Value *CGDebugInfo::getCachedInterfaceTypeOrNull(QualType Ty) {
1927 // Is there a cached interface that hasn't changed?
1928 llvm::DenseMap<void *, std::pair<llvm::WeakVH, unsigned > >
1929 ::iterator it1 = ObjCInterfaceCache.find(Ty.getAsOpaquePtr());
1930
1931 if (it1 != ObjCInterfaceCache.end())
1932 if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty))
1933 if (Checksum(Decl) == it1->second.second)
1934 // Return cached forward declaration.
1935 return it1->second.first;
1936
1937 return 0;
1938}
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001939
1940/// getOrCreateType - Get the type from the cache or create a new
1941/// one if necessary.
Eric Christopher56b108a2013-06-07 22:54:39 +00001942llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit,
1943 bool Declaration) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001944 if (Ty.isNull())
1945 return llvm::DIType();
1946
1947 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00001948 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001949
1950 llvm::DIType T = getCompletedTypeOrNull(Ty);
1951
David Blaikief0c31d92013-06-21 21:03:11 +00001952 if (T.Verify()) {
1953 // If we're looking for a definition, make sure we have definitions of any
1954 // underlying types.
1955 if (const TypedefType* TTy = dyn_cast<TypedefType>(Ty))
1956 getOrCreateType(TTy->getDecl()->getUnderlyingType(), Unit, Declaration);
1957 if (Ty.hasLocalQualifiers())
1958 getOrCreateType(QualType(Ty.getTypePtr(), 0), Unit, Declaration);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001959 return T;
David Blaikief0c31d92013-06-21 21:03:11 +00001960 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001961
1962 // Otherwise create the type.
David Blaikie5f6e2f42013-06-05 05:32:23 +00001963 llvm::DIType Res = CreateTypeNode(Ty, Unit, Declaration);
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001964 void* TyPtr = Ty.getAsOpaquePtr();
1965
1966 // And update the type cache.
1967 TypeCache[TyPtr] = Res;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001968
1969 llvm::DIType TC = getTypeOrNull(Ty);
1970 if (TC.Verify() && TC.isForwardDecl())
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001971 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
1972 else if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty)) {
1973 // Interface types may have elements added to them by a
1974 // subsequent implementation or extension, so we keep them in
1975 // the ObjCInterfaceCache together with a checksum. Instead of
Adrian Prantlf06989b2013-05-08 23:37:22 +00001976 // the (possibly) incomplete interface type, we return a forward
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001977 // declaration that gets RAUW'd in CGDebugInfo::finalize().
David Blaikiee2eb89a2013-05-21 18:29:40 +00001978 std::pair<llvm::WeakVH, unsigned> &V = ObjCInterfaceCache[TyPtr];
1979 if (V.first)
1980 return llvm::DIType(cast<llvm::MDNode>(V.first));
1981 TC = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
1982 Decl->getName(), TheCU, Unit,
1983 getLineNumber(Decl->getLocation()),
1984 TheCU.getLanguage());
1985 // Store the forward declaration in the cache.
1986 V.first = TC;
1987 V.second = Checksum(Decl);
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001988
David Blaikiee2eb89a2013-05-21 18:29:40 +00001989 // Register the type for replacement in finalize().
1990 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
1991
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001992 return TC;
Adrian Prantl4919de62013-03-06 22:03:30 +00001993 }
1994
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001995 if (!Res.isForwardDecl())
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001996 CompletedTypeCache[TyPtr] = Res;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001997
1998 return Res;
1999}
2000
Adrian Prantlb5a50072013-06-07 01:10:41 +00002001/// Currently the checksum of an interface includes the number of
2002/// ivars and property accessors.
Eric Christopher56b108a2013-06-07 22:54:39 +00002003unsigned CGDebugInfo::Checksum(const ObjCInterfaceDecl *ID) {
Adrian Prantl4f97f852013-06-07 01:10:48 +00002004 // The assumption is that the number of ivars can only increase
2005 // monotonically, so it is safe to just use their current number as
2006 // a checksum.
Adrian Prantlb5a50072013-06-07 01:10:41 +00002007 unsigned Sum = 0;
2008 for (const ObjCIvarDecl *Ivar = ID->all_declared_ivar_begin();
2009 Ivar != 0; Ivar = Ivar->getNextIvar())
2010 ++Sum;
2011
2012 return Sum;
Adrian Prantl4919de62013-03-06 22:03:30 +00002013}
2014
2015ObjCInterfaceDecl *CGDebugInfo::getObjCInterfaceDecl(QualType Ty) {
2016 switch (Ty->getTypeClass()) {
2017 case Type::ObjCObjectPointer:
Eric Christopherf0890c42013-05-16 00:52:20 +00002018 return getObjCInterfaceDecl(cast<ObjCObjectPointerType>(Ty)
2019 ->getPointeeType());
Adrian Prantl4919de62013-03-06 22:03:30 +00002020 case Type::ObjCInterface:
2021 return cast<ObjCInterfaceType>(Ty)->getDecl();
2022 default:
2023 return 0;
2024 }
2025}
2026
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002027/// CreateTypeNode - Create a new debug type node.
Eric Christopher56b108a2013-06-07 22:54:39 +00002028llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit,
2029 bool Declaration) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002030 // Handle qualifiers, which recursively handles what they refer to.
2031 if (Ty.hasLocalQualifiers())
David Blaikie5f6e2f42013-06-05 05:32:23 +00002032 return CreateQualifiedType(Ty, Unit, Declaration);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002033
2034 const char *Diag = 0;
Eric Christopher6537f082013-05-16 00:45:12 +00002035
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002036 // Work out details of type.
2037 switch (Ty->getTypeClass()) {
2038#define TYPE(Class, Base)
2039#define ABSTRACT_TYPE(Class, Base)
2040#define NON_CANONICAL_TYPE(Class, Base)
2041#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2042#include "clang/AST/TypeNodes.def"
2043 llvm_unreachable("Dependent types cannot show up in debug information");
2044
2045 case Type::ExtVector:
2046 case Type::Vector:
2047 return CreateType(cast<VectorType>(Ty), Unit);
2048 case Type::ObjCObjectPointer:
2049 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
2050 case Type::ObjCObject:
2051 return CreateType(cast<ObjCObjectType>(Ty), Unit);
2052 case Type::ObjCInterface:
2053 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
2054 case Type::Builtin:
2055 return CreateType(cast<BuiltinType>(Ty));
2056 case Type::Complex:
2057 return CreateType(cast<ComplexType>(Ty));
2058 case Type::Pointer:
2059 return CreateType(cast<PointerType>(Ty), Unit);
Reid Kleckner12df2462013-06-24 17:51:48 +00002060 case Type::Decayed:
2061 // Decayed types are just pointers in LLVM and DWARF.
2062 return CreateType(
2063 cast<PointerType>(cast<DecayedType>(Ty)->getDecayedType()), Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002064 case Type::BlockPointer:
2065 return CreateType(cast<BlockPointerType>(Ty), Unit);
2066 case Type::Typedef:
David Blaikie5f6e2f42013-06-05 05:32:23 +00002067 return CreateType(cast<TypedefType>(Ty), Unit, Declaration);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002068 case Type::Record:
David Blaikie5f6e2f42013-06-05 05:32:23 +00002069 return CreateType(cast<RecordType>(Ty), Declaration);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002070 case Type::Enum:
2071 return CreateEnumType(cast<EnumType>(Ty)->getDecl());
2072 case Type::FunctionProto:
2073 case Type::FunctionNoProto:
2074 return CreateType(cast<FunctionType>(Ty), Unit);
2075 case Type::ConstantArray:
2076 case Type::VariableArray:
2077 case Type::IncompleteArray:
2078 return CreateType(cast<ArrayType>(Ty), Unit);
2079
2080 case Type::LValueReference:
2081 return CreateType(cast<LValueReferenceType>(Ty), Unit);
2082 case Type::RValueReference:
2083 return CreateType(cast<RValueReferenceType>(Ty), Unit);
2084
2085 case Type::MemberPointer:
2086 return CreateType(cast<MemberPointerType>(Ty), Unit);
2087
2088 case Type::Atomic:
2089 return CreateType(cast<AtomicType>(Ty), Unit);
2090
2091 case Type::Attributed:
2092 case Type::TemplateSpecialization:
2093 case Type::Elaborated:
2094 case Type::Paren:
2095 case Type::SubstTemplateTypeParm:
2096 case Type::TypeOfExpr:
2097 case Type::TypeOf:
2098 case Type::Decltype:
2099 case Type::UnaryTransform:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002100 llvm_unreachable("type should have been unwrapped!");
David Blaikie91296482013-05-24 21:24:35 +00002101 case Type::Auto:
2102 Diag = "auto";
2103 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002104 }
Eric Christopher6537f082013-05-16 00:45:12 +00002105
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002106 assert(Diag && "Fall through without a diagnostic?");
2107 unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error,
2108 "debug information for %0 is not yet supported");
2109 CGM.getDiags().Report(DiagID)
2110 << Diag;
2111 return llvm::DIType();
2112}
2113
2114/// getOrCreateLimitedType - Get the type from the cache or create a new
2115/// limited type if necessary.
2116llvm::DIType CGDebugInfo::getOrCreateLimitedType(QualType Ty,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002117 llvm::DIFile Unit) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002118 if (Ty.isNull())
2119 return llvm::DIType();
2120
2121 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00002122 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002123
2124 llvm::DIType T = getTypeOrNull(Ty);
2125
2126 // We may have cached a forward decl when we could have created
2127 // a non-forward decl. Go ahead and create a non-forward decl
2128 // now.
2129 if (T.Verify() && !T.isForwardDecl()) return T;
2130
2131 // Otherwise create the type.
2132 llvm::DIType Res = CreateLimitedTypeNode(Ty, Unit);
2133
2134 if (T.Verify() && T.isForwardDecl())
2135 ReplaceMap.push_back(std::make_pair(Ty.getAsOpaquePtr(),
2136 static_cast<llvm::Value*>(T)));
2137
2138 // And update the type cache.
2139 TypeCache[Ty.getAsOpaquePtr()] = Res;
2140 return Res;
2141}
2142
2143// TODO: Currently used for context chains when limiting debug info.
2144llvm::DIType CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
2145 RecordDecl *RD = Ty->getDecl();
Eric Christopher6537f082013-05-16 00:45:12 +00002146
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002147 // Get overall information about the record type for the debug info.
2148 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
2149 unsigned Line = getLineNumber(RD->getLocation());
2150 StringRef RDName = getClassName(RD);
2151
2152 llvm::DIDescriptor RDContext;
Eric Christopher13c97672013-05-16 00:45:23 +00002153 if (DebugKind == CodeGenOptions::LimitedDebugInfo)
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002154 RDContext = createContextChain(cast<Decl>(RD->getDeclContext()));
2155 else
2156 RDContext = getContextDescriptor(cast<Decl>(RD->getDeclContext()));
2157
2158 // If this is just a forward declaration, construct an appropriately
2159 // marked node and just return it.
2160 if (!RD->getDefinition())
2161 return createRecordFwdDecl(RD, RDContext);
2162
2163 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2164 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
2165 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
David Blaikie2fcadbe2013-03-26 23:47:35 +00002166 llvm::DICompositeType RealDecl;
Eric Christopher6537f082013-05-16 00:45:12 +00002167
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002168 if (RD->isUnion())
2169 RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002170 Size, Align, 0, llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002171 else if (RD->isClass()) {
2172 // FIXME: This could be a struct type giving a default visibility different
2173 // than C++ class type, but needs llvm metadata changes first.
2174 RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002175 Size, Align, 0, 0, llvm::DIType(),
2176 llvm::DIArray(), llvm::DIType(),
2177 llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002178 } else
2179 RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line,
Eric Christopherf0890c42013-05-16 00:52:20 +00002180 Size, Align, 0, llvm::DIType(),
2181 llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002182
2183 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
David Blaikie2fcadbe2013-03-26 23:47:35 +00002184 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002185
2186 if (CXXDecl) {
2187 // A class's primary base or the class itself contains the vtable.
David Blaikie2fcadbe2013-03-26 23:47:35 +00002188 llvm::DICompositeType ContainingType;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002189 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2190 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
2191 // Seek non virtual primary base root.
2192 while (1) {
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002193 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
2194 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
2195 if (PBT && !BRL.isPrimaryBaseVirtual())
2196 PBase = PBT;
2197 else
2198 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002199 }
David Blaikie2fcadbe2013-03-26 23:47:35 +00002200 ContainingType = llvm::DICompositeType(
2201 getOrCreateType(QualType(PBase->getTypeForDecl(), 0), DefUnit));
2202 } else if (CXXDecl->isDynamicClass())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002203 ContainingType = RealDecl;
2204
David Blaikie2fcadbe2013-03-26 23:47:35 +00002205 RealDecl.setContainingType(ContainingType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002206 }
2207 return llvm::DIType(RealDecl);
2208}
2209
2210/// CreateLimitedTypeNode - Create a new debug type node, but only forward
2211/// declare composite types that haven't been processed yet.
2212llvm::DIType CGDebugInfo::CreateLimitedTypeNode(QualType Ty,llvm::DIFile Unit) {
2213
2214 // Work out details of type.
2215 switch (Ty->getTypeClass()) {
2216#define TYPE(Class, Base)
2217#define ABSTRACT_TYPE(Class, Base)
2218#define NON_CANONICAL_TYPE(Class, Base)
2219#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2220 #include "clang/AST/TypeNodes.def"
2221 llvm_unreachable("Dependent types cannot show up in debug information");
2222
2223 case Type::Record:
2224 return CreateLimitedType(cast<RecordType>(Ty));
2225 default:
David Blaikie5f6e2f42013-06-05 05:32:23 +00002226 return CreateTypeNode(Ty, Unit, false);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002227 }
2228}
2229
2230/// CreateMemberType - Create new member and increase Offset by FType's size.
2231llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
2232 StringRef Name,
2233 uint64_t *Offset) {
2234 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2235 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
2236 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
2237 llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0,
2238 FieldSize, FieldAlign,
2239 *Offset, 0, FieldTy);
2240 *Offset += FieldSize;
2241 return Ty;
2242}
2243
David Blaikie9faebd22013-05-20 04:58:53 +00002244llvm::DIDescriptor CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
2245 // We only need a declaration (not a definition) of the type - so use whatever
2246 // we would otherwise do to get a type for a pointee. (forward declarations in
2247 // limited debug info, full definitions (if the type definition is available)
2248 // in unlimited debug info)
2249 if (const TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
2250 llvm::DIFile DefUnit = getOrCreateFile(TD->getLocation());
David Blaikieb0f77b02013-05-24 21:33:22 +00002251 return getOrCreateTypeDeclaration(CGM.getContext().getTypeDeclType(TD),
2252 DefUnit);
David Blaikie9faebd22013-05-20 04:58:53 +00002253 }
2254 // Otherwise fall back to a fairly rudimentary cache of existing declarations.
2255 // This doesn't handle providing declarations (for functions or variables) for
2256 // entities without definitions in this TU, nor when the definition proceeds
2257 // the call to this function.
2258 // FIXME: This should be split out into more specific maps with support for
2259 // emitting forward declarations and merging definitions with declarations,
2260 // the same way as we do for types.
2261 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator I =
2262 DeclCache.find(D->getCanonicalDecl());
2263 if (I == DeclCache.end())
2264 return llvm::DIDescriptor();
2265 llvm::Value *V = I->second;
2266 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
2267}
2268
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002269/// getFunctionDeclaration - Return debug info descriptor to describe method
2270/// declaration for the given method definition.
2271llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
David Blaikie23e66db2013-06-22 00:09:36 +00002272 if (!D || DebugKind == CodeGenOptions::DebugLineTablesOnly)
2273 return llvm::DISubprogram();
2274
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002275 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
2276 if (!FD) return llvm::DISubprogram();
2277
2278 // Setup context.
2279 getContextDescriptor(cast<Decl>(D->getDeclContext()));
2280
2281 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2282 MI = SPCache.find(FD->getCanonicalDecl());
2283 if (MI != SPCache.end()) {
2284 llvm::Value *V = MI->second;
2285 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
David Blaikie23e66db2013-06-22 00:09:36 +00002286 if (SP.isSubprogram() && !SP.isDefinition())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002287 return SP;
2288 }
2289
2290 for (FunctionDecl::redecl_iterator I = FD->redecls_begin(),
2291 E = FD->redecls_end(); I != E; ++I) {
2292 const FunctionDecl *NextFD = *I;
2293 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2294 MI = SPCache.find(NextFD->getCanonicalDecl());
2295 if (MI != SPCache.end()) {
2296 llvm::Value *V = MI->second;
2297 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
David Blaikie23e66db2013-06-22 00:09:36 +00002298 if (SP.isSubprogram() && !SP.isDefinition())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002299 return SP;
2300 }
2301 }
2302 return llvm::DISubprogram();
2303}
2304
2305// getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
2306// implicit parameter "this".
David Blaikie9a845292013-05-22 23:22:42 +00002307llvm::DICompositeType CGDebugInfo::getOrCreateFunctionType(const Decl *D,
2308 QualType FnType,
2309 llvm::DIFile F) {
David Blaikie23e66db2013-06-22 00:09:36 +00002310 if (!D || DebugKind == CodeGenOptions::DebugLineTablesOnly)
2311 // Create fake but valid subroutine type. Otherwise
2312 // llvm::DISubprogram::Verify() would return false, and
2313 // subprogram DIE will miss DW_AT_decl_file and
2314 // DW_AT_decl_line fields.
2315 return DBuilder.createSubroutineType(F, DBuilder.getOrCreateArray(None));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002316
2317 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
2318 return getOrCreateMethodType(Method, F);
2319 if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
2320 // Add "self" and "_cmd"
2321 SmallVector<llvm::Value *, 16> Elts;
2322
2323 // First element is always return type. For 'void' functions it is NULL.
Adrian Prantl0cb00022013-05-22 21:37:49 +00002324 QualType ResultTy = OMethod->getResultType();
2325
2326 // Replace the instancetype keyword with the actual type.
2327 if (ResultTy == CGM.getContext().getObjCInstanceType())
2328 ResultTy = CGM.getContext().getPointerType(
2329 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
2330
Adrian Prantl566a9c32013-05-10 21:08:31 +00002331 Elts.push_back(getOrCreateType(ResultTy, F));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002332 // "self" pointer is always first argument.
Adrian Prantle86fcc42013-03-29 19:20:29 +00002333 QualType SelfDeclTy = OMethod->getSelfDecl()->getType();
2334 llvm::DIType SelfTy = getOrCreateType(SelfDeclTy, F);
2335 Elts.push_back(CreateSelfType(SelfDeclTy, SelfTy));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002336 // "_cmd" pointer is always second argument.
2337 llvm::DIType CmdTy = getOrCreateType(OMethod->getCmdDecl()->getType(), F);
2338 Elts.push_back(DBuilder.createArtificialType(CmdTy));
2339 // Get rest of the arguments.
Eric Christopher6537f082013-05-16 00:45:12 +00002340 for (ObjCMethodDecl::param_const_iterator PI = OMethod->param_begin(),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002341 PE = OMethod->param_end(); PI != PE; ++PI)
2342 Elts.push_back(getOrCreateType((*PI)->getType(), F));
2343
2344 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2345 return DBuilder.createSubroutineType(F, EltTypeArray);
2346 }
David Blaikie9a845292013-05-22 23:22:42 +00002347 return llvm::DICompositeType(getOrCreateType(FnType, F));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002348}
2349
2350/// EmitFunctionStart - Constructs the debug code for entering a function.
2351void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
2352 llvm::Function *Fn,
2353 CGBuilderTy &Builder) {
2354
2355 StringRef Name;
2356 StringRef LinkageName;
2357
2358 FnBeginRegionCount.push_back(LexicalBlockStack.size());
2359
2360 const Decl *D = GD.getDecl();
2361 // Function may lack declaration in source code if it is created by Clang
2362 // CodeGen (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
2363 bool HasDecl = (D != 0);
2364 // Use the location of the declaration.
2365 SourceLocation Loc;
2366 if (HasDecl)
2367 Loc = D->getLocation();
2368
2369 unsigned Flags = 0;
2370 llvm::DIFile Unit = getOrCreateFile(Loc);
2371 llvm::DIDescriptor FDContext(Unit);
2372 llvm::DIArray TParamsArray;
2373 if (!HasDecl) {
2374 // Use llvm function name.
2375 Name = Fn->getName();
2376 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2377 // If there is a DISubprogram for this function available then use it.
2378 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2379 FI = SPCache.find(FD->getCanonicalDecl());
2380 if (FI != SPCache.end()) {
2381 llvm::Value *V = FI->second;
2382 llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(V));
2383 if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
2384 llvm::MDNode *SPN = SP;
2385 LexicalBlockStack.push_back(SPN);
2386 RegionMap[D] = llvm::WeakVH(SP);
2387 return;
2388 }
2389 }
2390 Name = getFunctionName(FD);
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002391 // Use mangled name as linkage name for C/C++ functions.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002392 if (FD->hasPrototype()) {
2393 LinkageName = CGM.getMangledName(GD);
2394 Flags |= llvm::DIDescriptor::FlagPrototyped;
2395 }
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002396 // No need to replicate the linkage name if it isn't different from the
2397 // subprogram name, no need to have it at all unless coverage is enabled or
2398 // debug is set to more than just line tables.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002399 if (LinkageName == Name ||
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002400 (!CGM.getCodeGenOpts().EmitGcovArcs &&
2401 !CGM.getCodeGenOpts().EmitGcovNotes &&
Eric Christopher13c97672013-05-16 00:45:23 +00002402 DebugKind <= CodeGenOptions::DebugLineTablesOnly))
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002403 LinkageName = StringRef();
2404
Eric Christopher13c97672013-05-16 00:45:23 +00002405 if (DebugKind >= CodeGenOptions::LimitedDebugInfo) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002406 if (const NamespaceDecl *NSDecl =
2407 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
2408 FDContext = getOrCreateNameSpace(NSDecl);
2409 else if (const RecordDecl *RDecl =
2410 dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
2411 FDContext = getContextDescriptor(cast<Decl>(RDecl->getDeclContext()));
2412
2413 // Collect template parameters.
2414 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
2415 }
2416 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
2417 Name = getObjCMethodName(OMD);
2418 Flags |= llvm::DIDescriptor::FlagPrototyped;
2419 } else {
2420 // Use llvm function name.
2421 Name = Fn->getName();
2422 Flags |= llvm::DIDescriptor::FlagPrototyped;
2423 }
2424 if (!Name.empty() && Name[0] == '\01')
2425 Name = Name.substr(1);
2426
2427 unsigned LineNo = getLineNumber(Loc);
2428 if (!HasDecl || D->isImplicit())
2429 Flags |= llvm::DIDescriptor::FlagArtificial;
2430
David Blaikie23e66db2013-06-22 00:09:36 +00002431 llvm::DISubprogram SP = DBuilder.createFunction(
2432 FDContext, Name, LinkageName, Unit, LineNo,
2433 getOrCreateFunctionType(D, FnType, Unit), Fn->hasInternalLinkage(),
2434 true /*definition*/, getLineNumber(CurLoc), Flags,
2435 CGM.getLangOpts().Optimize, Fn, TParamsArray, getFunctionDeclaration(D));
David Blaikie9faebd22013-05-20 04:58:53 +00002436 if (HasDecl)
2437 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(SP)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002438
2439 // Push function on region stack.
2440 llvm::MDNode *SPN = SP;
2441 LexicalBlockStack.push_back(SPN);
2442 if (HasDecl)
2443 RegionMap[D] = llvm::WeakVH(SP);
2444}
2445
2446/// EmitLocation - Emit metadata to indicate a change in line/column
2447/// information in the source file.
Adrian Prantl00df5ea2013-03-12 20:43:25 +00002448void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc,
2449 bool ForceColumnInfo) {
Eric Christopher6537f082013-05-16 00:45:12 +00002450
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002451 // Update our current location
2452 setLocation(Loc);
2453
2454 if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
2455
2456 // Don't bother if things are the same as last time.
2457 SourceManager &SM = CGM.getContext().getSourceManager();
2458 if (CurLoc == PrevLoc ||
2459 SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc))
2460 // New Builder may not be in sync with CGDebugInfo.
David Blaikie0a0f93c2013-02-01 19:09:49 +00002461 if (!Builder.getCurrentDebugLocation().isUnknown() &&
2462 Builder.getCurrentDebugLocation().getScope(CGM.getLLVMContext()) ==
2463 LexicalBlockStack.back())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002464 return;
Eric Christopher6537f082013-05-16 00:45:12 +00002465
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002466 // Update last state.
2467 PrevLoc = CurLoc;
2468
2469 llvm::MDNode *Scope = LexicalBlockStack.back();
Adrian Prantl00df5ea2013-03-12 20:43:25 +00002470 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get
2471 (getLineNumber(CurLoc),
2472 getColumnNumber(CurLoc, ForceColumnInfo),
2473 Scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002474}
2475
2476/// CreateLexicalBlock - Creates a new lexical block node and pushes it on
2477/// the stack.
2478void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
2479 llvm::DIDescriptor D =
2480 DBuilder.createLexicalBlock(LexicalBlockStack.empty() ?
2481 llvm::DIDescriptor() :
2482 llvm::DIDescriptor(LexicalBlockStack.back()),
2483 getOrCreateFile(CurLoc),
2484 getLineNumber(CurLoc),
2485 getColumnNumber(CurLoc));
2486 llvm::MDNode *DN = D;
2487 LexicalBlockStack.push_back(DN);
2488}
2489
2490/// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
2491/// region - beginning of a DW_TAG_lexical_block.
Eric Christopherf0890c42013-05-16 00:52:20 +00002492void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
2493 SourceLocation Loc) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002494 // Set our current location.
2495 setLocation(Loc);
2496
2497 // Create a new lexical block and push it on the stack.
2498 CreateLexicalBlock(Loc);
2499
2500 // Emit a line table change for the current location inside the new scope.
2501 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc),
2502 getColumnNumber(Loc),
2503 LexicalBlockStack.back()));
2504}
2505
2506/// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative
2507/// region - end of a DW_TAG_lexical_block.
Eric Christopherf0890c42013-05-16 00:52:20 +00002508void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
2509 SourceLocation Loc) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002510 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2511
2512 // Provide an entry in the line table for the end of the block.
2513 EmitLocation(Builder, Loc);
2514
2515 LexicalBlockStack.pop_back();
2516}
2517
2518/// EmitFunctionEnd - Constructs the debug code for exiting a function.
2519void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
2520 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2521 unsigned RCount = FnBeginRegionCount.back();
2522 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
2523
2524 // Pop all regions for this function.
2525 while (LexicalBlockStack.size() != RCount)
2526 EmitLexicalBlockEnd(Builder, CurLoc);
2527 FnBeginRegionCount.pop_back();
2528}
2529
Eric Christopher6537f082013-05-16 00:45:12 +00002530// EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002531// See BuildByRefType.
2532llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
2533 uint64_t *XOffset) {
2534
2535 SmallVector<llvm::Value *, 5> EltTys;
2536 QualType FType;
2537 uint64_t FieldSize, FieldOffset;
2538 unsigned FieldAlign;
Eric Christopher6537f082013-05-16 00:45:12 +00002539
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002540 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
Eric Christopher6537f082013-05-16 00:45:12 +00002541 QualType Type = VD->getType();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002542
2543 FieldOffset = 0;
2544 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2545 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
2546 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
2547 FType = CGM.getContext().IntTy;
2548 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
2549 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
2550
2551 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
2552 if (HasCopyAndDispose) {
2553 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2554 EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
2555 &FieldOffset));
2556 EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
2557 &FieldOffset));
2558 }
2559 bool HasByrefExtendedLayout;
2560 Qualifiers::ObjCLifetime Lifetime;
2561 if (CGM.getContext().getByrefLifetime(Type,
2562 Lifetime, HasByrefExtendedLayout)
2563 && HasByrefExtendedLayout)
2564 EltTys.push_back(CreateMemberType(Unit, FType,
2565 "__byref_variable_layout",
2566 &FieldOffset));
Eric Christopher6537f082013-05-16 00:45:12 +00002567
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002568 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2569 if (Align > CGM.getContext().toCharUnitsFromBits(
John McCall64aa4b32013-04-16 22:48:15 +00002570 CGM.getTarget().getPointerAlign(0))) {
Eric Christopher6537f082013-05-16 00:45:12 +00002571 CharUnits FieldOffsetInBytes
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002572 = CGM.getContext().toCharUnitsFromBits(FieldOffset);
2573 CharUnits AlignedOffsetInBytes
2574 = FieldOffsetInBytes.RoundUpToAlignment(Align);
2575 CharUnits NumPaddingBytes
2576 = AlignedOffsetInBytes - FieldOffsetInBytes;
Eric Christopher6537f082013-05-16 00:45:12 +00002577
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002578 if (NumPaddingBytes.isPositive()) {
2579 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
2580 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
2581 pad, ArrayType::Normal, 0);
2582 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
2583 }
2584 }
Eric Christopher6537f082013-05-16 00:45:12 +00002585
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002586 FType = Type;
2587 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2588 FieldSize = CGM.getContext().getTypeSize(FType);
2589 FieldAlign = CGM.getContext().toBits(Align);
2590
Eric Christopher6537f082013-05-16 00:45:12 +00002591 *XOffset = FieldOffset;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002592 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit,
2593 0, FieldSize, FieldAlign,
2594 FieldOffset, 0, FieldTy);
2595 EltTys.push_back(FieldTy);
2596 FieldOffset += FieldSize;
Eric Christopher6537f082013-05-16 00:45:12 +00002597
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002598 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopher6537f082013-05-16 00:45:12 +00002599
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002600 unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
Eric Christopher6537f082013-05-16 00:45:12 +00002601
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002602 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
David Blaikiec1d0af12013-02-25 01:07:08 +00002603 llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002604}
2605
2606/// EmitDeclare - Emit local variable declaration debug info.
2607void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
Eric Christopher6537f082013-05-16 00:45:12 +00002608 llvm::Value *Storage,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002609 unsigned ArgNo, CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002610 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002611 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2612
2613 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2614 llvm::DIType Ty;
2615 uint64_t XOffset = 0;
2616 if (VD->hasAttr<BlocksAttr>())
2617 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopher6537f082013-05-16 00:45:12 +00002618 else
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002619 Ty = getOrCreateType(VD->getType(), Unit);
2620
2621 // If there is no debug info for this type then do not emit debug info
2622 // for this variable.
2623 if (!Ty)
2624 return;
2625
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002626 // Get location information.
2627 unsigned Line = getLineNumber(VD->getLocation());
2628 unsigned Column = getColumnNumber(VD->getLocation());
2629 unsigned Flags = 0;
2630 if (VD->isImplicit())
2631 Flags |= llvm::DIDescriptor::FlagArtificial;
2632 // If this is the first argument and it is implicit then
2633 // give it an object pointer flag.
2634 // FIXME: There has to be a better way to do this, but for static
2635 // functions there won't be an implicit param at arg1 and
2636 // otherwise it is 'self' or 'this'.
2637 if (isa<ImplicitParamDecl>(VD) && ArgNo == 1)
2638 Flags |= llvm::DIDescriptor::FlagObjectPointer;
David Blaikie41c9bae2013-06-19 21:53:53 +00002639 if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage))
2640 if (Arg->getType()->isPointerTy() && !Arg->hasByValAttr() && !VD->getType()->isPointerType())
2641 Flags |= llvm::DIDescriptor::FlagIndirectVariable;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002642
2643 llvm::MDNode *Scope = LexicalBlockStack.back();
2644
2645 StringRef Name = VD->getName();
2646 if (!Name.empty()) {
2647 if (VD->hasAttr<BlocksAttr>()) {
2648 CharUnits offset = CharUnits::fromQuantity(32);
2649 SmallVector<llvm::Value *, 9> addr;
2650 llvm::Type *Int64Ty = CGM.Int64Ty;
2651 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2652 // offset of __forwarding field
2653 offset = CGM.getContext().toCharUnitsFromBits(
John McCall64aa4b32013-04-16 22:48:15 +00002654 CGM.getTarget().getPointerWidth(0));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002655 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 // Create the descriptor for the variable.
2663 llvm::DIVariable D =
Eric Christopher6537f082013-05-16 00:45:12 +00002664 DBuilder.createComplexVariable(Tag,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002665 llvm::DIDescriptor(Scope),
2666 VD->getName(), Unit, Line, Ty,
2667 addr, ArgNo);
Eric Christopher6537f082013-05-16 00:45:12 +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.GetInsertBlock());
2672 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2673 return;
Adrian Prantl230ea412013-04-30 22:45:09 +00002674 } else if (isa<VariableArrayType>(VD->getType())) {
2675 // These are "complex" variables in that they need an op_deref.
2676 // Create the descriptor for the variable.
2677 llvm::Value *Addr = llvm::ConstantInt::get(CGM.Int64Ty,
2678 llvm::DIBuilder::OpDeref);
2679 llvm::DIVariable D =
2680 DBuilder.createComplexVariable(Tag,
2681 llvm::DIDescriptor(Scope),
2682 Name, Unit, Line, Ty,
2683 Addr, ArgNo);
2684
2685 // Insert an llvm.dbg.declare into the current block.
2686 llvm::Instruction *Call =
2687 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2688 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2689 return;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002690 }
David Blaikie436653b2013-01-05 05:58:35 +00002691 } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2692 // If VD is an anonymous union then Storage represents value for
2693 // all union fields.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002694 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
David Blaikied8180cf2013-01-05 20:03:07 +00002695 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002696 for (RecordDecl::field_iterator I = RD->field_begin(),
2697 E = RD->field_end();
2698 I != E; ++I) {
2699 FieldDecl *Field = *I;
2700 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2701 StringRef FieldName = Field->getName();
Eric Christopher6537f082013-05-16 00:45:12 +00002702
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002703 // Ignore unnamed fields. Do not ignore unnamed records.
2704 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2705 continue;
Eric Christopher6537f082013-05-16 00:45:12 +00002706
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002707 // Use VarDecl's Tag, Scope and Line number.
2708 llvm::DIVariable D =
2709 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
Eric Christopher6537f082013-05-16 00:45:12 +00002710 FieldName, Unit, Line, FieldTy,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002711 CGM.getLangOpts().Optimize, Flags,
2712 ArgNo);
Eric Christopher6537f082013-05-16 00:45:12 +00002713
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002714 // Insert an llvm.dbg.declare into the current block.
2715 llvm::Instruction *Call =
2716 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2717 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2718 }
David Blaikied8180cf2013-01-05 20:03:07 +00002719 return;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002720 }
2721 }
David Blaikie436653b2013-01-05 05:58:35 +00002722
2723 // Create the descriptor for the variable.
2724 llvm::DIVariable D =
2725 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2726 Name, Unit, Line, Ty,
2727 CGM.getLangOpts().Optimize, Flags, ArgNo);
2728
2729 // Insert an llvm.dbg.declare into the current block.
2730 llvm::Instruction *Call =
2731 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2732 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002733}
2734
2735void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2736 llvm::Value *Storage,
2737 CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002738 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002739 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2740}
2741
Adrian Prantle86fcc42013-03-29 19:20:29 +00002742/// Look up the completed type for a self pointer in the TypeCache and
2743/// create a copy of it with the ObjectPointer and Artificial flags
2744/// set. If the type is not cached, a new one is created. This should
2745/// never happen though, since creating a type for the implicit self
2746/// argument implies that we already parsed the interface definition
2747/// and the ivar declarations in the implementation.
Eric Christopherf0890c42013-05-16 00:52:20 +00002748llvm::DIType CGDebugInfo::CreateSelfType(const QualType &QualTy,
2749 llvm::DIType Ty) {
Adrian Prantle86fcc42013-03-29 19:20:29 +00002750 llvm::DIType CachedTy = getTypeOrNull(QualTy);
2751 if (CachedTy.Verify()) Ty = CachedTy;
2752 else DEBUG(llvm::dbgs() << "No cached type for self.");
2753 return DBuilder.createObjectPointerType(Ty);
2754}
2755
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002756void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(const VarDecl *VD,
2757 llvm::Value *Storage,
2758 CGBuilderTy &Builder,
2759 const CGBlockInfo &blockInfo) {
Eric Christopher13c97672013-05-16 00:45:23 +00002760 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002761 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
Eric Christopher6537f082013-05-16 00:45:12 +00002762
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002763 if (Builder.GetInsertBlock() == 0)
2764 return;
Eric Christopher6537f082013-05-16 00:45:12 +00002765
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002766 bool isByRef = VD->hasAttr<BlocksAttr>();
Eric Christopher6537f082013-05-16 00:45:12 +00002767
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002768 uint64_t XOffset = 0;
2769 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2770 llvm::DIType Ty;
2771 if (isByRef)
2772 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopher6537f082013-05-16 00:45:12 +00002773 else
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002774 Ty = getOrCreateType(VD->getType(), Unit);
2775
2776 // Self is passed along as an implicit non-arg variable in a
2777 // block. Mark it as the object pointer.
2778 if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self")
Adrian Prantle86fcc42013-03-29 19:20:29 +00002779 Ty = CreateSelfType(VD->getType(), Ty);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002780
2781 // Get location information.
2782 unsigned Line = getLineNumber(VD->getLocation());
2783 unsigned Column = getColumnNumber(VD->getLocation());
2784
2785 const llvm::DataLayout &target = CGM.getDataLayout();
2786
2787 CharUnits offset = CharUnits::fromQuantity(
2788 target.getStructLayout(blockInfo.StructureType)
2789 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2790
2791 SmallVector<llvm::Value *, 9> addr;
2792 llvm::Type *Int64Ty = CGM.Int64Ty;
Adrian Prantl9b97adf2013-03-29 19:20:35 +00002793 if (isa<llvm::AllocaInst>(Storage))
2794 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002795 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2796 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2797 if (isByRef) {
2798 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2799 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2800 // offset of __forwarding field
2801 offset = CGM.getContext()
2802 .toCharUnitsFromBits(target.getPointerSizeInBits(0));
2803 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2804 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2805 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2806 // offset of x field
2807 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2808 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2809 }
2810
2811 // Create the descriptor for the variable.
2812 llvm::DIVariable D =
Eric Christopher6537f082013-05-16 00:45:12 +00002813 DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002814 llvm::DIDescriptor(LexicalBlockStack.back()),
2815 VD->getName(), Unit, Line, Ty, addr);
Adrian Prantl9b97adf2013-03-29 19:20:35 +00002816
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002817 // Insert an llvm.dbg.declare into the current block.
2818 llvm::Instruction *Call =
2819 DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
2820 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column,
2821 LexicalBlockStack.back()));
2822}
2823
2824/// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2825/// variable declaration.
2826void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2827 unsigned ArgNo,
2828 CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002829 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002830 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2831}
2832
2833namespace {
2834 struct BlockLayoutChunk {
2835 uint64_t OffsetInBits;
2836 const BlockDecl::Capture *Capture;
2837 };
2838 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2839 return l.OffsetInBits < r.OffsetInBits;
2840 }
2841}
2842
2843void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
Adrian Prantl836e7c92013-03-14 17:53:33 +00002844 llvm::Value *Arg,
2845 llvm::Value *LocalAddr,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002846 CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002847 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002848 ASTContext &C = CGM.getContext();
2849 const BlockDecl *blockDecl = block.getBlockDecl();
2850
2851 // Collect some general information about the block's location.
2852 SourceLocation loc = blockDecl->getCaretLocation();
2853 llvm::DIFile tunit = getOrCreateFile(loc);
2854 unsigned line = getLineNumber(loc);
2855 unsigned column = getColumnNumber(loc);
Eric Christopher6537f082013-05-16 00:45:12 +00002856
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002857 // Build the debug-info type for the block literal.
2858 getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
2859
2860 const llvm::StructLayout *blockLayout =
2861 CGM.getDataLayout().getStructLayout(block.StructureType);
2862
2863 SmallVector<llvm::Value*, 16> fields;
2864 fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
2865 blockLayout->getElementOffsetInBits(0),
2866 tunit, tunit));
2867 fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
2868 blockLayout->getElementOffsetInBits(1),
2869 tunit, tunit));
2870 fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
2871 blockLayout->getElementOffsetInBits(2),
2872 tunit, tunit));
2873 fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
2874 blockLayout->getElementOffsetInBits(3),
2875 tunit, tunit));
2876 fields.push_back(createFieldType("__descriptor",
2877 C.getPointerType(block.NeedsCopyDispose ?
2878 C.getBlockDescriptorExtendedType() :
2879 C.getBlockDescriptorType()),
2880 0, loc, AS_public,
2881 blockLayout->getElementOffsetInBits(4),
2882 tunit, tunit));
2883
2884 // We want to sort the captures by offset, not because DWARF
2885 // requires this, but because we're paranoid about debuggers.
2886 SmallVector<BlockLayoutChunk, 8> chunks;
2887
2888 // 'this' capture.
2889 if (blockDecl->capturesCXXThis()) {
2890 BlockLayoutChunk chunk;
2891 chunk.OffsetInBits =
2892 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
2893 chunk.Capture = 0;
2894 chunks.push_back(chunk);
2895 }
2896
2897 // Variable captures.
2898 for (BlockDecl::capture_const_iterator
2899 i = blockDecl->capture_begin(), e = blockDecl->capture_end();
2900 i != e; ++i) {
2901 const BlockDecl::Capture &capture = *i;
2902 const VarDecl *variable = capture.getVariable();
2903 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
2904
2905 // Ignore constant captures.
2906 if (captureInfo.isConstant())
2907 continue;
2908
2909 BlockLayoutChunk chunk;
2910 chunk.OffsetInBits =
2911 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
2912 chunk.Capture = &capture;
2913 chunks.push_back(chunk);
2914 }
2915
2916 // Sort by offset.
2917 llvm::array_pod_sort(chunks.begin(), chunks.end());
2918
2919 for (SmallVectorImpl<BlockLayoutChunk>::iterator
2920 i = chunks.begin(), e = chunks.end(); i != e; ++i) {
2921 uint64_t offsetInBits = i->OffsetInBits;
2922 const BlockDecl::Capture *capture = i->Capture;
2923
2924 // If we have a null capture, this must be the C++ 'this' capture.
2925 if (!capture) {
2926 const CXXMethodDecl *method =
2927 cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
2928 QualType type = method->getThisType(C);
2929
2930 fields.push_back(createFieldType("this", type, 0, loc, AS_public,
2931 offsetInBits, tunit, tunit));
2932 continue;
2933 }
2934
2935 const VarDecl *variable = capture->getVariable();
2936 StringRef name = variable->getName();
2937
2938 llvm::DIType fieldType;
2939 if (capture->isByRef()) {
2940 std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
2941
2942 // FIXME: this creates a second copy of this type!
2943 uint64_t xoffset;
2944 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
2945 fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
2946 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
2947 ptrInfo.first, ptrInfo.second,
2948 offsetInBits, 0, fieldType);
2949 } else {
2950 fieldType = createFieldType(name, variable->getType(), 0,
2951 loc, AS_public, offsetInBits, tunit, tunit);
2952 }
2953 fields.push_back(fieldType);
2954 }
2955
2956 SmallString<36> typeName;
2957 llvm::raw_svector_ostream(typeName)
2958 << "__block_literal_" << CGM.getUniqueBlockCount();
2959
2960 llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
2961
2962 llvm::DIType type =
2963 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
2964 CGM.getContext().toBits(block.BlockSize),
2965 CGM.getContext().toBits(block.BlockAlign),
David Blaikiec1d0af12013-02-25 01:07:08 +00002966 0, llvm::DIType(), fieldsArray);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002967 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
2968
2969 // Get overall information about the block.
2970 unsigned flags = llvm::DIDescriptor::FlagArtificial;
2971 llvm::MDNode *scope = LexicalBlockStack.back();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002972
2973 // Create the descriptor for the parameter.
2974 llvm::DIVariable debugVar =
2975 DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
Eric Christopher6537f082013-05-16 00:45:12 +00002976 llvm::DIDescriptor(scope),
Adrian Prantl836e7c92013-03-14 17:53:33 +00002977 Arg->getName(), tunit, line, type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002978 CGM.getLangOpts().Optimize, flags,
Adrian Prantl836e7c92013-03-14 17:53:33 +00002979 cast<llvm::Argument>(Arg)->getArgNo() + 1);
2980
Adrian Prantlbea407c2013-03-14 21:52:59 +00002981 if (LocalAddr) {
Adrian Prantl836e7c92013-03-14 17:53:33 +00002982 // Insert an llvm.dbg.value into the current block.
Adrian Prantlbea407c2013-03-14 21:52:59 +00002983 llvm::Instruction *DbgVal =
2984 DBuilder.insertDbgValueIntrinsic(LocalAddr, 0, debugVar,
Eric Christopherf068c922013-04-02 22:59:11 +00002985 Builder.GetInsertBlock());
Adrian Prantlbea407c2013-03-14 21:52:59 +00002986 DbgVal->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
2987 }
Adrian Prantl836e7c92013-03-14 17:53:33 +00002988
Adrian Prantlbea407c2013-03-14 21:52:59 +00002989 // Insert an llvm.dbg.declare into the current block.
2990 llvm::Instruction *DbgDecl =
2991 DBuilder.insertDeclare(Arg, debugVar, Builder.GetInsertBlock());
2992 DbgDecl->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002993}
2994
Eric Christopher0395de32013-01-16 01:22:32 +00002995/// getStaticDataMemberDeclaration - If D is an out-of-class definition of
2996/// a static data member of a class, find its corresponding in-class
2997/// declaration.
2998llvm::DIDerivedType CGDebugInfo::getStaticDataMemberDeclaration(const Decl *D) {
2999 if (cast<VarDecl>(D)->isStaticDataMember()) {
3000 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
3001 MI = StaticDataMemberCache.find(D->getCanonicalDecl());
3002 if (MI != StaticDataMemberCache.end())
3003 // Verify the info still exists.
3004 if (llvm::Value *V = MI->second)
3005 return llvm::DIDerivedType(cast<llvm::MDNode>(V));
3006 }
3007 return llvm::DIDerivedType();
3008}
3009
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003010/// EmitGlobalVariable - Emit information about a global variable.
3011void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
3012 const VarDecl *D) {
Eric Christopher13c97672013-05-16 00:45:23 +00003013 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003014 // Create global variable debug descriptor.
3015 llvm::DIFile Unit = getOrCreateFile(D->getLocation());
3016 unsigned LineNo = getLineNumber(D->getLocation());
3017
3018 setLocation(D->getLocation());
3019
3020 QualType T = D->getType();
3021 if (T->isIncompleteArrayType()) {
3022
3023 // CodeGen turns int[] into int[1] so we'll do the same here.
3024 llvm::APInt ConstVal(32, 1);
3025 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3026
3027 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3028 ArrayType::Normal, 0);
3029 }
3030 StringRef DeclName = D->getName();
3031 StringRef LinkageName;
3032 if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext())
3033 && !isa<ObjCMethodDecl>(D->getDeclContext()))
3034 LinkageName = Var->getName();
3035 if (LinkageName == DeclName)
3036 LinkageName = StringRef();
Eric Christopher6537f082013-05-16 00:45:12 +00003037 llvm::DIDescriptor DContext =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003038 getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
Eric Christopher56b108a2013-06-07 22:54:39 +00003039 llvm::DIGlobalVariable GV =
3040 DBuilder.createStaticVariable(DContext, DeclName, LinkageName, Unit,
3041 LineNo, getOrCreateType(T, Unit),
3042 Var->hasInternalLinkage(), Var,
3043 getStaticDataMemberDeclaration(D));
David Blaikie9faebd22013-05-20 04:58:53 +00003044 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(GV)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003045}
3046
3047/// EmitGlobalVariable - Emit information about an objective-c interface.
3048void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
3049 ObjCInterfaceDecl *ID) {
Eric Christopher13c97672013-05-16 00:45:23 +00003050 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003051 // Create global variable debug descriptor.
3052 llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
3053 unsigned LineNo = getLineNumber(ID->getLocation());
3054
3055 StringRef Name = ID->getName();
3056
3057 QualType T = CGM.getContext().getObjCInterfaceType(ID);
3058 if (T->isIncompleteArrayType()) {
3059
3060 // CodeGen turns int[] into int[1] so we'll do the same here.
3061 llvm::APInt ConstVal(32, 1);
3062 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3063
3064 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3065 ArrayType::Normal, 0);
3066 }
3067
3068 DBuilder.createGlobalVariable(Name, Unit, LineNo,
3069 getOrCreateType(T, Unit),
3070 Var->hasInternalLinkage(), Var);
3071}
3072
3073/// EmitGlobalVariable - Emit global variable's debug info.
Eric Christopher6537f082013-05-16 00:45:12 +00003074void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003075 llvm::Constant *Init) {
Eric Christopher13c97672013-05-16 00:45:23 +00003076 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003077 // Create the descriptor for the variable.
3078 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
3079 StringRef Name = VD->getName();
3080 llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
3081 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
3082 const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext());
3083 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
3084 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
3085 }
3086 // Do not use DIGlobalVariable for enums.
3087 if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
3088 return;
Eric Christopher56b108a2013-06-07 22:54:39 +00003089 llvm::DIGlobalVariable GV =
3090 DBuilder.createStaticVariable(Unit, Name, Name, Unit,
3091 getLineNumber(VD->getLocation()), Ty, true,
3092 Init, getStaticDataMemberDeclaration(VD));
David Blaikie9faebd22013-05-20 04:58:53 +00003093 DeclCache.insert(std::make_pair(VD->getCanonicalDecl(), llvm::WeakVH(GV)));
3094}
3095
3096llvm::DIScope CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
3097 if (!LexicalBlockStack.empty())
3098 return llvm::DIScope(LexicalBlockStack.back());
3099 return getContextDescriptor(D);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003100}
3101
David Blaikie957dac52013-04-22 06:13:21 +00003102void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
David Blaikie9faebd22013-05-20 04:58:53 +00003103 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3104 return;
David Blaikie957dac52013-04-22 06:13:21 +00003105 DBuilder.createImportedModule(
David Blaikie9faebd22013-05-20 04:58:53 +00003106 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
3107 getOrCreateNameSpace(UD.getNominatedNamespace()),
David Blaikie957dac52013-04-22 06:13:21 +00003108 getLineNumber(UD.getLocation()));
3109}
3110
David Blaikie9faebd22013-05-20 04:58:53 +00003111void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
3112 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3113 return;
3114 assert(UD.shadow_size() &&
3115 "We shouldn't be codegening an invalid UsingDecl containing no decls");
3116 // Emitting one decl is sufficient - debuggers can detect that this is an
3117 // overloaded name & provide lookup for all the overloads.
3118 const UsingShadowDecl &USD = **UD.shadow_begin();
Eric Christopher56b108a2013-06-07 22:54:39 +00003119 if (llvm::DIDescriptor Target =
3120 getDeclarationOrDefinition(USD.getUnderlyingDecl()))
David Blaikie9faebd22013-05-20 04:58:53 +00003121 DBuilder.createImportedDeclaration(
3122 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
3123 getLineNumber(USD.getLocation()));
3124}
3125
David Blaikiefc46ebc2013-05-20 22:50:41 +00003126llvm::DIImportedEntity
3127CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
3128 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3129 return llvm::DIImportedEntity(0);
3130 llvm::WeakVH &VH = NamespaceAliasCache[&NA];
3131 if (VH)
3132 return llvm::DIImportedEntity(cast<llvm::MDNode>(VH));
3133 llvm::DIImportedEntity R(0);
3134 if (const NamespaceAliasDecl *Underlying =
3135 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
3136 // This could cache & dedup here rather than relying on metadata deduping.
3137 R = DBuilder.createImportedModule(
3138 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3139 EmitNamespaceAlias(*Underlying), getLineNumber(NA.getLocation()),
3140 NA.getName());
3141 else
3142 R = DBuilder.createImportedModule(
3143 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3144 getOrCreateNameSpace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
3145 getLineNumber(NA.getLocation()), NA.getName());
3146 VH = R;
3147 return R;
3148}
3149
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003150/// getOrCreateNamesSpace - Return namespace descriptor for the given
3151/// namespace decl.
Eric Christopher6537f082013-05-16 00:45:12 +00003152llvm::DINameSpace
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003153CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
Eric Christopher6537f082013-05-16 00:45:12 +00003154 llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003155 NameSpaceCache.find(NSDecl);
3156 if (I != NameSpaceCache.end())
3157 return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
Eric Christopher6537f082013-05-16 00:45:12 +00003158
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003159 unsigned LineNo = getLineNumber(NSDecl->getLocation());
3160 llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
Eric Christopher6537f082013-05-16 00:45:12 +00003161 llvm::DIDescriptor Context =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003162 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
3163 llvm::DINameSpace NS =
3164 DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
3165 NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
3166 return NS;
3167}
3168
3169void CGDebugInfo::finalize() {
3170 for (std::vector<std::pair<void *, llvm::WeakVH> >::const_iterator VI
3171 = ReplaceMap.begin(), VE = ReplaceMap.end(); VI != VE; ++VI) {
3172 llvm::DIType Ty, RepTy;
3173 // Verify that the debug info still exists.
3174 if (llvm::Value *V = VI->second)
3175 Ty = llvm::DIType(cast<llvm::MDNode>(V));
Eric Christopher6537f082013-05-16 00:45:12 +00003176
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003177 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
3178 TypeCache.find(VI->first);
3179 if (it != TypeCache.end()) {
3180 // Verify that the debug info still exists.
3181 if (llvm::Value *V = it->second)
3182 RepTy = llvm::DIType(cast<llvm::MDNode>(V));
3183 }
Adrian Prantlebbd7e02013-03-11 18:33:46 +00003184
Adrian Prantl9b97adf2013-03-29 19:20:35 +00003185 if (Ty.Verify() && Ty.isForwardDecl() && RepTy.Verify())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003186 Ty.replaceAllUsesWith(RepTy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003187 }
Adrian Prantlebbd7e02013-03-11 18:33:46 +00003188
3189 // We keep our own list of retained types, because we need to look
3190 // up the final type in the type cache.
3191 for (std::vector<void *>::const_iterator RI = RetainedTypes.begin(),
3192 RE = RetainedTypes.end(); RI != RE; ++RI)
3193 DBuilder.retainType(llvm::DIType(cast<llvm::MDNode>(TypeCache[*RI])));
3194
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003195 DBuilder.finalize();
3196}