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