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