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