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