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