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