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