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 "CGBlocks.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/DeclFriend.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/RecordLayout.h"
24 #include "clang/Basic/SourceManager.h"
25 #include "clang/Basic/FileManager.h"
26 #include "clang/Basic/Version.h"
27 #include "clang/Frontend/CodeGenOptions.h"
28 #include "llvm/Constants.h"
29 #include "llvm/DerivedTypes.h"
30 #include "llvm/Instructions.h"
31 #include "llvm/Intrinsics.h"
32 #include "llvm/Module.h"
33 #include "llvm/ADT/StringExtras.h"
34 #include "llvm/ADT/SmallVector.h"
35 #include "llvm/Support/Dwarf.h"
36 #include "llvm/Support/Path.h"
37 #include "llvm/Target/TargetData.h"
38 #include "llvm/Target/TargetMachine.h"
39 using namespace clang;
40 using namespace clang::CodeGen;
41 
42 CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
43   : CGM(CGM), DBuilder(CGM.getModule()),
44     BlockLiteralGenericSet(false) {
45   CreateCompileUnit();
46 }
47 
48 CGDebugInfo::~CGDebugInfo() {
49   assert(RegionStack.empty() && "Region stack mismatch, stack not empty!");
50 }
51 
52 void CGDebugInfo::setLocation(SourceLocation Loc) {
53   if (Loc.isValid())
54     CurLoc = CGM.getContext().getSourceManager().getInstantiationLoc(Loc);
55 }
56 
57 /// getContextDescriptor - Get context info for the decl.
58 llvm::DIDescriptor CGDebugInfo::getContextDescriptor(const Decl *Context) {
59   if (!Context)
60     return TheCU;
61 
62   llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
63     I = RegionMap.find(Context);
64   if (I != RegionMap.end())
65     return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(&*I->second));
66 
67   // Check namespace.
68   if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
69     return llvm::DIDescriptor(getOrCreateNameSpace(NSDecl));
70 
71   if (const RecordDecl *RDecl = dyn_cast<RecordDecl>(Context)) {
72     if (!RDecl->isDependentType()) {
73       llvm::DIType Ty = getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
74                                         getOrCreateMainFile());
75       return llvm::DIDescriptor(Ty);
76     }
77   }
78   return TheCU;
79 }
80 
81 /// getFunctionName - Get function name for the given FunctionDecl. If the
82 /// name is constructred on demand (e.g. C++ destructor) then the name
83 /// is stored on the side.
84 llvm::StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
85   assert (FD && "Invalid FunctionDecl!");
86   IdentifierInfo *FII = FD->getIdentifier();
87   if (FII)
88     return FII->getName();
89 
90   // Otherwise construct human readable name for debug info.
91   std::string NS = FD->getNameAsString();
92 
93   // Copy this name on the side and use its reference.
94   char *StrPtr = DebugInfoNames.Allocate<char>(NS.length());
95   memcpy(StrPtr, NS.data(), NS.length());
96   return llvm::StringRef(StrPtr, NS.length());
97 }
98 
99 llvm::StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
100   llvm::SmallString<256> MethodName;
101   llvm::raw_svector_ostream OS(MethodName);
102   OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
103   const DeclContext *DC = OMD->getDeclContext();
104   if (const ObjCImplementationDecl *OID =
105       dyn_cast<const ObjCImplementationDecl>(DC)) {
106      OS << OID->getName();
107   } else if (const ObjCInterfaceDecl *OID =
108              dyn_cast<const ObjCInterfaceDecl>(DC)) {
109       OS << OID->getName();
110   } else if (const ObjCCategoryImplDecl *OCD =
111              dyn_cast<const ObjCCategoryImplDecl>(DC)){
112       OS << ((NamedDecl *)OCD)->getIdentifier()->getNameStart() << '(' <<
113           OCD->getIdentifier()->getNameStart() << ')';
114   }
115   OS << ' ' << OMD->getSelector().getAsString() << ']';
116 
117   char *StrPtr = DebugInfoNames.Allocate<char>(OS.tell());
118   memcpy(StrPtr, MethodName.begin(), OS.tell());
119   return llvm::StringRef(StrPtr, OS.tell());
120 }
121 
122 /// getSelectorName - Return selector name. This is used for debugging
123 /// info.
124 llvm::StringRef CGDebugInfo::getSelectorName(Selector S) {
125   llvm::SmallString<256> SName;
126   llvm::raw_svector_ostream OS(SName);
127   OS << S.getAsString();
128   char *StrPtr = DebugInfoNames.Allocate<char>(OS.tell());
129   memcpy(StrPtr, SName.begin(), OS.tell());
130   return llvm::StringRef(StrPtr, OS.tell());
131 }
132 
133 /// getClassName - Get class name including template argument list.
134 llvm::StringRef
135 CGDebugInfo::getClassName(RecordDecl *RD) {
136   ClassTemplateSpecializationDecl *Spec
137     = dyn_cast<ClassTemplateSpecializationDecl>(RD);
138   if (!Spec)
139     return RD->getName();
140 
141   const TemplateArgument *Args;
142   unsigned NumArgs;
143   std::string Buffer;
144   if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) {
145     const TemplateSpecializationType *TST =
146       cast<TemplateSpecializationType>(TAW->getType());
147     Args = TST->getArgs();
148     NumArgs = TST->getNumArgs();
149   } else {
150     const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
151     Args = TemplateArgs.data();
152     NumArgs = TemplateArgs.size();
153   }
154   Buffer = RD->getIdentifier()->getNameStart();
155   PrintingPolicy Policy(CGM.getLangOptions());
156   Buffer += TemplateSpecializationType::PrintTemplateArgumentList(Args,
157                                                                   NumArgs,
158                                                                   Policy);
159 
160   // Copy this name on the side and use its reference.
161   char *StrPtr = DebugInfoNames.Allocate<char>(Buffer.length());
162   memcpy(StrPtr, Buffer.data(), Buffer.length());
163   return llvm::StringRef(StrPtr, Buffer.length());
164 }
165 
166 /// getOrCreateFile - Get the file debug info descriptor for the input location.
167 llvm::DIFile CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
168   if (!Loc.isValid())
169     // If Location is not valid then use main input file.
170     return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
171 
172   SourceManager &SM = CGM.getContext().getSourceManager();
173   PresumedLoc PLoc = SM.getPresumedLoc(Loc);
174 
175   if (PLoc.isInvalid() || llvm::StringRef(PLoc.getFilename()).empty())
176     // If the location is not valid then use main input file.
177     return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
178 
179   // Cache the results.
180   const char *fname = PLoc.getFilename();
181   llvm::DenseMap<const char *, llvm::WeakVH>::iterator it =
182     DIFileCache.find(fname);
183 
184   if (it != DIFileCache.end()) {
185     // Verify that the information still exists.
186     if (&*it->second)
187       return llvm::DIFile(cast<llvm::MDNode>(it->second));
188   }
189 
190   llvm::DIFile F = DBuilder.createFile(PLoc.getFilename(), getCurrentDirname());
191 
192   DIFileCache[fname] = F;
193   return F;
194 
195 }
196 
197 /// getOrCreateMainFile - Get the file info for main compile unit.
198 llvm::DIFile CGDebugInfo::getOrCreateMainFile() {
199   return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
200 }
201 
202 /// getLineNumber - Get line number for the location. If location is invalid
203 /// then use current location.
204 unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
205   assert (CurLoc.isValid() && "Invalid current location!");
206   SourceManager &SM = CGM.getContext().getSourceManager();
207   PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
208   return PLoc.isValid()? PLoc.getLine() : 0;
209 }
210 
211 /// getColumnNumber - Get column number for the location. If location is
212 /// invalid then use current location.
213 unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc) {
214   assert (CurLoc.isValid() && "Invalid current location!");
215   SourceManager &SM = CGM.getContext().getSourceManager();
216   PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
217   return PLoc.isValid()? PLoc.getColumn() : 0;
218 }
219 
220 llvm::StringRef CGDebugInfo::getCurrentDirname() {
221   if (!CWDName.empty())
222     return CWDName;
223   char *CompDirnamePtr = NULL;
224   llvm::sys::Path CWD = llvm::sys::Path::GetCurrentDirectory();
225   CompDirnamePtr = DebugInfoNames.Allocate<char>(CWD.size());
226   memcpy(CompDirnamePtr, CWD.c_str(), CWD.size());
227   return CWDName = llvm::StringRef(CompDirnamePtr, CWD.size());
228 }
229 
230 /// CreateCompileUnit - Create new compile unit.
231 void CGDebugInfo::CreateCompileUnit() {
232 
233   // Get absolute path name.
234   SourceManager &SM = CGM.getContext().getSourceManager();
235   std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
236   if (MainFileName.empty())
237     MainFileName = "<unknown>";
238 
239   // The main file name provided via the "-main-file-name" option contains just
240   // the file name itself with no path information. This file name may have had
241   // a relative path, so we look into the actual file entry for the main
242   // file to determine the real absolute path for the file.
243   std::string MainFileDir;
244   if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
245     MainFileDir = MainFile->getDir()->getName();
246     if (MainFileDir != ".")
247       MainFileName = MainFileDir + "/" + MainFileName;
248   }
249 
250   // Save filename string.
251   char *FilenamePtr = DebugInfoNames.Allocate<char>(MainFileName.length());
252   memcpy(FilenamePtr, MainFileName.c_str(), MainFileName.length());
253   llvm::StringRef Filename(FilenamePtr, MainFileName.length());
254 
255   unsigned LangTag;
256   const LangOptions &LO = CGM.getLangOptions();
257   if (LO.CPlusPlus) {
258     if (LO.ObjC1)
259       LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
260     else
261       LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
262   } else if (LO.ObjC1) {
263     LangTag = llvm::dwarf::DW_LANG_ObjC;
264   } else if (LO.C99) {
265     LangTag = llvm::dwarf::DW_LANG_C99;
266   } else {
267     LangTag = llvm::dwarf::DW_LANG_C89;
268   }
269 
270   std::string Producer = getClangFullVersion();
271 
272   // Figure out which version of the ObjC runtime we have.
273   unsigned RuntimeVers = 0;
274   if (LO.ObjC1)
275     RuntimeVers = LO.ObjCNonFragileABI ? 2 : 1;
276 
277   // Create new compile unit.
278   DBuilder.createCompileUnit(
279     LangTag, Filename, getCurrentDirname(),
280     Producer,
281     LO.Optimize, CGM.getCodeGenOpts().DwarfDebugFlags, RuntimeVers);
282   // FIXME - Eliminate TheCU.
283   TheCU = llvm::DICompileUnit(DBuilder.getCU());
284 }
285 
286 /// CreateType - Get the Basic type from the cache or create a new
287 /// one if necessary.
288 llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT) {
289   unsigned Encoding = 0;
290   const char *BTName = NULL;
291   switch (BT->getKind()) {
292   default:
293   case BuiltinType::Void:
294     return llvm::DIType();
295   case BuiltinType::ObjCClass:
296     return DBuilder.createStructType(TheCU, "objc_class",
297                                      getOrCreateMainFile(), 0, 0, 0,
298                                      llvm::DIDescriptor::FlagFwdDecl,
299                                      llvm::DIArray());
300   case BuiltinType::ObjCId: {
301     // typedef struct objc_class *Class;
302     // typedef struct objc_object {
303     //  Class isa;
304     // } *id;
305 
306     llvm::DIType OCTy =
307       DBuilder.createStructType(TheCU, "objc_class",
308                                 getOrCreateMainFile(), 0, 0, 0,
309                                 llvm::DIDescriptor::FlagFwdDecl,
310                                 llvm::DIArray());
311     unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
312 
313     llvm::DIType ISATy = DBuilder.createPointerType(OCTy, Size);
314 
315     llvm::SmallVector<llvm::Value *, 16> EltTys;
316     llvm::DIType FieldTy =
317       DBuilder.createMemberType("isa", getOrCreateMainFile(),
318                                 0,Size, 0, 0, 0, ISATy);
319     EltTys.push_back(FieldTy);
320     llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
321 
322     return DBuilder.createStructType(TheCU, "objc_object",
323                                      getOrCreateMainFile(),
324                                      0, 0, 0, 0, Elements);
325   }
326   case BuiltinType::ObjCSel: {
327     return  DBuilder.createStructType(TheCU, "objc_selector",
328                                       getOrCreateMainFile(), 0, 0, 0,
329                                       llvm::DIDescriptor::FlagFwdDecl,
330                                       llvm::DIArray());
331   }
332   case BuiltinType::UChar:
333   case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
334   case BuiltinType::Char_S:
335   case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
336   case BuiltinType::UShort:
337   case BuiltinType::UInt:
338   case BuiltinType::UInt128:
339   case BuiltinType::ULong:
340   case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
341   case BuiltinType::Short:
342   case BuiltinType::Int:
343   case BuiltinType::Int128:
344   case BuiltinType::Long:
345   case BuiltinType::LongLong:  Encoding = llvm::dwarf::DW_ATE_signed; break;
346   case BuiltinType::Bool:      Encoding = llvm::dwarf::DW_ATE_boolean; break;
347   case BuiltinType::Float:
348   case BuiltinType::LongDouble:
349   case BuiltinType::Double:    Encoding = llvm::dwarf::DW_ATE_float; break;
350   }
351 
352   switch (BT->getKind()) {
353   case BuiltinType::Long:      BTName = "long int"; break;
354   case BuiltinType::LongLong:  BTName = "long long int"; break;
355   case BuiltinType::ULong:     BTName = "long unsigned int"; break;
356   case BuiltinType::ULongLong: BTName = "long long unsigned int"; break;
357   default:
358     BTName = BT->getName(CGM.getContext().getLangOptions());
359     break;
360   }
361   // Bit size, align and offset of the type.
362   uint64_t Size = CGM.getContext().getTypeSize(BT);
363   uint64_t Align = CGM.getContext().getTypeAlign(BT);
364   llvm::DIType DbgTy =
365     DBuilder.createBasicType(BTName, Size, Align, Encoding);
366   return DbgTy;
367 }
368 
369 llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty) {
370   // Bit size, align and offset of the type.
371   unsigned Encoding = llvm::dwarf::DW_ATE_complex_float;
372   if (Ty->isComplexIntegerType())
373     Encoding = llvm::dwarf::DW_ATE_lo_user;
374 
375   uint64_t Size = CGM.getContext().getTypeSize(Ty);
376   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
377   llvm::DIType DbgTy =
378     DBuilder.createBasicType("complex", Size, Align, Encoding);
379 
380   return DbgTy;
381 }
382 
383 /// CreateCVRType - Get the qualified type from the cache or create
384 /// a new one if necessary.
385 llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit) {
386   QualifierCollector Qc;
387   const Type *T = Qc.strip(Ty);
388 
389   // Ignore these qualifiers for now.
390   Qc.removeObjCGCAttr();
391   Qc.removeAddressSpace();
392 
393   // We will create one Derived type for one qualifier and recurse to handle any
394   // additional ones.
395   unsigned Tag;
396   if (Qc.hasConst()) {
397     Tag = llvm::dwarf::DW_TAG_const_type;
398     Qc.removeConst();
399   } else if (Qc.hasVolatile()) {
400     Tag = llvm::dwarf::DW_TAG_volatile_type;
401     Qc.removeVolatile();
402   } else if (Qc.hasRestrict()) {
403     Tag = llvm::dwarf::DW_TAG_restrict_type;
404     Qc.removeRestrict();
405   } else {
406     assert(Qc.empty() && "Unknown type qualifier for debug info");
407     return getOrCreateType(QualType(T, 0), Unit);
408   }
409 
410   llvm::DIType FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
411 
412   // No need to fill in the Name, Line, Size, Alignment, Offset in case of
413   // CVR derived types.
414   llvm::DIType DbgTy = DBuilder.createQualifiedType(Tag, FromTy);
415 
416   return DbgTy;
417 }
418 
419 llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
420                                      llvm::DIFile Unit) {
421   llvm::DIType DbgTy =
422     CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
423                           Ty->getPointeeType(), Unit);
424   return DbgTy;
425 }
426 
427 llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
428                                      llvm::DIFile Unit) {
429   return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
430                                Ty->getPointeeType(), Unit);
431 }
432 
433 /// CreatePointeeType - Create PointTee type. If Pointee is a record
434 /// then emit record's fwd if debug info size reduction is enabled.
435 llvm::DIType CGDebugInfo::CreatePointeeType(QualType PointeeTy,
436                                             llvm::DIFile Unit) {
437   if (!CGM.getCodeGenOpts().LimitDebugInfo)
438     return getOrCreateType(PointeeTy, Unit);
439 
440   if (const RecordType *RTy = dyn_cast<RecordType>(PointeeTy)) {
441     RecordDecl *RD = RTy->getDecl();
442     llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
443     unsigned Line = getLineNumber(RD->getLocation());
444     llvm::DIDescriptor FDContext =
445       getContextDescriptor(cast<Decl>(RD->getDeclContext()));
446 
447     if (RD->isStruct())
448       return DBuilder.createStructType(FDContext, RD->getName(), DefUnit,
449                                        Line, 0, 0, llvm::DIType::FlagFwdDecl,
450                                        llvm::DIArray());
451     else if (RD->isUnion())
452       return DBuilder.createUnionType(FDContext, RD->getName(), DefUnit,
453                                       Line, 0, 0, llvm::DIType::FlagFwdDecl,
454                                       llvm::DIArray());
455     else {
456       assert(RD->isClass() && "Unknown RecordType!");
457       return DBuilder.createClassType(FDContext, RD->getName(), DefUnit,
458                                       Line, 0, 0, 0, llvm::DIType::FlagFwdDecl,
459                                       llvm::DIType(), llvm::DIArray());
460     }
461   }
462   return getOrCreateType(PointeeTy, Unit);
463 
464 }
465 
466 llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag,
467                                                 const Type *Ty,
468                                                 QualType PointeeTy,
469                                                 llvm::DIFile Unit) {
470 
471   if (Tag == llvm::dwarf::DW_TAG_reference_type)
472     return DBuilder.createReferenceType(CreatePointeeType(PointeeTy, Unit));
473 
474   // Bit size, align and offset of the type.
475   // Size is always the size of a pointer. We can't use getTypeSize here
476   // because that does not return the correct value for references.
477   unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
478   uint64_t Size = CGM.getContext().Target.getPointerWidth(AS);
479   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
480 
481   return
482     DBuilder.createPointerType(CreatePointeeType(PointeeTy, Unit), Size, Align);
483 }
484 
485 llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
486                                      llvm::DIFile Unit) {
487   if (BlockLiteralGenericSet)
488     return BlockLiteralGeneric;
489 
490   llvm::SmallVector<llvm::Value *, 8> EltTys;
491   llvm::DIType FieldTy;
492   QualType FType;
493   uint64_t FieldSize, FieldOffset;
494   unsigned FieldAlign;
495   llvm::DIArray Elements;
496   llvm::DIType EltTy, DescTy;
497 
498   FieldOffset = 0;
499   FType = CGM.getContext().UnsignedLongTy;
500   EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
501   EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
502 
503   Elements = DBuilder.getOrCreateArray(EltTys);
504   EltTys.clear();
505 
506   unsigned Flags = llvm::DIDescriptor::FlagAppleBlock;
507   unsigned LineNo = getLineNumber(CurLoc);
508 
509   EltTy = DBuilder.createStructType(Unit, "__block_descriptor",
510                                     Unit, LineNo, FieldOffset, 0,
511                                     Flags, Elements);
512 
513   // Bit size, align and offset of the type.
514   uint64_t Size = CGM.getContext().getTypeSize(Ty);
515 
516   DescTy = DBuilder.createPointerType(EltTy, Size);
517 
518   FieldOffset = 0;
519   FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
520   EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
521   FType = CGM.getContext().IntTy;
522   EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
523   EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
524   FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
525   EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
526 
527   FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
528   FieldTy = DescTy;
529   FieldSize = CGM.getContext().getTypeSize(Ty);
530   FieldAlign = CGM.getContext().getTypeAlign(Ty);
531   FieldTy = DBuilder.createMemberType("__descriptor", Unit,
532                                       LineNo, FieldSize, FieldAlign,
533                                       FieldOffset, 0, FieldTy);
534   EltTys.push_back(FieldTy);
535 
536   FieldOffset += FieldSize;
537   Elements = DBuilder.getOrCreateArray(EltTys);
538 
539   EltTy = DBuilder.createStructType(Unit, "__block_literal_generic",
540                                     Unit, LineNo, FieldOffset, 0,
541                                     Flags, Elements);
542 
543   BlockLiteralGenericSet = true;
544   BlockLiteralGeneric = DBuilder.createPointerType(EltTy, Size);
545   return BlockLiteralGeneric;
546 }
547 
548 llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty,
549                                      llvm::DIFile Unit) {
550   // Typedefs are derived from some other type.  If we have a typedef of a
551   // typedef, make sure to emit the whole chain.
552   llvm::DIType Src = getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
553   if (!Src.Verify())
554     return llvm::DIType();
555   // We don't set size information, but do specify where the typedef was
556   // declared.
557   unsigned Line = getLineNumber(Ty->getDecl()->getLocation());
558   llvm::DIType DbgTy = DBuilder.createTypedef(Src, Ty->getDecl()->getName(),
559                                               Unit, Line);
560   return DbgTy;
561 }
562 
563 llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
564                                      llvm::DIFile Unit) {
565   llvm::SmallVector<llvm::Value *, 16> EltTys;
566 
567   // Add the result type at least.
568   EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit));
569 
570   // Set up remainder of arguments if there is a prototype.
571   // FIXME: IF NOT, HOW IS THIS REPRESENTED?  llvm-gcc doesn't represent '...'!
572   if (isa<FunctionNoProtoType>(Ty))
573     EltTys.push_back(DBuilder.createUnspecifiedParameter());
574   else if (const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(Ty)) {
575     for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i)
576       EltTys.push_back(getOrCreateType(FTP->getArgType(i), Unit));
577   }
578 
579   llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
580 
581   llvm::DIType DbgTy = DBuilder.createSubroutineType(Unit, EltTypeArray);
582   return DbgTy;
583 }
584 
585 llvm::DIType CGDebugInfo::createFieldType(llvm::StringRef name,
586                                           QualType type,
587                                           Expr *bitWidth,
588                                           SourceLocation loc,
589                                           AccessSpecifier AS,
590                                           uint64_t offsetInBits,
591                                           llvm::DIFile tunit) {
592   llvm::DIType debugType = getOrCreateType(type, tunit);
593 
594   // Get the location for the field.
595   llvm::DIFile file = getOrCreateFile(loc);
596   unsigned line = getLineNumber(loc);
597 
598   uint64_t sizeInBits = 0;
599   unsigned alignInBits = 0;
600   if (!type->isIncompleteArrayType()) {
601     llvm::tie(sizeInBits, alignInBits) = CGM.getContext().getTypeInfo(type);
602 
603     if (bitWidth)
604       sizeInBits = bitWidth->EvaluateAsInt(CGM.getContext()).getZExtValue();
605   }
606 
607   unsigned flags = 0;
608   if (AS == clang::AS_private)
609     flags |= llvm::DIDescriptor::FlagPrivate;
610   else if (AS == clang::AS_protected)
611     flags |= llvm::DIDescriptor::FlagProtected;
612 
613   return DBuilder.createMemberType(name, file, line, sizeInBits, alignInBits,
614                                    offsetInBits, flags, debugType);
615 }
616 
617 /// CollectRecordFields - A helper function to collect debug info for
618 /// record fields. This is used while creating debug info entry for a Record.
619 void CGDebugInfo::
620 CollectRecordFields(const RecordDecl *record, llvm::DIFile tunit,
621                     llvm::SmallVectorImpl<llvm::Value *> &elements) {
622   unsigned fieldNo = 0;
623   const FieldDecl *LastFD = 0;
624   bool IsMsStruct = record->hasAttr<MsStructAttr>();
625 
626   const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
627   for (RecordDecl::field_iterator I = record->field_begin(),
628                                   E = record->field_end();
629        I != E; ++I, ++fieldNo) {
630     FieldDecl *field = *I;
631     if (IsMsStruct) {
632       // Zero-length bitfields following non-bitfield members are ignored
633       if (CGM.getContext().ZeroBitfieldFollowsNonBitfield((field), LastFD)) {
634         --fieldNo;
635         continue;
636       }
637       LastFD = field;
638     }
639 
640     llvm::StringRef name = field->getName();
641     QualType type = field->getType();
642 
643     // Ignore unnamed fields unless they're anonymous structs/unions.
644     if (name.empty() && !type->isRecordType()) {
645       LastFD = field;
646       continue;
647     }
648 
649     llvm::DIType fieldType
650       = createFieldType(name, type, field->getBitWidth(),
651                         field->getLocation(), field->getAccess(),
652                         layout.getFieldOffset(fieldNo), tunit);
653 
654     elements.push_back(fieldType);
655   }
656 }
657 
658 /// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
659 /// function type is not updated to include implicit "this" pointer. Use this
660 /// routine to get a method type which includes "this" pointer.
661 llvm::DIType
662 CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
663                                    llvm::DIFile Unit) {
664   llvm::DIType FnTy
665     = getOrCreateType(QualType(Method->getType()->getAs<FunctionProtoType>(),
666                                0),
667                       Unit);
668 
669   // Add "this" pointer.
670 
671   llvm::DIArray Args = llvm::DICompositeType(FnTy).getTypeArray();
672   assert (Args.getNumElements() && "Invalid number of arguments!");
673 
674   llvm::SmallVector<llvm::Value *, 16> Elts;
675 
676   // First element is always return type. For 'void' functions it is NULL.
677   Elts.push_back(Args.getElement(0));
678 
679   if (!Method->isStatic())
680   {
681         // "this" pointer is always first argument.
682         QualType ThisPtr = Method->getThisType(CGM.getContext());
683         llvm::DIType ThisPtrType =
684           DBuilder.createArtificialType(getOrCreateType(ThisPtr, Unit));
685 
686         TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
687         Elts.push_back(ThisPtrType);
688     }
689 
690   // Copy rest of the arguments.
691   for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
692     Elts.push_back(Args.getElement(i));
693 
694   llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
695 
696   return DBuilder.createSubroutineType(Unit, EltTypeArray);
697 }
698 
699 /// isFunctionLocalClass - Return true if CXXRecordDecl is defined
700 /// inside a function.
701 static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
702   if (const CXXRecordDecl *NRD =
703       dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
704     return isFunctionLocalClass(NRD);
705   else if (isa<FunctionDecl>(RD->getDeclContext()))
706     return true;
707   return false;
708 
709 }
710 /// CreateCXXMemberFunction - A helper function to create a DISubprogram for
711 /// a single member function GlobalDecl.
712 llvm::DISubprogram
713 CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
714                                      llvm::DIFile Unit,
715                                      llvm::DIType RecordTy) {
716   bool IsCtorOrDtor =
717     isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
718 
719   llvm::StringRef MethodName = getFunctionName(Method);
720   llvm::DIType MethodTy = getOrCreateMethodType(Method, Unit);
721 
722   // Since a single ctor/dtor corresponds to multiple functions, it doesn't
723   // make sense to give a single ctor/dtor a linkage name.
724   llvm::StringRef MethodLinkageName;
725   if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
726     MethodLinkageName = CGM.getMangledName(Method);
727 
728   // Get the location for the method.
729   llvm::DIFile MethodDefUnit = getOrCreateFile(Method->getLocation());
730   unsigned MethodLine = getLineNumber(Method->getLocation());
731 
732   // Collect virtual method info.
733   llvm::DIType ContainingType;
734   unsigned Virtuality = 0;
735   unsigned VIndex = 0;
736 
737   if (Method->isVirtual()) {
738     if (Method->isPure())
739       Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
740     else
741       Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
742 
743     // It doesn't make sense to give a virtual destructor a vtable index,
744     // since a single destructor has two entries in the vtable.
745     if (!isa<CXXDestructorDecl>(Method))
746       VIndex = CGM.getVTables().getMethodVTableIndex(Method);
747     ContainingType = RecordTy;
748   }
749 
750   unsigned Flags = 0;
751   if (Method->isImplicit())
752     Flags |= llvm::DIDescriptor::FlagArtificial;
753   AccessSpecifier Access = Method->getAccess();
754   if (Access == clang::AS_private)
755     Flags |= llvm::DIDescriptor::FlagPrivate;
756   else if (Access == clang::AS_protected)
757     Flags |= llvm::DIDescriptor::FlagProtected;
758   if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
759     if (CXXC->isExplicit())
760       Flags |= llvm::DIDescriptor::FlagExplicit;
761   } else if (const CXXConversionDecl *CXXC =
762              dyn_cast<CXXConversionDecl>(Method)) {
763     if (CXXC->isExplicit())
764       Flags |= llvm::DIDescriptor::FlagExplicit;
765   }
766   if (Method->hasPrototype())
767     Flags |= llvm::DIDescriptor::FlagPrototyped;
768 
769   llvm::DISubprogram SP =
770     DBuilder.createMethod(RecordTy , MethodName, MethodLinkageName,
771                           MethodDefUnit, MethodLine,
772                           MethodTy, /*isLocalToUnit=*/false,
773                           /* isDefinition=*/ false,
774                           Virtuality, VIndex, ContainingType,
775                           Flags, CGM.getLangOptions().Optimize);
776 
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::Value *> &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::Value *> &EltTys,
806                 llvm::DIType RecordTy) {
807 
808   for (CXXRecordDecl::friend_iterator BI =  RD->friend_begin(),
809          BE = RD->friend_end(); BI != BE; ++BI) {
810     if (TypeSourceInfo *TInfo = (*BI)->getFriendType())
811       EltTys.push_back(DBuilder.createFriend(RecordTy,
812                                              getOrCreateType(TInfo->getType(),
813                                                              Unit)));
814   }
815 }
816 
817 /// CollectCXXBases - A helper function to collect debug info for
818 /// C++ base classes. This is used while creating debug info entry for
819 /// a Record.
820 void CGDebugInfo::
821 CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
822                 llvm::SmallVectorImpl<llvm::Value *> &EltTys,
823                 llvm::DIType RecordTy) {
824 
825   const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
826   for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
827          BE = RD->bases_end(); BI != BE; ++BI) {
828     unsigned BFlags = 0;
829     uint64_t BaseOffset;
830 
831     const CXXRecordDecl *Base =
832       cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl());
833 
834     if (BI->isVirtual()) {
835       // virtual base offset offset is -ve. The code generator emits dwarf
836       // expression where it expects +ve number.
837       BaseOffset =
838         0 - CGM.getVTables().getVirtualBaseOffsetOffset(RD, Base).getQuantity();
839       BFlags = llvm::DIDescriptor::FlagVirtual;
840     } else
841       BaseOffset = RL.getBaseClassOffsetInBits(Base);
842     // FIXME: Inconsistent units for BaseOffset. It is in bytes when
843     // BI->isVirtual() and bits when not.
844 
845     AccessSpecifier Access = BI->getAccessSpecifier();
846     if (Access == clang::AS_private)
847       BFlags |= llvm::DIDescriptor::FlagPrivate;
848     else if (Access == clang::AS_protected)
849       BFlags |= llvm::DIDescriptor::FlagProtected;
850 
851     llvm::DIType DTy =
852       DBuilder.createInheritance(RecordTy,
853                                  getOrCreateType(BI->getType(), Unit),
854                                  BaseOffset, BFlags);
855     EltTys.push_back(DTy);
856   }
857 }
858 
859 /// CollectTemplateParams - A helper function to collect template parameters.
860 llvm::DIArray CGDebugInfo::
861 CollectTemplateParams(const TemplateParameterList *TPList,
862                       const TemplateArgumentList &TAList,
863                       llvm::DIFile Unit) {
864   llvm::SmallVector<llvm::Value *, 16> TemplateParams;
865   for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
866     const TemplateArgument &TA = TAList[i];
867     const NamedDecl *ND = TPList->getParam(i);
868     if (TA.getKind() == TemplateArgument::Type) {
869       llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit);
870       llvm::DITemplateTypeParameter TTP =
871         DBuilder.createTemplateTypeParameter(TheCU, ND->getName(), TTy);
872       TemplateParams.push_back(TTP);
873     } else if (TA.getKind() == TemplateArgument::Integral) {
874       llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit);
875       llvm::DITemplateValueParameter TVP =
876         DBuilder.createTemplateValueParameter(TheCU, ND->getName(), TTy,
877                                           TA.getAsIntegral()->getZExtValue());
878       TemplateParams.push_back(TVP);
879     }
880   }
881   return DBuilder.getOrCreateArray(TemplateParams);
882 }
883 
884 /// CollectFunctionTemplateParams - A helper function to collect debug
885 /// info for function template parameters.
886 llvm::DIArray CGDebugInfo::
887 CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) {
888   if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplateSpecialization){
889     const TemplateParameterList *TList =
890       FD->getTemplateSpecializationInfo()->getTemplate()->getTemplateParameters();
891     return
892       CollectTemplateParams(TList, *FD->getTemplateSpecializationArgs(), Unit);
893   }
894   return llvm::DIArray();
895 }
896 
897 /// CollectCXXTemplateParams - A helper function to collect debug info for
898 /// template parameters.
899 llvm::DIArray CGDebugInfo::
900 CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial,
901                          llvm::DIFile Unit) {
902   llvm::PointerUnion<ClassTemplateDecl *,
903                      ClassTemplatePartialSpecializationDecl *>
904     PU = TSpecial->getSpecializedTemplateOrPartial();
905 
906   TemplateParameterList *TPList = PU.is<ClassTemplateDecl *>() ?
907     PU.get<ClassTemplateDecl *>()->getTemplateParameters() :
908     PU.get<ClassTemplatePartialSpecializationDecl *>()->getTemplateParameters();
909   const TemplateArgumentList &TAList = TSpecial->getTemplateInstantiationArgs();
910   return CollectTemplateParams(TPList, TAList, Unit);
911 }
912 
913 /// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
914 llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
915   if (VTablePtrType.isValid())
916     return VTablePtrType;
917 
918   ASTContext &Context = CGM.getContext();
919 
920   /* Function type */
921   llvm::Value *STy = getOrCreateType(Context.IntTy, Unit);
922   llvm::DIArray SElements = DBuilder.getOrCreateArray(STy);
923   llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements);
924   unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
925   llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0,
926                                                           "__vtbl_ptr_type");
927   VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
928   return VTablePtrType;
929 }
930 
931 /// getVTableName - Get vtable name for the given Class.
932 llvm::StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
933   // Otherwise construct gdb compatible name name.
934   std::string Name = "_vptr$" + RD->getNameAsString();
935 
936   // Copy this name on the side and use its reference.
937   char *StrPtr = DebugInfoNames.Allocate<char>(Name.length());
938   memcpy(StrPtr, Name.data(), Name.length());
939   return llvm::StringRef(StrPtr, Name.length());
940 }
941 
942 
943 /// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
944 /// debug info entry in EltTys vector.
945 void CGDebugInfo::
946 CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
947                   llvm::SmallVectorImpl<llvm::Value *> &EltTys) {
948   const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
949 
950   // If there is a primary base then it will hold vtable info.
951   if (RL.getPrimaryBase())
952     return;
953 
954   // If this class is not dynamic then there is not any vtable info to collect.
955   if (!RD->isDynamicClass())
956     return;
957 
958   unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
959   llvm::DIType VPTR
960     = DBuilder.createMemberType(getVTableName(RD), Unit,
961                                 0, Size, 0, 0, 0,
962                                 getOrCreateVTablePtrType(Unit));
963   EltTys.push_back(VPTR);
964 }
965 
966 /// getOrCreateRecordType - Emit record type's standalone debug info.
967 llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy,
968                                                 SourceLocation Loc) {
969   llvm::DIType T =  getOrCreateType(RTy, getOrCreateFile(Loc));
970   DBuilder.retainType(T);
971   return T;
972 }
973 
974 /// CreateType - get structure or union type.
975 llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty) {
976   RecordDecl *RD = Ty->getDecl();
977   llvm::DIFile Unit = getOrCreateFile(RD->getLocation());
978 
979   // Get overall information about the record type for the debug info.
980   llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
981   unsigned Line = getLineNumber(RD->getLocation());
982 
983   // Records and classes and unions can all be recursive.  To handle them, we
984   // first generate a debug descriptor for the struct as a forward declaration.
985   // Then (if it is a definition) we go through and get debug info for all of
986   // its members.  Finally, we create a descriptor for the complete type (which
987   // may refer to the forward decl if the struct is recursive) and replace all
988   // uses of the forward declaration with the final definition.
989   llvm::DIDescriptor FDContext =
990     getContextDescriptor(cast<Decl>(RD->getDeclContext()));
991 
992   // If this is just a forward declaration, construct an appropriately
993   // marked node and just return it.
994   if (!RD->getDefinition()) {
995     llvm::DIType FwdDecl =
996       DBuilder.createStructType(FDContext, RD->getName(),
997                                 DefUnit, Line, 0, 0,
998                                 llvm::DIDescriptor::FlagFwdDecl,
999                                 llvm::DIArray());
1000 
1001       return FwdDecl;
1002   }
1003 
1004   llvm::DIType FwdDecl = DBuilder.createTemporaryType(DefUnit);
1005 
1006   llvm::MDNode *MN = FwdDecl;
1007   llvm::TrackingVH<llvm::MDNode> FwdDeclNode = MN;
1008   // Otherwise, insert it into the TypeCache so that recursive uses will find
1009   // it.
1010   TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1011   // Push the struct on region stack.
1012   RegionStack.push_back(FwdDeclNode);
1013   RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1014 
1015   // Convert all the elements.
1016   llvm::SmallVector<llvm::Value *, 16> EltTys;
1017 
1018   const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1019   if (CXXDecl) {
1020     CollectCXXBases(CXXDecl, Unit, EltTys, FwdDecl);
1021     CollectVTableInfo(CXXDecl, Unit, EltTys);
1022   }
1023 
1024   // Collect static variables with initializers.
1025   for (RecordDecl::decl_iterator I = RD->decls_begin(), E = RD->decls_end();
1026        I != E; ++I)
1027     if (const VarDecl *V = dyn_cast<VarDecl>(*I)) {
1028       if (const Expr *Init = V->getInit()) {
1029         Expr::EvalResult Result;
1030         if (Init->Evaluate(Result, CGM.getContext()) && Result.Val.isInt()) {
1031           llvm::ConstantInt *CI
1032             = llvm::ConstantInt::get(CGM.getLLVMContext(), Result.Val.getInt());
1033 
1034           // Create the descriptor for static variable.
1035           llvm::DIFile VUnit = getOrCreateFile(V->getLocation());
1036           llvm::StringRef VName = V->getName();
1037           llvm::DIType VTy = getOrCreateType(V->getType(), VUnit);
1038           // Do not use DIGlobalVariable for enums.
1039           if (VTy.getTag() != llvm::dwarf::DW_TAG_enumeration_type) {
1040             DBuilder.createStaticVariable(FwdDecl, VName, VName, VUnit,
1041                                           getLineNumber(V->getLocation()),
1042                                           VTy, true, CI);
1043           }
1044         }
1045       }
1046     }
1047 
1048   CollectRecordFields(RD, Unit, EltTys);
1049   llvm::DIArray TParamsArray;
1050   if (CXXDecl) {
1051     CollectCXXMemberFunctions(CXXDecl, Unit, EltTys, FwdDecl);
1052     CollectCXXFriends(CXXDecl, Unit, EltTys, FwdDecl);
1053     if (const ClassTemplateSpecializationDecl *TSpecial
1054         = dyn_cast<ClassTemplateSpecializationDecl>(RD))
1055       TParamsArray = CollectCXXTemplateParams(TSpecial, Unit);
1056   }
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(cast<Decl>(RD->getDeclContext()));
1066   llvm::StringRef RDName = RD->getName();
1067   uint64_t Size = CGM.getContext().getTypeSize(Ty);
1068   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1069   llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
1070   llvm::MDNode *RealDecl = NULL;
1071 
1072   if (RD->isUnion())
1073     RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
1074                                         Size, Align, 0, Elements);
1075   else if (CXXDecl) {
1076     RDName = getClassName(RD);
1077      // A class's primary base or the class itself contains the vtable.
1078     llvm::MDNode *ContainingType = NULL;
1079     const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1080     if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
1081       // Seek non virtual primary base root.
1082       while (1) {
1083         const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
1084         const CXXRecordDecl *PBT = BRL.getPrimaryBase();
1085         if (PBT && !BRL.isPrimaryBaseVirtual())
1086           PBase = PBT;
1087         else
1088           break;
1089       }
1090       ContainingType =
1091         getOrCreateType(QualType(PBase->getTypeForDecl(), 0), Unit);
1092     }
1093     else if (CXXDecl->isDynamicClass())
1094       ContainingType = FwdDecl;
1095 
1096    RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
1097                                        Size, Align, 0, 0, llvm::DIType(),
1098                                        Elements, ContainingType,
1099                                        TParamsArray);
1100   } else
1101     RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line,
1102                                          Size, Align, 0, Elements);
1103 
1104   // Now that we have a real decl for the struct, replace anything using the
1105   // old decl with the new one.  This will recursively update the debug info.
1106   llvm::DIType(FwdDeclNode).replaceAllUsesWith(RealDecl);
1107   RegionMap[RD] = llvm::WeakVH(RealDecl);
1108   return llvm::DIType(RealDecl);
1109 }
1110 
1111 /// CreateType - get objective-c object type.
1112 llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1113                                      llvm::DIFile Unit) {
1114   // Ignore protocols.
1115   return getOrCreateType(Ty->getBaseType(), Unit);
1116 }
1117 
1118 /// CreateType - get objective-c interface type.
1119 llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1120                                      llvm::DIFile Unit) {
1121   ObjCInterfaceDecl *ID = Ty->getDecl();
1122   if (!ID)
1123     return llvm::DIType();
1124 
1125   // Get overall information about the record type for the debug info.
1126   llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1127   unsigned Line = getLineNumber(ID->getLocation());
1128   unsigned RuntimeLang = TheCU.getLanguage();
1129 
1130   // If this is just a forward declaration, return a special forward-declaration
1131   // debug type.
1132   if (ID->isForwardDecl()) {
1133     llvm::DIType FwdDecl =
1134       DBuilder.createStructType(Unit, ID->getName(),
1135                                 DefUnit, Line, 0, 0, 0,
1136                                 llvm::DIArray(), RuntimeLang);
1137     return FwdDecl;
1138   }
1139 
1140   // To handle recursive interface, we
1141   // first generate a debug descriptor for the struct as a forward declaration.
1142   // Then (if it is a definition) we go through and get debug info for all of
1143   // its members.  Finally, we create a descriptor for the complete type (which
1144   // may refer to the forward decl if the struct is recursive) and replace all
1145   // uses of the forward declaration with the final definition.
1146   llvm::DIType FwdDecl = DBuilder.createTemporaryType(DefUnit);
1147 
1148   llvm::MDNode *MN = FwdDecl;
1149   llvm::TrackingVH<llvm::MDNode> FwdDeclNode = MN;
1150   // Otherwise, insert it into the TypeCache so that recursive uses will find
1151   // it.
1152   TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1153   // Push the struct on region stack.
1154   RegionStack.push_back(FwdDeclNode);
1155   RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1156 
1157   // Convert all the elements.
1158   llvm::SmallVector<llvm::Value *, 16> EltTys;
1159 
1160   ObjCInterfaceDecl *SClass = ID->getSuperClass();
1161   if (SClass) {
1162     llvm::DIType SClassTy =
1163       getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1164     if (!SClassTy.isValid())
1165       return llvm::DIType();
1166 
1167     llvm::DIType InhTag =
1168       DBuilder.createInheritance(FwdDecl, SClassTy, 0, 0);
1169     EltTys.push_back(InhTag);
1170   }
1171 
1172   const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1173 
1174   unsigned FieldNo = 0;
1175   for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1176        Field = Field->getNextIvar(), ++FieldNo) {
1177     llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1178     if (!FieldTy.isValid())
1179       return llvm::DIType();
1180 
1181     llvm::StringRef FieldName = Field->getName();
1182 
1183     // Ignore unnamed fields.
1184     if (FieldName.empty())
1185       continue;
1186 
1187     // Get the location for the field.
1188     llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1189     unsigned FieldLine = getLineNumber(Field->getLocation());
1190     QualType FType = Field->getType();
1191     uint64_t FieldSize = 0;
1192     unsigned FieldAlign = 0;
1193 
1194     if (!FType->isIncompleteArrayType()) {
1195 
1196       // Bit size, align and offset of the type.
1197       FieldSize = CGM.getContext().getTypeSize(FType);
1198       Expr *BitWidth = Field->getBitWidth();
1199       if (BitWidth)
1200         FieldSize = BitWidth->EvaluateAsInt(CGM.getContext()).getZExtValue();
1201 
1202       FieldAlign =  CGM.getContext().getTypeAlign(FType);
1203     }
1204 
1205     uint64_t FieldOffset = RL.getFieldOffset(FieldNo);
1206 
1207     unsigned Flags = 0;
1208     if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1209       Flags = llvm::DIDescriptor::FlagProtected;
1210     else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1211       Flags = llvm::DIDescriptor::FlagPrivate;
1212 
1213     llvm::StringRef PropertyName;
1214     llvm::StringRef PropertyGetter;
1215     llvm::StringRef PropertySetter;
1216     unsigned PropertyAttributes = 0;
1217     if (ObjCPropertyDecl *PD =
1218         ID->FindPropertyVisibleInPrimaryClass(Field->getIdentifier())) {
1219       PropertyName = PD->getName();
1220       PropertyGetter = getSelectorName(PD->getGetterName());
1221       PropertySetter = getSelectorName(PD->getSetterName());
1222       PropertyAttributes = PD->getPropertyAttributes();
1223     }
1224     FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
1225                                       FieldLine, FieldSize, FieldAlign,
1226                                       FieldOffset, Flags, FieldTy,
1227                                       PropertyName, PropertyGetter,
1228                                       PropertySetter, PropertyAttributes);
1229     EltTys.push_back(FieldTy);
1230   }
1231 
1232   llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
1233 
1234   RegionStack.pop_back();
1235   llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator RI =
1236     RegionMap.find(Ty->getDecl());
1237   if (RI != RegionMap.end())
1238     RegionMap.erase(RI);
1239 
1240   // Bit size, align and offset of the type.
1241   uint64_t Size = CGM.getContext().getTypeSize(Ty);
1242   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1243 
1244   unsigned Flags = 0;
1245   if (ID->getImplementation())
1246     Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
1247 
1248   llvm::DIType RealDecl =
1249     DBuilder.createStructType(Unit, ID->getName(), DefUnit,
1250                                   Line, Size, Align, Flags,
1251                                   Elements, RuntimeLang);
1252 
1253   // Now that we have a real decl for the struct, replace anything using the
1254   // old decl with the new one.  This will recursively update the debug info.
1255   llvm::DIType(FwdDeclNode).replaceAllUsesWith(RealDecl);
1256   RegionMap[ID] = llvm::WeakVH(RealDecl);
1257 
1258   return RealDecl;
1259 }
1260 
1261 llvm::DIType CGDebugInfo::CreateType(const TagType *Ty) {
1262   if (const RecordType *RT = dyn_cast<RecordType>(Ty))
1263     return CreateType(RT);
1264   else if (const EnumType *ET = dyn_cast<EnumType>(Ty))
1265     return CreateEnumType(ET->getDecl());
1266 
1267   return llvm::DIType();
1268 }
1269 
1270 llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty,
1271                                      llvm::DIFile Unit) {
1272   llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1273   int64_t NumElems = Ty->getNumElements();
1274   int64_t LowerBound = 0;
1275   if (NumElems == 0)
1276     // If number of elements are not known then this is an unbounded array.
1277     // Use Low = 1, Hi = 0 to express such arrays.
1278     LowerBound = 1;
1279   else
1280     --NumElems;
1281 
1282   llvm::Value *Subscript = DBuilder.getOrCreateSubrange(LowerBound, NumElems);
1283   llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1284 
1285   uint64_t Size = CGM.getContext().getTypeSize(Ty);
1286   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1287 
1288   return
1289     DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1290 }
1291 
1292 llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1293                                      llvm::DIFile Unit) {
1294   uint64_t Size;
1295   uint64_t Align;
1296 
1297 
1298   // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1299   if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1300     Size = 0;
1301     Align =
1302       CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1303   } else if (Ty->isIncompleteArrayType()) {
1304     Size = 0;
1305     Align = CGM.getContext().getTypeAlign(Ty->getElementType());
1306   } else if (Ty->isDependentSizedArrayType() || Ty->isIncompleteType()) {
1307     Size = 0;
1308     Align = 0;
1309   } else {
1310     // Size and align of the whole array, not the element type.
1311     Size = CGM.getContext().getTypeSize(Ty);
1312     Align = CGM.getContext().getTypeAlign(Ty);
1313   }
1314 
1315   // Add the dimensions of the array.  FIXME: This loses CV qualifiers from
1316   // interior arrays, do we care?  Why aren't nested arrays represented the
1317   // obvious/recursive way?
1318   llvm::SmallVector<llvm::Value *, 8> Subscripts;
1319   QualType EltTy(Ty, 0);
1320   if (Ty->isIncompleteArrayType())
1321     EltTy = Ty->getElementType();
1322   else {
1323     while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1324       int64_t UpperBound = 0;
1325       int64_t LowerBound = 0;
1326       if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty)) {
1327         if (CAT->getSize().getZExtValue())
1328           UpperBound = CAT->getSize().getZExtValue() - 1;
1329       } else
1330         // This is an unbounded array. Use Low = 1, Hi = 0 to express such
1331         // arrays.
1332         LowerBound = 1;
1333 
1334       // FIXME: Verify this is right for VLAs.
1335       Subscripts.push_back(DBuilder.getOrCreateSubrange(LowerBound, UpperBound));
1336       EltTy = Ty->getElementType();
1337     }
1338   }
1339 
1340   llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1341 
1342   llvm::DIType DbgTy =
1343     DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1344                              SubscriptArray);
1345   return DbgTy;
1346 }
1347 
1348 llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
1349                                      llvm::DIFile Unit) {
1350   return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
1351                                Ty, Ty->getPointeeType(), Unit);
1352 }
1353 
1354 llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
1355                                      llvm::DIFile Unit) {
1356   return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
1357                                Ty, Ty->getPointeeType(), Unit);
1358 }
1359 
1360 llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
1361                                      llvm::DIFile U) {
1362   QualType PointerDiffTy = CGM.getContext().getPointerDiffType();
1363   llvm::DIType PointerDiffDITy = getOrCreateType(PointerDiffTy, U);
1364 
1365   if (!Ty->getPointeeType()->isFunctionType()) {
1366     // We have a data member pointer type.
1367     return PointerDiffDITy;
1368   }
1369 
1370   // We have a member function pointer type. Treat it as a struct with two
1371   // ptrdiff_t members.
1372   std::pair<uint64_t, unsigned> Info = CGM.getContext().getTypeInfo(Ty);
1373 
1374   uint64_t FieldOffset = 0;
1375   llvm::Value *ElementTypes[2];
1376 
1377   // FIXME: This should probably be a function type instead.
1378   ElementTypes[0] =
1379     DBuilder.createMemberType("ptr", U, 0,
1380                               Info.first, Info.second, FieldOffset, 0,
1381                               PointerDiffDITy);
1382   FieldOffset += Info.first;
1383 
1384   ElementTypes[1] =
1385     DBuilder.createMemberType("ptr", U, 0,
1386                               Info.first, Info.second, FieldOffset, 0,
1387                               PointerDiffDITy);
1388 
1389   llvm::DIArray Elements = DBuilder.getOrCreateArray(ElementTypes);
1390 
1391   return DBuilder.createStructType(U, llvm::StringRef("test"),
1392                                    U, 0, FieldOffset,
1393                                    0, 0, Elements);
1394 }
1395 
1396 /// CreateEnumType - get enumeration type.
1397 llvm::DIType CGDebugInfo::CreateEnumType(const EnumDecl *ED) {
1398   llvm::DIFile Unit = getOrCreateFile(ED->getLocation());
1399   llvm::SmallVector<llvm::Value *, 16> Enumerators;
1400 
1401   // Create DIEnumerator elements for each enumerator.
1402   for (EnumDecl::enumerator_iterator
1403          Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
1404        Enum != EnumEnd; ++Enum) {
1405     Enumerators.push_back(
1406       DBuilder.createEnumerator(Enum->getName(),
1407                                 Enum->getInitVal().getZExtValue()));
1408   }
1409 
1410   // Return a CompositeType for the enum itself.
1411   llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1412 
1413   llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1414   unsigned Line = getLineNumber(ED->getLocation());
1415   uint64_t Size = 0;
1416   uint64_t Align = 0;
1417   if (!ED->getTypeForDecl()->isIncompleteType()) {
1418     Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1419     Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1420   }
1421   llvm::DIDescriptor EnumContext =
1422     getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1423   llvm::DIType DbgTy =
1424     DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1425                                    Size, Align, EltArray);
1426   return DbgTy;
1427 }
1428 
1429 static QualType UnwrapTypeForDebugInfo(QualType T) {
1430   do {
1431     QualType LastT = T;
1432     switch (T->getTypeClass()) {
1433     default:
1434       return T;
1435     case Type::TemplateSpecialization:
1436       T = cast<TemplateSpecializationType>(T)->desugar();
1437       break;
1438     case Type::TypeOfExpr:
1439       T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1440       break;
1441     case Type::TypeOf:
1442       T = cast<TypeOfType>(T)->getUnderlyingType();
1443       break;
1444     case Type::Decltype:
1445       T = cast<DecltypeType>(T)->getUnderlyingType();
1446       break;
1447     case Type::UnaryTransform:
1448       T = cast<UnaryTransformType>(T)->getUnderlyingType();
1449       break;
1450     case Type::Attributed:
1451       T = cast<AttributedType>(T)->getEquivalentType();
1452       break;
1453     case Type::Elaborated:
1454       T = cast<ElaboratedType>(T)->getNamedType();
1455       break;
1456     case Type::Paren:
1457       T = cast<ParenType>(T)->getInnerType();
1458       break;
1459     case Type::SubstTemplateTypeParm:
1460       T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
1461       break;
1462     case Type::Auto:
1463       T = cast<AutoType>(T)->getDeducedType();
1464       break;
1465     }
1466 
1467     assert(T != LastT && "Type unwrapping failed to unwrap!");
1468     if (T == LastT)
1469       return T;
1470   } while (true);
1471 
1472   return T;
1473 }
1474 
1475 /// getOrCreateType - Get the type from the cache or create a new
1476 /// one if necessary.
1477 llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty,
1478                                           llvm::DIFile Unit) {
1479   if (Ty.isNull())
1480     return llvm::DIType();
1481 
1482   // Unwrap the type as needed for debug information.
1483   Ty = UnwrapTypeForDebugInfo(Ty);
1484 
1485   // Check for existing entry.
1486   llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1487     TypeCache.find(Ty.getAsOpaquePtr());
1488   if (it != TypeCache.end()) {
1489     // Verify that the debug info still exists.
1490     if (&*it->second)
1491       return llvm::DIType(cast<llvm::MDNode>(it->second));
1492   }
1493 
1494   // Otherwise create the type.
1495   llvm::DIType Res = CreateTypeNode(Ty, Unit);
1496 
1497   // And update the type cache.
1498   TypeCache[Ty.getAsOpaquePtr()] = Res;
1499   return Res;
1500 }
1501 
1502 /// CreateTypeNode - Create a new debug type node.
1503 llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty,
1504                                          llvm::DIFile Unit) {
1505   // Handle qualifiers, which recursively handles what they refer to.
1506   if (Ty.hasLocalQualifiers())
1507     return CreateQualifiedType(Ty, Unit);
1508 
1509   const char *Diag = 0;
1510 
1511   // Work out details of type.
1512   switch (Ty->getTypeClass()) {
1513 #define TYPE(Class, Base)
1514 #define ABSTRACT_TYPE(Class, Base)
1515 #define NON_CANONICAL_TYPE(Class, Base)
1516 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1517 #include "clang/AST/TypeNodes.def"
1518     assert(false && "Dependent types cannot show up in debug information");
1519 
1520   // FIXME: Handle these.
1521   case Type::ExtVector:
1522     return llvm::DIType();
1523 
1524   case Type::Vector:
1525     return CreateType(cast<VectorType>(Ty), Unit);
1526   case Type::ObjCObjectPointer:
1527     return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
1528   case Type::ObjCObject:
1529     return CreateType(cast<ObjCObjectType>(Ty), Unit);
1530   case Type::ObjCInterface:
1531     return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
1532   case Type::Builtin: return CreateType(cast<BuiltinType>(Ty));
1533   case Type::Complex: return CreateType(cast<ComplexType>(Ty));
1534   case Type::Pointer: return CreateType(cast<PointerType>(Ty), Unit);
1535   case Type::BlockPointer:
1536     return CreateType(cast<BlockPointerType>(Ty), Unit);
1537   case Type::Typedef: return CreateType(cast<TypedefType>(Ty), Unit);
1538   case Type::Record:
1539   case Type::Enum:
1540     return CreateType(cast<TagType>(Ty));
1541   case Type::FunctionProto:
1542   case Type::FunctionNoProto:
1543     return CreateType(cast<FunctionType>(Ty), Unit);
1544   case Type::ConstantArray:
1545   case Type::VariableArray:
1546   case Type::IncompleteArray:
1547     return CreateType(cast<ArrayType>(Ty), Unit);
1548 
1549   case Type::LValueReference:
1550     return CreateType(cast<LValueReferenceType>(Ty), Unit);
1551   case Type::RValueReference:
1552     return CreateType(cast<RValueReferenceType>(Ty), Unit);
1553 
1554   case Type::MemberPointer:
1555     return CreateType(cast<MemberPointerType>(Ty), Unit);
1556 
1557   case Type::Attributed:
1558   case Type::TemplateSpecialization:
1559   case Type::Elaborated:
1560   case Type::Paren:
1561   case Type::SubstTemplateTypeParm:
1562   case Type::TypeOfExpr:
1563   case Type::TypeOf:
1564   case Type::Decltype:
1565   case Type::UnaryTransform:
1566   case Type::Auto:
1567     llvm_unreachable("type should have been unwrapped!");
1568     return llvm::DIType();
1569   }
1570 
1571   assert(Diag && "Fall through without a diagnostic?");
1572   unsigned DiagID = CGM.getDiags().getCustomDiagID(Diagnostic::Error,
1573                                "debug information for %0 is not yet supported");
1574   CGM.getDiags().Report(DiagID)
1575     << Diag;
1576   return llvm::DIType();
1577 }
1578 
1579 /// CreateMemberType - Create new member and increase Offset by FType's size.
1580 llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
1581                                            llvm::StringRef Name,
1582                                            uint64_t *Offset) {
1583   llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1584   uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
1585   unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
1586   llvm::DIType Ty = DBuilder.createMemberType(Name, Unit, 0,
1587                                               FieldSize, FieldAlign,
1588                                               *Offset, 0, FieldTy);
1589   *Offset += FieldSize;
1590   return Ty;
1591 }
1592 
1593 /// getFunctionDeclaration - Return debug info descriptor to describe method
1594 /// declaration for the given method definition.
1595 llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
1596   const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
1597   if (!FD) return llvm::DISubprogram();
1598 
1599   // Setup context.
1600   getContextDescriptor(cast<Decl>(D->getDeclContext()));
1601 
1602   llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
1603     MI = SPCache.find(FD);
1604   if (MI != SPCache.end()) {
1605     llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(&*MI->second));
1606     if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
1607       return SP;
1608   }
1609 
1610   for (FunctionDecl::redecl_iterator I = FD->redecls_begin(),
1611          E = FD->redecls_end(); I != E; ++I) {
1612     const FunctionDecl *NextFD = *I;
1613     llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
1614       MI = SPCache.find(NextFD);
1615     if (MI != SPCache.end()) {
1616       llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(&*MI->second));
1617       if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
1618         return SP;
1619     }
1620   }
1621   return llvm::DISubprogram();
1622 }
1623 
1624 // getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
1625 // implicit parameter "this".
1626 llvm::DIType CGDebugInfo::getOrCreateFunctionType(const Decl * D, QualType FnType,
1627                                                   llvm::DIFile F) {
1628   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1629     return getOrCreateMethodType(Method, F);
1630   else if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
1631     // Add "self" and "_cmd"
1632     llvm::SmallVector<llvm::Value *, 16> Elts;
1633 
1634     // First element is always return type. For 'void' functions it is NULL.
1635     Elts.push_back(getOrCreateType(OMethod->getResultType(), F));
1636     // "self" pointer is always first argument.
1637     Elts.push_back(getOrCreateType(OMethod->getSelfDecl()->getType(), F));
1638     // "cmd" pointer is always second argument.
1639     Elts.push_back(getOrCreateType(OMethod->getCmdDecl()->getType(), F));
1640     // Get rest of the arguments.
1641     for (ObjCMethodDecl::param_iterator PI = OMethod->param_begin(),
1642            PE = OMethod->param_end(); PI != PE; ++PI)
1643       Elts.push_back(getOrCreateType((*PI)->getType(), F));
1644 
1645     llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
1646     return DBuilder.createSubroutineType(F, EltTypeArray);
1647   }
1648   return getOrCreateType(FnType, F);
1649 }
1650 
1651 /// EmitFunctionStart - Constructs the debug code for entering a function -
1652 /// "llvm.dbg.func.start.".
1653 void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
1654                                     llvm::Function *Fn,
1655                                     CGBuilderTy &Builder) {
1656 
1657   llvm::StringRef Name;
1658   llvm::StringRef LinkageName;
1659 
1660   FnBeginRegionCount.push_back(RegionStack.size());
1661 
1662   const Decl *D = GD.getDecl();
1663 
1664   unsigned Flags = 0;
1665   llvm::DIFile Unit = getOrCreateFile(CurLoc);
1666   llvm::DIDescriptor FDContext(Unit);
1667   llvm::DIArray TParamsArray;
1668   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1669     // If there is a DISubprogram for  this function available then use it.
1670     llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
1671       FI = SPCache.find(FD);
1672     if (FI != SPCache.end()) {
1673       llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(&*FI->second));
1674       if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
1675         llvm::MDNode *SPN = SP;
1676         RegionStack.push_back(SPN);
1677         RegionMap[D] = llvm::WeakVH(SP);
1678         return;
1679       }
1680     }
1681     Name = getFunctionName(FD);
1682     // Use mangled name as linkage name for c/c++ functions.
1683     if (!Fn->hasInternalLinkage())
1684       LinkageName = CGM.getMangledName(GD);
1685     if (LinkageName == Name)
1686       LinkageName = llvm::StringRef();
1687     if (FD->hasPrototype())
1688       Flags |= llvm::DIDescriptor::FlagPrototyped;
1689     if (const NamespaceDecl *NSDecl =
1690         dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
1691       FDContext = getOrCreateNameSpace(NSDecl);
1692     else if (const RecordDecl *RDecl =
1693              dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
1694       FDContext = getContextDescriptor(cast<Decl>(RDecl->getDeclContext()));
1695 
1696     // Collect template parameters.
1697     TParamsArray = CollectFunctionTemplateParams(FD, Unit);
1698   } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
1699     Name = getObjCMethodName(OMD);
1700     Flags |= llvm::DIDescriptor::FlagPrototyped;
1701   } else {
1702     // Use llvm function name.
1703     Name = Fn->getName();
1704     Flags |= llvm::DIDescriptor::FlagPrototyped;
1705   }
1706   if (!Name.empty() && Name[0] == '\01')
1707     Name = Name.substr(1);
1708 
1709   // It is expected that CurLoc is set before using EmitFunctionStart.
1710   // Usually, CurLoc points to the left bracket location of compound
1711   // statement representing function body.
1712   unsigned LineNo = getLineNumber(CurLoc);
1713   if (D->isImplicit())
1714     Flags |= llvm::DIDescriptor::FlagArtificial;
1715   llvm::DISubprogram SPDecl = getFunctionDeclaration(D);
1716   llvm::DISubprogram SP =
1717     DBuilder.createFunction(FDContext, Name, LinkageName, Unit,
1718                             LineNo, getOrCreateFunctionType(D, FnType, Unit),
1719                             Fn->hasInternalLinkage(), true/*definition*/,
1720                             Flags, CGM.getLangOptions().Optimize, Fn,
1721                             TParamsArray, SPDecl);
1722 
1723   // Push function on region stack.
1724   llvm::MDNode *SPN = SP;
1725   RegionStack.push_back(SPN);
1726   RegionMap[D] = llvm::WeakVH(SP);
1727 
1728   // Clear stack used to keep track of #line directives.
1729   LineDirectiveFiles.clear();
1730 }
1731 
1732 
1733 void CGDebugInfo::EmitStopPoint(CGBuilderTy &Builder) {
1734   if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
1735 
1736   // Don't bother if things are the same as last time.
1737   SourceManager &SM = CGM.getContext().getSourceManager();
1738   if (CurLoc == PrevLoc
1739        || (SM.getInstantiationLineNumber(CurLoc) ==
1740            SM.getInstantiationLineNumber(PrevLoc)
1741            && SM.isFromSameFile(CurLoc, PrevLoc)))
1742     // New Builder may not be in sync with CGDebugInfo.
1743     if (!Builder.getCurrentDebugLocation().isUnknown())
1744       return;
1745 
1746   // Update last state.
1747   PrevLoc = CurLoc;
1748 
1749   llvm::MDNode *Scope = RegionStack.back();
1750   Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(CurLoc),
1751                                                       getColumnNumber(CurLoc),
1752                                                       Scope));
1753 }
1754 
1755 /// UpdateLineDirectiveRegion - Update region stack only if #line directive
1756 /// has introduced scope change.
1757 void CGDebugInfo::UpdateLineDirectiveRegion(CGBuilderTy &Builder) {
1758   if (CurLoc.isInvalid() || CurLoc.isMacroID() ||
1759       PrevLoc.isInvalid() || PrevLoc.isMacroID())
1760     return;
1761   SourceManager &SM = CGM.getContext().getSourceManager();
1762   PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
1763   PresumedLoc PPLoc = SM.getPresumedLoc(PrevLoc);
1764 
1765   if (PCLoc.isInvalid() || PPLoc.isInvalid() ||
1766       !strcmp(PPLoc.getFilename(), PCLoc.getFilename()))
1767     return;
1768 
1769   // If #line directive stack is empty then we are entering a new scope.
1770   if (LineDirectiveFiles.empty()) {
1771     EmitRegionStart(Builder);
1772     LineDirectiveFiles.push_back(PCLoc.getFilename());
1773     return;
1774   }
1775 
1776   assert (RegionStack.size() >= LineDirectiveFiles.size()
1777           && "error handling  #line regions!");
1778 
1779   bool SeenThisFile = false;
1780   // Chek if current file is already seen earlier.
1781   for(std::vector<const char *>::iterator I = LineDirectiveFiles.begin(),
1782         E = LineDirectiveFiles.end(); I != E; ++I)
1783     if (!strcmp(PCLoc.getFilename(), *I)) {
1784       SeenThisFile = true;
1785       break;
1786     }
1787 
1788   // If #line for this file is seen earlier then pop out #line regions.
1789   if (SeenThisFile) {
1790     while (!LineDirectiveFiles.empty()) {
1791       const char *LastFile = LineDirectiveFiles.back();
1792       RegionStack.pop_back();
1793       LineDirectiveFiles.pop_back();
1794       if (!strcmp(PPLoc.getFilename(), LastFile))
1795         break;
1796     }
1797     return;
1798   }
1799 
1800   // .. otherwise insert new #line region.
1801   EmitRegionStart(Builder);
1802   LineDirectiveFiles.push_back(PCLoc.getFilename());
1803 
1804   return;
1805 }
1806 /// EmitRegionStart- Constructs the debug code for entering a declarative
1807 /// region - "llvm.dbg.region.start.".
1808 void CGDebugInfo::EmitRegionStart(CGBuilderTy &Builder) {
1809   llvm::DIDescriptor D =
1810     DBuilder.createLexicalBlock(RegionStack.empty() ?
1811                                 llvm::DIDescriptor() :
1812                                 llvm::DIDescriptor(RegionStack.back()),
1813                                 getOrCreateFile(CurLoc),
1814                                 getLineNumber(CurLoc),
1815                                 getColumnNumber(CurLoc));
1816   llvm::MDNode *DN = D;
1817   RegionStack.push_back(DN);
1818 }
1819 
1820 /// EmitRegionEnd - Constructs the debug code for exiting a declarative
1821 /// region - "llvm.dbg.region.end."
1822 void CGDebugInfo::EmitRegionEnd(CGBuilderTy &Builder) {
1823   assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
1824 
1825   // Provide an region stop point.
1826   EmitStopPoint(Builder);
1827 
1828   RegionStack.pop_back();
1829 }
1830 
1831 /// EmitFunctionEnd - Constructs the debug code for exiting a function.
1832 void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
1833   assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
1834   unsigned RCount = FnBeginRegionCount.back();
1835   assert(RCount <= RegionStack.size() && "Region stack mismatch");
1836 
1837   // Pop all regions for this function.
1838   while (RegionStack.size() != RCount)
1839     EmitRegionEnd(Builder);
1840   FnBeginRegionCount.pop_back();
1841 }
1842 
1843 // EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
1844 // See BuildByRefType.
1845 llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const ValueDecl *VD,
1846                                                        uint64_t *XOffset) {
1847 
1848   llvm::SmallVector<llvm::Value *, 5> EltTys;
1849   QualType FType;
1850   uint64_t FieldSize, FieldOffset;
1851   unsigned FieldAlign;
1852 
1853   llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
1854   QualType Type = VD->getType();
1855 
1856   FieldOffset = 0;
1857   FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1858   EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
1859   EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
1860   FType = CGM.getContext().IntTy;
1861   EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
1862   EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
1863 
1864   bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type);
1865   if (HasCopyAndDispose) {
1866     FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1867     EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
1868                                       &FieldOffset));
1869     EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
1870                                       &FieldOffset));
1871   }
1872 
1873   CharUnits Align = CGM.getContext().getDeclAlign(VD);
1874   if (Align > CGM.getContext().toCharUnitsFromBits(
1875         CGM.getContext().Target.getPointerAlign(0))) {
1876     CharUnits FieldOffsetInBytes
1877       = CGM.getContext().toCharUnitsFromBits(FieldOffset);
1878     CharUnits AlignedOffsetInBytes
1879       = FieldOffsetInBytes.RoundUpToAlignment(Align);
1880     CharUnits NumPaddingBytes
1881       = AlignedOffsetInBytes - FieldOffsetInBytes;
1882 
1883     if (NumPaddingBytes.isPositive()) {
1884       llvm::APInt pad(32, NumPaddingBytes.getQuantity());
1885       FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
1886                                                     pad, ArrayType::Normal, 0);
1887       EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
1888     }
1889   }
1890 
1891   FType = Type;
1892   llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1893   FieldSize = CGM.getContext().getTypeSize(FType);
1894   FieldAlign = CGM.getContext().toBits(Align);
1895 
1896   *XOffset = FieldOffset;
1897   FieldTy = DBuilder.createMemberType(VD->getName(), Unit,
1898                                       0, FieldSize, FieldAlign,
1899                                       FieldOffset, 0, FieldTy);
1900   EltTys.push_back(FieldTy);
1901   FieldOffset += FieldSize;
1902 
1903   llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
1904 
1905   unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
1906 
1907   return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
1908                                    Elements);
1909 }
1910 
1911 /// EmitDeclare - Emit local variable declaration debug info.
1912 void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
1913                               llvm::Value *Storage,
1914                               unsigned ArgNo, CGBuilderTy &Builder) {
1915   assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
1916 
1917   llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
1918   llvm::DIType Ty;
1919   uint64_t XOffset = 0;
1920   if (VD->hasAttr<BlocksAttr>())
1921     Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
1922   else
1923     Ty = getOrCreateType(VD->getType(), Unit);
1924 
1925   // If there is not any debug info for type then do not emit debug info
1926   // for this variable.
1927   if (!Ty)
1928     return;
1929 
1930   if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage)) {
1931     // If Storage is an aggregate returned as 'sret' then let debugger know
1932     // about this.
1933     if (Arg->hasStructRetAttr())
1934       Ty = DBuilder.createReferenceType(Ty);
1935     else if (CXXRecordDecl *Record = VD->getType()->getAsCXXRecordDecl()) {
1936       // If an aggregate variable has non trivial destructor or non trivial copy
1937       // constructor than it is pass indirectly. Let debug info know about this
1938       // by using reference of the aggregate type as a argument type.
1939       if (!Record->hasTrivialCopyConstructor() || !Record->hasTrivialDestructor())
1940         Ty = DBuilder.createReferenceType(Ty);
1941     }
1942   }
1943 
1944   // Get location information.
1945   unsigned Line = getLineNumber(VD->getLocation());
1946   unsigned Column = getColumnNumber(VD->getLocation());
1947   unsigned Flags = 0;
1948   if (VD->isImplicit())
1949     Flags |= llvm::DIDescriptor::FlagArtificial;
1950   llvm::MDNode *Scope = RegionStack.back();
1951 
1952   llvm::StringRef Name = VD->getName();
1953   if (!Name.empty()) {
1954     if (VD->hasAttr<BlocksAttr>()) {
1955       CharUnits offset = CharUnits::fromQuantity(32);
1956       llvm::SmallVector<llvm::Value *, 9> addr;
1957       const llvm::Type *Int64Ty = llvm::Type::getInt64Ty(CGM.getLLVMContext());
1958       addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
1959       // offset of __forwarding field
1960       offset = CGM.getContext().toCharUnitsFromBits(
1961         CGM.getContext().Target.getPointerWidth(0));
1962       addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
1963       addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
1964       addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
1965       // offset of x field
1966       offset = CGM.getContext().toCharUnitsFromBits(XOffset);
1967       addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
1968 
1969       // Create the descriptor for the variable.
1970       llvm::DIVariable D =
1971         DBuilder.createComplexVariable(Tag,
1972                                        llvm::DIDescriptor(RegionStack.back()),
1973                                        VD->getName(), Unit, Line, Ty,
1974                                        addr, ArgNo);
1975 
1976       // Insert an llvm.dbg.declare into the current block.
1977       llvm::Instruction *Call =
1978         DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
1979 
1980       Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
1981       return;
1982     }
1983       // Create the descriptor for the variable.
1984     llvm::DIVariable D =
1985       DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
1986                                    Name, Unit, Line, Ty,
1987                                    CGM.getLangOptions().Optimize, Flags, ArgNo);
1988 
1989     // Insert an llvm.dbg.declare into the current block.
1990     llvm::Instruction *Call =
1991       DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
1992 
1993     Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
1994     return;
1995   }
1996 
1997   // If VD is an anonymous union then Storage represents value for
1998   // all union fields.
1999   if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2000     const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
2001     if (RD->isUnion()) {
2002       for (RecordDecl::field_iterator I = RD->field_begin(),
2003              E = RD->field_end();
2004            I != E; ++I) {
2005         FieldDecl *Field = *I;
2006         llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2007         llvm::StringRef FieldName = Field->getName();
2008 
2009         // Ignore unnamed fields. Do not ignore unnamed records.
2010         if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2011           continue;
2012 
2013         // Use VarDecl's Tag, Scope and Line number.
2014         llvm::DIVariable D =
2015           DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2016                                        FieldName, Unit, Line, FieldTy,
2017                                        CGM.getLangOptions().Optimize, Flags,
2018                                        ArgNo);
2019 
2020         // Insert an llvm.dbg.declare into the current block.
2021         llvm::Instruction *Call =
2022           DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2023 
2024         Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2025       }
2026     }
2027   }
2028 }
2029 
2030 void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2031                                             llvm::Value *Storage,
2032                                             CGBuilderTy &Builder) {
2033   EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2034 }
2035 
2036 void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(
2037   const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder,
2038   const CGBlockInfo &blockInfo) {
2039   assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
2040 
2041   if (Builder.GetInsertBlock() == 0)
2042     return;
2043 
2044   bool isByRef = VD->hasAttr<BlocksAttr>();
2045 
2046   uint64_t XOffset = 0;
2047   llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2048   llvm::DIType Ty;
2049   if (isByRef)
2050     Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
2051   else
2052     Ty = getOrCreateType(VD->getType(), Unit);
2053 
2054   // Get location information.
2055   unsigned Line = getLineNumber(VD->getLocation());
2056   unsigned Column = getColumnNumber(VD->getLocation());
2057 
2058   const llvm::TargetData &target = CGM.getTargetData();
2059 
2060   CharUnits offset = CharUnits::fromQuantity(
2061     target.getStructLayout(blockInfo.StructureType)
2062           ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2063 
2064   llvm::SmallVector<llvm::Value *, 9> addr;
2065   const llvm::Type *Int64Ty = llvm::Type::getInt64Ty(CGM.getLLVMContext());
2066   addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2067   addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2068   if (isByRef) {
2069     addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2070     addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2071     // offset of __forwarding field
2072     offset = CGM.getContext().toCharUnitsFromBits(target.getPointerSizeInBits());
2073     addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2074     addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2075     addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2076     // offset of x field
2077     offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2078     addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2079   }
2080 
2081   // Create the descriptor for the variable.
2082   llvm::DIVariable D =
2083     DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable,
2084                                    llvm::DIDescriptor(RegionStack.back()),
2085                                    VD->getName(), Unit, Line, Ty, addr);
2086   // Insert an llvm.dbg.declare into the current block.
2087   llvm::Instruction *Call =
2088     DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
2089 
2090   llvm::MDNode *Scope = RegionStack.back();
2091   Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2092 }
2093 
2094 /// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2095 /// variable declaration.
2096 void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2097                                            unsigned ArgNo,
2098                                            CGBuilderTy &Builder) {
2099   EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2100 }
2101 
2102 namespace {
2103   struct BlockLayoutChunk {
2104     uint64_t OffsetInBits;
2105     const BlockDecl::Capture *Capture;
2106   };
2107   bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2108     return l.OffsetInBits < r.OffsetInBits;
2109   }
2110 }
2111 
2112 void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
2113                                                        llvm::Value *addr,
2114                                                        CGBuilderTy &Builder) {
2115   ASTContext &C = CGM.getContext();
2116   const BlockDecl *blockDecl = block.getBlockDecl();
2117 
2118   // Collect some general information about the block's location.
2119   SourceLocation loc = blockDecl->getCaretLocation();
2120   llvm::DIFile tunit = getOrCreateFile(loc);
2121   unsigned line = getLineNumber(loc);
2122   unsigned column = getColumnNumber(loc);
2123 
2124   // Build the debug-info type for the block literal.
2125   getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
2126 
2127   const llvm::StructLayout *blockLayout =
2128     CGM.getTargetData().getStructLayout(block.StructureType);
2129 
2130   llvm::SmallVector<llvm::Value*, 16> fields;
2131   fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
2132                                    blockLayout->getElementOffsetInBits(0),
2133                                    tunit));
2134   fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
2135                                    blockLayout->getElementOffsetInBits(1),
2136                                    tunit));
2137   fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
2138                                    blockLayout->getElementOffsetInBits(2),
2139                                    tunit));
2140   fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
2141                                    blockLayout->getElementOffsetInBits(3),
2142                                    tunit));
2143   fields.push_back(createFieldType("__descriptor",
2144                                    C.getPointerType(block.NeedsCopyDispose ?
2145                                         C.getBlockDescriptorExtendedType() :
2146                                         C.getBlockDescriptorType()),
2147                                    0, loc, AS_public,
2148                                    blockLayout->getElementOffsetInBits(4),
2149                                    tunit));
2150 
2151   // We want to sort the captures by offset, not because DWARF
2152   // requires this, but because we're paranoid about debuggers.
2153   llvm::SmallVector<BlockLayoutChunk, 8> chunks;
2154 
2155   // 'this' capture.
2156   if (blockDecl->capturesCXXThis()) {
2157     BlockLayoutChunk chunk;
2158     chunk.OffsetInBits =
2159       blockLayout->getElementOffsetInBits(block.CXXThisIndex);
2160     chunk.Capture = 0;
2161     chunks.push_back(chunk);
2162   }
2163 
2164   // Variable captures.
2165   for (BlockDecl::capture_const_iterator
2166          i = blockDecl->capture_begin(), e = blockDecl->capture_end();
2167        i != e; ++i) {
2168     const BlockDecl::Capture &capture = *i;
2169     const VarDecl *variable = capture.getVariable();
2170     const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
2171 
2172     // Ignore constant captures.
2173     if (captureInfo.isConstant())
2174       continue;
2175 
2176     BlockLayoutChunk chunk;
2177     chunk.OffsetInBits =
2178       blockLayout->getElementOffsetInBits(captureInfo.getIndex());
2179     chunk.Capture = &capture;
2180     chunks.push_back(chunk);
2181   }
2182 
2183   // Sort by offset.
2184   llvm::array_pod_sort(chunks.begin(), chunks.end());
2185 
2186   for (llvm::SmallVectorImpl<BlockLayoutChunk>::iterator
2187          i = chunks.begin(), e = chunks.end(); i != e; ++i) {
2188     uint64_t offsetInBits = i->OffsetInBits;
2189     const BlockDecl::Capture *capture = i->Capture;
2190 
2191     // If we have a null capture, this must be the C++ 'this' capture.
2192     if (!capture) {
2193       const CXXMethodDecl *method =
2194         cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
2195       QualType type = method->getThisType(C);
2196 
2197       fields.push_back(createFieldType("this", type, 0, loc, AS_public,
2198                                        offsetInBits, tunit));
2199       continue;
2200     }
2201 
2202     const VarDecl *variable = capture->getVariable();
2203     llvm::StringRef name = variable->getName();
2204 
2205     llvm::DIType fieldType;
2206     if (capture->isByRef()) {
2207       std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
2208 
2209       // FIXME: this creates a second copy of this type!
2210       uint64_t xoffset;
2211       fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
2212       fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
2213       fieldType = DBuilder.createMemberType(name, tunit, line,
2214                                             ptrInfo.first, ptrInfo.second,
2215                                             offsetInBits, 0, fieldType);
2216     } else {
2217       fieldType = createFieldType(name, variable->getType(), 0,
2218                                   loc, AS_public, offsetInBits, tunit);
2219     }
2220     fields.push_back(fieldType);
2221   }
2222 
2223   llvm::SmallString<36> typeName;
2224   llvm::raw_svector_ostream(typeName)
2225     << "__block_literal_" << CGM.getUniqueBlockCount();
2226 
2227   llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
2228 
2229   llvm::DIType type =
2230     DBuilder.createStructType(tunit, typeName.str(), tunit, line,
2231                               CGM.getContext().toBits(block.BlockSize),
2232                               CGM.getContext().toBits(block.BlockAlign),
2233                               0, fieldsArray);
2234   type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
2235 
2236   // Get overall information about the block.
2237   unsigned flags = llvm::DIDescriptor::FlagArtificial;
2238   llvm::MDNode *scope = RegionStack.back();
2239   llvm::StringRef name = ".block_descriptor";
2240 
2241   // Create the descriptor for the parameter.
2242   llvm::DIVariable debugVar =
2243     DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
2244                                  llvm::DIDescriptor(scope),
2245                                  name, tunit, line, type,
2246                                  CGM.getLangOptions().Optimize, flags,
2247                                  cast<llvm::Argument>(addr)->getArgNo() + 1);
2248 
2249   // Insert an llvm.dbg.value into the current block.
2250   llvm::Instruction *declare =
2251     DBuilder.insertDbgValueIntrinsic(addr, 0, debugVar,
2252                                      Builder.GetInsertBlock());
2253   declare->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
2254 }
2255 
2256 /// EmitGlobalVariable - Emit information about a global variable.
2257 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
2258                                      const VarDecl *D) {
2259 
2260   // Create global variable debug descriptor.
2261   llvm::DIFile Unit = getOrCreateFile(D->getLocation());
2262   unsigned LineNo = getLineNumber(D->getLocation());
2263 
2264   QualType T = D->getType();
2265   if (T->isIncompleteArrayType()) {
2266 
2267     // CodeGen turns int[] into int[1] so we'll do the same here.
2268     llvm::APSInt ConstVal(32);
2269 
2270     ConstVal = 1;
2271     QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
2272 
2273     T = CGM.getContext().getConstantArrayType(ET, ConstVal,
2274                                            ArrayType::Normal, 0);
2275   }
2276   llvm::StringRef DeclName = D->getName();
2277   llvm::StringRef LinkageName;
2278   if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext())
2279       && !isa<ObjCMethodDecl>(D->getDeclContext()))
2280     LinkageName = Var->getName();
2281   if (LinkageName == DeclName)
2282     LinkageName = llvm::StringRef();
2283   llvm::DIDescriptor DContext =
2284     getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
2285   DBuilder.createStaticVariable(DContext, DeclName, LinkageName,
2286                                 Unit, LineNo, getOrCreateType(T, Unit),
2287                                 Var->hasInternalLinkage(), Var);
2288 }
2289 
2290 /// EmitGlobalVariable - Emit information about an objective-c interface.
2291 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
2292                                      ObjCInterfaceDecl *ID) {
2293   // Create global variable debug descriptor.
2294   llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
2295   unsigned LineNo = getLineNumber(ID->getLocation());
2296 
2297   llvm::StringRef Name = ID->getName();
2298 
2299   QualType T = CGM.getContext().getObjCInterfaceType(ID);
2300   if (T->isIncompleteArrayType()) {
2301 
2302     // CodeGen turns int[] into int[1] so we'll do the same here.
2303     llvm::APSInt ConstVal(32);
2304 
2305     ConstVal = 1;
2306     QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
2307 
2308     T = CGM.getContext().getConstantArrayType(ET, ConstVal,
2309                                            ArrayType::Normal, 0);
2310   }
2311 
2312   DBuilder.createGlobalVariable(Name, Unit, LineNo,
2313                                 getOrCreateType(T, Unit),
2314                                 Var->hasInternalLinkage(), Var);
2315 }
2316 
2317 /// EmitGlobalVariable - Emit global variable's debug info.
2318 void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
2319                                      llvm::Constant *Init) {
2320   // Create the descriptor for the variable.
2321   llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2322   llvm::StringRef Name = VD->getName();
2323   llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
2324   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
2325     if (const EnumDecl *ED = dyn_cast<EnumDecl>(ECD->getDeclContext()))
2326       Ty = CreateEnumType(ED);
2327   }
2328   // Do not use DIGlobalVariable for enums.
2329   if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
2330     return;
2331   DBuilder.createStaticVariable(Unit, Name, Name, Unit,
2332                                 getLineNumber(VD->getLocation()),
2333                                 Ty, true, Init);
2334 }
2335 
2336 /// getOrCreateNamesSpace - Return namespace descriptor for the given
2337 /// namespace decl.
2338 llvm::DINameSpace
2339 CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
2340   llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
2341     NameSpaceCache.find(NSDecl);
2342   if (I != NameSpaceCache.end())
2343     return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
2344 
2345   unsigned LineNo = getLineNumber(NSDecl->getLocation());
2346   llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
2347   llvm::DIDescriptor Context =
2348     getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
2349   llvm::DINameSpace NS =
2350     DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
2351   NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
2352   return NS;
2353 }
2354 
2355 /// UpdateCompletedType - Update type cache because the type is now
2356 /// translated.
2357 void CGDebugInfo::UpdateCompletedType(const TagDecl *TD) {
2358   QualType Ty = CGM.getContext().getTagDeclType(TD);
2359 
2360   // If the type exist in type cache then remove it from the cache.
2361   // There is no need to prepare debug info for the completed type
2362   // right now. It will be generated on demand lazily.
2363   llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
2364     TypeCache.find(Ty.getAsOpaquePtr());
2365   if (it != TypeCache.end())
2366     TypeCache.erase(it);
2367 }
2368