blob: e38327a92707eb12a7330de5b5ace74647578703 [file] [log] [blame]
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001//===--- CGDebugInfo.cpp - Emit Debug Information for a Module ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the debug information generation while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGDebugInfo.h"
15#include "CGBlocks.h"
David Blaikie9dfd2432013-05-10 21:53:14 +000016#include "CGCXXABI.h"
Guy Benyei7f92f2d2012-12-18 14:30:41 +000017#include "CGObjCRuntime.h"
18#include "CodeGenFunction.h"
19#include "CodeGenModule.h"
20#include "clang/AST/ASTContext.h"
21#include "clang/AST/DeclFriend.h"
22#include "clang/AST/DeclObjC.h"
23#include "clang/AST/DeclTemplate.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/RecordLayout.h"
26#include "clang/Basic/FileManager.h"
27#include "clang/Basic/SourceManager.h"
28#include "clang/Basic/Version.h"
29#include "clang/Frontend/CodeGenOptions.h"
30#include "llvm/ADT/SmallVector.h"
31#include "llvm/ADT/StringExtras.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000032#include "llvm/IR/Constants.h"
33#include "llvm/IR/DataLayout.h"
34#include "llvm/IR/DerivedTypes.h"
35#include "llvm/IR/Instructions.h"
36#include "llvm/IR/Intrinsics.h"
37#include "llvm/IR/Module.h"
Guy Benyei7f92f2d2012-12-18 14:30:41 +000038#include "llvm/Support/Dwarf.h"
39#include "llvm/Support/FileSystem.h"
40using namespace clang;
41using namespace clang::CodeGen;
42
43CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
Eric Christopher13c97672013-05-16 00:45:23 +000044 : CGM(CGM), DebugKind(CGM.getCodeGenOpts().getDebugInfo()),
45 DBuilder(CGM.getModule()),
Guy Benyei7f92f2d2012-12-18 14:30:41 +000046 BlockLiteralGenericSet(false) {
47 CreateCompileUnit();
48}
49
50CGDebugInfo::~CGDebugInfo() {
51 assert(LexicalBlockStack.empty() &&
52 "Region stack mismatch, stack not empty!");
53}
54
55void CGDebugInfo::setLocation(SourceLocation Loc) {
56 // If the new location isn't valid return.
57 if (!Loc.isValid()) return;
58
59 CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc);
60
61 // If we've changed files in the middle of a lexical scope go ahead
62 // and create a new lexical scope with file node if it's different
63 // from the one in the scope.
64 if (LexicalBlockStack.empty()) return;
65
66 SourceManager &SM = CGM.getContext().getSourceManager();
67 PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
68 PresumedLoc PPLoc = SM.getPresumedLoc(PrevLoc);
69
70 if (PCLoc.isInvalid() || PPLoc.isInvalid() ||
71 !strcmp(PPLoc.getFilename(), PCLoc.getFilename()))
72 return;
73
74 llvm::MDNode *LB = LexicalBlockStack.back();
75 llvm::DIScope Scope = llvm::DIScope(LB);
76 if (Scope.isLexicalBlockFile()) {
77 llvm::DILexicalBlockFile LBF = llvm::DILexicalBlockFile(LB);
78 llvm::DIDescriptor D
79 = DBuilder.createLexicalBlockFile(LBF.getScope(),
80 getOrCreateFile(CurLoc));
81 llvm::MDNode *N = D;
82 LexicalBlockStack.pop_back();
83 LexicalBlockStack.push_back(N);
David Blaikiea6504852013-01-26 22:16:26 +000084 } else if (Scope.isLexicalBlock() || Scope.isSubprogram()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +000085 llvm::DIDescriptor D
86 = DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc));
87 llvm::MDNode *N = D;
88 LexicalBlockStack.pop_back();
89 LexicalBlockStack.push_back(N);
90 }
91}
92
93/// getContextDescriptor - Get context info for the decl.
David Blaikiebb000792013-04-19 06:56:38 +000094llvm::DIScope CGDebugInfo::getContextDescriptor(const Decl *Context) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +000095 if (!Context)
96 return TheCU;
97
98 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
99 I = RegionMap.find(Context);
100 if (I != RegionMap.end()) {
101 llvm::Value *V = I->second;
David Blaikiebb000792013-04-19 06:56:38 +0000102 return llvm::DIScope(dyn_cast_or_null<llvm::MDNode>(V));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000103 }
104
105 // Check namespace.
106 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
David Blaikiebb000792013-04-19 06:56:38 +0000107 return getOrCreateNameSpace(NSDecl);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000108
David Blaikiebb000792013-04-19 06:56:38 +0000109 if (const RecordDecl *RDecl = dyn_cast<RecordDecl>(Context))
110 if (!RDecl->isDependentType())
111 return getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000112 getOrCreateMainFile());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000113 return TheCU;
114}
115
116/// getFunctionName - Get function name for the given FunctionDecl. If the
117/// name is constructred on demand (e.g. C++ destructor) then the name
118/// is stored on the side.
119StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
120 assert (FD && "Invalid FunctionDecl!");
121 IdentifierInfo *FII = FD->getIdentifier();
122 FunctionTemplateSpecializationInfo *Info
123 = FD->getTemplateSpecializationInfo();
124 if (!Info && FII)
125 return FII->getName();
126
127 // Otherwise construct human readable name for debug info.
Benjamin Kramer5eada842013-02-22 15:46:01 +0000128 SmallString<128> NS;
129 llvm::raw_svector_ostream OS(NS);
130 FD->printName(OS);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000131
132 // Add any template specialization args.
133 if (Info) {
134 const TemplateArgumentList *TArgs = Info->TemplateArguments;
135 const TemplateArgument *Args = TArgs->data();
136 unsigned NumArgs = TArgs->size();
137 PrintingPolicy Policy(CGM.getLangOpts());
Benjamin Kramer5eada842013-02-22 15:46:01 +0000138 TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs,
139 Policy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000140 }
141
142 // Copy this name on the side and use its reference.
Benjamin Kramer5eada842013-02-22 15:46:01 +0000143 OS.flush();
144 char *StrPtr = DebugInfoNames.Allocate<char>(NS.size());
145 memcpy(StrPtr, NS.data(), NS.size());
146 return StringRef(StrPtr, NS.size());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000147}
148
149StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
150 SmallString<256> MethodName;
151 llvm::raw_svector_ostream OS(MethodName);
152 OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
153 const DeclContext *DC = OMD->getDeclContext();
Eric Christopher6537f082013-05-16 00:45:12 +0000154 if (const ObjCImplementationDecl *OID =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000155 dyn_cast<const ObjCImplementationDecl>(DC)) {
156 OS << OID->getName();
Eric Christopher6537f082013-05-16 00:45:12 +0000157 } else if (const ObjCInterfaceDecl *OID =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000158 dyn_cast<const ObjCInterfaceDecl>(DC)) {
159 OS << OID->getName();
Eric Christopher6537f082013-05-16 00:45:12 +0000160 } else if (const ObjCCategoryImplDecl *OCD =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000161 dyn_cast<const ObjCCategoryImplDecl>(DC)){
162 OS << ((const NamedDecl *)OCD)->getIdentifier()->getNameStart() << '(' <<
163 OCD->getIdentifier()->getNameStart() << ')';
Adrian Prantlb5092242013-05-17 23:58:45 +0000164 } else if (isa<ObjCProtocolDecl>(DC)) {
Adrian Prantl687ecae2013-05-17 23:49:10 +0000165 // We can extract the type of the class from the self pointer.
166 if (ImplicitParamDecl* SelfDecl = OMD->getSelfDecl()) {
167 QualType ClassTy =
168 cast<ObjCObjectPointerType>(SelfDecl->getType())->getPointeeType();
169 ClassTy.print(OS, PrintingPolicy(LangOptions()));
170 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000171 }
172 OS << ' ' << OMD->getSelector().getAsString() << ']';
173
174 char *StrPtr = DebugInfoNames.Allocate<char>(OS.tell());
175 memcpy(StrPtr, MethodName.begin(), OS.tell());
176 return StringRef(StrPtr, OS.tell());
177}
178
179/// getSelectorName - Return selector name. This is used for debugging
180/// info.
181StringRef CGDebugInfo::getSelectorName(Selector S) {
182 const std::string &SName = S.getAsString();
183 char *StrPtr = DebugInfoNames.Allocate<char>(SName.size());
184 memcpy(StrPtr, SName.data(), SName.size());
185 return StringRef(StrPtr, SName.size());
186}
187
188/// getClassName - Get class name including template argument list.
Eric Christopher6537f082013-05-16 00:45:12 +0000189StringRef
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000190CGDebugInfo::getClassName(const RecordDecl *RD) {
191 const ClassTemplateSpecializationDecl *Spec
192 = dyn_cast<ClassTemplateSpecializationDecl>(RD);
193 if (!Spec)
194 return RD->getName();
195
196 const TemplateArgument *Args;
197 unsigned NumArgs;
198 if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) {
199 const TemplateSpecializationType *TST =
200 cast<TemplateSpecializationType>(TAW->getType());
201 Args = TST->getArgs();
202 NumArgs = TST->getNumArgs();
203 } else {
204 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
205 Args = TemplateArgs.data();
206 NumArgs = TemplateArgs.size();
207 }
208 StringRef Name = RD->getIdentifier()->getName();
209 PrintingPolicy Policy(CGM.getLangOpts());
Benjamin Kramer5eada842013-02-22 15:46:01 +0000210 SmallString<128> TemplateArgList;
211 {
212 llvm::raw_svector_ostream OS(TemplateArgList);
213 TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs,
214 Policy);
215 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000216
217 // Copy this name on the side and use its reference.
218 size_t Length = Name.size() + TemplateArgList.size();
219 char *StrPtr = DebugInfoNames.Allocate<char>(Length);
220 memcpy(StrPtr, Name.data(), Name.size());
221 memcpy(StrPtr + Name.size(), TemplateArgList.data(), TemplateArgList.size());
222 return StringRef(StrPtr, Length);
223}
224
225/// getOrCreateFile - Get the file debug info descriptor for the input location.
226llvm::DIFile CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
227 if (!Loc.isValid())
228 // If Location is not valid then use main input file.
229 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
230
231 SourceManager &SM = CGM.getContext().getSourceManager();
232 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
233
234 if (PLoc.isInvalid() || StringRef(PLoc.getFilename()).empty())
235 // If the location is not valid then use main input file.
236 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
237
238 // Cache the results.
239 const char *fname = PLoc.getFilename();
240 llvm::DenseMap<const char *, llvm::WeakVH>::iterator it =
241 DIFileCache.find(fname);
242
243 if (it != DIFileCache.end()) {
244 // Verify that the information still exists.
245 if (llvm::Value *V = it->second)
246 return llvm::DIFile(cast<llvm::MDNode>(V));
247 }
248
249 llvm::DIFile F = DBuilder.createFile(PLoc.getFilename(), getCurrentDirname());
250
251 DIFileCache[fname] = F;
252 return F;
253}
254
255/// getOrCreateMainFile - Get the file info for main compile unit.
256llvm::DIFile CGDebugInfo::getOrCreateMainFile() {
257 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
258}
259
260/// getLineNumber - Get line number for the location. If location is invalid
261/// then use current location.
262unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
263 if (Loc.isInvalid() && CurLoc.isInvalid())
264 return 0;
265 SourceManager &SM = CGM.getContext().getSourceManager();
266 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
267 return PLoc.isValid()? PLoc.getLine() : 0;
268}
269
270/// getColumnNumber - Get column number for the location.
Adrian Prantl00df5ea2013-03-12 20:43:25 +0000271unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000272 // We may not want column information at all.
Adrian Prantl00df5ea2013-03-12 20:43:25 +0000273 if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000274 return 0;
275
276 // If the location is invalid then use the current column.
277 if (Loc.isInvalid() && CurLoc.isInvalid())
278 return 0;
279 SourceManager &SM = CGM.getContext().getSourceManager();
280 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
281 return PLoc.isValid()? PLoc.getColumn() : 0;
282}
283
284StringRef CGDebugInfo::getCurrentDirname() {
285 if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
286 return CGM.getCodeGenOpts().DebugCompilationDir;
287
288 if (!CWDName.empty())
289 return CWDName;
290 SmallString<256> CWD;
291 llvm::sys::fs::current_path(CWD);
292 char *CompDirnamePtr = DebugInfoNames.Allocate<char>(CWD.size());
293 memcpy(CompDirnamePtr, CWD.data(), CWD.size());
294 return CWDName = StringRef(CompDirnamePtr, CWD.size());
295}
296
297/// CreateCompileUnit - Create new compile unit.
298void CGDebugInfo::CreateCompileUnit() {
299
300 // Get absolute path name.
301 SourceManager &SM = CGM.getContext().getSourceManager();
302 std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
303 if (MainFileName.empty())
304 MainFileName = "<unknown>";
305
306 // The main file name provided via the "-main-file-name" option contains just
307 // the file name itself with no path information. This file name may have had
308 // a relative path, so we look into the actual file entry for the main
309 // file to determine the real absolute path for the file.
310 std::string MainFileDir;
311 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
312 MainFileDir = MainFile->getDir()->getName();
313 if (MainFileDir != ".")
314 MainFileName = MainFileDir + "/" + MainFileName;
315 }
316
317 // Save filename string.
318 char *FilenamePtr = DebugInfoNames.Allocate<char>(MainFileName.length());
319 memcpy(FilenamePtr, MainFileName.c_str(), MainFileName.length());
320 StringRef Filename(FilenamePtr, MainFileName.length());
Eric Christopherff971d72013-02-22 23:50:16 +0000321
322 // Save split dwarf file string.
323 std::string SplitDwarfFile = CGM.getCodeGenOpts().SplitDwarfFile;
324 char *SplitDwarfPtr = DebugInfoNames.Allocate<char>(SplitDwarfFile.length());
325 memcpy(SplitDwarfPtr, SplitDwarfFile.c_str(), SplitDwarfFile.length());
326 StringRef SplitDwarfFilename(SplitDwarfPtr, SplitDwarfFile.length());
Eric Christopher6537f082013-05-16 00:45:12 +0000327
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000328 unsigned LangTag;
329 const LangOptions &LO = CGM.getLangOpts();
330 if (LO.CPlusPlus) {
331 if (LO.ObjC1)
332 LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
333 else
334 LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
335 } else if (LO.ObjC1) {
336 LangTag = llvm::dwarf::DW_LANG_ObjC;
337 } else if (LO.C99) {
338 LangTag = llvm::dwarf::DW_LANG_C99;
339 } else {
340 LangTag = llvm::dwarf::DW_LANG_C89;
341 }
342
343 std::string Producer = getClangFullVersion();
344
345 // Figure out which version of the ObjC runtime we have.
346 unsigned RuntimeVers = 0;
347 if (LO.ObjC1)
348 RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
349
350 // Create new compile unit.
Eric Christopherbe5f1be2013-02-21 22:35:08 +0000351 DBuilder.createCompileUnit(LangTag, Filename, getCurrentDirname(),
352 Producer, LO.Optimize,
Eric Christopherff971d72013-02-22 23:50:16 +0000353 CGM.getCodeGenOpts().DwarfDebugFlags,
354 RuntimeVers, SplitDwarfFilename);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000355 // FIXME - Eliminate TheCU.
356 TheCU = llvm::DICompileUnit(DBuilder.getCU());
357}
358
359/// CreateType - Get the Basic type from the cache or create a new
360/// one if necessary.
361llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT) {
362 unsigned Encoding = 0;
363 StringRef BTName;
364 switch (BT->getKind()) {
365#define BUILTIN_TYPE(Id, SingletonId)
366#define PLACEHOLDER_TYPE(Id, SingletonId) \
367 case BuiltinType::Id:
368#include "clang/AST/BuiltinTypes.def"
369 case BuiltinType::Dependent:
370 llvm_unreachable("Unexpected builtin type");
371 case BuiltinType::NullPtr:
372 return DBuilder.
373 createNullPtrType(BT->getName(CGM.getLangOpts()));
374 case BuiltinType::Void:
375 return llvm::DIType();
376 case BuiltinType::ObjCClass:
377 if (ClassTy.Verify())
378 return ClassTy;
379 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
380 "objc_class", TheCU,
381 getOrCreateMainFile(), 0);
382 return ClassTy;
383 case BuiltinType::ObjCId: {
384 // typedef struct objc_class *Class;
385 // typedef struct objc_object {
386 // Class isa;
387 // } *id;
388
389 if (ObjTy.Verify())
390 return ObjTy;
391
392 if (!ClassTy.Verify())
393 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
394 "objc_class", TheCU,
395 getOrCreateMainFile(), 0);
396
397 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
Eric Christopher6537f082013-05-16 00:45:12 +0000398
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000399 llvm::DIType ISATy = DBuilder.createPointerType(ClassTy, Size);
400
Eric Christopherf068c922013-04-02 22:59:11 +0000401 ObjTy =
David Blaikiec1d0af12013-02-25 01:07:08 +0000402 DBuilder.createStructType(TheCU, "objc_object", getOrCreateMainFile(),
403 0, 0, 0, 0, llvm::DIType(), llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000404
Eric Christopherf068c922013-04-02 22:59:11 +0000405 ObjTy.setTypeArray(DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
406 ObjTy, "isa", getOrCreateMainFile(), 0, Size, 0, 0, 0, ISATy)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000407 return ObjTy;
408 }
409 case BuiltinType::ObjCSel: {
410 if (SelTy.Verify())
411 return SelTy;
412 SelTy =
413 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
414 "objc_selector", TheCU, getOrCreateMainFile(),
415 0);
416 return SelTy;
417 }
Guy Benyeib13621d2012-12-18 14:38:23 +0000418
419 case BuiltinType::OCLImage1d:
420 return getOrCreateStructPtrType("opencl_image1d_t",
421 OCLImage1dDITy);
422 case BuiltinType::OCLImage1dArray:
Eric Christopher6537f082013-05-16 00:45:12 +0000423 return getOrCreateStructPtrType("opencl_image1d_array_t",
Guy Benyeib13621d2012-12-18 14:38:23 +0000424 OCLImage1dArrayDITy);
425 case BuiltinType::OCLImage1dBuffer:
426 return getOrCreateStructPtrType("opencl_image1d_buffer_t",
427 OCLImage1dBufferDITy);
428 case BuiltinType::OCLImage2d:
429 return getOrCreateStructPtrType("opencl_image2d_t",
430 OCLImage2dDITy);
431 case BuiltinType::OCLImage2dArray:
432 return getOrCreateStructPtrType("opencl_image2d_array_t",
433 OCLImage2dArrayDITy);
434 case BuiltinType::OCLImage3d:
435 return getOrCreateStructPtrType("opencl_image3d_t",
436 OCLImage3dDITy);
Guy Benyei21f18c42013-02-07 10:55:47 +0000437 case BuiltinType::OCLSampler:
438 return DBuilder.createBasicType("opencl_sampler_t",
439 CGM.getContext().getTypeSize(BT),
440 CGM.getContext().getTypeAlign(BT),
441 llvm::dwarf::DW_ATE_unsigned);
Guy Benyeie6b9d802013-01-20 12:31:11 +0000442 case BuiltinType::OCLEvent:
443 return getOrCreateStructPtrType("opencl_event_t",
444 OCLEventDITy);
Guy Benyeib13621d2012-12-18 14:38:23 +0000445
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000446 case BuiltinType::UChar:
447 case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
448 case BuiltinType::Char_S:
449 case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
450 case BuiltinType::Char16:
451 case BuiltinType::Char32: Encoding = llvm::dwarf::DW_ATE_UTF; break;
452 case BuiltinType::UShort:
453 case BuiltinType::UInt:
454 case BuiltinType::UInt128:
455 case BuiltinType::ULong:
456 case BuiltinType::WChar_U:
457 case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
458 case BuiltinType::Short:
459 case BuiltinType::Int:
460 case BuiltinType::Int128:
461 case BuiltinType::Long:
462 case BuiltinType::WChar_S:
463 case BuiltinType::LongLong: Encoding = llvm::dwarf::DW_ATE_signed; break;
464 case BuiltinType::Bool: Encoding = llvm::dwarf::DW_ATE_boolean; break;
465 case BuiltinType::Half:
466 case BuiltinType::Float:
467 case BuiltinType::LongDouble:
468 case BuiltinType::Double: Encoding = llvm::dwarf::DW_ATE_float; break;
469 }
470
471 switch (BT->getKind()) {
472 case BuiltinType::Long: BTName = "long int"; break;
473 case BuiltinType::LongLong: BTName = "long long int"; break;
474 case BuiltinType::ULong: BTName = "long unsigned int"; break;
475 case BuiltinType::ULongLong: BTName = "long long unsigned int"; break;
476 default:
477 BTName = BT->getName(CGM.getLangOpts());
478 break;
479 }
480 // Bit size, align and offset of the type.
481 uint64_t Size = CGM.getContext().getTypeSize(BT);
482 uint64_t Align = CGM.getContext().getTypeAlign(BT);
Eric Christopher6537f082013-05-16 00:45:12 +0000483 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000484 DBuilder.createBasicType(BTName, Size, Align, Encoding);
485 return DbgTy;
486}
487
488llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty) {
489 // Bit size, align and offset of the type.
490 unsigned Encoding = llvm::dwarf::DW_ATE_complex_float;
491 if (Ty->isComplexIntegerType())
492 Encoding = llvm::dwarf::DW_ATE_lo_user;
493
494 uint64_t Size = CGM.getContext().getTypeSize(Ty);
495 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
Eric Christopher6537f082013-05-16 00:45:12 +0000496 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000497 DBuilder.createBasicType("complex", Size, Align, Encoding);
498
499 return DbgTy;
500}
501
502/// CreateCVRType - Get the qualified type from the cache or create
503/// a new one if necessary.
Eric Christopher56b108a2013-06-07 22:54:39 +0000504llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit,
505 bool Declaration) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000506 QualifierCollector Qc;
507 const Type *T = Qc.strip(Ty);
508
509 // Ignore these qualifiers for now.
510 Qc.removeObjCGCAttr();
511 Qc.removeAddressSpace();
512 Qc.removeObjCLifetime();
513
514 // We will create one Derived type for one qualifier and recurse to handle any
515 // additional ones.
516 unsigned Tag;
517 if (Qc.hasConst()) {
518 Tag = llvm::dwarf::DW_TAG_const_type;
519 Qc.removeConst();
520 } else if (Qc.hasVolatile()) {
521 Tag = llvm::dwarf::DW_TAG_volatile_type;
522 Qc.removeVolatile();
523 } else if (Qc.hasRestrict()) {
524 Tag = llvm::dwarf::DW_TAG_restrict_type;
525 Qc.removeRestrict();
526 } else {
527 assert(Qc.empty() && "Unknown type qualifier for debug info");
528 return getOrCreateType(QualType(T, 0), Unit);
529 }
530
Eric Christopher56b108a2013-06-07 22:54:39 +0000531 llvm::DIType FromTy =
532 getOrCreateType(Qc.apply(CGM.getContext(), T), Unit, Declaration);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000533
534 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
535 // CVR derived types.
536 llvm::DIType DbgTy = DBuilder.createQualifiedType(Tag, FromTy);
Eric Christopher6537f082013-05-16 00:45:12 +0000537
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000538 return DbgTy;
539}
540
541llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
542 llvm::DIFile Unit) {
Fariborz Jahanian05f8ff12013-02-21 20:42:11 +0000543
544 // The frontend treats 'id' as a typedef to an ObjCObjectType,
545 // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
546 // debug info, we want to emit 'id' in both cases.
547 if (Ty->isObjCQualifiedIdType())
548 return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
549
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000550 llvm::DIType DbgTy =
Eric Christopher6537f082013-05-16 00:45:12 +0000551 CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000552 Ty->getPointeeType(), Unit);
553 return DbgTy;
554}
555
556llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
557 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +0000558 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000559 Ty->getPointeeType(), Unit);
560}
561
562// Creates a forward declaration for a RecordDecl in the given context.
563llvm::DIType CGDebugInfo::createRecordFwdDecl(const RecordDecl *RD,
564 llvm::DIDescriptor Ctx) {
565 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
566 unsigned Line = getLineNumber(RD->getLocation());
567 StringRef RDName = getClassName(RD);
568
569 unsigned Tag = 0;
570 if (RD->isStruct() || RD->isInterface())
571 Tag = llvm::dwarf::DW_TAG_structure_type;
572 else if (RD->isUnion())
573 Tag = llvm::dwarf::DW_TAG_union_type;
574 else {
575 assert(RD->isClass());
576 Tag = llvm::dwarf::DW_TAG_class_type;
577 }
578
579 // Create the type.
580 return DBuilder.createForwardDecl(Tag, RDName, Ctx, DefUnit, Line);
581}
582
583// Walk up the context chain and create forward decls for record decls,
584// and normal descriptors for namespaces.
585llvm::DIDescriptor CGDebugInfo::createContextChain(const Decl *Context) {
586 if (!Context)
587 return TheCU;
588
589 // See if we already have the parent.
590 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
591 I = RegionMap.find(Context);
592 if (I != RegionMap.end()) {
593 llvm::Value *V = I->second;
594 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
595 }
Eric Christopher6537f082013-05-16 00:45:12 +0000596
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000597 // Check namespace.
598 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
599 return llvm::DIDescriptor(getOrCreateNameSpace(NSDecl));
600
601 if (const RecordDecl *RD = dyn_cast<RecordDecl>(Context)) {
602 if (!RD->isDependentType()) {
Eric Christopherf0890c42013-05-16 00:52:20 +0000603 llvm::DIType Ty =
604 getOrCreateLimitedType(CGM.getContext().getTypeDeclType(RD),
605 getOrCreateMainFile());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000606 return llvm::DIDescriptor(Ty);
607 }
608 }
609 return TheCU;
610}
611
David Blaikieb0f77b02013-05-24 21:33:22 +0000612/// getOrCreateTypeDeclaration - Create Pointee type. If Pointee is a record
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000613/// then emit record's fwd if debug info size reduction is enabled.
David Blaikieb0f77b02013-05-24 21:33:22 +0000614llvm::DIType CGDebugInfo::getOrCreateTypeDeclaration(QualType PointeeTy,
615 llvm::DIFile Unit) {
David Blaikie9faebd22013-05-20 04:58:53 +0000616 if (DebugKind > CodeGenOptions::LimitedDebugInfo)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000617 return getOrCreateType(PointeeTy, Unit);
David Blaikie5f6e2f42013-06-05 05:32:23 +0000618 return getOrCreateType(PointeeTy, Unit, true);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000619}
620
621llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag,
Eric Christopher6537f082013-05-16 00:45:12 +0000622 const Type *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000623 QualType PointeeTy,
624 llvm::DIFile Unit) {
625 if (Tag == llvm::dwarf::DW_TAG_reference_type ||
626 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
David Blaikieb0f77b02013-05-24 21:33:22 +0000627 return DBuilder.createReferenceType(
628 Tag, getOrCreateTypeDeclaration(PointeeTy, Unit));
Fariborz Jahanian05f8ff12013-02-21 20:42:11 +0000629
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000630 // Bit size, align and offset of the type.
631 // Size is always the size of a pointer. We can't use getTypeSize here
632 // because that does not return the correct value for references.
633 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCall64aa4b32013-04-16 22:48:15 +0000634 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000635 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
636
David Blaikieb0f77b02013-05-24 21:33:22 +0000637 return DBuilder.createPointerType(getOrCreateTypeDeclaration(PointeeTy, Unit),
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000638 Size, Align);
639}
640
Eric Christopherf0890c42013-05-16 00:52:20 +0000641llvm::DIType CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
642 llvm::DIType &Cache) {
David Blaikie1e97c1e2013-05-21 17:58:54 +0000643 if (Cache.Verify())
Guy Benyeib13621d2012-12-18 14:38:23 +0000644 return Cache;
David Blaikie1e97c1e2013-05-21 17:58:54 +0000645 Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
646 TheCU, getOrCreateMainFile(), 0);
647 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
648 Cache = DBuilder.createPointerType(Cache, Size);
649 return Cache;
Guy Benyeib13621d2012-12-18 14:38:23 +0000650}
651
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000652llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
653 llvm::DIFile Unit) {
654 if (BlockLiteralGenericSet)
655 return BlockLiteralGeneric;
656
657 SmallVector<llvm::Value *, 8> EltTys;
658 llvm::DIType FieldTy;
659 QualType FType;
660 uint64_t FieldSize, FieldOffset;
661 unsigned FieldAlign;
662 llvm::DIArray Elements;
663 llvm::DIType EltTy, DescTy;
664
665 FieldOffset = 0;
666 FType = CGM.getContext().UnsignedLongTy;
667 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
668 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
669
670 Elements = DBuilder.getOrCreateArray(EltTys);
671 EltTys.clear();
672
673 unsigned Flags = llvm::DIDescriptor::FlagAppleBlock;
674 unsigned LineNo = getLineNumber(CurLoc);
675
676 EltTy = DBuilder.createStructType(Unit, "__block_descriptor",
677 Unit, LineNo, FieldOffset, 0,
David Blaikiec1d0af12013-02-25 01:07:08 +0000678 Flags, llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000679
680 // Bit size, align and offset of the type.
681 uint64_t Size = CGM.getContext().getTypeSize(Ty);
682
683 DescTy = DBuilder.createPointerType(EltTy, Size);
684
685 FieldOffset = 0;
686 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
687 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
688 FType = CGM.getContext().IntTy;
689 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
690 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
691 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
692 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
693
694 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
695 FieldTy = DescTy;
696 FieldSize = CGM.getContext().getTypeSize(Ty);
697 FieldAlign = CGM.getContext().getTypeAlign(Ty);
698 FieldTy = DBuilder.createMemberType(Unit, "__descriptor", Unit,
699 LineNo, FieldSize, FieldAlign,
700 FieldOffset, 0, FieldTy);
701 EltTys.push_back(FieldTy);
702
703 FieldOffset += FieldSize;
704 Elements = DBuilder.getOrCreateArray(EltTys);
705
706 EltTy = DBuilder.createStructType(Unit, "__block_literal_generic",
707 Unit, LineNo, FieldOffset, 0,
David Blaikiec1d0af12013-02-25 01:07:08 +0000708 Flags, llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000709
710 BlockLiteralGenericSet = true;
711 BlockLiteralGeneric = DBuilder.createPointerType(EltTy, Size);
712 return BlockLiteralGeneric;
713}
714
David Blaikie5f6e2f42013-06-05 05:32:23 +0000715llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty, llvm::DIFile Unit,
716 bool Declaration) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000717 // Typedefs are derived from some other type. If we have a typedef of a
718 // typedef, make sure to emit the whole chain.
David Blaikieb0f77b02013-05-24 21:33:22 +0000719 llvm::DIType Src =
David Blaikie5f6e2f42013-06-05 05:32:23 +0000720 getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit, Declaration);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000721 if (!Src.Verify())
722 return llvm::DIType();
723 // We don't set size information, but do specify where the typedef was
724 // declared.
725 unsigned Line = getLineNumber(Ty->getDecl()->getLocation());
726 const TypedefNameDecl *TyDecl = Ty->getDecl();
Eric Christopher6537f082013-05-16 00:45:12 +0000727
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000728 llvm::DIDescriptor TypedefContext =
729 getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext()));
Eric Christopher6537f082013-05-16 00:45:12 +0000730
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000731 return
732 DBuilder.createTypedef(Src, TyDecl->getName(), Unit, Line, TypedefContext);
733}
734
735llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
736 llvm::DIFile Unit) {
737 SmallVector<llvm::Value *, 16> EltTys;
738
739 // Add the result type at least.
740 EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit));
741
742 // Set up remainder of arguments if there is a prototype.
743 // FIXME: IF NOT, HOW IS THIS REPRESENTED? llvm-gcc doesn't represent '...'!
744 if (isa<FunctionNoProtoType>(Ty))
745 EltTys.push_back(DBuilder.createUnspecifiedParameter());
746 else if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Ty)) {
747 for (unsigned i = 0, e = FPT->getNumArgs(); i != e; ++i)
748 EltTys.push_back(getOrCreateType(FPT->getArgType(i), Unit));
749 }
750
751 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
752 return DBuilder.createSubroutineType(Unit, EltTypeArray);
753}
754
755
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000756llvm::DIType CGDebugInfo::createFieldType(StringRef name,
757 QualType type,
758 uint64_t sizeInBitsOverride,
759 SourceLocation loc,
760 AccessSpecifier AS,
761 uint64_t offsetInBits,
762 llvm::DIFile tunit,
763 llvm::DIDescriptor scope) {
764 llvm::DIType debugType = getOrCreateType(type, tunit);
765
766 // Get the location for the field.
767 llvm::DIFile file = getOrCreateFile(loc);
768 unsigned line = getLineNumber(loc);
769
770 uint64_t sizeInBits = 0;
771 unsigned alignInBits = 0;
772 if (!type->isIncompleteArrayType()) {
773 llvm::tie(sizeInBits, alignInBits) = CGM.getContext().getTypeInfo(type);
774
775 if (sizeInBitsOverride)
776 sizeInBits = sizeInBitsOverride;
777 }
778
779 unsigned flags = 0;
780 if (AS == clang::AS_private)
781 flags |= llvm::DIDescriptor::FlagPrivate;
782 else if (AS == clang::AS_protected)
783 flags |= llvm::DIDescriptor::FlagProtected;
784
785 return DBuilder.createMemberType(scope, name, file, line, sizeInBits,
786 alignInBits, offsetInBits, flags, debugType);
787}
788
Eric Christopher0395de32013-01-16 01:22:32 +0000789/// CollectRecordLambdaFields - Helper for CollectRecordFields.
790void CGDebugInfo::
791CollectRecordLambdaFields(const CXXRecordDecl *CXXDecl,
792 SmallVectorImpl<llvm::Value *> &elements,
793 llvm::DIType RecordTy) {
794 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
795 // has the name and the location of the variable so we should iterate over
796 // both concurrently.
797 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
798 RecordDecl::field_iterator Field = CXXDecl->field_begin();
799 unsigned fieldno = 0;
800 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
801 E = CXXDecl->captures_end(); I != E; ++I, ++Field, ++fieldno) {
802 const LambdaExpr::Capture C = *I;
803 if (C.capturesVariable()) {
804 VarDecl *V = C.getCapturedVar();
805 llvm::DIFile VUnit = getOrCreateFile(C.getLocation());
806 StringRef VName = V->getName();
807 uint64_t SizeInBitsOverride = 0;
808 if (Field->isBitField()) {
809 SizeInBitsOverride = Field->getBitWidthValue(CGM.getContext());
810 assert(SizeInBitsOverride && "found named 0-width bitfield");
811 }
812 llvm::DIType fieldType
813 = createFieldType(VName, Field->getType(), SizeInBitsOverride,
814 C.getLocation(), Field->getAccess(),
815 layout.getFieldOffset(fieldno), VUnit, RecordTy);
816 elements.push_back(fieldType);
817 } else {
818 // TODO: Need to handle 'this' in some way by probably renaming the
819 // this of the lambda class and having a field member of 'this' or
820 // by using AT_object_pointer for the function and having that be
821 // used as 'this' for semantic references.
822 assert(C.capturesThis() && "Field that isn't captured and isn't this?");
823 FieldDecl *f = *Field;
824 llvm::DIFile VUnit = getOrCreateFile(f->getLocation());
825 QualType type = f->getType();
826 llvm::DIType fieldType
827 = createFieldType("this", type, 0, f->getLocation(), f->getAccess(),
828 layout.getFieldOffset(fieldno), VUnit, RecordTy);
829
830 elements.push_back(fieldType);
831 }
832 }
833}
834
835/// CollectRecordStaticField - Helper for CollectRecordFields.
836void CGDebugInfo::
837CollectRecordStaticField(const VarDecl *Var,
838 SmallVectorImpl<llvm::Value *> &elements,
839 llvm::DIType RecordTy) {
840 // Create the descriptor for the static variable, with or without
841 // constant initializers.
842 llvm::DIFile VUnit = getOrCreateFile(Var->getLocation());
843 llvm::DIType VTy = getOrCreateType(Var->getType(), VUnit);
844
845 // Do not describe enums as static members.
846 if (VTy.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
847 return;
848
849 unsigned LineNumber = getLineNumber(Var->getLocation());
850 StringRef VName = Var->getName();
David Blaikiea89701b2013-01-20 01:19:17 +0000851 llvm::Constant *C = NULL;
Eric Christopher0395de32013-01-16 01:22:32 +0000852 if (Var->getInit()) {
853 const APValue *Value = Var->evaluateValue();
David Blaikiea89701b2013-01-20 01:19:17 +0000854 if (Value) {
855 if (Value->isInt())
856 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
857 if (Value->isFloat())
858 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
859 }
Eric Christopher0395de32013-01-16 01:22:32 +0000860 }
861
862 unsigned Flags = 0;
863 AccessSpecifier Access = Var->getAccess();
864 if (Access == clang::AS_private)
865 Flags |= llvm::DIDescriptor::FlagPrivate;
866 else if (Access == clang::AS_protected)
867 Flags |= llvm::DIDescriptor::FlagProtected;
868
869 llvm::DIType GV = DBuilder.createStaticMemberType(RecordTy, VName, VUnit,
David Blaikiea89701b2013-01-20 01:19:17 +0000870 LineNumber, VTy, Flags, C);
Eric Christopher0395de32013-01-16 01:22:32 +0000871 elements.push_back(GV);
872 StaticDataMemberCache[Var->getCanonicalDecl()] = llvm::WeakVH(GV);
873}
874
875/// CollectRecordNormalField - Helper for CollectRecordFields.
876void CGDebugInfo::
877CollectRecordNormalField(const FieldDecl *field, uint64_t OffsetInBits,
878 llvm::DIFile tunit,
879 SmallVectorImpl<llvm::Value *> &elements,
880 llvm::DIType RecordTy) {
881 StringRef name = field->getName();
882 QualType type = field->getType();
883
884 // Ignore unnamed fields unless they're anonymous structs/unions.
885 if (name.empty() && !type->isRecordType())
886 return;
887
888 uint64_t SizeInBitsOverride = 0;
889 if (field->isBitField()) {
890 SizeInBitsOverride = field->getBitWidthValue(CGM.getContext());
891 assert(SizeInBitsOverride && "found named 0-width bitfield");
892 }
893
894 llvm::DIType fieldType
895 = createFieldType(name, type, SizeInBitsOverride,
896 field->getLocation(), field->getAccess(),
897 OffsetInBits, tunit, RecordTy);
898
899 elements.push_back(fieldType);
900}
901
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000902/// CollectRecordFields - A helper function to collect debug info for
903/// record fields. This is used while creating debug info entry for a Record.
904void CGDebugInfo::
905CollectRecordFields(const RecordDecl *record, llvm::DIFile tunit,
906 SmallVectorImpl<llvm::Value *> &elements,
907 llvm::DIType RecordTy) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000908 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(record);
909
Eric Christopher0395de32013-01-16 01:22:32 +0000910 if (CXXDecl && CXXDecl->isLambda())
911 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
912 else {
913 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000914
Eric Christopher0395de32013-01-16 01:22:32 +0000915 // Field number for non-static fields.
Eric Christopherfd5ac0d2013-01-04 17:59:07 +0000916 unsigned fieldNo = 0;
Eric Christopher0395de32013-01-16 01:22:32 +0000917
918 // Bookkeeping for an ms struct, which ignores certain fields.
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000919 bool IsMsStruct = record->isMsStruct(CGM.getContext());
920 const FieldDecl *LastFD = 0;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000921
Eric Christopher0395de32013-01-16 01:22:32 +0000922 // Static and non-static members should appear in the same order as
923 // the corresponding declarations in the source program.
924 for (RecordDecl::decl_iterator I = record->decls_begin(),
925 E = record->decls_end(); I != E; ++I)
926 if (const VarDecl *V = dyn_cast<VarDecl>(*I))
927 CollectRecordStaticField(V, elements, RecordTy);
928 else if (FieldDecl *field = dyn_cast<FieldDecl>(*I)) {
929 if (IsMsStruct) {
930 // Zero-length bitfields following non-bitfield members are
931 // completely ignored; we don't even count them.
932 if (CGM.getContext().ZeroBitfieldFollowsNonBitfield((field), LastFD))
933 continue;
934 LastFD = field;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000935 }
Eric Christopher0395de32013-01-16 01:22:32 +0000936 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo),
937 tunit, elements, RecordTy);
938
939 // Bump field number for next field.
940 ++fieldNo;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000941 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000942 }
943}
944
945/// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
946/// function type is not updated to include implicit "this" pointer. Use this
947/// routine to get a method type which includes "this" pointer.
David Blaikie9a845292013-05-22 23:22:42 +0000948llvm::DICompositeType
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000949CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
950 llvm::DIFile Unit) {
David Blaikie9c78f9b2013-01-07 23:06:35 +0000951 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
David Blaikie67f8b5e2013-01-07 22:24:59 +0000952 if (Method->isStatic())
David Blaikie9a845292013-05-22 23:22:42 +0000953 return llvm::DICompositeType(getOrCreateType(QualType(Func, 0), Unit));
David Blaikie9c78f9b2013-01-07 23:06:35 +0000954 return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()),
955 Func, Unit);
956}
David Blaikie67f8b5e2013-01-07 22:24:59 +0000957
David Blaikie9a845292013-05-22 23:22:42 +0000958llvm::DICompositeType CGDebugInfo::getOrCreateInstanceMethodType(
David Blaikie9c78f9b2013-01-07 23:06:35 +0000959 QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile Unit) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000960 // Add "this" pointer.
David Blaikie9c78f9b2013-01-07 23:06:35 +0000961 llvm::DIArray Args = llvm::DICompositeType(
962 getOrCreateType(QualType(Func, 0), Unit)).getTypeArray();
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000963 assert (Args.getNumElements() && "Invalid number of arguments!");
964
965 SmallVector<llvm::Value *, 16> Elts;
966
967 // First element is always return type. For 'void' functions it is NULL.
968 Elts.push_back(Args.getElement(0));
969
David Blaikie67f8b5e2013-01-07 22:24:59 +0000970 // "this" pointer is always first argument.
David Blaikie9c78f9b2013-01-07 23:06:35 +0000971 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
David Blaikie67f8b5e2013-01-07 22:24:59 +0000972 if (isa<ClassTemplateSpecializationDecl>(RD)) {
973 // Create pointer type directly in this case.
974 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
975 QualType PointeeTy = ThisPtrTy->getPointeeType();
976 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCall64aa4b32013-04-16 22:48:15 +0000977 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
David Blaikie67f8b5e2013-01-07 22:24:59 +0000978 uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy);
979 llvm::DIType PointeeType = getOrCreateType(PointeeTy, Unit);
Eric Christopherf0890c42013-05-16 00:52:20 +0000980 llvm::DIType ThisPtrType =
981 DBuilder.createPointerType(PointeeType, Size, Align);
David Blaikie67f8b5e2013-01-07 22:24:59 +0000982 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
983 // TODO: This and the artificial type below are misleading, the
984 // types aren't artificial the argument is, but the current
985 // metadata doesn't represent that.
986 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
987 Elts.push_back(ThisPtrType);
988 } else {
989 llvm::DIType ThisPtrType = getOrCreateType(ThisPtr, Unit);
990 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
991 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
992 Elts.push_back(ThisPtrType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000993 }
994
995 // Copy rest of the arguments.
996 for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
997 Elts.push_back(Args.getElement(i));
998
999 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
1000
1001 return DBuilder.createSubroutineType(Unit, EltTypeArray);
1002}
1003
Eric Christopher6537f082013-05-16 00:45:12 +00001004/// isFunctionLocalClass - Return true if CXXRecordDecl is defined
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001005/// inside a function.
1006static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
1007 if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
1008 return isFunctionLocalClass(NRD);
1009 if (isa<FunctionDecl>(RD->getDeclContext()))
1010 return true;
1011 return false;
1012}
1013
1014/// CreateCXXMemberFunction - A helper function to create a DISubprogram for
1015/// a single member function GlobalDecl.
1016llvm::DISubprogram
1017CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
1018 llvm::DIFile Unit,
1019 llvm::DIType RecordTy) {
Eric Christopher6537f082013-05-16 00:45:12 +00001020 bool IsCtorOrDtor =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001021 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
Eric Christopher6537f082013-05-16 00:45:12 +00001022
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001023 StringRef MethodName = getFunctionName(Method);
David Blaikie9a845292013-05-22 23:22:42 +00001024 llvm::DICompositeType MethodTy = getOrCreateMethodType(Method, Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001025
1026 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1027 // make sense to give a single ctor/dtor a linkage name.
1028 StringRef MethodLinkageName;
1029 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1030 MethodLinkageName = CGM.getMangledName(Method);
1031
1032 // Get the location for the method.
1033 llvm::DIFile MethodDefUnit = getOrCreateFile(Method->getLocation());
1034 unsigned MethodLine = getLineNumber(Method->getLocation());
1035
1036 // Collect virtual method info.
1037 llvm::DIType ContainingType;
Eric Christopher6537f082013-05-16 00:45:12 +00001038 unsigned Virtuality = 0;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001039 unsigned VIndex = 0;
Eric Christopher6537f082013-05-16 00:45:12 +00001040
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001041 if (Method->isVirtual()) {
1042 if (Method->isPure())
1043 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
1044 else
1045 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
Eric Christopher6537f082013-05-16 00:45:12 +00001046
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001047 // It doesn't make sense to give a virtual destructor a vtable index,
1048 // since a single destructor has two entries in the vtable.
1049 if (!isa<CXXDestructorDecl>(Method))
1050 VIndex = CGM.getVTableContext().getMethodVTableIndex(Method);
1051 ContainingType = RecordTy;
1052 }
1053
1054 unsigned Flags = 0;
1055 if (Method->isImplicit())
1056 Flags |= llvm::DIDescriptor::FlagArtificial;
1057 AccessSpecifier Access = Method->getAccess();
1058 if (Access == clang::AS_private)
1059 Flags |= llvm::DIDescriptor::FlagPrivate;
1060 else if (Access == clang::AS_protected)
1061 Flags |= llvm::DIDescriptor::FlagProtected;
1062 if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1063 if (CXXC->isExplicit())
1064 Flags |= llvm::DIDescriptor::FlagExplicit;
Eric Christopher6537f082013-05-16 00:45:12 +00001065 } else if (const CXXConversionDecl *CXXC =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001066 dyn_cast<CXXConversionDecl>(Method)) {
1067 if (CXXC->isExplicit())
1068 Flags |= llvm::DIDescriptor::FlagExplicit;
1069 }
1070 if (Method->hasPrototype())
1071 Flags |= llvm::DIDescriptor::FlagPrototyped;
1072
1073 llvm::DIArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1074 llvm::DISubprogram SP =
Eric Christopher6537f082013-05-16 00:45:12 +00001075 DBuilder.createMethod(RecordTy, MethodName, MethodLinkageName,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001076 MethodDefUnit, MethodLine,
Eric Christopher6537f082013-05-16 00:45:12 +00001077 MethodTy, /*isLocalToUnit=*/false,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001078 /* isDefinition=*/ false,
1079 Virtuality, VIndex, ContainingType,
1080 Flags, CGM.getLangOpts().Optimize, NULL,
1081 TParamsArray);
Eric Christopher6537f082013-05-16 00:45:12 +00001082
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001083 SPCache[Method->getCanonicalDecl()] = llvm::WeakVH(SP);
1084
1085 return SP;
1086}
1087
1088/// CollectCXXMemberFunctions - A helper function to collect debug info for
Eric Christopher6537f082013-05-16 00:45:12 +00001089/// C++ member functions. This is used while creating debug info entry for
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001090/// a Record.
1091void CGDebugInfo::
1092CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
1093 SmallVectorImpl<llvm::Value *> &EltTys,
1094 llvm::DIType RecordTy) {
1095
1096 // Since we want more than just the individual member decls if we
1097 // have templated functions iterate over every declaration to gather
1098 // the functions.
1099 for(DeclContext::decl_iterator I = RD->decls_begin(),
1100 E = RD->decls_end(); I != E; ++I) {
1101 Decl *D = *I;
1102 if (D->isImplicit() && !D->isUsed())
1103 continue;
1104
1105 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1106 EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
1107 else if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
1108 for (FunctionTemplateDecl::spec_iterator SI = FTD->spec_begin(),
1109 SE = FTD->spec_end(); SI != SE; ++SI)
1110 EltTys.push_back(CreateCXXMemberFunction(cast<CXXMethodDecl>(*SI), Unit,
1111 RecordTy));
1112 }
Eric Christopher6537f082013-05-16 00:45:12 +00001113}
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001114
1115/// CollectCXXFriends - A helper function to collect debug info for
1116/// C++ base classes. This is used while creating debug info entry for
1117/// a Record.
1118void CGDebugInfo::
1119CollectCXXFriends(const CXXRecordDecl *RD, llvm::DIFile Unit,
1120 SmallVectorImpl<llvm::Value *> &EltTys,
1121 llvm::DIType RecordTy) {
1122 for (CXXRecordDecl::friend_iterator BI = RD->friend_begin(),
1123 BE = RD->friend_end(); BI != BE; ++BI) {
1124 if ((*BI)->isUnsupportedFriend())
1125 continue;
1126 if (TypeSourceInfo *TInfo = (*BI)->getFriendType())
Eric Christopher6537f082013-05-16 00:45:12 +00001127 EltTys.push_back(DBuilder.createFriend(RecordTy,
1128 getOrCreateType(TInfo->getType(),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001129 Unit)));
1130 }
1131}
1132
1133/// CollectCXXBases - A helper function to collect debug info for
Eric Christopher6537f082013-05-16 00:45:12 +00001134/// C++ base classes. This is used while creating debug info entry for
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001135/// a Record.
1136void CGDebugInfo::
1137CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
1138 SmallVectorImpl<llvm::Value *> &EltTys,
1139 llvm::DIType RecordTy) {
1140
1141 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1142 for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
1143 BE = RD->bases_end(); BI != BE; ++BI) {
1144 unsigned BFlags = 0;
1145 uint64_t BaseOffset;
Eric Christopher6537f082013-05-16 00:45:12 +00001146
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001147 const CXXRecordDecl *Base =
1148 cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl());
Eric Christopher6537f082013-05-16 00:45:12 +00001149
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001150 if (BI->isVirtual()) {
1151 // virtual base offset offset is -ve. The code generator emits dwarf
1152 // expression where it expects +ve number.
Eric Christopher6537f082013-05-16 00:45:12 +00001153 BaseOffset =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001154 0 - CGM.getVTableContext()
1155 .getVirtualBaseOffsetOffset(RD, Base).getQuantity();
1156 BFlags = llvm::DIDescriptor::FlagVirtual;
1157 } else
1158 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1159 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1160 // BI->isVirtual() and bits when not.
Eric Christopher6537f082013-05-16 00:45:12 +00001161
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001162 AccessSpecifier Access = BI->getAccessSpecifier();
1163 if (Access == clang::AS_private)
1164 BFlags |= llvm::DIDescriptor::FlagPrivate;
1165 else if (Access == clang::AS_protected)
1166 BFlags |= llvm::DIDescriptor::FlagProtected;
Eric Christopher6537f082013-05-16 00:45:12 +00001167
1168 llvm::DIType DTy =
1169 DBuilder.createInheritance(RecordTy,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001170 getOrCreateType(BI->getType(), Unit),
1171 BaseOffset, BFlags);
1172 EltTys.push_back(DTy);
1173 }
1174}
1175
1176/// CollectTemplateParams - A helper function to collect template parameters.
1177llvm::DIArray CGDebugInfo::
1178CollectTemplateParams(const TemplateParameterList *TPList,
David Blaikie35178dc2013-06-22 18:59:18 +00001179 ArrayRef<TemplateArgument> TAList,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001180 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +00001181 SmallVector<llvm::Value *, 16> TemplateParams;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001182 for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1183 const TemplateArgument &TA = TAList[i];
David Blaikie35178dc2013-06-22 18:59:18 +00001184 StringRef Name;
1185 if (TPList)
1186 Name = TPList->getParam(i)->getName();
David Blaikie9dfd2432013-05-10 21:53:14 +00001187 switch (TA.getKind()) {
1188 case TemplateArgument::Type: {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001189 llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit);
1190 llvm::DITemplateTypeParameter TTP =
David Blaikie35178dc2013-06-22 18:59:18 +00001191 DBuilder.createTemplateTypeParameter(TheCU, Name, TTy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001192 TemplateParams.push_back(TTP);
David Blaikie9dfd2432013-05-10 21:53:14 +00001193 } break;
1194 case TemplateArgument::Integral: {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001195 llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit);
1196 llvm::DITemplateValueParameter TVP =
David Blaikie9dfd2432013-05-10 21:53:14 +00001197 DBuilder.createTemplateValueParameter(
David Blaikie35178dc2013-06-22 18:59:18 +00001198 TheCU, Name, TTy,
David Blaikie9dfd2432013-05-10 21:53:14 +00001199 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral()));
1200 TemplateParams.push_back(TVP);
1201 } break;
1202 case TemplateArgument::Declaration: {
1203 const ValueDecl *D = TA.getAsDecl();
1204 bool InstanceMember = D->isCXXInstanceMember();
1205 QualType T = InstanceMember
1206 ? CGM.getContext().getMemberPointerType(
1207 D->getType(), cast<RecordDecl>(D->getDeclContext())
1208 ->getTypeForDecl())
1209 : CGM.getContext().getPointerType(D->getType());
1210 llvm::DIType TTy = getOrCreateType(T, Unit);
1211 llvm::Value *V = 0;
1212 // Variable pointer template parameters have a value that is the address
1213 // of the variable.
1214 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1215 V = CGM.GetAddrOfGlobalVar(VD);
1216 // Member function pointers have special support for building them, though
1217 // this is currently unsupported in LLVM CodeGen.
David Blaikief8aa1552013-05-13 06:57:50 +00001218 if (InstanceMember) {
David Blaikie9dfd2432013-05-10 21:53:14 +00001219 if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(D))
1220 V = CGM.getCXXABI().EmitMemberPointer(method);
David Blaikief8aa1552013-05-13 06:57:50 +00001221 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1222 V = CGM.GetAddrOfFunction(FD);
David Blaikie9dfd2432013-05-10 21:53:14 +00001223 // Member data pointers have special handling too to compute the fixed
1224 // offset within the object.
1225 if (isa<FieldDecl>(D)) {
1226 // These five lines (& possibly the above member function pointer
1227 // handling) might be able to be refactored to use similar code in
1228 // CodeGenModule::getMemberPointerConstant
1229 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
1230 CharUnits chars =
1231 CGM.getContext().toCharUnitsFromBits((int64_t) fieldOffset);
1232 V = CGM.getCXXABI().EmitMemberDataPointer(
1233 cast<MemberPointerType>(T.getTypePtr()), chars);
1234 }
1235 llvm::DITemplateValueParameter TVP =
David Blaikie35178dc2013-06-22 18:59:18 +00001236 DBuilder.createTemplateValueParameter(TheCU, Name, TTy, V);
David Blaikie9dfd2432013-05-10 21:53:14 +00001237 TemplateParams.push_back(TVP);
1238 } break;
1239 case TemplateArgument::NullPtr: {
1240 QualType T = TA.getNullPtrType();
1241 llvm::DIType TTy = getOrCreateType(T, Unit);
1242 llvm::Value *V = 0;
1243 // Special case member data pointer null values since they're actually -1
1244 // instead of zero.
1245 if (const MemberPointerType *MPT =
1246 dyn_cast<MemberPointerType>(T.getTypePtr()))
1247 // But treat member function pointers as simple zero integers because
1248 // it's easier than having a special case in LLVM's CodeGen. If LLVM
1249 // CodeGen grows handling for values of non-null member function
1250 // pointers then perhaps we could remove this special case and rely on
1251 // EmitNullMemberPointer for member function pointers.
1252 if (MPT->isMemberDataPointer())
1253 V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1254 if (!V)
1255 V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
1256 llvm::DITemplateValueParameter TVP =
David Blaikie35178dc2013-06-22 18:59:18 +00001257 DBuilder.createTemplateValueParameter(TheCU, Name, TTy, V);
David Blaikie9dfd2432013-05-10 21:53:14 +00001258 TemplateParams.push_back(TVP);
1259 } break;
David Blaikie35178dc2013-06-22 18:59:18 +00001260 case TemplateArgument::Template: {
1261 llvm::DITemplateValueParameter TVP =
1262 DBuilder.createTemplateTemplateParameter(
1263 TheCU, Name, llvm::DIType(),
1264 TA.getAsTemplate().getAsTemplateDecl()
1265 ->getQualifiedNameAsString());
1266 TemplateParams.push_back(TVP);
1267 } break;
1268 case TemplateArgument::Pack: {
1269 llvm::DITemplateValueParameter TVP =
1270 DBuilder.createTemplateParameterPack(
1271 TheCU, Name, llvm::DIType(),
1272 CollectTemplateParams(NULL, TA.getPackAsArray(), Unit));
1273 TemplateParams.push_back(TVP);
1274 } break;
David Blaikiee8065122013-05-10 23:36:06 +00001275 // And the following should never occur:
David Blaikie9dfd2432013-05-10 21:53:14 +00001276 case TemplateArgument::Expression:
1277 case TemplateArgument::TemplateExpansion:
David Blaikie9dfd2432013-05-10 21:53:14 +00001278 case TemplateArgument::Null:
1279 llvm_unreachable(
1280 "These argument types shouldn't exist in concrete types");
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001281 }
1282 }
1283 return DBuilder.getOrCreateArray(TemplateParams);
1284}
1285
1286/// CollectFunctionTemplateParams - A helper function to collect debug
1287/// info for function template parameters.
1288llvm::DIArray CGDebugInfo::
1289CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) {
1290 if (FD->getTemplatedKind() ==
1291 FunctionDecl::TK_FunctionTemplateSpecialization) {
1292 const TemplateParameterList *TList =
1293 FD->getTemplateSpecializationInfo()->getTemplate()
1294 ->getTemplateParameters();
David Blaikie35178dc2013-06-22 18:59:18 +00001295 return CollectTemplateParams(
1296 TList, FD->getTemplateSpecializationArgs()->asArray(), Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001297 }
1298 return llvm::DIArray();
1299}
1300
1301/// CollectCXXTemplateParams - A helper function to collect debug info for
1302/// template parameters.
1303llvm::DIArray CGDebugInfo::
1304CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial,
1305 llvm::DIFile Unit) {
1306 llvm::PointerUnion<ClassTemplateDecl *,
1307 ClassTemplatePartialSpecializationDecl *>
1308 PU = TSpecial->getSpecializedTemplateOrPartial();
Eric Christopher6537f082013-05-16 00:45:12 +00001309
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001310 TemplateParameterList *TPList = PU.is<ClassTemplateDecl *>() ?
1311 PU.get<ClassTemplateDecl *>()->getTemplateParameters() :
1312 PU.get<ClassTemplatePartialSpecializationDecl *>()->getTemplateParameters();
1313 const TemplateArgumentList &TAList = TSpecial->getTemplateInstantiationArgs();
David Blaikie35178dc2013-06-22 18:59:18 +00001314 return CollectTemplateParams(TPList, TAList.asArray(), Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001315}
1316
1317/// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
1318llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
1319 if (VTablePtrType.isValid())
1320 return VTablePtrType;
1321
1322 ASTContext &Context = CGM.getContext();
1323
1324 /* Function type */
1325 llvm::Value *STy = getOrCreateType(Context.IntTy, Unit);
1326 llvm::DIArray SElements = DBuilder.getOrCreateArray(STy);
1327 llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements);
1328 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1329 llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0,
1330 "__vtbl_ptr_type");
1331 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1332 return VTablePtrType;
1333}
1334
1335/// getVTableName - Get vtable name for the given Class.
1336StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
1337 // Construct gdb compatible name name.
1338 std::string Name = "_vptr$" + RD->getNameAsString();
1339
1340 // Copy this name on the side and use its reference.
1341 char *StrPtr = DebugInfoNames.Allocate<char>(Name.length());
1342 memcpy(StrPtr, Name.data(), Name.length());
1343 return StringRef(StrPtr, Name.length());
1344}
1345
1346
1347/// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
1348/// debug info entry in EltTys vector.
1349void CGDebugInfo::
1350CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
1351 SmallVectorImpl<llvm::Value *> &EltTys) {
1352 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1353
1354 // If there is a primary base then it will hold vtable info.
1355 if (RL.getPrimaryBase())
1356 return;
1357
1358 // If this class is not dynamic then there is not any vtable info to collect.
1359 if (!RD->isDynamicClass())
1360 return;
1361
1362 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1363 llvm::DIType VPTR
1364 = DBuilder.createMemberType(Unit, getVTableName(RD), Unit,
Eric Christopherf0890c42013-05-16 00:52:20 +00001365 0, Size, 0, 0,
1366 llvm::DIDescriptor::FlagArtificial,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001367 getOrCreateVTablePtrType(Unit));
1368 EltTys.push_back(VPTR);
1369}
1370
Eric Christopher6537f082013-05-16 00:45:12 +00001371/// getOrCreateRecordType - Emit record type's standalone debug info.
1372llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001373 SourceLocation Loc) {
Eric Christopher13c97672013-05-16 00:45:23 +00001374 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001375 llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc));
1376 return T;
1377}
1378
1379/// getOrCreateInterfaceType - Emit an objective c interface type standalone
1380/// debug info.
1381llvm::DIType CGDebugInfo::getOrCreateInterfaceType(QualType D,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001382 SourceLocation Loc) {
Eric Christopher13c97672013-05-16 00:45:23 +00001383 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001384 llvm::DIType T = getOrCreateType(D, getOrCreateFile(Loc));
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001385 RetainedTypes.push_back(D.getAsOpaquePtr());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001386 return T;
1387}
1388
1389/// CreateType - get structure or union type.
David Blaikie5f6e2f42013-06-05 05:32:23 +00001390llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty, bool Declaration) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001391 RecordDecl *RD = Ty->getDecl();
Adrian Prantl776bfa12013-06-18 23:32:21 +00001392 // Limited debug info should only remove struct definitions that can
1393 // safely be replaced by a forward declaration in the source code.
Adrian Prantl14c1a132013-06-18 23:01:56 +00001394 if (DebugKind <= CodeGenOptions::LimitedDebugInfo && Declaration) {
Adrian Prantl776bfa12013-06-18 23:32:21 +00001395 // FIXME: This implementation is problematic; there are some test
1396 // cases where we violate the above principle, such as
1397 // test/CodeGen/debug-info-records.c .
David Blaikie5f6e2f42013-06-05 05:32:23 +00001398 llvm::DIDescriptor FDContext =
1399 getContextDescriptor(cast<Decl>(RD->getDeclContext()));
1400 llvm::DIType RetTy = createRecordFwdDecl(RD, FDContext);
1401 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RetTy;
1402 return RetTy;
1403 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001404
1405 // Get overall information about the record type for the debug info.
1406 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1407
1408 // Records and classes and unions can all be recursive. To handle them, we
1409 // first generate a debug descriptor for the struct as a forward declaration.
1410 // Then (if it is a definition) we go through and get debug info for all of
1411 // its members. Finally, we create a descriptor for the complete type (which
1412 // may refer to the forward decl if the struct is recursive) and replace all
1413 // uses of the forward declaration with the final definition.
1414
Eric Christopherf068c922013-04-02 22:59:11 +00001415 llvm::DICompositeType FwdDecl(
1416 getOrCreateLimitedType(QualType(Ty, 0), DefUnit));
1417 assert(FwdDecl.Verify() &&
David Blaikie9a845292013-05-22 23:22:42 +00001418 "The debug type of a RecordType should be a llvm::DICompositeType");
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001419
1420 if (FwdDecl.isForwardDecl())
1421 return FwdDecl;
1422
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001423 // Push the struct on region stack.
Eric Christopherf068c922013-04-02 22:59:11 +00001424 LexicalBlockStack.push_back(&*FwdDecl);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001425 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1426
Adrian Prantl4919de62013-03-06 22:03:30 +00001427 // Add this to the completed-type cache while we're completing it recursively.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001428 CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1429
1430 // Convert all the elements.
1431 SmallVector<llvm::Value *, 16> EltTys;
1432
1433 // Note: The split of CXXDecl information here is intentional, the
1434 // gdb tests will depend on a certain ordering at printout. The debug
1435 // information offsets are still correct if we merge them all together
1436 // though.
1437 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1438 if (CXXDecl) {
1439 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1440 CollectVTableInfo(CXXDecl, DefUnit, EltTys);
1441 }
1442
Eric Christopher0395de32013-01-16 01:22:32 +00001443 // Collect data fields (including static variables and any initializers).
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001444 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
1445 llvm::DIArray TParamsArray;
1446 if (CXXDecl) {
1447 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
1448 CollectCXXFriends(CXXDecl, DefUnit, EltTys, FwdDecl);
1449 if (const ClassTemplateSpecializationDecl *TSpecial
1450 = dyn_cast<ClassTemplateSpecializationDecl>(RD))
1451 TParamsArray = CollectCXXTemplateParams(TSpecial, DefUnit);
1452 }
1453
1454 LexicalBlockStack.pop_back();
1455 RegionMap.erase(Ty->getDecl());
1456
1457 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopherf068c922013-04-02 22:59:11 +00001458 FwdDecl.setTypeArray(Elements, TParamsArray);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001459
Eric Christopherf068c922013-04-02 22:59:11 +00001460 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1461 return FwdDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001462}
1463
1464/// CreateType - get objective-c object type.
1465llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1466 llvm::DIFile Unit) {
1467 // Ignore protocols.
1468 return getOrCreateType(Ty->getBaseType(), Unit);
1469}
1470
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001471
1472/// \return true if Getter has the default name for the property PD.
1473static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
1474 const ObjCMethodDecl *Getter) {
1475 assert(PD);
1476 if (!Getter)
1477 return true;
1478
1479 assert(Getter->getDeclName().isObjCZeroArgSelector());
1480 return PD->getName() ==
1481 Getter->getDeclName().getObjCSelector().getNameForSlot(0);
1482}
1483
1484/// \return true if Setter has the default name for the property PD.
1485static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
1486 const ObjCMethodDecl *Setter) {
1487 assert(PD);
1488 if (!Setter)
1489 return true;
1490
1491 assert(Setter->getDeclName().isObjCOneArgSelector());
Adrian Prantl80e8ea92013-06-07 22:29:12 +00001492 return SelectorTable::constructSetterName(PD->getName()) ==
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001493 Setter->getDeclName().getObjCSelector().getNameForSlot(0);
1494}
1495
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001496/// CreateType - get objective-c interface type.
1497llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1498 llvm::DIFile Unit) {
1499 ObjCInterfaceDecl *ID = Ty->getDecl();
1500 if (!ID)
1501 return llvm::DIType();
1502
1503 // Get overall information about the record type for the debug info.
1504 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1505 unsigned Line = getLineNumber(ID->getLocation());
1506 unsigned RuntimeLang = TheCU.getLanguage();
1507
1508 // If this is just a forward declaration return a special forward-declaration
1509 // debug type since we won't be able to lay out the entire type.
1510 ObjCInterfaceDecl *Def = ID->getDefinition();
1511 if (!Def) {
1512 llvm::DIType FwdDecl =
1513 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001514 ID->getName(), TheCU, DefUnit, Line,
1515 RuntimeLang);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001516 return FwdDecl;
1517 }
1518
1519 ID = Def;
1520
1521 // Bit size, align and offset of the type.
1522 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1523 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1524
1525 unsigned Flags = 0;
1526 if (ID->getImplementation())
1527 Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
1528
Eric Christopherf068c922013-04-02 22:59:11 +00001529 llvm::DICompositeType RealDecl =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001530 DBuilder.createStructType(Unit, ID->getName(), DefUnit,
1531 Line, Size, Align, Flags,
David Blaikiec1d0af12013-02-25 01:07:08 +00001532 llvm::DIType(), llvm::DIArray(), RuntimeLang);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001533
1534 // Otherwise, insert it into the CompletedTypeCache so that recursive uses
1535 // will find it and we're emitting the complete type.
Adrian Prantl4919de62013-03-06 22:03:30 +00001536 QualType QualTy = QualType(Ty, 0);
1537 CompletedTypeCache[QualTy.getAsOpaquePtr()] = RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001538 // Push the struct on region stack.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001539
Eric Christopherf068c922013-04-02 22:59:11 +00001540 LexicalBlockStack.push_back(static_cast<llvm::MDNode*>(RealDecl));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001541 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1542
1543 // Convert all the elements.
1544 SmallVector<llvm::Value *, 16> EltTys;
1545
1546 ObjCInterfaceDecl *SClass = ID->getSuperClass();
1547 if (SClass) {
1548 llvm::DIType SClassTy =
1549 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1550 if (!SClassTy.isValid())
1551 return llvm::DIType();
Eric Christopher6537f082013-05-16 00:45:12 +00001552
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001553 llvm::DIType InhTag =
1554 DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
1555 EltTys.push_back(InhTag);
1556 }
1557
1558 for (ObjCContainerDecl::prop_iterator I = ID->prop_begin(),
1559 E = ID->prop_end(); I != E; ++I) {
1560 const ObjCPropertyDecl *PD = *I;
1561 SourceLocation Loc = PD->getLocation();
1562 llvm::DIFile PUnit = getOrCreateFile(Loc);
1563 unsigned PLine = getLineNumber(Loc);
1564 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1565 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1566 llvm::MDNode *PropertyNode =
1567 DBuilder.createObjCProperty(PD->getName(),
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001568 PUnit, PLine,
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001569 hasDefaultGetterName(PD, Getter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001570 getSelectorName(PD->getGetterName()),
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001571 hasDefaultSetterName(PD, Setter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001572 getSelectorName(PD->getSetterName()),
1573 PD->getPropertyAttributes(),
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001574 getOrCreateType(PD->getType(), PUnit));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001575 EltTys.push_back(PropertyNode);
1576 }
1577
1578 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1579 unsigned FieldNo = 0;
1580 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1581 Field = Field->getNextIvar(), ++FieldNo) {
1582 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1583 if (!FieldTy.isValid())
1584 return llvm::DIType();
Eric Christopher6537f082013-05-16 00:45:12 +00001585
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001586 StringRef FieldName = Field->getName();
1587
1588 // Ignore unnamed fields.
1589 if (FieldName.empty())
1590 continue;
1591
1592 // Get the location for the field.
1593 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1594 unsigned FieldLine = getLineNumber(Field->getLocation());
1595 QualType FType = Field->getType();
1596 uint64_t FieldSize = 0;
1597 unsigned FieldAlign = 0;
1598
1599 if (!FType->isIncompleteArrayType()) {
1600
1601 // Bit size, align and offset of the type.
1602 FieldSize = Field->isBitField()
1603 ? Field->getBitWidthValue(CGM.getContext())
1604 : CGM.getContext().getTypeSize(FType);
1605 FieldAlign = CGM.getContext().getTypeAlign(FType);
1606 }
1607
1608 uint64_t FieldOffset;
1609 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1610 // We don't know the runtime offset of an ivar if we're using the
1611 // non-fragile ABI. For bitfields, use the bit offset into the first
1612 // byte of storage of the bitfield. For other fields, use zero.
1613 if (Field->isBitField()) {
1614 FieldOffset = CGM.getObjCRuntime().ComputeBitfieldBitOffset(
1615 CGM, ID, Field);
1616 FieldOffset %= CGM.getContext().getCharWidth();
1617 } else {
1618 FieldOffset = 0;
1619 }
1620 } else {
1621 FieldOffset = RL.getFieldOffset(FieldNo);
1622 }
1623
1624 unsigned Flags = 0;
1625 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1626 Flags = llvm::DIDescriptor::FlagProtected;
1627 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1628 Flags = llvm::DIDescriptor::FlagPrivate;
1629
1630 llvm::MDNode *PropertyNode = NULL;
1631 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
Eric Christopher6537f082013-05-16 00:45:12 +00001632 if (ObjCPropertyImplDecl *PImpD =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001633 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
1634 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001635 SourceLocation Loc = PD->getLocation();
1636 llvm::DIFile PUnit = getOrCreateFile(Loc);
1637 unsigned PLine = getLineNumber(Loc);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001638 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1639 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1640 PropertyNode =
1641 DBuilder.createObjCProperty(PD->getName(),
1642 PUnit, PLine,
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001643 hasDefaultGetterName(PD, Getter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001644 getSelectorName(PD->getGetterName()),
Adrian Prantl5ae17a12013-06-07 01:10:45 +00001645 hasDefaultSetterName(PD, Setter) ? "" :
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001646 getSelectorName(PD->getSetterName()),
1647 PD->getPropertyAttributes(),
1648 getOrCreateType(PD->getType(), PUnit));
1649 }
1650 }
1651 }
1652 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
1653 FieldLine, FieldSize, FieldAlign,
1654 FieldOffset, Flags, FieldTy,
1655 PropertyNode);
1656 EltTys.push_back(FieldTy);
1657 }
1658
1659 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopherf068c922013-04-02 22:59:11 +00001660 RealDecl.setTypeArray(Elements);
Adrian Prantl4919de62013-03-06 22:03:30 +00001661
1662 // If the implementation is not yet set, we do not want to mark it
1663 // as complete. An implementation may declare additional
1664 // private ivars that we would miss otherwise.
1665 if (ID->getImplementation() == 0)
1666 CompletedTypeCache.erase(QualTy.getAsOpaquePtr());
Eric Christopher6537f082013-05-16 00:45:12 +00001667
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001668 LexicalBlockStack.pop_back();
Eric Christopherf068c922013-04-02 22:59:11 +00001669 return RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001670}
1671
1672llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) {
1673 llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1674 int64_t Count = Ty->getNumElements();
1675 if (Count == 0)
1676 // If number of elements are not known then this is an unbounded array.
1677 // Use Count == -1 to express such arrays.
1678 Count = -1;
1679
1680 llvm::Value *Subscript = DBuilder.getOrCreateSubrange(0, Count);
1681 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1682
1683 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1684 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1685
1686 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1687}
1688
1689llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1690 llvm::DIFile Unit) {
1691 uint64_t Size;
1692 uint64_t Align;
1693
1694 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1695 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1696 Size = 0;
1697 Align =
1698 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1699 } else if (Ty->isIncompleteArrayType()) {
1700 Size = 0;
1701 if (Ty->getElementType()->isIncompleteType())
1702 Align = 0;
1703 else
1704 Align = CGM.getContext().getTypeAlign(Ty->getElementType());
David Blaikie089db2e2013-05-09 20:48:12 +00001705 } else if (Ty->isIncompleteType()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001706 Size = 0;
1707 Align = 0;
1708 } else {
1709 // Size and align of the whole array, not the element type.
1710 Size = CGM.getContext().getTypeSize(Ty);
1711 Align = CGM.getContext().getTypeAlign(Ty);
1712 }
1713
1714 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
1715 // interior arrays, do we care? Why aren't nested arrays represented the
1716 // obvious/recursive way?
1717 SmallVector<llvm::Value *, 8> Subscripts;
1718 QualType EltTy(Ty, 0);
1719 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1720 // If the number of elements is known, then count is that number. Otherwise,
1721 // it's -1. This allows us to represent a subrange with an array of 0
1722 // elements, like this:
1723 //
1724 // struct foo {
1725 // int x[0];
1726 // };
1727 int64_t Count = -1; // Count == -1 is an unbounded array.
1728 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1729 Count = CAT->getSize().getZExtValue();
Eric Christopher6537f082013-05-16 00:45:12 +00001730
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001731 // FIXME: Verify this is right for VLAs.
1732 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
1733 EltTy = Ty->getElementType();
1734 }
1735
1736 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1737
Eric Christopher6537f082013-05-16 00:45:12 +00001738 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001739 DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1740 SubscriptArray);
1741 return DbgTy;
1742}
1743
Eric Christopher6537f082013-05-16 00:45:12 +00001744llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001745 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +00001746 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001747 Ty, Ty->getPointeeType(), Unit);
1748}
1749
Eric Christopher6537f082013-05-16 00:45:12 +00001750llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001751 llvm::DIFile Unit) {
Eric Christopher6537f082013-05-16 00:45:12 +00001752 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001753 Ty, Ty->getPointeeType(), Unit);
1754}
1755
Eric Christopher6537f082013-05-16 00:45:12 +00001756llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001757 llvm::DIFile U) {
David Blaikiee8d75142013-01-19 19:20:56 +00001758 llvm::DIType ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
1759 if (!Ty->getPointeeType()->isFunctionType())
1760 return DBuilder.createMemberPointerType(
David Blaikieb0f77b02013-05-24 21:33:22 +00001761 getOrCreateTypeDeclaration(Ty->getPointeeType(), U), ClassType);
David Blaikiee8d75142013-01-19 19:20:56 +00001762 return DBuilder.createMemberPointerType(getOrCreateInstanceMethodType(
1763 CGM.getContext().getPointerType(
1764 QualType(Ty->getClass(), Ty->getPointeeType().getCVRQualifiers())),
1765 Ty->getPointeeType()->getAs<FunctionProtoType>(), U),
1766 ClassType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001767}
1768
Eric Christopher6537f082013-05-16 00:45:12 +00001769llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001770 llvm::DIFile U) {
1771 // Ignore the atomic wrapping
1772 // FIXME: What is the correct representation?
1773 return getOrCreateType(Ty->getValueType(), U);
1774}
1775
1776/// CreateEnumType - get enumeration type.
1777llvm::DIType CGDebugInfo::CreateEnumType(const EnumDecl *ED) {
1778 uint64_t Size = 0;
1779 uint64_t Align = 0;
1780 if (!ED->getTypeForDecl()->isIncompleteType()) {
1781 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1782 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1783 }
1784
1785 // If this is just a forward declaration, construct an appropriately
1786 // marked node and just return it.
1787 if (!ED->getDefinition()) {
1788 llvm::DIDescriptor EDContext;
1789 EDContext = getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1790 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1791 unsigned Line = getLineNumber(ED->getLocation());
1792 StringRef EDName = ED->getName();
1793 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_enumeration_type,
1794 EDName, EDContext, DefUnit, Line, 0,
1795 Size, Align);
1796 }
1797
1798 // Create DIEnumerator elements for each enumerator.
1799 SmallVector<llvm::Value *, 16> Enumerators;
1800 ED = ED->getDefinition();
1801 for (EnumDecl::enumerator_iterator
1802 Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
1803 Enum != EnumEnd; ++Enum) {
1804 Enumerators.push_back(
1805 DBuilder.createEnumerator(Enum->getName(),
David Blaikieac8f43c2013-06-24 07:13:13 +00001806 Enum->getInitVal().getSExtValue()));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001807 }
1808
1809 // Return a CompositeType for the enum itself.
1810 llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1811
1812 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1813 unsigned Line = getLineNumber(ED->getLocation());
Eric Christopher6537f082013-05-16 00:45:12 +00001814 llvm::DIDescriptor EnumContext =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001815 getContextDescriptor(cast<Decl>(ED->getDeclContext()));
Adrian Prantl59d6a712013-04-19 19:56:39 +00001816 llvm::DIType ClassTy = ED->isFixed() ?
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001817 getOrCreateType(ED->getIntegerType(), DefUnit) : llvm::DIType();
Eric Christopher6537f082013-05-16 00:45:12 +00001818 llvm::DIType DbgTy =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001819 DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1820 Size, Align, EltArray,
1821 ClassTy);
1822 return DbgTy;
1823}
1824
David Blaikie4b12be62013-01-21 04:37:12 +00001825static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
1826 Qualifiers Quals;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001827 do {
David Blaikie4b12be62013-01-21 04:37:12 +00001828 Quals += T.getLocalQualifiers();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001829 QualType LastT = T;
1830 switch (T->getTypeClass()) {
1831 default:
David Blaikie4b12be62013-01-21 04:37:12 +00001832 return C.getQualifiedType(T.getTypePtr(), Quals);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001833 case Type::TemplateSpecialization:
1834 T = cast<TemplateSpecializationType>(T)->desugar();
1835 break;
1836 case Type::TypeOfExpr:
1837 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1838 break;
1839 case Type::TypeOf:
1840 T = cast<TypeOfType>(T)->getUnderlyingType();
1841 break;
1842 case Type::Decltype:
1843 T = cast<DecltypeType>(T)->getUnderlyingType();
1844 break;
1845 case Type::UnaryTransform:
1846 T = cast<UnaryTransformType>(T)->getUnderlyingType();
1847 break;
1848 case Type::Attributed:
1849 T = cast<AttributedType>(T)->getEquivalentType();
1850 break;
1851 case Type::Elaborated:
1852 T = cast<ElaboratedType>(T)->getNamedType();
1853 break;
1854 case Type::Paren:
1855 T = cast<ParenType>(T)->getInnerType();
1856 break;
David Blaikie4b12be62013-01-21 04:37:12 +00001857 case Type::SubstTemplateTypeParm:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001858 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001859 break;
1860 case Type::Auto:
David Blaikie91296482013-05-24 21:24:35 +00001861 QualType DT = cast<AutoType>(T)->getDeducedType();
1862 if (DT.isNull())
1863 return T;
1864 T = DT;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001865 break;
1866 }
Eric Christopher6537f082013-05-16 00:45:12 +00001867
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001868 assert(T != LastT && "Type unwrapping failed to unwrap!");
NAKAMURA Takumid24c9ab2013-01-21 10:51:28 +00001869 (void)LastT;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001870 } while (true);
1871}
1872
Eric Christopherf0890c42013-05-16 00:52:20 +00001873/// getType - Get the type from the cache or return null type if it doesn't
1874/// exist.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001875llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) {
1876
1877 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00001878 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Eric Christopher6537f082013-05-16 00:45:12 +00001879
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001880 // Check for existing entry.
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001881 if (Ty->getTypeClass() == Type::ObjCInterface) {
1882 llvm::Value *V = getCachedInterfaceTypeOrNull(Ty);
1883 if (V)
1884 return llvm::DIType(cast<llvm::MDNode>(V));
1885 else return llvm::DIType();
1886 }
1887
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001888 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1889 TypeCache.find(Ty.getAsOpaquePtr());
1890 if (it != TypeCache.end()) {
1891 // Verify that the debug info still exists.
1892 if (llvm::Value *V = it->second)
1893 return llvm::DIType(cast<llvm::MDNode>(V));
1894 }
1895
1896 return llvm::DIType();
1897}
1898
1899/// getCompletedTypeOrNull - Get the type from the cache or return null if it
1900/// doesn't exist.
1901llvm::DIType CGDebugInfo::getCompletedTypeOrNull(QualType Ty) {
1902
1903 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00001904 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001905
1906 // Check for existing entry.
Adrian Prantl4919de62013-03-06 22:03:30 +00001907 llvm::Value *V = 0;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001908 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1909 CompletedTypeCache.find(Ty.getAsOpaquePtr());
Adrian Prantl4919de62013-03-06 22:03:30 +00001910 if (it != CompletedTypeCache.end())
1911 V = it->second;
1912 else {
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001913 V = getCachedInterfaceTypeOrNull(Ty);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001914 }
1915
Adrian Prantl4919de62013-03-06 22:03:30 +00001916 // Verify that any cached debug info still exists.
David Blaikieeab6a362013-06-21 00:40:50 +00001917 if (V != 0)
1918 return llvm::DIType(cast<llvm::MDNode>(V));
Adrian Prantl4919de62013-03-06 22:03:30 +00001919
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001920 return llvm::DIType();
1921}
1922
David Blaikieeab6a362013-06-21 00:40:50 +00001923void CGDebugInfo::completeFwdDecl(const RecordDecl &RD) {
1924 // In limited debug info we only want to do this if the complete type was
1925 // required.
1926 if (DebugKind <= CodeGenOptions::LimitedDebugInfo)
1927 return;
1928
David Blaikie076f51f2013-06-21 00:59:44 +00001929 QualType QTy = CGM.getContext().getRecordType(&RD);
1930 llvm::DIType T = getTypeOrNull(QTy);
David Blaikieeab6a362013-06-21 00:40:50 +00001931
1932 if (T.Verify() && T.isForwardDecl())
David Blaikie076f51f2013-06-21 00:59:44 +00001933 getOrCreateType(QTy, getOrCreateFile(RD.getLocation()));
David Blaikieeab6a362013-06-21 00:40:50 +00001934}
1935
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001936/// getCachedInterfaceTypeOrNull - Get the type from the interface
1937/// cache, unless it needs to regenerated. Otherwise return null.
1938llvm::Value *CGDebugInfo::getCachedInterfaceTypeOrNull(QualType Ty) {
1939 // Is there a cached interface that hasn't changed?
1940 llvm::DenseMap<void *, std::pair<llvm::WeakVH, unsigned > >
1941 ::iterator it1 = ObjCInterfaceCache.find(Ty.getAsOpaquePtr());
1942
1943 if (it1 != ObjCInterfaceCache.end())
1944 if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty))
1945 if (Checksum(Decl) == it1->second.second)
1946 // Return cached forward declaration.
1947 return it1->second.first;
1948
1949 return 0;
1950}
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001951
1952/// getOrCreateType - Get the type from the cache or create a new
1953/// one if necessary.
Eric Christopher56b108a2013-06-07 22:54:39 +00001954llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit,
1955 bool Declaration) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001956 if (Ty.isNull())
1957 return llvm::DIType();
1958
1959 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00001960 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001961
1962 llvm::DIType T = getCompletedTypeOrNull(Ty);
1963
David Blaikief0c31d92013-06-21 21:03:11 +00001964 if (T.Verify()) {
1965 // If we're looking for a definition, make sure we have definitions of any
1966 // underlying types.
1967 if (const TypedefType* TTy = dyn_cast<TypedefType>(Ty))
1968 getOrCreateType(TTy->getDecl()->getUnderlyingType(), Unit, Declaration);
1969 if (Ty.hasLocalQualifiers())
1970 getOrCreateType(QualType(Ty.getTypePtr(), 0), Unit, Declaration);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001971 return T;
David Blaikief0c31d92013-06-21 21:03:11 +00001972 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001973
1974 // Otherwise create the type.
David Blaikie5f6e2f42013-06-05 05:32:23 +00001975 llvm::DIType Res = CreateTypeNode(Ty, Unit, Declaration);
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001976 void* TyPtr = Ty.getAsOpaquePtr();
1977
1978 // And update the type cache.
1979 TypeCache[TyPtr] = Res;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001980
1981 llvm::DIType TC = getTypeOrNull(Ty);
1982 if (TC.Verify() && TC.isForwardDecl())
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001983 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
1984 else if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty)) {
1985 // Interface types may have elements added to them by a
1986 // subsequent implementation or extension, so we keep them in
1987 // the ObjCInterfaceCache together with a checksum. Instead of
Adrian Prantlf06989b2013-05-08 23:37:22 +00001988 // the (possibly) incomplete interface type, we return a forward
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001989 // declaration that gets RAUW'd in CGDebugInfo::finalize().
David Blaikiee2eb89a2013-05-21 18:29:40 +00001990 std::pair<llvm::WeakVH, unsigned> &V = ObjCInterfaceCache[TyPtr];
1991 if (V.first)
1992 return llvm::DIType(cast<llvm::MDNode>(V.first));
1993 TC = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
1994 Decl->getName(), TheCU, Unit,
1995 getLineNumber(Decl->getLocation()),
1996 TheCU.getLanguage());
1997 // Store the forward declaration in the cache.
1998 V.first = TC;
1999 V.second = Checksum(Decl);
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002000
David Blaikiee2eb89a2013-05-21 18:29:40 +00002001 // Register the type for replacement in finalize().
2002 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
2003
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002004 return TC;
Adrian Prantl4919de62013-03-06 22:03:30 +00002005 }
2006
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002007 if (!Res.isForwardDecl())
Adrian Prantlebbd7e02013-03-11 18:33:46 +00002008 CompletedTypeCache[TyPtr] = Res;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002009
2010 return Res;
2011}
2012
Adrian Prantlb5a50072013-06-07 01:10:41 +00002013/// Currently the checksum of an interface includes the number of
2014/// ivars and property accessors.
Eric Christopher56b108a2013-06-07 22:54:39 +00002015unsigned CGDebugInfo::Checksum(const ObjCInterfaceDecl *ID) {
Adrian Prantl4f97f852013-06-07 01:10:48 +00002016 // The assumption is that the number of ivars can only increase
2017 // monotonically, so it is safe to just use their current number as
2018 // a checksum.
Adrian Prantlb5a50072013-06-07 01:10:41 +00002019 unsigned Sum = 0;
2020 for (const ObjCIvarDecl *Ivar = ID->all_declared_ivar_begin();
2021 Ivar != 0; Ivar = Ivar->getNextIvar())
2022 ++Sum;
2023
2024 return Sum;
Adrian Prantl4919de62013-03-06 22:03:30 +00002025}
2026
2027ObjCInterfaceDecl *CGDebugInfo::getObjCInterfaceDecl(QualType Ty) {
2028 switch (Ty->getTypeClass()) {
2029 case Type::ObjCObjectPointer:
Eric Christopherf0890c42013-05-16 00:52:20 +00002030 return getObjCInterfaceDecl(cast<ObjCObjectPointerType>(Ty)
2031 ->getPointeeType());
Adrian Prantl4919de62013-03-06 22:03:30 +00002032 case Type::ObjCInterface:
2033 return cast<ObjCInterfaceType>(Ty)->getDecl();
2034 default:
2035 return 0;
2036 }
2037}
2038
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002039/// CreateTypeNode - Create a new debug type node.
Eric Christopher56b108a2013-06-07 22:54:39 +00002040llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit,
2041 bool Declaration) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002042 // Handle qualifiers, which recursively handles what they refer to.
2043 if (Ty.hasLocalQualifiers())
David Blaikie5f6e2f42013-06-05 05:32:23 +00002044 return CreateQualifiedType(Ty, Unit, Declaration);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002045
2046 const char *Diag = 0;
Eric Christopher6537f082013-05-16 00:45:12 +00002047
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002048 // Work out details of type.
2049 switch (Ty->getTypeClass()) {
2050#define TYPE(Class, Base)
2051#define ABSTRACT_TYPE(Class, Base)
2052#define NON_CANONICAL_TYPE(Class, Base)
2053#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2054#include "clang/AST/TypeNodes.def"
2055 llvm_unreachable("Dependent types cannot show up in debug information");
2056
2057 case Type::ExtVector:
2058 case Type::Vector:
2059 return CreateType(cast<VectorType>(Ty), Unit);
2060 case Type::ObjCObjectPointer:
2061 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
2062 case Type::ObjCObject:
2063 return CreateType(cast<ObjCObjectType>(Ty), Unit);
2064 case Type::ObjCInterface:
2065 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
2066 case Type::Builtin:
2067 return CreateType(cast<BuiltinType>(Ty));
2068 case Type::Complex:
2069 return CreateType(cast<ComplexType>(Ty));
2070 case Type::Pointer:
2071 return CreateType(cast<PointerType>(Ty), Unit);
2072 case Type::BlockPointer:
2073 return CreateType(cast<BlockPointerType>(Ty), Unit);
2074 case Type::Typedef:
David Blaikie5f6e2f42013-06-05 05:32:23 +00002075 return CreateType(cast<TypedefType>(Ty), Unit, Declaration);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002076 case Type::Record:
David Blaikie5f6e2f42013-06-05 05:32:23 +00002077 return CreateType(cast<RecordType>(Ty), Declaration);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002078 case Type::Enum:
2079 return CreateEnumType(cast<EnumType>(Ty)->getDecl());
2080 case Type::FunctionProto:
2081 case Type::FunctionNoProto:
2082 return CreateType(cast<FunctionType>(Ty), Unit);
2083 case Type::ConstantArray:
2084 case Type::VariableArray:
2085 case Type::IncompleteArray:
2086 return CreateType(cast<ArrayType>(Ty), Unit);
2087
2088 case Type::LValueReference:
2089 return CreateType(cast<LValueReferenceType>(Ty), Unit);
2090 case Type::RValueReference:
2091 return CreateType(cast<RValueReferenceType>(Ty), Unit);
2092
2093 case Type::MemberPointer:
2094 return CreateType(cast<MemberPointerType>(Ty), Unit);
2095
2096 case Type::Atomic:
2097 return CreateType(cast<AtomicType>(Ty), Unit);
2098
2099 case Type::Attributed:
2100 case Type::TemplateSpecialization:
2101 case Type::Elaborated:
2102 case Type::Paren:
2103 case Type::SubstTemplateTypeParm:
2104 case Type::TypeOfExpr:
2105 case Type::TypeOf:
2106 case Type::Decltype:
2107 case Type::UnaryTransform:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002108 llvm_unreachable("type should have been unwrapped!");
David Blaikie91296482013-05-24 21:24:35 +00002109 case Type::Auto:
2110 Diag = "auto";
2111 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002112 }
Eric Christopher6537f082013-05-16 00:45:12 +00002113
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002114 assert(Diag && "Fall through without a diagnostic?");
2115 unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error,
2116 "debug information for %0 is not yet supported");
2117 CGM.getDiags().Report(DiagID)
2118 << Diag;
2119 return llvm::DIType();
2120}
2121
2122/// getOrCreateLimitedType - Get the type from the cache or create a new
2123/// limited type if necessary.
2124llvm::DIType CGDebugInfo::getOrCreateLimitedType(QualType Ty,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002125 llvm::DIFile Unit) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002126 if (Ty.isNull())
2127 return llvm::DIType();
2128
2129 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00002130 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002131
2132 llvm::DIType T = getTypeOrNull(Ty);
2133
2134 // We may have cached a forward decl when we could have created
2135 // a non-forward decl. Go ahead and create a non-forward decl
2136 // now.
2137 if (T.Verify() && !T.isForwardDecl()) return T;
2138
2139 // Otherwise create the type.
2140 llvm::DIType Res = CreateLimitedTypeNode(Ty, Unit);
2141
2142 if (T.Verify() && T.isForwardDecl())
2143 ReplaceMap.push_back(std::make_pair(Ty.getAsOpaquePtr(),
2144 static_cast<llvm::Value*>(T)));
2145
2146 // And update the type cache.
2147 TypeCache[Ty.getAsOpaquePtr()] = Res;
2148 return Res;
2149}
2150
2151// TODO: Currently used for context chains when limiting debug info.
2152llvm::DIType CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
2153 RecordDecl *RD = Ty->getDecl();
Eric Christopher6537f082013-05-16 00:45:12 +00002154
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002155 // Get overall information about the record type for the debug info.
2156 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
2157 unsigned Line = getLineNumber(RD->getLocation());
2158 StringRef RDName = getClassName(RD);
2159
2160 llvm::DIDescriptor RDContext;
Eric Christopher13c97672013-05-16 00:45:23 +00002161 if (DebugKind == CodeGenOptions::LimitedDebugInfo)
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002162 RDContext = createContextChain(cast<Decl>(RD->getDeclContext()));
2163 else
2164 RDContext = getContextDescriptor(cast<Decl>(RD->getDeclContext()));
2165
2166 // If this is just a forward declaration, construct an appropriately
2167 // marked node and just return it.
2168 if (!RD->getDefinition())
2169 return createRecordFwdDecl(RD, RDContext);
2170
2171 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2172 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
2173 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
David Blaikie2fcadbe2013-03-26 23:47:35 +00002174 llvm::DICompositeType RealDecl;
Eric Christopher6537f082013-05-16 00:45:12 +00002175
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002176 if (RD->isUnion())
2177 RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002178 Size, Align, 0, llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002179 else if (RD->isClass()) {
2180 // FIXME: This could be a struct type giving a default visibility different
2181 // than C++ class type, but needs llvm metadata changes first.
2182 RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002183 Size, Align, 0, 0, llvm::DIType(),
2184 llvm::DIArray(), llvm::DIType(),
2185 llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002186 } else
2187 RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line,
Eric Christopherf0890c42013-05-16 00:52:20 +00002188 Size, Align, 0, llvm::DIType(),
2189 llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002190
2191 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
David Blaikie2fcadbe2013-03-26 23:47:35 +00002192 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002193
2194 if (CXXDecl) {
2195 // A class's primary base or the class itself contains the vtable.
David Blaikie2fcadbe2013-03-26 23:47:35 +00002196 llvm::DICompositeType ContainingType;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002197 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2198 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
2199 // Seek non virtual primary base root.
2200 while (1) {
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002201 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
2202 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
2203 if (PBT && !BRL.isPrimaryBaseVirtual())
2204 PBase = PBT;
2205 else
2206 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002207 }
David Blaikie2fcadbe2013-03-26 23:47:35 +00002208 ContainingType = llvm::DICompositeType(
2209 getOrCreateType(QualType(PBase->getTypeForDecl(), 0), DefUnit));
2210 } else if (CXXDecl->isDynamicClass())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002211 ContainingType = RealDecl;
2212
David Blaikie2fcadbe2013-03-26 23:47:35 +00002213 RealDecl.setContainingType(ContainingType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002214 }
2215 return llvm::DIType(RealDecl);
2216}
2217
2218/// CreateLimitedTypeNode - Create a new debug type node, but only forward
2219/// declare composite types that haven't been processed yet.
2220llvm::DIType CGDebugInfo::CreateLimitedTypeNode(QualType Ty,llvm::DIFile Unit) {
2221
2222 // Work out details of type.
2223 switch (Ty->getTypeClass()) {
2224#define TYPE(Class, Base)
2225#define ABSTRACT_TYPE(Class, Base)
2226#define NON_CANONICAL_TYPE(Class, Base)
2227#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2228 #include "clang/AST/TypeNodes.def"
2229 llvm_unreachable("Dependent types cannot show up in debug information");
2230
2231 case Type::Record:
2232 return CreateLimitedType(cast<RecordType>(Ty));
2233 default:
David Blaikie5f6e2f42013-06-05 05:32:23 +00002234 return CreateTypeNode(Ty, Unit, false);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002235 }
2236}
2237
2238/// CreateMemberType - Create new member and increase Offset by FType's size.
2239llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
2240 StringRef Name,
2241 uint64_t *Offset) {
2242 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2243 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
2244 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
2245 llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0,
2246 FieldSize, FieldAlign,
2247 *Offset, 0, FieldTy);
2248 *Offset += FieldSize;
2249 return Ty;
2250}
2251
David Blaikie9faebd22013-05-20 04:58:53 +00002252llvm::DIDescriptor CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
2253 // We only need a declaration (not a definition) of the type - so use whatever
2254 // we would otherwise do to get a type for a pointee. (forward declarations in
2255 // limited debug info, full definitions (if the type definition is available)
2256 // in unlimited debug info)
2257 if (const TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
2258 llvm::DIFile DefUnit = getOrCreateFile(TD->getLocation());
David Blaikieb0f77b02013-05-24 21:33:22 +00002259 return getOrCreateTypeDeclaration(CGM.getContext().getTypeDeclType(TD),
2260 DefUnit);
David Blaikie9faebd22013-05-20 04:58:53 +00002261 }
2262 // Otherwise fall back to a fairly rudimentary cache of existing declarations.
2263 // This doesn't handle providing declarations (for functions or variables) for
2264 // entities without definitions in this TU, nor when the definition proceeds
2265 // the call to this function.
2266 // FIXME: This should be split out into more specific maps with support for
2267 // emitting forward declarations and merging definitions with declarations,
2268 // the same way as we do for types.
2269 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator I =
2270 DeclCache.find(D->getCanonicalDecl());
2271 if (I == DeclCache.end())
2272 return llvm::DIDescriptor();
2273 llvm::Value *V = I->second;
2274 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
2275}
2276
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002277/// getFunctionDeclaration - Return debug info descriptor to describe method
2278/// declaration for the given method definition.
2279llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
David Blaikie23e66db2013-06-22 00:09:36 +00002280 if (!D || DebugKind == CodeGenOptions::DebugLineTablesOnly)
2281 return llvm::DISubprogram();
2282
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002283 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
2284 if (!FD) return llvm::DISubprogram();
2285
2286 // Setup context.
2287 getContextDescriptor(cast<Decl>(D->getDeclContext()));
2288
2289 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2290 MI = SPCache.find(FD->getCanonicalDecl());
2291 if (MI != SPCache.end()) {
2292 llvm::Value *V = MI->second;
2293 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
David Blaikie23e66db2013-06-22 00:09:36 +00002294 if (SP.isSubprogram() && !SP.isDefinition())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002295 return SP;
2296 }
2297
2298 for (FunctionDecl::redecl_iterator I = FD->redecls_begin(),
2299 E = FD->redecls_end(); I != E; ++I) {
2300 const FunctionDecl *NextFD = *I;
2301 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2302 MI = SPCache.find(NextFD->getCanonicalDecl());
2303 if (MI != SPCache.end()) {
2304 llvm::Value *V = MI->second;
2305 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
David Blaikie23e66db2013-06-22 00:09:36 +00002306 if (SP.isSubprogram() && !SP.isDefinition())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002307 return SP;
2308 }
2309 }
2310 return llvm::DISubprogram();
2311}
2312
2313// getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
2314// implicit parameter "this".
David Blaikie9a845292013-05-22 23:22:42 +00002315llvm::DICompositeType CGDebugInfo::getOrCreateFunctionType(const Decl *D,
2316 QualType FnType,
2317 llvm::DIFile F) {
David Blaikie23e66db2013-06-22 00:09:36 +00002318 if (!D || DebugKind == CodeGenOptions::DebugLineTablesOnly)
2319 // Create fake but valid subroutine type. Otherwise
2320 // llvm::DISubprogram::Verify() would return false, and
2321 // subprogram DIE will miss DW_AT_decl_file and
2322 // DW_AT_decl_line fields.
2323 return DBuilder.createSubroutineType(F, DBuilder.getOrCreateArray(None));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002324
2325 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
2326 return getOrCreateMethodType(Method, F);
2327 if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
2328 // Add "self" and "_cmd"
2329 SmallVector<llvm::Value *, 16> Elts;
2330
2331 // First element is always return type. For 'void' functions it is NULL.
Adrian Prantl0cb00022013-05-22 21:37:49 +00002332 QualType ResultTy = OMethod->getResultType();
2333
2334 // Replace the instancetype keyword with the actual type.
2335 if (ResultTy == CGM.getContext().getObjCInstanceType())
2336 ResultTy = CGM.getContext().getPointerType(
2337 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
2338
Adrian Prantl566a9c32013-05-10 21:08:31 +00002339 Elts.push_back(getOrCreateType(ResultTy, F));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002340 // "self" pointer is always first argument.
Adrian Prantle86fcc42013-03-29 19:20:29 +00002341 QualType SelfDeclTy = OMethod->getSelfDecl()->getType();
2342 llvm::DIType SelfTy = getOrCreateType(SelfDeclTy, F);
2343 Elts.push_back(CreateSelfType(SelfDeclTy, SelfTy));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002344 // "_cmd" pointer is always second argument.
2345 llvm::DIType CmdTy = getOrCreateType(OMethod->getCmdDecl()->getType(), F);
2346 Elts.push_back(DBuilder.createArtificialType(CmdTy));
2347 // Get rest of the arguments.
Eric Christopher6537f082013-05-16 00:45:12 +00002348 for (ObjCMethodDecl::param_const_iterator PI = OMethod->param_begin(),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002349 PE = OMethod->param_end(); PI != PE; ++PI)
2350 Elts.push_back(getOrCreateType((*PI)->getType(), F));
2351
2352 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2353 return DBuilder.createSubroutineType(F, EltTypeArray);
2354 }
David Blaikie9a845292013-05-22 23:22:42 +00002355 return llvm::DICompositeType(getOrCreateType(FnType, F));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002356}
2357
2358/// EmitFunctionStart - Constructs the debug code for entering a function.
2359void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
2360 llvm::Function *Fn,
2361 CGBuilderTy &Builder) {
2362
2363 StringRef Name;
2364 StringRef LinkageName;
2365
2366 FnBeginRegionCount.push_back(LexicalBlockStack.size());
2367
2368 const Decl *D = GD.getDecl();
2369 // Function may lack declaration in source code if it is created by Clang
2370 // CodeGen (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
2371 bool HasDecl = (D != 0);
2372 // Use the location of the declaration.
2373 SourceLocation Loc;
2374 if (HasDecl)
2375 Loc = D->getLocation();
2376
2377 unsigned Flags = 0;
2378 llvm::DIFile Unit = getOrCreateFile(Loc);
2379 llvm::DIDescriptor FDContext(Unit);
2380 llvm::DIArray TParamsArray;
2381 if (!HasDecl) {
2382 // Use llvm function name.
2383 Name = Fn->getName();
2384 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2385 // If there is a DISubprogram for this function available then use it.
2386 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2387 FI = SPCache.find(FD->getCanonicalDecl());
2388 if (FI != SPCache.end()) {
2389 llvm::Value *V = FI->second;
2390 llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(V));
2391 if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
2392 llvm::MDNode *SPN = SP;
2393 LexicalBlockStack.push_back(SPN);
2394 RegionMap[D] = llvm::WeakVH(SP);
2395 return;
2396 }
2397 }
2398 Name = getFunctionName(FD);
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002399 // Use mangled name as linkage name for C/C++ functions.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002400 if (FD->hasPrototype()) {
2401 LinkageName = CGM.getMangledName(GD);
2402 Flags |= llvm::DIDescriptor::FlagPrototyped;
2403 }
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002404 // No need to replicate the linkage name if it isn't different from the
2405 // subprogram name, no need to have it at all unless coverage is enabled or
2406 // debug is set to more than just line tables.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002407 if (LinkageName == Name ||
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002408 (!CGM.getCodeGenOpts().EmitGcovArcs &&
2409 !CGM.getCodeGenOpts().EmitGcovNotes &&
Eric Christopher13c97672013-05-16 00:45:23 +00002410 DebugKind <= CodeGenOptions::DebugLineTablesOnly))
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002411 LinkageName = StringRef();
2412
Eric Christopher13c97672013-05-16 00:45:23 +00002413 if (DebugKind >= CodeGenOptions::LimitedDebugInfo) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002414 if (const NamespaceDecl *NSDecl =
2415 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
2416 FDContext = getOrCreateNameSpace(NSDecl);
2417 else if (const RecordDecl *RDecl =
2418 dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
2419 FDContext = getContextDescriptor(cast<Decl>(RDecl->getDeclContext()));
2420
2421 // Collect template parameters.
2422 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
2423 }
2424 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
2425 Name = getObjCMethodName(OMD);
2426 Flags |= llvm::DIDescriptor::FlagPrototyped;
2427 } else {
2428 // Use llvm function name.
2429 Name = Fn->getName();
2430 Flags |= llvm::DIDescriptor::FlagPrototyped;
2431 }
2432 if (!Name.empty() && Name[0] == '\01')
2433 Name = Name.substr(1);
2434
2435 unsigned LineNo = getLineNumber(Loc);
2436 if (!HasDecl || D->isImplicit())
2437 Flags |= llvm::DIDescriptor::FlagArtificial;
2438
David Blaikie23e66db2013-06-22 00:09:36 +00002439 llvm::DISubprogram SP = DBuilder.createFunction(
2440 FDContext, Name, LinkageName, Unit, LineNo,
2441 getOrCreateFunctionType(D, FnType, Unit), Fn->hasInternalLinkage(),
2442 true /*definition*/, getLineNumber(CurLoc), Flags,
2443 CGM.getLangOpts().Optimize, Fn, TParamsArray, getFunctionDeclaration(D));
David Blaikie9faebd22013-05-20 04:58:53 +00002444 if (HasDecl)
2445 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(SP)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002446
2447 // Push function on region stack.
2448 llvm::MDNode *SPN = SP;
2449 LexicalBlockStack.push_back(SPN);
2450 if (HasDecl)
2451 RegionMap[D] = llvm::WeakVH(SP);
2452}
2453
2454/// EmitLocation - Emit metadata to indicate a change in line/column
2455/// information in the source file.
Adrian Prantl00df5ea2013-03-12 20:43:25 +00002456void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc,
2457 bool ForceColumnInfo) {
Eric Christopher6537f082013-05-16 00:45:12 +00002458
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002459 // Update our current location
2460 setLocation(Loc);
2461
2462 if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
2463
2464 // Don't bother if things are the same as last time.
2465 SourceManager &SM = CGM.getContext().getSourceManager();
2466 if (CurLoc == PrevLoc ||
2467 SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc))
2468 // New Builder may not be in sync with CGDebugInfo.
David Blaikie0a0f93c2013-02-01 19:09:49 +00002469 if (!Builder.getCurrentDebugLocation().isUnknown() &&
2470 Builder.getCurrentDebugLocation().getScope(CGM.getLLVMContext()) ==
2471 LexicalBlockStack.back())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002472 return;
Eric Christopher6537f082013-05-16 00:45:12 +00002473
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002474 // Update last state.
2475 PrevLoc = CurLoc;
2476
2477 llvm::MDNode *Scope = LexicalBlockStack.back();
Adrian Prantl00df5ea2013-03-12 20:43:25 +00002478 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get
2479 (getLineNumber(CurLoc),
2480 getColumnNumber(CurLoc, ForceColumnInfo),
2481 Scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002482}
2483
2484/// CreateLexicalBlock - Creates a new lexical block node and pushes it on
2485/// the stack.
2486void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
2487 llvm::DIDescriptor D =
2488 DBuilder.createLexicalBlock(LexicalBlockStack.empty() ?
2489 llvm::DIDescriptor() :
2490 llvm::DIDescriptor(LexicalBlockStack.back()),
2491 getOrCreateFile(CurLoc),
2492 getLineNumber(CurLoc),
2493 getColumnNumber(CurLoc));
2494 llvm::MDNode *DN = D;
2495 LexicalBlockStack.push_back(DN);
2496}
2497
2498/// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
2499/// region - beginning of a DW_TAG_lexical_block.
Eric Christopherf0890c42013-05-16 00:52:20 +00002500void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
2501 SourceLocation Loc) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002502 // Set our current location.
2503 setLocation(Loc);
2504
2505 // Create a new lexical block and push it on the stack.
2506 CreateLexicalBlock(Loc);
2507
2508 // Emit a line table change for the current location inside the new scope.
2509 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc),
2510 getColumnNumber(Loc),
2511 LexicalBlockStack.back()));
2512}
2513
2514/// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative
2515/// region - end of a DW_TAG_lexical_block.
Eric Christopherf0890c42013-05-16 00:52:20 +00002516void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
2517 SourceLocation Loc) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002518 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2519
2520 // Provide an entry in the line table for the end of the block.
2521 EmitLocation(Builder, Loc);
2522
2523 LexicalBlockStack.pop_back();
2524}
2525
2526/// EmitFunctionEnd - Constructs the debug code for exiting a function.
2527void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
2528 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2529 unsigned RCount = FnBeginRegionCount.back();
2530 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
2531
2532 // Pop all regions for this function.
2533 while (LexicalBlockStack.size() != RCount)
2534 EmitLexicalBlockEnd(Builder, CurLoc);
2535 FnBeginRegionCount.pop_back();
2536}
2537
Eric Christopher6537f082013-05-16 00:45:12 +00002538// EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002539// See BuildByRefType.
2540llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
2541 uint64_t *XOffset) {
2542
2543 SmallVector<llvm::Value *, 5> EltTys;
2544 QualType FType;
2545 uint64_t FieldSize, FieldOffset;
2546 unsigned FieldAlign;
Eric Christopher6537f082013-05-16 00:45:12 +00002547
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002548 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
Eric Christopher6537f082013-05-16 00:45:12 +00002549 QualType Type = VD->getType();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002550
2551 FieldOffset = 0;
2552 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2553 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
2554 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
2555 FType = CGM.getContext().IntTy;
2556 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
2557 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
2558
2559 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
2560 if (HasCopyAndDispose) {
2561 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2562 EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
2563 &FieldOffset));
2564 EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
2565 &FieldOffset));
2566 }
2567 bool HasByrefExtendedLayout;
2568 Qualifiers::ObjCLifetime Lifetime;
2569 if (CGM.getContext().getByrefLifetime(Type,
2570 Lifetime, HasByrefExtendedLayout)
2571 && HasByrefExtendedLayout)
2572 EltTys.push_back(CreateMemberType(Unit, FType,
2573 "__byref_variable_layout",
2574 &FieldOffset));
Eric Christopher6537f082013-05-16 00:45:12 +00002575
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002576 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2577 if (Align > CGM.getContext().toCharUnitsFromBits(
John McCall64aa4b32013-04-16 22:48:15 +00002578 CGM.getTarget().getPointerAlign(0))) {
Eric Christopher6537f082013-05-16 00:45:12 +00002579 CharUnits FieldOffsetInBytes
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002580 = CGM.getContext().toCharUnitsFromBits(FieldOffset);
2581 CharUnits AlignedOffsetInBytes
2582 = FieldOffsetInBytes.RoundUpToAlignment(Align);
2583 CharUnits NumPaddingBytes
2584 = AlignedOffsetInBytes - FieldOffsetInBytes;
Eric Christopher6537f082013-05-16 00:45:12 +00002585
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002586 if (NumPaddingBytes.isPositive()) {
2587 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
2588 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
2589 pad, ArrayType::Normal, 0);
2590 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
2591 }
2592 }
Eric Christopher6537f082013-05-16 00:45:12 +00002593
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002594 FType = Type;
2595 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2596 FieldSize = CGM.getContext().getTypeSize(FType);
2597 FieldAlign = CGM.getContext().toBits(Align);
2598
Eric Christopher6537f082013-05-16 00:45:12 +00002599 *XOffset = FieldOffset;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002600 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit,
2601 0, FieldSize, FieldAlign,
2602 FieldOffset, 0, FieldTy);
2603 EltTys.push_back(FieldTy);
2604 FieldOffset += FieldSize;
Eric Christopher6537f082013-05-16 00:45:12 +00002605
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002606 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopher6537f082013-05-16 00:45:12 +00002607
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002608 unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
Eric Christopher6537f082013-05-16 00:45:12 +00002609
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002610 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
David Blaikiec1d0af12013-02-25 01:07:08 +00002611 llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002612}
2613
2614/// EmitDeclare - Emit local variable declaration debug info.
2615void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
Eric Christopher6537f082013-05-16 00:45:12 +00002616 llvm::Value *Storage,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002617 unsigned ArgNo, CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002618 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002619 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2620
2621 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2622 llvm::DIType Ty;
2623 uint64_t XOffset = 0;
2624 if (VD->hasAttr<BlocksAttr>())
2625 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopher6537f082013-05-16 00:45:12 +00002626 else
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002627 Ty = getOrCreateType(VD->getType(), Unit);
2628
2629 // If there is no debug info for this type then do not emit debug info
2630 // for this variable.
2631 if (!Ty)
2632 return;
2633
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002634 // Get location information.
2635 unsigned Line = getLineNumber(VD->getLocation());
2636 unsigned Column = getColumnNumber(VD->getLocation());
2637 unsigned Flags = 0;
2638 if (VD->isImplicit())
2639 Flags |= llvm::DIDescriptor::FlagArtificial;
2640 // If this is the first argument and it is implicit then
2641 // give it an object pointer flag.
2642 // FIXME: There has to be a better way to do this, but for static
2643 // functions there won't be an implicit param at arg1 and
2644 // otherwise it is 'self' or 'this'.
2645 if (isa<ImplicitParamDecl>(VD) && ArgNo == 1)
2646 Flags |= llvm::DIDescriptor::FlagObjectPointer;
David Blaikie41c9bae2013-06-19 21:53:53 +00002647 if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage))
2648 if (Arg->getType()->isPointerTy() && !Arg->hasByValAttr() && !VD->getType()->isPointerType())
2649 Flags |= llvm::DIDescriptor::FlagIndirectVariable;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002650
2651 llvm::MDNode *Scope = LexicalBlockStack.back();
2652
2653 StringRef Name = VD->getName();
2654 if (!Name.empty()) {
2655 if (VD->hasAttr<BlocksAttr>()) {
2656 CharUnits offset = CharUnits::fromQuantity(32);
2657 SmallVector<llvm::Value *, 9> addr;
2658 llvm::Type *Int64Ty = CGM.Int64Ty;
2659 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2660 // offset of __forwarding field
2661 offset = CGM.getContext().toCharUnitsFromBits(
John McCall64aa4b32013-04-16 22:48:15 +00002662 CGM.getTarget().getPointerWidth(0));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002663 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2664 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2665 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2666 // offset of x field
2667 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2668 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2669
2670 // Create the descriptor for the variable.
2671 llvm::DIVariable D =
Eric Christopher6537f082013-05-16 00:45:12 +00002672 DBuilder.createComplexVariable(Tag,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002673 llvm::DIDescriptor(Scope),
2674 VD->getName(), Unit, Line, Ty,
2675 addr, ArgNo);
Eric Christopher6537f082013-05-16 00:45:12 +00002676
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002677 // Insert an llvm.dbg.declare into the current block.
2678 llvm::Instruction *Call =
2679 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2680 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2681 return;
Adrian Prantl230ea412013-04-30 22:45:09 +00002682 } else if (isa<VariableArrayType>(VD->getType())) {
2683 // These are "complex" variables in that they need an op_deref.
2684 // Create the descriptor for the variable.
2685 llvm::Value *Addr = llvm::ConstantInt::get(CGM.Int64Ty,
2686 llvm::DIBuilder::OpDeref);
2687 llvm::DIVariable D =
2688 DBuilder.createComplexVariable(Tag,
2689 llvm::DIDescriptor(Scope),
2690 Name, Unit, Line, Ty,
2691 Addr, ArgNo);
2692
2693 // Insert an llvm.dbg.declare into the current block.
2694 llvm::Instruction *Call =
2695 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2696 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2697 return;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002698 }
David Blaikie436653b2013-01-05 05:58:35 +00002699 } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2700 // If VD is an anonymous union then Storage represents value for
2701 // all union fields.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002702 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
David Blaikied8180cf2013-01-05 20:03:07 +00002703 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002704 for (RecordDecl::field_iterator I = RD->field_begin(),
2705 E = RD->field_end();
2706 I != E; ++I) {
2707 FieldDecl *Field = *I;
2708 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2709 StringRef FieldName = Field->getName();
Eric Christopher6537f082013-05-16 00:45:12 +00002710
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002711 // Ignore unnamed fields. Do not ignore unnamed records.
2712 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2713 continue;
Eric Christopher6537f082013-05-16 00:45:12 +00002714
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002715 // Use VarDecl's Tag, Scope and Line number.
2716 llvm::DIVariable D =
2717 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
Eric Christopher6537f082013-05-16 00:45:12 +00002718 FieldName, Unit, Line, FieldTy,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002719 CGM.getLangOpts().Optimize, Flags,
2720 ArgNo);
Eric Christopher6537f082013-05-16 00:45:12 +00002721
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002722 // Insert an llvm.dbg.declare into the current block.
2723 llvm::Instruction *Call =
2724 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2725 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2726 }
David Blaikied8180cf2013-01-05 20:03:07 +00002727 return;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002728 }
2729 }
David Blaikie436653b2013-01-05 05:58:35 +00002730
2731 // Create the descriptor for the variable.
2732 llvm::DIVariable D =
2733 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2734 Name, Unit, Line, Ty,
2735 CGM.getLangOpts().Optimize, Flags, ArgNo);
2736
2737 // Insert an llvm.dbg.declare into the current block.
2738 llvm::Instruction *Call =
2739 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2740 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002741}
2742
2743void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2744 llvm::Value *Storage,
2745 CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002746 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002747 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2748}
2749
Adrian Prantle86fcc42013-03-29 19:20:29 +00002750/// Look up the completed type for a self pointer in the TypeCache and
2751/// create a copy of it with the ObjectPointer and Artificial flags
2752/// set. If the type is not cached, a new one is created. This should
2753/// never happen though, since creating a type for the implicit self
2754/// argument implies that we already parsed the interface definition
2755/// and the ivar declarations in the implementation.
Eric Christopherf0890c42013-05-16 00:52:20 +00002756llvm::DIType CGDebugInfo::CreateSelfType(const QualType &QualTy,
2757 llvm::DIType Ty) {
Adrian Prantle86fcc42013-03-29 19:20:29 +00002758 llvm::DIType CachedTy = getTypeOrNull(QualTy);
2759 if (CachedTy.Verify()) Ty = CachedTy;
2760 else DEBUG(llvm::dbgs() << "No cached type for self.");
2761 return DBuilder.createObjectPointerType(Ty);
2762}
2763
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002764void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(const VarDecl *VD,
2765 llvm::Value *Storage,
2766 CGBuilderTy &Builder,
2767 const CGBlockInfo &blockInfo) {
Eric Christopher13c97672013-05-16 00:45:23 +00002768 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002769 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
Eric Christopher6537f082013-05-16 00:45:12 +00002770
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002771 if (Builder.GetInsertBlock() == 0)
2772 return;
Eric Christopher6537f082013-05-16 00:45:12 +00002773
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002774 bool isByRef = VD->hasAttr<BlocksAttr>();
Eric Christopher6537f082013-05-16 00:45:12 +00002775
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002776 uint64_t XOffset = 0;
2777 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2778 llvm::DIType Ty;
2779 if (isByRef)
2780 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopher6537f082013-05-16 00:45:12 +00002781 else
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002782 Ty = getOrCreateType(VD->getType(), Unit);
2783
2784 // Self is passed along as an implicit non-arg variable in a
2785 // block. Mark it as the object pointer.
2786 if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self")
Adrian Prantle86fcc42013-03-29 19:20:29 +00002787 Ty = CreateSelfType(VD->getType(), Ty);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002788
2789 // Get location information.
2790 unsigned Line = getLineNumber(VD->getLocation());
2791 unsigned Column = getColumnNumber(VD->getLocation());
2792
2793 const llvm::DataLayout &target = CGM.getDataLayout();
2794
2795 CharUnits offset = CharUnits::fromQuantity(
2796 target.getStructLayout(blockInfo.StructureType)
2797 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2798
2799 SmallVector<llvm::Value *, 9> addr;
2800 llvm::Type *Int64Ty = CGM.Int64Ty;
Adrian Prantl9b97adf2013-03-29 19:20:35 +00002801 if (isa<llvm::AllocaInst>(Storage))
2802 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002803 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2804 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2805 if (isByRef) {
2806 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2807 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2808 // offset of __forwarding field
2809 offset = CGM.getContext()
2810 .toCharUnitsFromBits(target.getPointerSizeInBits(0));
2811 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2812 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2813 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2814 // offset of x field
2815 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2816 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2817 }
2818
2819 // Create the descriptor for the variable.
2820 llvm::DIVariable D =
Eric Christopher6537f082013-05-16 00:45:12 +00002821 DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002822 llvm::DIDescriptor(LexicalBlockStack.back()),
2823 VD->getName(), Unit, Line, Ty, addr);
Adrian Prantl9b97adf2013-03-29 19:20:35 +00002824
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002825 // Insert an llvm.dbg.declare into the current block.
2826 llvm::Instruction *Call =
2827 DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
2828 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column,
2829 LexicalBlockStack.back()));
2830}
2831
2832/// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2833/// variable declaration.
2834void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2835 unsigned ArgNo,
2836 CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002837 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002838 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2839}
2840
2841namespace {
2842 struct BlockLayoutChunk {
2843 uint64_t OffsetInBits;
2844 const BlockDecl::Capture *Capture;
2845 };
2846 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2847 return l.OffsetInBits < r.OffsetInBits;
2848 }
2849}
2850
2851void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
Adrian Prantl836e7c92013-03-14 17:53:33 +00002852 llvm::Value *Arg,
2853 llvm::Value *LocalAddr,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002854 CGBuilderTy &Builder) {
Eric Christopher13c97672013-05-16 00:45:23 +00002855 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002856 ASTContext &C = CGM.getContext();
2857 const BlockDecl *blockDecl = block.getBlockDecl();
2858
2859 // Collect some general information about the block's location.
2860 SourceLocation loc = blockDecl->getCaretLocation();
2861 llvm::DIFile tunit = getOrCreateFile(loc);
2862 unsigned line = getLineNumber(loc);
2863 unsigned column = getColumnNumber(loc);
Eric Christopher6537f082013-05-16 00:45:12 +00002864
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002865 // Build the debug-info type for the block literal.
2866 getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
2867
2868 const llvm::StructLayout *blockLayout =
2869 CGM.getDataLayout().getStructLayout(block.StructureType);
2870
2871 SmallVector<llvm::Value*, 16> fields;
2872 fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
2873 blockLayout->getElementOffsetInBits(0),
2874 tunit, tunit));
2875 fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
2876 blockLayout->getElementOffsetInBits(1),
2877 tunit, tunit));
2878 fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
2879 blockLayout->getElementOffsetInBits(2),
2880 tunit, tunit));
2881 fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
2882 blockLayout->getElementOffsetInBits(3),
2883 tunit, tunit));
2884 fields.push_back(createFieldType("__descriptor",
2885 C.getPointerType(block.NeedsCopyDispose ?
2886 C.getBlockDescriptorExtendedType() :
2887 C.getBlockDescriptorType()),
2888 0, loc, AS_public,
2889 blockLayout->getElementOffsetInBits(4),
2890 tunit, tunit));
2891
2892 // We want to sort the captures by offset, not because DWARF
2893 // requires this, but because we're paranoid about debuggers.
2894 SmallVector<BlockLayoutChunk, 8> chunks;
2895
2896 // 'this' capture.
2897 if (blockDecl->capturesCXXThis()) {
2898 BlockLayoutChunk chunk;
2899 chunk.OffsetInBits =
2900 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
2901 chunk.Capture = 0;
2902 chunks.push_back(chunk);
2903 }
2904
2905 // Variable captures.
2906 for (BlockDecl::capture_const_iterator
2907 i = blockDecl->capture_begin(), e = blockDecl->capture_end();
2908 i != e; ++i) {
2909 const BlockDecl::Capture &capture = *i;
2910 const VarDecl *variable = capture.getVariable();
2911 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
2912
2913 // Ignore constant captures.
2914 if (captureInfo.isConstant())
2915 continue;
2916
2917 BlockLayoutChunk chunk;
2918 chunk.OffsetInBits =
2919 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
2920 chunk.Capture = &capture;
2921 chunks.push_back(chunk);
2922 }
2923
2924 // Sort by offset.
2925 llvm::array_pod_sort(chunks.begin(), chunks.end());
2926
2927 for (SmallVectorImpl<BlockLayoutChunk>::iterator
2928 i = chunks.begin(), e = chunks.end(); i != e; ++i) {
2929 uint64_t offsetInBits = i->OffsetInBits;
2930 const BlockDecl::Capture *capture = i->Capture;
2931
2932 // If we have a null capture, this must be the C++ 'this' capture.
2933 if (!capture) {
2934 const CXXMethodDecl *method =
2935 cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
2936 QualType type = method->getThisType(C);
2937
2938 fields.push_back(createFieldType("this", type, 0, loc, AS_public,
2939 offsetInBits, tunit, tunit));
2940 continue;
2941 }
2942
2943 const VarDecl *variable = capture->getVariable();
2944 StringRef name = variable->getName();
2945
2946 llvm::DIType fieldType;
2947 if (capture->isByRef()) {
2948 std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
2949
2950 // FIXME: this creates a second copy of this type!
2951 uint64_t xoffset;
2952 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
2953 fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
2954 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
2955 ptrInfo.first, ptrInfo.second,
2956 offsetInBits, 0, fieldType);
2957 } else {
2958 fieldType = createFieldType(name, variable->getType(), 0,
2959 loc, AS_public, offsetInBits, tunit, tunit);
2960 }
2961 fields.push_back(fieldType);
2962 }
2963
2964 SmallString<36> typeName;
2965 llvm::raw_svector_ostream(typeName)
2966 << "__block_literal_" << CGM.getUniqueBlockCount();
2967
2968 llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
2969
2970 llvm::DIType type =
2971 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
2972 CGM.getContext().toBits(block.BlockSize),
2973 CGM.getContext().toBits(block.BlockAlign),
David Blaikiec1d0af12013-02-25 01:07:08 +00002974 0, llvm::DIType(), fieldsArray);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002975 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
2976
2977 // Get overall information about the block.
2978 unsigned flags = llvm::DIDescriptor::FlagArtificial;
2979 llvm::MDNode *scope = LexicalBlockStack.back();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002980
2981 // Create the descriptor for the parameter.
2982 llvm::DIVariable debugVar =
2983 DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
Eric Christopher6537f082013-05-16 00:45:12 +00002984 llvm::DIDescriptor(scope),
Adrian Prantl836e7c92013-03-14 17:53:33 +00002985 Arg->getName(), tunit, line, type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002986 CGM.getLangOpts().Optimize, flags,
Adrian Prantl836e7c92013-03-14 17:53:33 +00002987 cast<llvm::Argument>(Arg)->getArgNo() + 1);
2988
Adrian Prantlbea407c2013-03-14 21:52:59 +00002989 if (LocalAddr) {
Adrian Prantl836e7c92013-03-14 17:53:33 +00002990 // Insert an llvm.dbg.value into the current block.
Adrian Prantlbea407c2013-03-14 21:52:59 +00002991 llvm::Instruction *DbgVal =
2992 DBuilder.insertDbgValueIntrinsic(LocalAddr, 0, debugVar,
Eric Christopherf068c922013-04-02 22:59:11 +00002993 Builder.GetInsertBlock());
Adrian Prantlbea407c2013-03-14 21:52:59 +00002994 DbgVal->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
2995 }
Adrian Prantl836e7c92013-03-14 17:53:33 +00002996
Adrian Prantlbea407c2013-03-14 21:52:59 +00002997 // Insert an llvm.dbg.declare into the current block.
2998 llvm::Instruction *DbgDecl =
2999 DBuilder.insertDeclare(Arg, debugVar, Builder.GetInsertBlock());
3000 DbgDecl->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003001}
3002
Eric Christopher0395de32013-01-16 01:22:32 +00003003/// getStaticDataMemberDeclaration - If D is an out-of-class definition of
3004/// a static data member of a class, find its corresponding in-class
3005/// declaration.
3006llvm::DIDerivedType CGDebugInfo::getStaticDataMemberDeclaration(const Decl *D) {
3007 if (cast<VarDecl>(D)->isStaticDataMember()) {
3008 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
3009 MI = StaticDataMemberCache.find(D->getCanonicalDecl());
3010 if (MI != StaticDataMemberCache.end())
3011 // Verify the info still exists.
3012 if (llvm::Value *V = MI->second)
3013 return llvm::DIDerivedType(cast<llvm::MDNode>(V));
3014 }
3015 return llvm::DIDerivedType();
3016}
3017
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003018/// EmitGlobalVariable - Emit information about a global variable.
3019void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
3020 const VarDecl *D) {
Eric Christopher13c97672013-05-16 00:45:23 +00003021 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003022 // Create global variable debug descriptor.
3023 llvm::DIFile Unit = getOrCreateFile(D->getLocation());
3024 unsigned LineNo = getLineNumber(D->getLocation());
3025
3026 setLocation(D->getLocation());
3027
3028 QualType T = D->getType();
3029 if (T->isIncompleteArrayType()) {
3030
3031 // CodeGen turns int[] into int[1] so we'll do the same here.
3032 llvm::APInt ConstVal(32, 1);
3033 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3034
3035 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3036 ArrayType::Normal, 0);
3037 }
3038 StringRef DeclName = D->getName();
3039 StringRef LinkageName;
3040 if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext())
3041 && !isa<ObjCMethodDecl>(D->getDeclContext()))
3042 LinkageName = Var->getName();
3043 if (LinkageName == DeclName)
3044 LinkageName = StringRef();
Eric Christopher6537f082013-05-16 00:45:12 +00003045 llvm::DIDescriptor DContext =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003046 getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
Eric Christopher56b108a2013-06-07 22:54:39 +00003047 llvm::DIGlobalVariable GV =
3048 DBuilder.createStaticVariable(DContext, DeclName, LinkageName, Unit,
3049 LineNo, getOrCreateType(T, Unit),
3050 Var->hasInternalLinkage(), Var,
3051 getStaticDataMemberDeclaration(D));
David Blaikie9faebd22013-05-20 04:58:53 +00003052 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(GV)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003053}
3054
3055/// EmitGlobalVariable - Emit information about an objective-c interface.
3056void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
3057 ObjCInterfaceDecl *ID) {
Eric Christopher13c97672013-05-16 00:45:23 +00003058 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003059 // Create global variable debug descriptor.
3060 llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
3061 unsigned LineNo = getLineNumber(ID->getLocation());
3062
3063 StringRef Name = ID->getName();
3064
3065 QualType T = CGM.getContext().getObjCInterfaceType(ID);
3066 if (T->isIncompleteArrayType()) {
3067
3068 // CodeGen turns int[] into int[1] so we'll do the same here.
3069 llvm::APInt ConstVal(32, 1);
3070 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3071
3072 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3073 ArrayType::Normal, 0);
3074 }
3075
3076 DBuilder.createGlobalVariable(Name, Unit, LineNo,
3077 getOrCreateType(T, Unit),
3078 Var->hasInternalLinkage(), Var);
3079}
3080
3081/// EmitGlobalVariable - Emit global variable's debug info.
Eric Christopher6537f082013-05-16 00:45:12 +00003082void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003083 llvm::Constant *Init) {
Eric Christopher13c97672013-05-16 00:45:23 +00003084 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003085 // Create the descriptor for the variable.
3086 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
3087 StringRef Name = VD->getName();
3088 llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
3089 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
3090 const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext());
3091 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
3092 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
3093 }
3094 // Do not use DIGlobalVariable for enums.
3095 if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
3096 return;
Eric Christopher56b108a2013-06-07 22:54:39 +00003097 llvm::DIGlobalVariable GV =
3098 DBuilder.createStaticVariable(Unit, Name, Name, Unit,
3099 getLineNumber(VD->getLocation()), Ty, true,
3100 Init, getStaticDataMemberDeclaration(VD));
David Blaikie9faebd22013-05-20 04:58:53 +00003101 DeclCache.insert(std::make_pair(VD->getCanonicalDecl(), llvm::WeakVH(GV)));
3102}
3103
3104llvm::DIScope CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
3105 if (!LexicalBlockStack.empty())
3106 return llvm::DIScope(LexicalBlockStack.back());
3107 return getContextDescriptor(D);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003108}
3109
David Blaikie957dac52013-04-22 06:13:21 +00003110void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
David Blaikie9faebd22013-05-20 04:58:53 +00003111 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3112 return;
David Blaikie957dac52013-04-22 06:13:21 +00003113 DBuilder.createImportedModule(
David Blaikie9faebd22013-05-20 04:58:53 +00003114 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
3115 getOrCreateNameSpace(UD.getNominatedNamespace()),
David Blaikie957dac52013-04-22 06:13:21 +00003116 getLineNumber(UD.getLocation()));
3117}
3118
David Blaikie9faebd22013-05-20 04:58:53 +00003119void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
3120 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3121 return;
3122 assert(UD.shadow_size() &&
3123 "We shouldn't be codegening an invalid UsingDecl containing no decls");
3124 // Emitting one decl is sufficient - debuggers can detect that this is an
3125 // overloaded name & provide lookup for all the overloads.
3126 const UsingShadowDecl &USD = **UD.shadow_begin();
Eric Christopher56b108a2013-06-07 22:54:39 +00003127 if (llvm::DIDescriptor Target =
3128 getDeclarationOrDefinition(USD.getUnderlyingDecl()))
David Blaikie9faebd22013-05-20 04:58:53 +00003129 DBuilder.createImportedDeclaration(
3130 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
3131 getLineNumber(USD.getLocation()));
3132}
3133
David Blaikiefc46ebc2013-05-20 22:50:41 +00003134llvm::DIImportedEntity
3135CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
3136 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3137 return llvm::DIImportedEntity(0);
3138 llvm::WeakVH &VH = NamespaceAliasCache[&NA];
3139 if (VH)
3140 return llvm::DIImportedEntity(cast<llvm::MDNode>(VH));
3141 llvm::DIImportedEntity R(0);
3142 if (const NamespaceAliasDecl *Underlying =
3143 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
3144 // This could cache & dedup here rather than relying on metadata deduping.
3145 R = DBuilder.createImportedModule(
3146 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3147 EmitNamespaceAlias(*Underlying), getLineNumber(NA.getLocation()),
3148 NA.getName());
3149 else
3150 R = DBuilder.createImportedModule(
3151 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3152 getOrCreateNameSpace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
3153 getLineNumber(NA.getLocation()), NA.getName());
3154 VH = R;
3155 return R;
3156}
3157
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003158/// getOrCreateNamesSpace - Return namespace descriptor for the given
3159/// namespace decl.
Eric Christopher6537f082013-05-16 00:45:12 +00003160llvm::DINameSpace
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003161CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
Eric Christopher6537f082013-05-16 00:45:12 +00003162 llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003163 NameSpaceCache.find(NSDecl);
3164 if (I != NameSpaceCache.end())
3165 return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
Eric Christopher6537f082013-05-16 00:45:12 +00003166
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003167 unsigned LineNo = getLineNumber(NSDecl->getLocation());
3168 llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
Eric Christopher6537f082013-05-16 00:45:12 +00003169 llvm::DIDescriptor Context =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003170 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
3171 llvm::DINameSpace NS =
3172 DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
3173 NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
3174 return NS;
3175}
3176
3177void CGDebugInfo::finalize() {
3178 for (std::vector<std::pair<void *, llvm::WeakVH> >::const_iterator VI
3179 = ReplaceMap.begin(), VE = ReplaceMap.end(); VI != VE; ++VI) {
3180 llvm::DIType Ty, RepTy;
3181 // Verify that the debug info still exists.
3182 if (llvm::Value *V = VI->second)
3183 Ty = llvm::DIType(cast<llvm::MDNode>(V));
Eric Christopher6537f082013-05-16 00:45:12 +00003184
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003185 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
3186 TypeCache.find(VI->first);
3187 if (it != TypeCache.end()) {
3188 // Verify that the debug info still exists.
3189 if (llvm::Value *V = it->second)
3190 RepTy = llvm::DIType(cast<llvm::MDNode>(V));
3191 }
Adrian Prantlebbd7e02013-03-11 18:33:46 +00003192
Adrian Prantl9b97adf2013-03-29 19:20:35 +00003193 if (Ty.Verify() && Ty.isForwardDecl() && RepTy.Verify())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003194 Ty.replaceAllUsesWith(RepTy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003195 }
Adrian Prantlebbd7e02013-03-11 18:33:46 +00003196
3197 // We keep our own list of retained types, because we need to look
3198 // up the final type in the type cache.
3199 for (std::vector<void *>::const_iterator RI = RetainedTypes.begin(),
3200 RE = RetainedTypes.end(); RI != RE; ++RI)
3201 DBuilder.retainType(llvm::DIType(cast<llvm::MDNode>(TypeCache[*RI])));
3202
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003203 DBuilder.finalize();
3204}