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 "CodeGenFunction.h"
16 #include "CodeGenModule.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/DeclFriend.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/DeclTemplate.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/RecordLayout.h"
23 #include "clang/Basic/SourceManager.h"
24 #include "clang/Basic/FileManager.h"
25 #include "clang/Basic/Version.h"
26 #include "clang/Frontend/CodeGenOptions.h"
27 #include "llvm/Constants.h"
28 #include "llvm/DerivedTypes.h"
29 #include "llvm/Instructions.h"
30 #include "llvm/Intrinsics.h"
31 #include "llvm/Module.h"
32 #include "llvm/ADT/StringExtras.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/Support/Dwarf.h"
35 #include "llvm/System/Path.h"
36 #include "llvm/Target/TargetMachine.h"
37 using namespace clang;
38 using namespace clang::CodeGen;
39 
40 CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
41   : CGM(CGM), DebugFactory(CGM.getModule()),
42     BlockLiteralGenericSet(false) {
43   CreateCompileUnit();
44 }
45 
46 CGDebugInfo::~CGDebugInfo() {
47   assert(RegionStack.empty() && "Region stack mismatch, stack not empty!");
48 }
49 
50 void CGDebugInfo::setLocation(SourceLocation Loc) {
51   if (Loc.isValid())
52     CurLoc = CGM.getContext().getSourceManager().getInstantiationLoc(Loc);
53 }
54 
55 /// getContextDescriptor - Get context info for the decl.
56 llvm::DIDescriptor CGDebugInfo::getContextDescriptor(const Decl *Context,
57                                               llvm::DIDescriptor &CompileUnit) {
58   if (!Context)
59     return CompileUnit;
60 
61   llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
62     I = RegionMap.find(Context);
63   if (I != RegionMap.end())
64     return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(I->second));
65 
66   // Check namespace.
67   if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
68     return llvm::DIDescriptor(getOrCreateNameSpace(NSDecl, CompileUnit));
69 
70   if (const RecordDecl *RDecl = dyn_cast<RecordDecl>(Context)) {
71     if (!RDecl->isDependentType()) {
72       llvm::DIType Ty = getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
73                                         llvm::DIFile(CompileUnit));
74       return llvm::DIDescriptor(Ty);
75     }
76   }
77   return CompileUnit;
78 }
79 
80 /// getFunctionName - Get function name for the given FunctionDecl. If the
81 /// name is constructred on demand (e.g. C++ destructor) then the name
82 /// is stored on the side.
83 llvm::StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
84   assert (FD && "Invalid FunctionDecl!");
85   IdentifierInfo *FII = FD->getIdentifier();
86   if (FII)
87     return FII->getName();
88 
89   // Otherwise construct human readable name for debug info.
90   std::string NS = FD->getNameAsString();
91 
92   // Copy this name on the side and use its reference.
93   char *StrPtr = DebugInfoNames.Allocate<char>(NS.length());
94   memcpy(StrPtr, NS.data(), NS.length());
95   return llvm::StringRef(StrPtr, NS.length());
96 }
97 
98 llvm::StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
99   llvm::SmallString<256> MethodName;
100   llvm::raw_svector_ostream OS(MethodName);
101   OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
102   const DeclContext *DC = OMD->getDeclContext();
103   if (const ObjCImplementationDecl *OID = dyn_cast<const ObjCImplementationDecl>(DC)) {
104      OS << OID->getName();
105   } else if (const ObjCCategoryImplDecl *OCD = dyn_cast<const ObjCCategoryImplDecl>(DC)){
106       OS << ((NamedDecl *)OCD)->getIdentifier()->getNameStart() << '(' <<
107           OCD->getIdentifier()->getNameStart() << ')';
108   }
109   OS << ' ' << OMD->getSelector().getAsString() << ']';
110 
111   char *StrPtr = DebugInfoNames.Allocate<char>(OS.tell());
112   memcpy(StrPtr, MethodName.begin(), OS.tell());
113   return llvm::StringRef(StrPtr, OS.tell());
114 }
115 
116 /// getClassName - Get class name including template argument list.
117 llvm::StringRef
118 CGDebugInfo::getClassName(RecordDecl *RD) {
119   ClassTemplateSpecializationDecl *Spec
120     = dyn_cast<ClassTemplateSpecializationDecl>(RD);
121   if (!Spec)
122     return RD->getName();
123 
124   const TemplateArgument *Args;
125   unsigned NumArgs;
126   std::string Buffer;
127   if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) {
128     const TemplateSpecializationType *TST =
129       cast<TemplateSpecializationType>(TAW->getType());
130     Args = TST->getArgs();
131     NumArgs = TST->getNumArgs();
132   } else {
133     const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
134     Args = TemplateArgs.getFlatArgumentList();
135     NumArgs = TemplateArgs.flat_size();
136   }
137   Buffer = RD->getIdentifier()->getNameStart();
138   PrintingPolicy Policy(CGM.getLangOptions());
139   Buffer += TemplateSpecializationType::PrintTemplateArgumentList(Args,
140                                                                   NumArgs,
141                                                                   Policy);
142 
143   // Copy this name on the side and use its reference.
144   char *StrPtr = DebugInfoNames.Allocate<char>(Buffer.length());
145   memcpy(StrPtr, Buffer.data(), Buffer.length());
146   return llvm::StringRef(StrPtr, Buffer.length());
147 
148 }
149 
150 /// getOrCreateFile - Get the file debug info descriptor for the input location.
151 llvm::DIFile CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
152   if (!Loc.isValid())
153     // If Location is not valid then use main input file.
154     return DebugFactory.CreateFile(TheCU.getFilename(), TheCU.getDirectory(),
155                                    TheCU);
156   SourceManager &SM = CGM.getContext().getSourceManager();
157   PresumedLoc PLoc = SM.getPresumedLoc(Loc);
158 
159   // Cache the results.
160   const char *fname = PLoc.getFilename();
161   llvm::DenseMap<const char *, llvm::WeakVH>::iterator it =
162     DIFileCache.find(fname);
163 
164   if (it != DIFileCache.end()) {
165     // Verify that the information still exists.
166     if (&*it->second)
167       return llvm::DIFile(cast<llvm::MDNode>(it->second));
168   }
169 
170   llvm::DIFile F = DebugFactory.CreateFile(PLoc.getFilename(),
171                                            getCurrentDirname(), TheCU);
172 
173   DIFileCache[fname] = F;
174   return F;
175 
176 }
177 
178 /// getLineNumber - Get line number for the location. If location is invalid
179 /// then use current location.
180 unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
181   assert (CurLoc.isValid() && "Invalid current location!");
182   SourceManager &SM = CGM.getContext().getSourceManager();
183   PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
184   return PLoc.getLine();
185 }
186 
187 /// getColumnNumber - Get column number for the location. If location is
188 /// invalid then use current location.
189 unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc) {
190   assert (CurLoc.isValid() && "Invalid current location!");
191   SourceManager &SM = CGM.getContext().getSourceManager();
192   PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
193   return PLoc.getColumn();
194 }
195 
196 llvm::StringRef CGDebugInfo::getCurrentDirname() {
197   if (!CWDName.empty())
198     return CWDName;
199   char *CompDirnamePtr = NULL;
200   llvm::sys::Path CWD = llvm::sys::Path::GetCurrentDirectory();
201   CompDirnamePtr = DebugInfoNames.Allocate<char>(CWD.size());
202   memcpy(CompDirnamePtr, CWD.c_str(), CWD.size());
203   return CWDName = llvm::StringRef(CompDirnamePtr, CWD.size());
204 }
205 
206 /// CreateCompileUnit - Create new compile unit.
207 void CGDebugInfo::CreateCompileUnit() {
208 
209   // Get absolute path name.
210   SourceManager &SM = CGM.getContext().getSourceManager();
211   std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
212   if (MainFileName.empty())
213     MainFileName = "<unknown>";
214 
215   // The main file name provided via the "-main-file-name" option contains just
216   // the file name itself with no path information. This file name may have had
217   // a relative path, so we look into the actual file entry for the main
218   // file to determine the real absolute path for the file.
219   std::string MainFileDir;
220   if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
221     MainFileDir = MainFile->getDir()->getName();
222     if (MainFileDir != ".")
223       MainFileName = MainFileDir + "/" + MainFileName;
224   }
225 
226   // Save filename string.
227   char *FilenamePtr = DebugInfoNames.Allocate<char>(MainFileName.length());
228   memcpy(FilenamePtr, MainFileName.c_str(), MainFileName.length());
229   llvm::StringRef Filename(FilenamePtr, MainFileName.length());
230 
231   unsigned LangTag;
232   const LangOptions &LO = CGM.getLangOptions();
233   if (LO.CPlusPlus) {
234     if (LO.ObjC1)
235       LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
236     else
237       LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
238   } else if (LO.ObjC1) {
239     LangTag = llvm::dwarf::DW_LANG_ObjC;
240   } else if (LO.C99) {
241     LangTag = llvm::dwarf::DW_LANG_C99;
242   } else {
243     LangTag = llvm::dwarf::DW_LANG_C89;
244   }
245 
246   std::string Producer = getClangFullVersion();
247 
248   // Figure out which version of the ObjC runtime we have.
249   unsigned RuntimeVers = 0;
250   if (LO.ObjC1)
251     RuntimeVers = LO.ObjCNonFragileABI ? 2 : 1;
252 
253   // Create new compile unit.
254   TheCU = DebugFactory.CreateCompileUnit(
255     LangTag, Filename, getCurrentDirname(),
256     Producer, true,
257     LO.Optimize, CGM.getCodeGenOpts().DwarfDebugFlags, RuntimeVers);
258 }
259 
260 /// CreateType - Get the Basic type from the cache or create a new
261 /// one if necessary.
262 llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT,
263                                      llvm::DIFile Unit) {
264   unsigned Encoding = 0;
265   const char *BTName = NULL;
266   switch (BT->getKind()) {
267   default:
268   case BuiltinType::Void:
269     return llvm::DIType();
270   case BuiltinType::ObjCClass:
271     return DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_structure_type,
272                                             Unit, "objc_class", Unit, 0, 0, 0, 0,
273                                             llvm::DIType::FlagFwdDecl,
274                                             llvm::DIType(), llvm::DIArray());
275   case BuiltinType::ObjCId: {
276     // typedef struct objc_class *Class;
277     // typedef struct objc_object {
278     //  Class isa;
279     // } *id;
280 
281     llvm::DIType OCTy =
282       DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_structure_type,
283                                        Unit, "objc_class", Unit, 0, 0, 0, 0,
284                                        llvm::DIType::FlagFwdDecl,
285                                        llvm::DIType(), llvm::DIArray());
286     unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
287 
288     llvm::DIType ISATy =
289       DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type,
290                                      Unit, "", Unit,
291                                      0, Size, 0, 0, 0, OCTy);
292 
293     llvm::SmallVector<llvm::DIDescriptor, 16> EltTys;
294 
295     llvm::DIType FieldTy =
296       DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
297                                      "isa", Unit,
298                                      0,Size, 0, 0, 0, ISATy);
299     EltTys.push_back(FieldTy);
300     llvm::DIArray Elements =
301       DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
302 
303     return DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_structure_type,
304                                             Unit, "objc_object", Unit, 0, 0, 0, 0,
305                                             0,
306                                             llvm::DIType(), Elements);
307   }
308   case BuiltinType::UChar:
309   case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
310   case BuiltinType::Char_S:
311   case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
312   case BuiltinType::UShort:
313   case BuiltinType::UInt:
314   case BuiltinType::ULong:
315   case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
316   case BuiltinType::Short:
317   case BuiltinType::Int:
318   case BuiltinType::Long:
319   case BuiltinType::LongLong:  Encoding = llvm::dwarf::DW_ATE_signed; break;
320   case BuiltinType::Bool:      Encoding = llvm::dwarf::DW_ATE_boolean; break;
321   case BuiltinType::Float:
322   case BuiltinType::LongDouble:
323   case BuiltinType::Double:    Encoding = llvm::dwarf::DW_ATE_float; break;
324   }
325 
326   switch (BT->getKind()) {
327   case BuiltinType::Long:      BTName = "long int"; break;
328   case BuiltinType::LongLong:  BTName = "long long int"; break;
329   case BuiltinType::ULong:     BTName = "long unsigned int"; break;
330   case BuiltinType::ULongLong: BTName = "long long unsigned int"; break;
331   default:
332     BTName = BT->getName(CGM.getContext().getLangOptions());
333     break;
334   }
335   // Bit size, align and offset of the type.
336   uint64_t Size = CGM.getContext().getTypeSize(BT);
337   uint64_t Align = CGM.getContext().getTypeAlign(BT);
338   uint64_t Offset = 0;
339 
340   llvm::DIType DbgTy =
341     DebugFactory.CreateBasicType(Unit, BTName,
342                                  Unit, 0, Size, Align,
343                                  Offset, /*flags*/ 0, Encoding);
344   return DbgTy;
345 }
346 
347 llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty,
348                                      llvm::DIFile Unit) {
349   // Bit size, align and offset of the type.
350   unsigned Encoding = llvm::dwarf::DW_ATE_complex_float;
351   if (Ty->isComplexIntegerType())
352     Encoding = llvm::dwarf::DW_ATE_lo_user;
353 
354   uint64_t Size = CGM.getContext().getTypeSize(Ty);
355   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
356   uint64_t Offset = 0;
357 
358   llvm::DIType DbgTy =
359     DebugFactory.CreateBasicType(Unit, "complex",
360                                  Unit, 0, Size, Align,
361                                  Offset, /*flags*/ 0, Encoding);
362   return DbgTy;
363 }
364 
365 /// CreateCVRType - Get the qualified type from the cache or create
366 /// a new one if necessary.
367 llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit) {
368   QualifierCollector Qc;
369   const Type *T = Qc.strip(Ty);
370 
371   // Ignore these qualifiers for now.
372   Qc.removeObjCGCAttr();
373   Qc.removeAddressSpace();
374 
375   // We will create one Derived type for one qualifier and recurse to handle any
376   // additional ones.
377   unsigned Tag;
378   if (Qc.hasConst()) {
379     Tag = llvm::dwarf::DW_TAG_const_type;
380     Qc.removeConst();
381   } else if (Qc.hasVolatile()) {
382     Tag = llvm::dwarf::DW_TAG_volatile_type;
383     Qc.removeVolatile();
384   } else if (Qc.hasRestrict()) {
385     Tag = llvm::dwarf::DW_TAG_restrict_type;
386     Qc.removeRestrict();
387   } else {
388     assert(Qc.empty() && "Unknown type qualifier for debug info");
389     return getOrCreateType(QualType(T, 0), Unit);
390   }
391 
392   llvm::DIType FromTy = getOrCreateType(Qc.apply(T), Unit);
393 
394   // No need to fill in the Name, Line, Size, Alignment, Offset in case of
395   // CVR derived types.
396   llvm::DIType DbgTy =
397     DebugFactory.CreateDerivedType(Tag, Unit, "", Unit,
398                                    0, 0, 0, 0, 0, FromTy);
399   return DbgTy;
400 }
401 
402 llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
403                                      llvm::DIFile Unit) {
404   llvm::DIType DbgTy =
405     CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
406                           Ty->getPointeeType(), Unit);
407   return DbgTy;
408 }
409 
410 llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
411                                      llvm::DIFile Unit) {
412   return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
413                                Ty->getPointeeType(), Unit);
414 }
415 
416 llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag,
417                                                 const Type *Ty,
418                                                 QualType PointeeTy,
419                                                 llvm::DIFile Unit) {
420   llvm::DIType EltTy = getOrCreateType(PointeeTy, Unit);
421 
422   // Bit size, align and offset of the type.
423 
424   // Size is always the size of a pointer. We can't use getTypeSize here
425   // because that does not return the correct value for references.
426   uint64_t Size =
427     CGM.getContext().Target.getPointerWidth(PointeeTy.getAddressSpace());
428   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
429 
430   return
431     DebugFactory.CreateDerivedType(Tag, Unit, "", Unit,
432                                    0, Size, Align, 0, 0, EltTy);
433 
434 }
435 
436 llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
437                                      llvm::DIFile Unit) {
438   if (BlockLiteralGenericSet)
439     return BlockLiteralGeneric;
440 
441   unsigned Tag = llvm::dwarf::DW_TAG_structure_type;
442 
443   llvm::SmallVector<llvm::DIDescriptor, 5> EltTys;
444 
445   llvm::DIType FieldTy;
446 
447   QualType FType;
448   uint64_t FieldSize, FieldOffset;
449   unsigned FieldAlign;
450 
451   llvm::DIArray Elements;
452   llvm::DIType EltTy, DescTy;
453 
454   FieldOffset = 0;
455   FType = CGM.getContext().UnsignedLongTy;
456   EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
457   EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
458 
459   Elements = DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
460   EltTys.clear();
461 
462   unsigned Flags = llvm::DIType::FlagAppleBlock;
463   unsigned LineNo = getLineNumber(CurLoc);
464 
465   EltTy = DebugFactory.CreateCompositeType(Tag, Unit, "__block_descriptor",
466                                            Unit, LineNo, FieldOffset, 0, 0,
467                                            Flags, llvm::DIType(), Elements);
468 
469   // Bit size, align and offset of the type.
470   uint64_t Size = CGM.getContext().getTypeSize(Ty);
471   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
472 
473   DescTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type,
474                                           Unit, "", Unit,
475                                           LineNo, Size, Align, 0, 0, EltTy);
476 
477   FieldOffset = 0;
478   FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
479   EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
480   FType = CGM.getContext().IntTy;
481   EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
482   EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
483   FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
484   EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
485 
486   FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
487   FieldTy = DescTy;
488   FieldSize = CGM.getContext().getTypeSize(Ty);
489   FieldAlign = CGM.getContext().getTypeAlign(Ty);
490   FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
491                                            "__descriptor", Unit,
492                                            LineNo, FieldSize, FieldAlign,
493                                            FieldOffset, 0, FieldTy);
494   EltTys.push_back(FieldTy);
495 
496   FieldOffset += FieldSize;
497   Elements = DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
498 
499   EltTy = DebugFactory.CreateCompositeType(Tag, Unit, "__block_literal_generic",
500                                            Unit, LineNo, FieldOffset, 0, 0,
501                                            Flags, llvm::DIType(), Elements);
502 
503   BlockLiteralGenericSet = true;
504   BlockLiteralGeneric
505     = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type, Unit,
506                                      "", Unit,
507                                      LineNo, Size, Align, 0, 0, EltTy);
508   return BlockLiteralGeneric;
509 }
510 
511 llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty,
512                                      llvm::DIFile Unit) {
513   // Typedefs are derived from some other type.  If we have a typedef of a
514   // typedef, make sure to emit the whole chain.
515   llvm::DIType Src = getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
516 
517   // We don't set size information, but do specify where the typedef was
518   // declared.
519   unsigned Line = getLineNumber(Ty->getDecl()->getLocation());
520 
521   llvm::DIDescriptor TyContext
522     = getContextDescriptor(dyn_cast<Decl>(Ty->getDecl()->getDeclContext()),
523                            Unit);
524   llvm::DIType DbgTy =
525     DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_typedef,
526                                    TyContext,
527                                    Ty->getDecl()->getName(), Unit,
528                                    Line, 0, 0, 0, 0, Src);
529   return DbgTy;
530 }
531 
532 llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
533                                      llvm::DIFile Unit) {
534   llvm::SmallVector<llvm::DIDescriptor, 16> EltTys;
535 
536   // Add the result type at least.
537   EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit));
538 
539   // Set up remainder of arguments if there is a prototype.
540   // FIXME: IF NOT, HOW IS THIS REPRESENTED?  llvm-gcc doesn't represent '...'!
541   if (const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(Ty)) {
542     for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i)
543       EltTys.push_back(getOrCreateType(FTP->getArgType(i), Unit));
544   } else {
545     // FIXME: Handle () case in C.  llvm-gcc doesn't do it either.
546   }
547 
548   llvm::DIArray EltTypeArray =
549     DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
550 
551   llvm::DIType DbgTy =
552     DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_subroutine_type,
553                                      Unit, "", Unit,
554                                      0, 0, 0, 0, 0,
555                                      llvm::DIType(), EltTypeArray);
556   return DbgTy;
557 }
558 
559 /// CollectRecordFields - A helper function to collect debug info for
560 /// record fields. This is used while creating debug info entry for a Record.
561 void CGDebugInfo::
562 CollectRecordFields(const RecordDecl *RD, llvm::DIFile Unit,
563                     llvm::SmallVectorImpl<llvm::DIDescriptor> &EltTys) {
564   unsigned FieldNo = 0;
565   const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
566   for (RecordDecl::field_iterator I = RD->field_begin(),
567                                   E = RD->field_end();
568        I != E; ++I, ++FieldNo) {
569     FieldDecl *Field = *I;
570     llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
571     llvm::StringRef FieldName = Field->getName();
572 
573     // Ignore unnamed fields. Do not ignore unnamed records.
574     if (FieldName.empty() && !isa<RecordType>(Field->getType()))
575       continue;
576 
577     // Get the location for the field.
578     llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
579     unsigned FieldLine = getLineNumber(Field->getLocation());
580     QualType FType = Field->getType();
581     uint64_t FieldSize = 0;
582     unsigned FieldAlign = 0;
583     if (!FType->isIncompleteArrayType()) {
584 
585       // Bit size, align and offset of the type.
586       FieldSize = CGM.getContext().getTypeSize(FType);
587       Expr *BitWidth = Field->getBitWidth();
588       if (BitWidth)
589         FieldSize = BitWidth->EvaluateAsInt(CGM.getContext()).getZExtValue();
590       FieldAlign =  CGM.getContext().getTypeAlign(FType);
591     }
592 
593     uint64_t FieldOffset = RL.getFieldOffset(FieldNo);
594 
595     unsigned Flags = 0;
596     AccessSpecifier Access = I->getAccess();
597     if (Access == clang::AS_private)
598       Flags |= llvm::DIType::FlagPrivate;
599     else if (Access == clang::AS_protected)
600       Flags |= llvm::DIType::FlagProtected;
601 
602     // Create a DW_TAG_member node to remember the offset of this field in the
603     // struct.  FIXME: This is an absolutely insane way to capture this
604     // information.  When we gut debug info, this should be fixed.
605     FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
606                                              FieldName, FieldDefUnit,
607                                              FieldLine, FieldSize, FieldAlign,
608                                              FieldOffset, Flags, FieldTy);
609     EltTys.push_back(FieldTy);
610   }
611 }
612 
613 /// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
614 /// function type is not updated to include implicit "this" pointer. Use this
615 /// routine to get a method type which includes "this" pointer.
616 llvm::DIType
617 CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
618                                    llvm::DIFile Unit) {
619   llvm::DIType FnTy
620     = getOrCreateType(QualType(Method->getType()->getAs<FunctionProtoType>(),
621                                0),
622                       Unit);
623 
624   unsigned BFlags=0;
625   AccessSpecifier Access = Method->getAccess();
626   if (Access == clang::AS_private)
627     BFlags |= llvm::DIType::FlagPrivate;
628   else if (Access == clang::AS_protected)
629     BFlags |= llvm::DIType::FlagProtected;
630 
631   // Add "this" pointer.
632 
633   llvm::DIArray Args = llvm::DICompositeType(FnTy).getTypeArray();
634   assert (Args.getNumElements() && "Invalid number of arguments!");
635 
636   llvm::SmallVector<llvm::DIDescriptor, 16> Elts;
637 
638   // First element is always return type. For 'void' functions it is NULL.
639   Elts.push_back(Args.getElement(0));
640 
641   if (!Method->isStatic())
642   {
643         // "this" pointer is always first argument.
644         ASTContext &Context = CGM.getContext();
645         QualType ThisPtr =
646           Context.getPointerType(Context.getTagDeclType(Method->getParent()));
647         llvm::DIType ThisPtrType =
648           DebugFactory.CreateArtificialType(getOrCreateType(ThisPtr, Unit));
649 
650         TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
651         Elts.push_back(ThisPtrType);
652     }
653 
654   // Copy rest of the arguments.
655   for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
656     Elts.push_back(Args.getElement(i));
657 
658   llvm::DIArray EltTypeArray =
659     DebugFactory.GetOrCreateArray(Elts.data(), Elts.size());
660 
661   return
662     DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_subroutine_type,
663                                      Unit, "", Unit,
664                                      0, 0, 0, 0, 0,
665                                      llvm::DIType(), EltTypeArray);
666 }
667 
668 /// CreateCXXMemberFunction - A helper function to create a DISubprogram for
669 /// a single member function GlobalDecl.
670 llvm::DISubprogram
671 CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
672                                      llvm::DIFile Unit,
673                                      llvm::DIType RecordTy) {
674   bool IsCtorOrDtor =
675     isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
676 
677   llvm::StringRef MethodName = getFunctionName(Method);
678   llvm::DIType MethodTy = getOrCreateMethodType(Method, Unit);
679 
680   // Since a single ctor/dtor corresponds to multiple functions, it doesn't
681   // make sense to give a single ctor/dtor a linkage name.
682   llvm::StringRef MethodLinkageName;
683   if (!IsCtorOrDtor)
684     MethodLinkageName = CGM.getMangledName(Method);
685 
686   // Get the location for the method.
687   llvm::DIFile MethodDefUnit = getOrCreateFile(Method->getLocation());
688   unsigned MethodLine = getLineNumber(Method->getLocation());
689 
690   // Collect virtual method info.
691   llvm::DIType ContainingType;
692   unsigned Virtuality = 0;
693   unsigned VIndex = 0;
694 
695   if (Method->isVirtual()) {
696     if (Method->isPure())
697       Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
698     else
699       Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
700 
701     // It doesn't make sense to give a virtual destructor a vtable index,
702     // since a single destructor has two entries in the vtable.
703     if (!isa<CXXDestructorDecl>(Method))
704       VIndex = CGM.getVTables().getMethodVTableIndex(Method);
705     ContainingType = RecordTy;
706   }
707 
708   llvm::DISubprogram SP =
709     DebugFactory.CreateSubprogram(RecordTy , MethodName, MethodName,
710                                   MethodLinkageName,
711                                   MethodDefUnit, MethodLine,
712                                   MethodTy, /*isLocalToUnit=*/false,
713                                   /* isDefintion=*/ false,
714                                   Virtuality, VIndex, ContainingType,
715                                   Method->isImplicit(),
716                                   CGM.getLangOptions().Optimize);
717 
718   // Don't cache ctors or dtors since we have to emit multiple functions for
719   // a single ctor or dtor.
720   if (!IsCtorOrDtor && Method->isThisDeclarationADefinition())
721     SPCache[Method] = llvm::WeakVH(SP);
722 
723   return SP;
724 }
725 
726 /// CollectCXXMemberFunctions - A helper function to collect debug info for
727 /// C++ member functions.This is used while creating debug info entry for
728 /// a Record.
729 void CGDebugInfo::
730 CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
731                           llvm::SmallVectorImpl<llvm::DIDescriptor> &EltTys,
732                           llvm::DIType RecordTy) {
733   for(CXXRecordDecl::method_iterator I = RD->method_begin(),
734         E = RD->method_end(); I != E; ++I) {
735     const CXXMethodDecl *Method = *I;
736 
737     if (Method->isImplicit() && !Method->isUsed())
738       continue;
739 
740     EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
741   }
742 }
743 
744 /// CollectCXXFriends - A helper function to collect debug info for
745 /// C++ base classes. This is used while creating debug info entry for
746 /// a Record.
747 void CGDebugInfo::
748 CollectCXXFriends(const CXXRecordDecl *RD, llvm::DIFile Unit,
749                 llvm::SmallVectorImpl<llvm::DIDescriptor> &EltTys,
750                 llvm::DIType RecordTy) {
751 
752   for (CXXRecordDecl::friend_iterator BI =  RD->friend_begin(),
753          BE = RD->friend_end(); BI != BE; ++BI) {
754 
755     TypeSourceInfo *TInfo = (*BI)->getFriendType();
756     if(TInfo)
757     {
758         llvm::DIType Ty = getOrCreateType(TInfo->getType(), Unit);
759 
760             llvm::DIType DTy =
761           DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_friend,
762                                          RecordTy, llvm::StringRef(),
763                                          Unit, 0, 0, 0,
764                                          0, 0, Ty);
765 
766         EltTys.push_back(DTy);
767     }
768 
769   }
770 }
771 
772 /// CollectCXXBases - A helper function to collect debug info for
773 /// C++ base classes. This is used while creating debug info entry for
774 /// a Record.
775 void CGDebugInfo::
776 CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
777                 llvm::SmallVectorImpl<llvm::DIDescriptor> &EltTys,
778                 llvm::DIType RecordTy) {
779 
780   const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
781   for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
782          BE = RD->bases_end(); BI != BE; ++BI) {
783     unsigned BFlags = 0;
784     uint64_t BaseOffset;
785 
786     const CXXRecordDecl *Base =
787       cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl());
788 
789     if (BI->isVirtual()) {
790       // virtual base offset offset is -ve. The code generator emits dwarf
791       // expression where it expects +ve number.
792       BaseOffset = 0 - CGM.getVTables().getVirtualBaseOffsetOffset(RD, Base);
793       BFlags = llvm::DIType::FlagVirtual;
794     } else
795       BaseOffset = RL.getBaseClassOffset(Base);
796 
797     AccessSpecifier Access = BI->getAccessSpecifier();
798     if (Access == clang::AS_private)
799       BFlags |= llvm::DIType::FlagPrivate;
800     else if (Access == clang::AS_protected)
801       BFlags |= llvm::DIType::FlagProtected;
802 
803     llvm::DIType DTy =
804       DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_inheritance,
805                                      RecordTy, llvm::StringRef(),
806                                      Unit, 0, 0, 0,
807                                      BaseOffset, BFlags,
808                                      getOrCreateType(BI->getType(),
809                                                      Unit));
810     EltTys.push_back(DTy);
811   }
812 }
813 
814 /// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
815 llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
816   if (VTablePtrType.isValid())
817     return VTablePtrType;
818 
819   ASTContext &Context = CGM.getContext();
820 
821   /* Function type */
822   llvm::DIDescriptor STy = getOrCreateType(Context.IntTy, Unit);
823   llvm::DIArray SElements = DebugFactory.GetOrCreateArray(&STy, 1);
824   llvm::DIType SubTy =
825     DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_subroutine_type,
826                                      Unit, "", Unit,
827                                      0, 0, 0, 0, 0, llvm::DIType(), SElements);
828 
829   unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
830   llvm::DIType vtbl_ptr_type
831     = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type,
832                                      Unit, "__vtbl_ptr_type", Unit,
833                                      0, Size, 0, 0, 0, SubTy);
834 
835   VTablePtrType =
836     DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type,
837                                    Unit, "", Unit,
838                                    0, Size, 0, 0, 0, vtbl_ptr_type);
839   return VTablePtrType;
840 }
841 
842 /// getVTableName - Get vtable name for the given Class.
843 llvm::StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
844   // Otherwise construct gdb compatible name name.
845   std::string Name = "_vptr$" + RD->getNameAsString();
846 
847   // Copy this name on the side and use its reference.
848   char *StrPtr = DebugInfoNames.Allocate<char>(Name.length());
849   memcpy(StrPtr, Name.data(), Name.length());
850   return llvm::StringRef(StrPtr, Name.length());
851 }
852 
853 
854 /// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
855 /// debug info entry in EltTys vector.
856 void CGDebugInfo::
857 CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
858                   llvm::SmallVectorImpl<llvm::DIDescriptor> &EltTys) {
859   const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
860 
861   // If there is a primary base then it will hold vtable info.
862   if (RL.getPrimaryBase())
863     return;
864 
865   // If this class is not dynamic then there is not any vtable info to collect.
866   if (!RD->isDynamicClass())
867     return;
868 
869   unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
870   llvm::DIType VPTR
871     = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
872                                      getVTableName(RD), Unit,
873                                      0, Size, 0, 0, 0,
874                                      getOrCreateVTablePtrType(Unit));
875   EltTys.push_back(VPTR);
876 }
877 
878 /// CreateType - get structure or union type.
879 llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty,
880                                      llvm::DIFile Unit) {
881   RecordDecl *RD = Ty->getDecl();
882 
883   unsigned Tag;
884   if (RD->isStruct())
885     Tag = llvm::dwarf::DW_TAG_structure_type;
886   else if (RD->isUnion())
887     Tag = llvm::dwarf::DW_TAG_union_type;
888   else {
889     assert(RD->isClass() && "Unknown RecordType!");
890     Tag = llvm::dwarf::DW_TAG_class_type;
891   }
892 
893   // Get overall information about the record type for the debug info.
894   llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
895   unsigned Line = getLineNumber(RD->getLocation());
896 
897   // Records and classes and unions can all be recursive.  To handle them, we
898   // first generate a debug descriptor for the struct as a forward declaration.
899   // Then (if it is a definition) we go through and get debug info for all of
900   // its members.  Finally, we create a descriptor for the complete type (which
901   // may refer to the forward decl if the struct is recursive) and replace all
902   // uses of the forward declaration with the final definition.
903   llvm::DIDescriptor FDContext =
904     getContextDescriptor(dyn_cast<Decl>(RD->getDeclContext()), Unit);
905 
906   // If this is just a forward declaration, construct an appropriately
907   // marked node and just return it.
908   if (!RD->getDefinition()) {
909     llvm::DICompositeType FwdDecl =
910       DebugFactory.CreateCompositeType(Tag, FDContext, RD->getName(),
911                                        DefUnit, Line, 0, 0, 0,
912                                        llvm::DIType::FlagFwdDecl,
913                                        llvm::DIType(), llvm::DIArray());
914 
915       return FwdDecl;
916   }
917 
918   llvm::DIType FwdDecl = DebugFactory.CreateTemporaryType();
919 
920   llvm::MDNode *MN = FwdDecl;
921   llvm::TrackingVH<llvm::MDNode> FwdDeclNode = MN;
922   // Otherwise, insert it into the TypeCache so that recursive uses will find
923   // it.
924   TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
925   // Push the struct on region stack.
926   RegionStack.push_back(FwdDeclNode);
927   RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
928 
929   // Convert all the elements.
930   llvm::SmallVector<llvm::DIDescriptor, 16> EltTys;
931 
932   const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
933   if (CXXDecl) {
934     CollectCXXBases(CXXDecl, Unit, EltTys, FwdDecl);
935     CollectVTableInfo(CXXDecl, Unit, EltTys);
936   }
937 
938   // Collect static variables with initializers.
939   for (RecordDecl::decl_iterator I = RD->decls_begin(), E = RD->decls_end();
940        I != E; ++I)
941     if (const VarDecl *V = dyn_cast<VarDecl>(*I)) {
942       if (const Expr *Init = V->getInit()) {
943         Expr::EvalResult Result;
944         if (Init->Evaluate(Result, CGM.getContext()) && Result.Val.isInt()) {
945           llvm::ConstantInt *CI
946             = llvm::ConstantInt::get(CGM.getLLVMContext(), Result.Val.getInt());
947 
948           // Create the descriptor for static variable.
949           llvm::DIFile VUnit = getOrCreateFile(V->getLocation());
950           llvm::StringRef VName = V->getName();
951           llvm::DIType VTy = getOrCreateType(V->getType(), VUnit);
952           // Do not use DIGlobalVariable for enums.
953           if (VTy.getTag() != llvm::dwarf::DW_TAG_enumeration_type) {
954             DebugFactory.CreateGlobalVariable(FwdDecl, VName, VName, VName, VUnit,
955                                               getLineNumber(V->getLocation()),
956                                               VTy, true, true, CI);
957           }
958         }
959       }
960     }
961 
962   CollectRecordFields(RD, Unit, EltTys);
963   llvm::MDNode *ContainingType = NULL;
964   if (CXXDecl) {
965     CollectCXXMemberFunctions(CXXDecl, Unit, EltTys, FwdDecl);
966     CollectCXXFriends(CXXDecl, Unit, EltTys, FwdDecl);
967 
968     // A class's primary base or the class itself contains the vtable.
969     const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
970     if (const CXXRecordDecl *PBase = RL.getPrimaryBase())
971       ContainingType =
972         getOrCreateType(QualType(PBase->getTypeForDecl(), 0), Unit);
973     else if (CXXDecl->isDynamicClass())
974       ContainingType = FwdDecl;
975   }
976 
977   llvm::DIArray Elements =
978     DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
979 
980   // Bit size, align and offset of the type.
981   uint64_t Size = CGM.getContext().getTypeSize(Ty);
982   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
983 
984   RegionStack.pop_back();
985   llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator RI =
986     RegionMap.find(Ty->getDecl());
987   if (RI != RegionMap.end())
988     RegionMap.erase(RI);
989 
990   llvm::DIDescriptor RDContext =
991     getContextDescriptor(dyn_cast<Decl>(RD->getDeclContext()), Unit);
992 
993   llvm::StringRef RDName = RD->getName();
994   // If this is a class, include the template arguments also.
995   if (Tag == llvm::dwarf::DW_TAG_class_type)
996     RDName = getClassName(RD);
997 
998   llvm::DICompositeType RealDecl =
999     DebugFactory.CreateCompositeType(Tag, RDContext,
1000                                      RDName,
1001                                      DefUnit, Line, Size, Align, 0, 0,
1002                                      llvm::DIType(), Elements,
1003                                      0, ContainingType);
1004 
1005   // Now that we have a real decl for the struct, replace anything using the
1006   // old decl with the new one.  This will recursively update the debug info.
1007   llvm::DIType(FwdDeclNode).replaceAllUsesWith(RealDecl);
1008   RegionMap[RD] = llvm::WeakVH(RealDecl);
1009   return RealDecl;
1010 }
1011 
1012 /// CreateType - get objective-c object type.
1013 llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1014                                      llvm::DIFile Unit) {
1015   // Ignore protocols.
1016   return getOrCreateType(Ty->getBaseType(), Unit);
1017 }
1018 
1019 /// CreateType - get objective-c interface type.
1020 llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1021                                      llvm::DIFile Unit) {
1022   ObjCInterfaceDecl *ID = Ty->getDecl();
1023   unsigned Tag = llvm::dwarf::DW_TAG_structure_type;
1024 
1025   // Get overall information about the record type for the debug info.
1026   llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1027   unsigned Line = getLineNumber(ID->getLocation());
1028   unsigned RuntimeLang = TheCU.getLanguage();
1029 
1030   // If this is just a forward declaration, return a special forward-declaration
1031   // debug type.
1032   if (ID->isForwardDecl()) {
1033     llvm::DICompositeType FwdDecl =
1034       DebugFactory.CreateCompositeType(Tag, Unit, ID->getName(),
1035                                        DefUnit, Line, 0, 0, 0, 0,
1036                                        llvm::DIType(), llvm::DIArray(),
1037                                        RuntimeLang);
1038     return FwdDecl;
1039   }
1040 
1041   // To handle recursive interface, we
1042   // first generate a debug descriptor for the struct as a forward declaration.
1043   // Then (if it is a definition) we go through and get debug info for all of
1044   // its members.  Finally, we create a descriptor for the complete type (which
1045   // may refer to the forward decl if the struct is recursive) and replace all
1046   // uses of the forward declaration with the final definition.
1047   llvm::DIType FwdDecl = DebugFactory.CreateTemporaryType();
1048 
1049   llvm::MDNode *MN = FwdDecl;
1050   llvm::TrackingVH<llvm::MDNode> FwdDeclNode = MN;
1051   // Otherwise, insert it into the TypeCache so that recursive uses will find
1052   // it.
1053   TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1054   // Push the struct on region stack.
1055   RegionStack.push_back(FwdDeclNode);
1056   RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1057 
1058   // Convert all the elements.
1059   llvm::SmallVector<llvm::DIDescriptor, 16> EltTys;
1060 
1061   ObjCInterfaceDecl *SClass = ID->getSuperClass();
1062   if (SClass) {
1063     llvm::DIType SClassTy =
1064       getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1065     llvm::DIType InhTag =
1066       DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_inheritance,
1067                                      Unit, "", Unit, 0, 0, 0,
1068                                      0 /* offset */, 0, SClassTy);
1069     EltTys.push_back(InhTag);
1070   }
1071 
1072   const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1073 
1074   unsigned FieldNo = 0;
1075   for (ObjCInterfaceDecl::ivar_iterator I = ID->ivar_begin(),
1076          E = ID->ivar_end();  I != E; ++I, ++FieldNo) {
1077     ObjCIvarDecl *Field = *I;
1078     llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1079 
1080     llvm::StringRef FieldName = Field->getName();
1081 
1082     // Ignore unnamed fields.
1083     if (FieldName.empty())
1084       continue;
1085 
1086     // Get the location for the field.
1087     llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1088     unsigned FieldLine = getLineNumber(Field->getLocation());
1089     QualType FType = Field->getType();
1090     uint64_t FieldSize = 0;
1091     unsigned FieldAlign = 0;
1092 
1093     if (!FType->isIncompleteArrayType()) {
1094 
1095       // Bit size, align and offset of the type.
1096       FieldSize = CGM.getContext().getTypeSize(FType);
1097       Expr *BitWidth = Field->getBitWidth();
1098       if (BitWidth)
1099         FieldSize = BitWidth->EvaluateAsInt(CGM.getContext()).getZExtValue();
1100 
1101       FieldAlign =  CGM.getContext().getTypeAlign(FType);
1102     }
1103 
1104     uint64_t FieldOffset = RL.getFieldOffset(FieldNo);
1105 
1106     unsigned Flags = 0;
1107     if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1108       Flags = llvm::DIType::FlagProtected;
1109     else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1110       Flags = llvm::DIType::FlagPrivate;
1111 
1112     // Create a DW_TAG_member node to remember the offset of this field in the
1113     // struct.  FIXME: This is an absolutely insane way to capture this
1114     // information.  When we gut debug info, this should be fixed.
1115     FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1116                                              FieldName, FieldDefUnit,
1117                                              FieldLine, FieldSize, FieldAlign,
1118                                              FieldOffset, Flags, FieldTy);
1119     EltTys.push_back(FieldTy);
1120   }
1121 
1122   llvm::DIArray Elements =
1123     DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
1124 
1125   RegionStack.pop_back();
1126   llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator RI =
1127     RegionMap.find(Ty->getDecl());
1128   if (RI != RegionMap.end())
1129     RegionMap.erase(RI);
1130 
1131   // Bit size, align and offset of the type.
1132   uint64_t Size = CGM.getContext().getTypeSize(Ty);
1133   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1134 
1135   llvm::DICompositeType RealDecl =
1136     DebugFactory.CreateCompositeType(Tag, Unit, ID->getName(), DefUnit,
1137                                      Line, Size, Align, 0, 0, llvm::DIType(),
1138                                      Elements, RuntimeLang);
1139 
1140   // Now that we have a real decl for the struct, replace anything using the
1141   // old decl with the new one.  This will recursively update the debug info.
1142   llvm::DIType(FwdDeclNode).replaceAllUsesWith(RealDecl);
1143   RegionMap[ID] = llvm::WeakVH(RealDecl);
1144 
1145   return RealDecl;
1146 }
1147 
1148 llvm::DIType CGDebugInfo::CreateType(const EnumType *Ty,
1149                                      llvm::DIFile Unit) {
1150   return CreateEnumType(Ty->getDecl(), Unit);
1151 
1152 }
1153 
1154 llvm::DIType CGDebugInfo::CreateType(const TagType *Ty,
1155                                      llvm::DIFile Unit) {
1156   if (const RecordType *RT = dyn_cast<RecordType>(Ty))
1157     return CreateType(RT, Unit);
1158   else if (const EnumType *ET = dyn_cast<EnumType>(Ty))
1159     return CreateType(ET, Unit);
1160 
1161   return llvm::DIType();
1162 }
1163 
1164 llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty,
1165                                      llvm::DIFile Unit) {
1166   llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1167   uint64_t NumElems = Ty->getNumElements();
1168   if (NumElems > 0)
1169     --NumElems;
1170 
1171   llvm::DIDescriptor Subscript = DebugFactory.GetOrCreateSubrange(0, NumElems);
1172   llvm::DIArray SubscriptArray = DebugFactory.GetOrCreateArray(&Subscript, 1);
1173 
1174   uint64_t Size = CGM.getContext().getTypeSize(Ty);
1175   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1176 
1177   return
1178     DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_vector_type,
1179                                      Unit, "", Unit,
1180                                      0, Size, Align, 0, 0,
1181                                      ElementTy,  SubscriptArray);
1182 }
1183 
1184 llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1185                                      llvm::DIFile Unit) {
1186   uint64_t Size;
1187   uint64_t Align;
1188 
1189 
1190   // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1191   if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1192     Size = 0;
1193     Align =
1194       CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1195   } else if (Ty->isIncompleteArrayType()) {
1196     Size = 0;
1197     Align = CGM.getContext().getTypeAlign(Ty->getElementType());
1198   } else {
1199     // Size and align of the whole array, not the element type.
1200     Size = CGM.getContext().getTypeSize(Ty);
1201     Align = CGM.getContext().getTypeAlign(Ty);
1202   }
1203 
1204   // Add the dimensions of the array.  FIXME: This loses CV qualifiers from
1205   // interior arrays, do we care?  Why aren't nested arrays represented the
1206   // obvious/recursive way?
1207   llvm::SmallVector<llvm::DIDescriptor, 8> Subscripts;
1208   QualType EltTy(Ty, 0);
1209   while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1210     uint64_t Upper = 0;
1211     if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1212       if (CAT->getSize().getZExtValue())
1213         Upper = CAT->getSize().getZExtValue() - 1;
1214     // FIXME: Verify this is right for VLAs.
1215     Subscripts.push_back(DebugFactory.GetOrCreateSubrange(0, Upper));
1216     EltTy = Ty->getElementType();
1217   }
1218 
1219   llvm::DIArray SubscriptArray =
1220     DebugFactory.GetOrCreateArray(Subscripts.data(), Subscripts.size());
1221 
1222   llvm::DIType DbgTy =
1223     DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_array_type,
1224                                      Unit, "", Unit,
1225                                      0, Size, Align, 0, 0,
1226                                      getOrCreateType(EltTy, Unit),
1227                                      SubscriptArray);
1228   return DbgTy;
1229 }
1230 
1231 llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
1232                                      llvm::DIFile Unit) {
1233   return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
1234                                Ty, Ty->getPointeeType(), Unit);
1235 }
1236 
1237 llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
1238                                      llvm::DIFile U) {
1239   QualType PointerDiffTy = CGM.getContext().getPointerDiffType();
1240   llvm::DIType PointerDiffDITy = getOrCreateType(PointerDiffTy, U);
1241 
1242   if (!Ty->getPointeeType()->isFunctionType()) {
1243     // We have a data member pointer type.
1244     return PointerDiffDITy;
1245   }
1246 
1247   // We have a member function pointer type. Treat it as a struct with two
1248   // ptrdiff_t members.
1249   std::pair<uint64_t, unsigned> Info = CGM.getContext().getTypeInfo(Ty);
1250 
1251   uint64_t FieldOffset = 0;
1252   llvm::DIDescriptor ElementTypes[2];
1253 
1254   // FIXME: This should probably be a function type instead.
1255   ElementTypes[0] =
1256     DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, U,
1257                                    "ptr", U, 0,
1258                                    Info.first, Info.second, FieldOffset, 0,
1259                                    PointerDiffDITy);
1260   FieldOffset += Info.first;
1261 
1262   ElementTypes[1] =
1263     DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, U,
1264                                    "ptr", U, 0,
1265                                    Info.first, Info.second, FieldOffset, 0,
1266                                    PointerDiffDITy);
1267 
1268   llvm::DIArray Elements =
1269     DebugFactory.GetOrCreateArray(&ElementTypes[0],
1270                                   llvm::array_lengthof(ElementTypes));
1271 
1272   return DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_structure_type,
1273                                           U, llvm::StringRef("test"),
1274                                           U, 0, FieldOffset,
1275                                           0, 0, 0, llvm::DIType(), Elements);
1276 }
1277 
1278 /// CreateEnumType - get enumeration type.
1279 llvm::DIType CGDebugInfo::CreateEnumType(const EnumDecl *ED, llvm::DIFile Unit){
1280   llvm::SmallVector<llvm::DIDescriptor, 32> Enumerators;
1281 
1282   // Create DIEnumerator elements for each enumerator.
1283   for (EnumDecl::enumerator_iterator
1284          Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
1285        Enum != EnumEnd; ++Enum) {
1286     Enumerators.push_back(DebugFactory.CreateEnumerator(Enum->getName(),
1287                                             Enum->getInitVal().getZExtValue()));
1288   }
1289 
1290   // Return a CompositeType for the enum itself.
1291   llvm::DIArray EltArray =
1292     DebugFactory.GetOrCreateArray(Enumerators.data(), Enumerators.size());
1293 
1294   llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1295   unsigned Line = getLineNumber(ED->getLocation());
1296   uint64_t Size = 0;
1297   uint64_t Align = 0;
1298   if (!ED->getTypeForDecl()->isIncompleteType()) {
1299     Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1300     Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1301   }
1302   llvm::DIType DbgTy =
1303     DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_enumeration_type,
1304                                      Unit, ED->getName(), DefUnit, Line,
1305                                      Size, Align, 0, 0,
1306                                      llvm::DIType(), EltArray);
1307   return DbgTy;
1308 }
1309 
1310 static QualType UnwrapTypeForDebugInfo(QualType T) {
1311   do {
1312     QualType LastT = T;
1313     switch (T->getTypeClass()) {
1314     default:
1315       return T;
1316     case Type::TemplateSpecialization:
1317       T = cast<TemplateSpecializationType>(T)->desugar();
1318       break;
1319     case Type::TypeOfExpr: {
1320       TypeOfExprType *Ty = cast<TypeOfExprType>(T);
1321       T = Ty->getUnderlyingExpr()->getType();
1322       break;
1323     }
1324     case Type::TypeOf:
1325       T = cast<TypeOfType>(T)->getUnderlyingType();
1326       break;
1327     case Type::Decltype:
1328       T = cast<DecltypeType>(T)->getUnderlyingType();
1329       break;
1330     case Type::Elaborated:
1331       T = cast<ElaboratedType>(T)->getNamedType();
1332       break;
1333     case Type::SubstTemplateTypeParm:
1334       T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
1335       break;
1336     }
1337 
1338     assert(T != LastT && "Type unwrapping failed to unwrap!");
1339     if (T == LastT)
1340       return T;
1341   } while (true);
1342 
1343   return T;
1344 }
1345 
1346 /// getOrCreateType - Get the type from the cache or create a new
1347 /// one if necessary.
1348 llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty,
1349                                           llvm::DIFile Unit) {
1350   if (Ty.isNull())
1351     return llvm::DIType();
1352 
1353   // Unwrap the type as needed for debug information.
1354   Ty = UnwrapTypeForDebugInfo(Ty);
1355 
1356   // Check for existing entry.
1357   llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1358     TypeCache.find(Ty.getAsOpaquePtr());
1359   if (it != TypeCache.end()) {
1360     // Verify that the debug info still exists.
1361     if (&*it->second)
1362       return llvm::DIType(cast<llvm::MDNode>(it->second));
1363   }
1364 
1365   // Otherwise create the type.
1366   llvm::DIType Res = CreateTypeNode(Ty, Unit);
1367 
1368   // And update the type cache.
1369   TypeCache[Ty.getAsOpaquePtr()] = Res;
1370   return Res;
1371 }
1372 
1373 /// CreateTypeNode - Create a new debug type node.
1374 llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty,
1375                                          llvm::DIFile Unit) {
1376   // Handle qualifiers, which recursively handles what they refer to.
1377   if (Ty.hasLocalQualifiers())
1378     return CreateQualifiedType(Ty, Unit);
1379 
1380   const char *Diag = 0;
1381 
1382   // Work out details of type.
1383   switch (Ty->getTypeClass()) {
1384 #define TYPE(Class, Base)
1385 #define ABSTRACT_TYPE(Class, Base)
1386 #define NON_CANONICAL_TYPE(Class, Base)
1387 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1388 #include "clang/AST/TypeNodes.def"
1389     assert(false && "Dependent types cannot show up in debug information");
1390 
1391   // FIXME: Handle these.
1392   case Type::ExtVector:
1393     return llvm::DIType();
1394 
1395   case Type::Vector:
1396     return CreateType(cast<VectorType>(Ty), Unit);
1397   case Type::ObjCObjectPointer:
1398     return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
1399   case Type::ObjCObject:
1400     return CreateType(cast<ObjCObjectType>(Ty), Unit);
1401   case Type::ObjCInterface:
1402     return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
1403   case Type::Builtin: return CreateType(cast<BuiltinType>(Ty), Unit);
1404   case Type::Complex: return CreateType(cast<ComplexType>(Ty), Unit);
1405   case Type::Pointer: return CreateType(cast<PointerType>(Ty), Unit);
1406   case Type::BlockPointer:
1407     return CreateType(cast<BlockPointerType>(Ty), Unit);
1408   case Type::Typedef: return CreateType(cast<TypedefType>(Ty), Unit);
1409   case Type::Record:
1410   case Type::Enum:
1411     return CreateType(cast<TagType>(Ty), Unit);
1412   case Type::FunctionProto:
1413   case Type::FunctionNoProto:
1414     return CreateType(cast<FunctionType>(Ty), Unit);
1415   case Type::ConstantArray:
1416   case Type::VariableArray:
1417   case Type::IncompleteArray:
1418     return CreateType(cast<ArrayType>(Ty), Unit);
1419 
1420   case Type::LValueReference:
1421     return CreateType(cast<LValueReferenceType>(Ty), Unit);
1422 
1423   case Type::MemberPointer:
1424     return CreateType(cast<MemberPointerType>(Ty), Unit);
1425 
1426   case Type::TemplateSpecialization:
1427   case Type::Elaborated:
1428   case Type::SubstTemplateTypeParm:
1429   case Type::TypeOfExpr:
1430   case Type::TypeOf:
1431   case Type::Decltype:
1432     llvm_unreachable("type should have been unwrapped!");
1433     return llvm::DIType();
1434 
1435   case Type::RValueReference:
1436     // FIXME: Implement!
1437     Diag = "rvalue references";
1438     break;
1439   }
1440 
1441   assert(Diag && "Fall through without a diagnostic?");
1442   unsigned DiagID = CGM.getDiags().getCustomDiagID(Diagnostic::Error,
1443                                "debug information for %0 is not yet supported");
1444   CGM.getDiags().Report(FullSourceLoc(), DiagID)
1445     << Diag;
1446   return llvm::DIType();
1447 }
1448 
1449 /// CreateMemberType - Create new member and increase Offset by FType's size.
1450 llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
1451                                            llvm::StringRef Name,
1452                                            uint64_t *Offset) {
1453   llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1454   uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
1455   unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
1456   llvm::DIType Ty = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member,
1457                                                    Unit, Name, Unit, 0,
1458                                                    FieldSize, FieldAlign,
1459                                                    *Offset, 0, FieldTy);
1460   *Offset += FieldSize;
1461   return Ty;
1462 }
1463 
1464 /// EmitFunctionStart - Constructs the debug code for entering a function -
1465 /// "llvm.dbg.func.start.".
1466 void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
1467                                     llvm::Function *Fn,
1468                                     CGBuilderTy &Builder) {
1469 
1470   llvm::StringRef Name;
1471   llvm::StringRef LinkageName;
1472 
1473   FnBeginRegionCount.push_back(RegionStack.size());
1474 
1475   const Decl *D = GD.getDecl();
1476   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1477     // If there is a DISubprogram for  this function available then use it.
1478     llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
1479       FI = SPCache.find(FD);
1480     if (FI != SPCache.end()) {
1481       llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(FI->second));
1482       if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
1483         llvm::MDNode *SPN = SP;
1484         RegionStack.push_back(SPN);
1485         RegionMap[D] = llvm::WeakVH(SP);
1486         return;
1487       }
1488     }
1489     Name = getFunctionName(FD);
1490     // Use mangled name as linkage name for c/c++ functions.
1491     LinkageName = CGM.getMangledName(GD);
1492   } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
1493     Name = getObjCMethodName(OMD);
1494     LinkageName = Name;
1495   } else {
1496     // Use llvm function name as linkage name.
1497     Name = Fn->getName();
1498     LinkageName = Name;
1499   }
1500   if (!Name.empty() && Name[0] == '\01')
1501     Name = Name.substr(1);
1502 
1503   // It is expected that CurLoc is set before using EmitFunctionStart.
1504   // Usually, CurLoc points to the left bracket location of compound
1505   // statement representing function body.
1506   llvm::DIFile Unit = getOrCreateFile(CurLoc);
1507   unsigned LineNo = getLineNumber(CurLoc);
1508 
1509   llvm::DISubprogram SP =
1510     DebugFactory.CreateSubprogram(Unit, Name, Name, LinkageName, Unit, LineNo,
1511                                   getOrCreateType(FnType, Unit),
1512                                   Fn->hasInternalLinkage(), true/*definition*/,
1513                                   0, 0, llvm::DIType(),
1514                                   D->isImplicit(),
1515                                   CGM.getLangOptions().Optimize, Fn);
1516 
1517   // Push function on region stack.
1518   llvm::MDNode *SPN = SP;
1519   RegionStack.push_back(SPN);
1520   RegionMap[D] = llvm::WeakVH(SP);
1521 
1522   // Clear stack used to keep track of #line directives.
1523   LineDirectiveFiles.clear();
1524 }
1525 
1526 
1527 void CGDebugInfo::EmitStopPoint(CGBuilderTy &Builder) {
1528   if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
1529 
1530   // Don't bother if things are the same as last time.
1531   SourceManager &SM = CGM.getContext().getSourceManager();
1532   if (CurLoc == PrevLoc
1533        || (SM.getInstantiationLineNumber(CurLoc) ==
1534            SM.getInstantiationLineNumber(PrevLoc)
1535            && SM.isFromSameFile(CurLoc, PrevLoc)))
1536     // New Builder may not be in sync with CGDebugInfo.
1537     if (!Builder.getCurrentDebugLocation().isUnknown())
1538       return;
1539 
1540   // Update last state.
1541   PrevLoc = CurLoc;
1542 
1543   llvm::MDNode *Scope = RegionStack.back();
1544   Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(CurLoc),
1545                                                       getColumnNumber(CurLoc),
1546                                                       Scope));
1547 }
1548 
1549 /// UpdateLineDirectiveRegion - Update region stack only if #line directive
1550 /// has introduced scope change.
1551 void CGDebugInfo::UpdateLineDirectiveRegion(CGBuilderTy &Builder) {
1552   if (CurLoc.isInvalid() || CurLoc.isMacroID() ||
1553       PrevLoc.isInvalid() || PrevLoc.isMacroID())
1554     return;
1555   SourceManager &SM = CGM.getContext().getSourceManager();
1556   PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
1557   PresumedLoc PPLoc = SM.getPresumedLoc(PrevLoc);
1558 
1559   if (!strcmp(PPLoc.getFilename(), PCLoc.getFilename()))
1560     return;
1561 
1562   // If #line directive stack is empty then we are entering a new scope.
1563   if (LineDirectiveFiles.empty()) {
1564     EmitRegionStart(Builder);
1565     LineDirectiveFiles.push_back(PCLoc.getFilename());
1566     return;
1567   }
1568 
1569   assert (RegionStack.size() >= LineDirectiveFiles.size()
1570           && "error handling  #line regions!");
1571 
1572   bool SeenThisFile = false;
1573   for(std::vector<const char *>::iterator I = LineDirectiveFiles.begin(),
1574         E = LineDirectiveFiles.end(); I != E; ++I)
1575     if (!strcmp(PPLoc.getFilename(), *I)) {
1576       SeenThisFile = true;
1577       break;
1578     }
1579 
1580   // If #line for this file is seen earlier then pop out #line regions.
1581   if (SeenThisFile) {
1582     while (!LineDirectiveFiles.empty()) {
1583       const char *LastFile = LineDirectiveFiles.back();
1584       RegionStack.pop_back();
1585       LineDirectiveFiles.pop_back();
1586       if (!strcmp(PPLoc.getFilename(), LastFile))
1587         break;
1588     }
1589     return;
1590   }
1591 
1592   // .. otherwise insert new #line region.
1593   EmitRegionStart(Builder);
1594   LineDirectiveFiles.push_back(PCLoc.getFilename());
1595 
1596   return;
1597 }
1598 /// EmitRegionStart- Constructs the debug code for entering a declarative
1599 /// region - "llvm.dbg.region.start.".
1600 void CGDebugInfo::EmitRegionStart(CGBuilderTy &Builder) {
1601   llvm::DIDescriptor D =
1602     DebugFactory.CreateLexicalBlock(RegionStack.empty() ?
1603                                     llvm::DIDescriptor() :
1604                                     llvm::DIDescriptor(RegionStack.back()),
1605                                     getOrCreateFile(CurLoc),
1606                                     getLineNumber(CurLoc),
1607                                     getColumnNumber(CurLoc));
1608   llvm::MDNode *DN = D;
1609   RegionStack.push_back(DN);
1610 }
1611 
1612 /// EmitRegionEnd - Constructs the debug code for exiting a declarative
1613 /// region - "llvm.dbg.region.end."
1614 void CGDebugInfo::EmitRegionEnd(CGBuilderTy &Builder) {
1615   assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
1616 
1617   // Provide an region stop point.
1618   EmitStopPoint(Builder);
1619 
1620   RegionStack.pop_back();
1621 }
1622 
1623 /// EmitFunctionEnd - Constructs the debug code for exiting a function.
1624 void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
1625   assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
1626   unsigned RCount = FnBeginRegionCount.back();
1627   assert(RCount <= RegionStack.size() && "Region stack mismatch");
1628 
1629   // Pop all regions for this function.
1630   while (RegionStack.size() != RCount)
1631     EmitRegionEnd(Builder);
1632   FnBeginRegionCount.pop_back();
1633 }
1634 
1635 // EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
1636 // See BuildByRefType.
1637 llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const ValueDecl *VD,
1638                                                        uint64_t *XOffset) {
1639 
1640   llvm::SmallVector<llvm::DIDescriptor, 5> EltTys;
1641 
1642   QualType FType;
1643   uint64_t FieldSize, FieldOffset;
1644   unsigned FieldAlign;
1645 
1646   llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
1647   QualType Type = VD->getType();
1648 
1649   FieldOffset = 0;
1650   FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1651   EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
1652   EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
1653   FType = CGM.getContext().IntTy;
1654   EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
1655   EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
1656 
1657   bool HasCopyAndDispose = CGM.BlockRequiresCopying(Type);
1658   if (HasCopyAndDispose) {
1659     FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1660     EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
1661                                       &FieldOffset));
1662     EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
1663                                       &FieldOffset));
1664   }
1665 
1666   CharUnits Align = CGM.getContext().getDeclAlign(VD);
1667   if (Align > CharUnits::fromQuantity(
1668         CGM.getContext().Target.getPointerAlign(0) / 8)) {
1669     unsigned AlignedOffsetInBytes
1670       = llvm::RoundUpToAlignment(FieldOffset/8, Align.getQuantity());
1671     unsigned NumPaddingBytes
1672       = AlignedOffsetInBytes - FieldOffset/8;
1673 
1674     if (NumPaddingBytes > 0) {
1675       llvm::APInt pad(32, NumPaddingBytes);
1676       FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
1677                                                     pad, ArrayType::Normal, 0);
1678       EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
1679     }
1680   }
1681 
1682   FType = Type;
1683   llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1684   FieldSize = CGM.getContext().getTypeSize(FType);
1685   FieldAlign = Align.getQuantity()*8;
1686 
1687   *XOffset = FieldOffset;
1688   FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1689                                            VD->getName(), Unit,
1690                                            0, FieldSize, FieldAlign,
1691                                            FieldOffset, 0, FieldTy);
1692   EltTys.push_back(FieldTy);
1693   FieldOffset += FieldSize;
1694 
1695   llvm::DIArray Elements =
1696     DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
1697 
1698   unsigned Flags = llvm::DIType::FlagBlockByrefStruct;
1699 
1700   return DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_structure_type,
1701                                           Unit, "", Unit,
1702                                           0, FieldOffset, 0, 0, Flags,
1703                                           llvm::DIType(), Elements);
1704 
1705 }
1706 /// EmitDeclare - Emit local variable declaration debug info.
1707 void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
1708                               llvm::Value *Storage, CGBuilderTy &Builder) {
1709   assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
1710 
1711   llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
1712   llvm::DIType Ty;
1713   uint64_t XOffset = 0;
1714   if (VD->hasAttr<BlocksAttr>())
1715     Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
1716   else
1717     Ty = getOrCreateType(VD->getType(), Unit);
1718 
1719   // If there is not any debug info for type then do not emit debug info
1720   // for this variable.
1721   if (!Ty)
1722     return;
1723 
1724   // Get location information.
1725   unsigned Line = getLineNumber(VD->getLocation());
1726   unsigned Column = getColumnNumber(VD->getLocation());
1727 
1728   // Create the descriptor for the variable.
1729   llvm::DIVariable D =
1730     DebugFactory.CreateVariable(Tag, llvm::DIDescriptor(RegionStack.back()),
1731                                 VD->getName(),
1732                                 Unit, Line, Ty, CGM.getLangOptions().Optimize);
1733   // Insert an llvm.dbg.declare into the current block.
1734   llvm::Instruction *Call =
1735     DebugFactory.InsertDeclare(Storage, D, Builder.GetInsertBlock());
1736 
1737   llvm::MDNode *Scope = RegionStack.back();
1738   Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
1739 }
1740 
1741 /// EmitDeclare - Emit local variable declaration debug info.
1742 void CGDebugInfo::EmitDeclare(const BlockDeclRefExpr *BDRE, unsigned Tag,
1743                               llvm::Value *Storage, CGBuilderTy &Builder,
1744                               CodeGenFunction *CGF) {
1745   const ValueDecl *VD = BDRE->getDecl();
1746   assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
1747 
1748   if (Builder.GetInsertBlock() == 0)
1749     return;
1750 
1751   uint64_t XOffset = 0;
1752   llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
1753   llvm::DIType Ty;
1754   if (VD->hasAttr<BlocksAttr>())
1755     Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
1756   else
1757     Ty = getOrCreateType(VD->getType(), Unit);
1758 
1759   // Get location information.
1760   unsigned Line = getLineNumber(VD->getLocation());
1761   unsigned Column = getColumnNumber(VD->getLocation());
1762 
1763   CharUnits offset = CGF->BlockDecls[VD];
1764   llvm::SmallVector<llvm::Value *, 9> addr;
1765   const llvm::Type *Int64Ty = llvm::Type::getInt64Ty(CGM.getLLVMContext());
1766   addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpDeref));
1767   addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpPlus));
1768   addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
1769   if (BDRE->isByRef()) {
1770     addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpDeref));
1771     addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpPlus));
1772     // offset of __forwarding field
1773     offset = CharUnits::fromQuantity(CGF->LLVMPointerWidth/8);
1774     addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
1775     addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpDeref));
1776     addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpPlus));
1777     // offset of x field
1778     offset = CharUnits::fromQuantity(XOffset/8);
1779     addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
1780   }
1781 
1782   // Create the descriptor for the variable.
1783   llvm::DIVariable D =
1784     DebugFactory.CreateComplexVariable(Tag,
1785                                        llvm::DIDescriptor(RegionStack.back()),
1786                                        VD->getName(), Unit, Line, Ty,
1787                                        addr);
1788   // Insert an llvm.dbg.declare into the current block.
1789   llvm::Instruction *Call =
1790     DebugFactory.InsertDeclare(Storage, D, Builder.GetInsertBlock());
1791 
1792   llvm::MDNode *Scope = RegionStack.back();
1793   Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
1794 }
1795 
1796 void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
1797                                             llvm::Value *Storage,
1798                                             CGBuilderTy &Builder) {
1799   EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, Builder);
1800 }
1801 
1802 void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(
1803   const BlockDeclRefExpr *BDRE, llvm::Value *Storage, CGBuilderTy &Builder,
1804   CodeGenFunction *CGF) {
1805   EmitDeclare(BDRE, llvm::dwarf::DW_TAG_auto_variable, Storage, Builder, CGF);
1806 }
1807 
1808 /// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
1809 /// variable declaration.
1810 void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
1811                                            CGBuilderTy &Builder) {
1812   EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, Builder);
1813 }
1814 
1815 
1816 
1817 /// EmitGlobalVariable - Emit information about a global variable.
1818 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
1819                                      const VarDecl *D) {
1820 
1821   // Create global variable debug descriptor.
1822   llvm::DIFile Unit = getOrCreateFile(D->getLocation());
1823   unsigned LineNo = getLineNumber(D->getLocation());
1824 
1825   QualType T = D->getType();
1826   if (T->isIncompleteArrayType()) {
1827 
1828     // CodeGen turns int[] into int[1] so we'll do the same here.
1829     llvm::APSInt ConstVal(32);
1830 
1831     ConstVal = 1;
1832     QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
1833 
1834     T = CGM.getContext().getConstantArrayType(ET, ConstVal,
1835                                            ArrayType::Normal, 0);
1836   }
1837   llvm::StringRef DeclName = D->getName();
1838   llvm::StringRef LinkageName;
1839   if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext()))
1840     LinkageName = Var->getName();
1841   llvm::DIDescriptor DContext =
1842     getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()), Unit);
1843   DebugFactory.CreateGlobalVariable(DContext, DeclName, DeclName, LinkageName,
1844                                     Unit, LineNo, getOrCreateType(T, Unit),
1845                                     Var->hasInternalLinkage(),
1846                                     true/*definition*/, Var);
1847 }
1848 
1849 /// EmitGlobalVariable - Emit information about an objective-c interface.
1850 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
1851                                      ObjCInterfaceDecl *ID) {
1852   // Create global variable debug descriptor.
1853   llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
1854   unsigned LineNo = getLineNumber(ID->getLocation());
1855 
1856   llvm::StringRef Name = ID->getName();
1857 
1858   QualType T = CGM.getContext().getObjCInterfaceType(ID);
1859   if (T->isIncompleteArrayType()) {
1860 
1861     // CodeGen turns int[] into int[1] so we'll do the same here.
1862     llvm::APSInt ConstVal(32);
1863 
1864     ConstVal = 1;
1865     QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
1866 
1867     T = CGM.getContext().getConstantArrayType(ET, ConstVal,
1868                                            ArrayType::Normal, 0);
1869   }
1870 
1871   DebugFactory.CreateGlobalVariable(Unit, Name, Name, Name, Unit, LineNo,
1872                                     getOrCreateType(T, Unit),
1873                                     Var->hasInternalLinkage(),
1874                                     true/*definition*/, Var);
1875 }
1876 
1877 /// EmitGlobalVariable - Emit global variable's debug info.
1878 void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
1879                                      llvm::ConstantInt *Init,
1880                                      CGBuilderTy &Builder) {
1881   // Create the descriptor for the variable.
1882   llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
1883   llvm::StringRef Name = VD->getName();
1884   llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
1885   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
1886     if (const EnumDecl *ED = dyn_cast<EnumDecl>(ECD->getDeclContext()))
1887       Ty = CreateEnumType(ED, Unit);
1888   }
1889   // Do not use DIGlobalVariable for enums.
1890   if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
1891     return;
1892   DebugFactory.CreateGlobalVariable(Unit, Name, Name, Name, Unit,
1893                                     getLineNumber(VD->getLocation()),
1894                                     Ty, true, true, Init);
1895 }
1896 
1897 /// getOrCreateNamesSpace - Return namespace descriptor for the given
1898 /// namespace decl.
1899 llvm::DINameSpace
1900 CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl,
1901                                   llvm::DIDescriptor Unit) {
1902   llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
1903     NameSpaceCache.find(NSDecl);
1904   if (I != NameSpaceCache.end())
1905     return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
1906 
1907   unsigned LineNo = getLineNumber(NSDecl->getLocation());
1908 
1909   llvm::DIDescriptor Context =
1910     getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()), Unit);
1911   llvm::DINameSpace NS =
1912     DebugFactory.CreateNameSpace(Context, NSDecl->getName(),
1913                                  llvm::DIFile(Unit), LineNo);
1914   NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
1915   return NS;
1916 }
1917