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