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/Target/TargetData.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. If location is
258 /// invalid then use current location.
259 unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc) {
260   if (Loc.isInvalid() && CurLoc.isInvalid())
261     return 0;
262   SourceManager &SM = CGM.getContext().getSourceManager();
263   PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
264   return PLoc.isValid()? PLoc.getColumn() : 0;
265 }
266 
267 StringRef CGDebugInfo::getCurrentDirname() {
268   if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
269     return CGM.getCodeGenOpts().DebugCompilationDir;
270 
271   if (!CWDName.empty())
272     return CWDName;
273   SmallString<256> CWD;
274   llvm::sys::fs::current_path(CWD);
275   char *CompDirnamePtr = DebugInfoNames.Allocate<char>(CWD.size());
276   memcpy(CompDirnamePtr, CWD.data(), CWD.size());
277   return CWDName = StringRef(CompDirnamePtr, CWD.size());
278 }
279 
280 /// CreateCompileUnit - Create new compile unit.
281 void CGDebugInfo::CreateCompileUnit() {
282 
283   // Get absolute path name.
284   SourceManager &SM = CGM.getContext().getSourceManager();
285   std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
286   if (MainFileName.empty())
287     MainFileName = "<unknown>";
288 
289   // The main file name provided via the "-main-file-name" option contains just
290   // the file name itself with no path information. This file name may have had
291   // a relative path, so we look into the actual file entry for the main
292   // file to determine the real absolute path for the file.
293   std::string MainFileDir;
294   if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
295     MainFileDir = MainFile->getDir()->getName();
296     if (MainFileDir != ".")
297       MainFileName = MainFileDir + "/" + MainFileName;
298   }
299 
300   // Save filename string.
301   char *FilenamePtr = DebugInfoNames.Allocate<char>(MainFileName.length());
302   memcpy(FilenamePtr, MainFileName.c_str(), MainFileName.length());
303   StringRef Filename(FilenamePtr, MainFileName.length());
304 
305   unsigned LangTag;
306   const LangOptions &LO = CGM.getLangOpts();
307   if (LO.CPlusPlus) {
308     if (LO.ObjC1)
309       LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
310     else
311       LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
312   } else if (LO.ObjC1) {
313     LangTag = llvm::dwarf::DW_LANG_ObjC;
314   } else if (LO.C99) {
315     LangTag = llvm::dwarf::DW_LANG_C99;
316   } else {
317     LangTag = llvm::dwarf::DW_LANG_C89;
318   }
319 
320   std::string Producer = getClangFullVersion();
321 
322   // Figure out which version of the ObjC runtime we have.
323   unsigned RuntimeVers = 0;
324   if (LO.ObjC1)
325     RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
326 
327   // Create new compile unit.
328   DBuilder.createCompileUnit(
329     LangTag, Filename, getCurrentDirname(),
330     Producer,
331     LO.Optimize, CGM.getCodeGenOpts().DwarfDebugFlags, RuntimeVers);
332   // FIXME - Eliminate TheCU.
333   TheCU = llvm::DICompileUnit(DBuilder.getCU());
334 }
335 
336 /// CreateType - Get the Basic type from the cache or create a new
337 /// one if necessary.
338 llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT) {
339   unsigned Encoding = 0;
340   StringRef BTName;
341   switch (BT->getKind()) {
342 #define BUILTIN_TYPE(Id, SingletonId)
343 #define PLACEHOLDER_TYPE(Id, SingletonId) \
344   case BuiltinType::Id:
345 #include "clang/AST/BuiltinTypes.def"
346   case BuiltinType::Dependent:
347     llvm_unreachable("Unexpected builtin type");
348   case BuiltinType::NullPtr:
349     return DBuilder.
350       createNullPtrType(BT->getName(CGM.getContext().getLangOpts()));
351   case BuiltinType::Void:
352     return llvm::DIType();
353   case BuiltinType::ObjCClass:
354     if (ClassTy.Verify())
355       return ClassTy;
356     ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
357                                          "objc_class", TheCU,
358                                          getOrCreateMainFile(), 0);
359     return ClassTy;
360   case BuiltinType::ObjCId: {
361     // typedef struct objc_class *Class;
362     // typedef struct objc_object {
363     //  Class isa;
364     // } *id;
365 
366     if (ObjTy.Verify())
367       return ObjTy;
368 
369     if (!ClassTy.Verify())
370       ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
371                                            "objc_class", TheCU,
372                                            getOrCreateMainFile(), 0);
373 
374     unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
375 
376     llvm::DIType ISATy = DBuilder.createPointerType(ClassTy, Size);
377 
378     llvm::DIType FwdTy =  DBuilder.createStructType(TheCU, "objc_object",
379                                                     getOrCreateMainFile(),
380                                                     0, 0, 0, 0,
381                                                     llvm::DIArray());
382 
383     llvm::TrackingVH<llvm::MDNode> ObjNode(FwdTy);
384     SmallVector<llvm::Value *, 1> EltTys;
385     llvm::DIType FieldTy =
386       DBuilder.createMemberType(llvm::DIDescriptor(ObjNode), "isa",
387                                 getOrCreateMainFile(), 0, Size,
388                                 0, 0, 0, ISATy);
389     EltTys.push_back(FieldTy);
390     llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
391 
392     ObjNode->replaceOperandWith(10, Elements);
393     ObjTy = llvm::DIType(ObjNode);
394     return ObjTy;
395   }
396   case BuiltinType::ObjCSel: {
397     if (SelTy.Verify())
398       return SelTy;
399     SelTy =
400       DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
401                                  "objc_selector", TheCU, getOrCreateMainFile(),
402                                  0);
403     return SelTy;
404   }
405   case BuiltinType::UChar:
406   case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
407   case BuiltinType::Char_S:
408   case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
409   case BuiltinType::Char16:
410   case BuiltinType::Char32: Encoding = llvm::dwarf::DW_ATE_UTF; break;
411   case BuiltinType::UShort:
412   case BuiltinType::UInt:
413   case BuiltinType::UInt128:
414   case BuiltinType::ULong:
415   case BuiltinType::WChar_U:
416   case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
417   case BuiltinType::Short:
418   case BuiltinType::Int:
419   case BuiltinType::Int128:
420   case BuiltinType::Long:
421   case BuiltinType::WChar_S:
422   case BuiltinType::LongLong:  Encoding = llvm::dwarf::DW_ATE_signed; break;
423   case BuiltinType::Bool:      Encoding = llvm::dwarf::DW_ATE_boolean; break;
424   case BuiltinType::Half:
425   case BuiltinType::Float:
426   case BuiltinType::LongDouble:
427   case BuiltinType::Double:    Encoding = llvm::dwarf::DW_ATE_float; break;
428   }
429 
430   switch (BT->getKind()) {
431   case BuiltinType::Long:      BTName = "long int"; break;
432   case BuiltinType::LongLong:  BTName = "long long int"; break;
433   case BuiltinType::ULong:     BTName = "long unsigned int"; break;
434   case BuiltinType::ULongLong: BTName = "long long unsigned int"; break;
435   default:
436     BTName = BT->getName(CGM.getContext().getLangOpts());
437     break;
438   }
439   // Bit size, align and offset of the type.
440   uint64_t Size = CGM.getContext().getTypeSize(BT);
441   uint64_t Align = CGM.getContext().getTypeAlign(BT);
442   llvm::DIType DbgTy =
443     DBuilder.createBasicType(BTName, Size, Align, Encoding);
444   return DbgTy;
445 }
446 
447 llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty) {
448   // Bit size, align and offset of the type.
449   unsigned Encoding = llvm::dwarf::DW_ATE_complex_float;
450   if (Ty->isComplexIntegerType())
451     Encoding = llvm::dwarf::DW_ATE_lo_user;
452 
453   uint64_t Size = CGM.getContext().getTypeSize(Ty);
454   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
455   llvm::DIType DbgTy =
456     DBuilder.createBasicType("complex", Size, Align, Encoding);
457 
458   return DbgTy;
459 }
460 
461 /// CreateCVRType - Get the qualified type from the cache or create
462 /// a new one if necessary.
463 llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit) {
464   QualifierCollector Qc;
465   const Type *T = Qc.strip(Ty);
466 
467   // Ignore these qualifiers for now.
468   Qc.removeObjCGCAttr();
469   Qc.removeAddressSpace();
470   Qc.removeObjCLifetime();
471 
472   // We will create one Derived type for one qualifier and recurse to handle any
473   // additional ones.
474   unsigned Tag;
475   if (Qc.hasConst()) {
476     Tag = llvm::dwarf::DW_TAG_const_type;
477     Qc.removeConst();
478   } else if (Qc.hasVolatile()) {
479     Tag = llvm::dwarf::DW_TAG_volatile_type;
480     Qc.removeVolatile();
481   } else if (Qc.hasRestrict()) {
482     Tag = llvm::dwarf::DW_TAG_restrict_type;
483     Qc.removeRestrict();
484   } else {
485     assert(Qc.empty() && "Unknown type qualifier for debug info");
486     return getOrCreateType(QualType(T, 0), Unit);
487   }
488 
489   llvm::DIType FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
490 
491   // No need to fill in the Name, Line, Size, Alignment, Offset in case of
492   // CVR derived types.
493   llvm::DIType DbgTy = DBuilder.createQualifiedType(Tag, FromTy);
494 
495   return DbgTy;
496 }
497 
498 llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
499                                      llvm::DIFile Unit) {
500   llvm::DIType DbgTy =
501     CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
502                           Ty->getPointeeType(), Unit);
503   return DbgTy;
504 }
505 
506 llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
507                                      llvm::DIFile Unit) {
508   return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
509                                Ty->getPointeeType(), Unit);
510 }
511 
512 // Creates a forward declaration for a RecordDecl in the given context.
513 llvm::DIType CGDebugInfo::createRecordFwdDecl(const RecordDecl *RD,
514                                               llvm::DIDescriptor Ctx) {
515   llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
516   unsigned Line = getLineNumber(RD->getLocation());
517   StringRef RDName = RD->getName();
518 
519   // Get the tag.
520   const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
521   unsigned Tag = 0;
522   if (CXXDecl) {
523     RDName = getClassName(RD);
524     Tag = llvm::dwarf::DW_TAG_class_type;
525   }
526   else if (RD->isStruct() || RD->isInterface())
527     Tag = llvm::dwarf::DW_TAG_structure_type;
528   else if (RD->isUnion())
529     Tag = llvm::dwarf::DW_TAG_union_type;
530   else
531     llvm_unreachable("Unknown RecordDecl type!");
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().DebugInfo != 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->hasAttr<MsStructAttr>();
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       // Only emit debug information for user provided functions, we're
1028       // unlikely to want info for artificial functions.
1029       if (Method->isUserProvided())
1030         EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
1031     }
1032     else if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
1033       for (FunctionTemplateDecl::spec_iterator SI = FTD->spec_begin(),
1034              SE = FTD->spec_end(); SI != SE; ++SI)
1035         EltTys.push_back(CreateCXXMemberFunction(cast<CXXMethodDecl>(*SI), Unit,
1036                                                  RecordTy));
1037   }
1038 }
1039 
1040 /// CollectCXXFriends - A helper function to collect debug info for
1041 /// C++ base classes. This is used while creating debug info entry for
1042 /// a Record.
1043 void CGDebugInfo::
1044 CollectCXXFriends(const CXXRecordDecl *RD, llvm::DIFile Unit,
1045                 SmallVectorImpl<llvm::Value *> &EltTys,
1046                 llvm::DIType RecordTy) {
1047   for (CXXRecordDecl::friend_iterator BI = RD->friend_begin(),
1048          BE = RD->friend_end(); BI != BE; ++BI) {
1049     if ((*BI)->isUnsupportedFriend())
1050       continue;
1051     if (TypeSourceInfo *TInfo = (*BI)->getFriendType())
1052       EltTys.push_back(DBuilder.createFriend(RecordTy,
1053                                              getOrCreateType(TInfo->getType(),
1054                                                              Unit)));
1055   }
1056 }
1057 
1058 /// CollectCXXBases - A helper function to collect debug info for
1059 /// C++ base classes. This is used while creating debug info entry for
1060 /// a Record.
1061 void CGDebugInfo::
1062 CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
1063                 SmallVectorImpl<llvm::Value *> &EltTys,
1064                 llvm::DIType RecordTy) {
1065 
1066   const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1067   for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
1068          BE = RD->bases_end(); BI != BE; ++BI) {
1069     unsigned BFlags = 0;
1070     uint64_t BaseOffset;
1071 
1072     const CXXRecordDecl *Base =
1073       cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl());
1074 
1075     if (BI->isVirtual()) {
1076       // virtual base offset offset is -ve. The code generator emits dwarf
1077       // expression where it expects +ve number.
1078       BaseOffset =
1079         0 - CGM.getVTableContext()
1080                .getVirtualBaseOffsetOffset(RD, Base).getQuantity();
1081       BFlags = llvm::DIDescriptor::FlagVirtual;
1082     } else
1083       BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1084     // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1085     // BI->isVirtual() and bits when not.
1086 
1087     AccessSpecifier Access = BI->getAccessSpecifier();
1088     if (Access == clang::AS_private)
1089       BFlags |= llvm::DIDescriptor::FlagPrivate;
1090     else if (Access == clang::AS_protected)
1091       BFlags |= llvm::DIDescriptor::FlagProtected;
1092 
1093     llvm::DIType DTy =
1094       DBuilder.createInheritance(RecordTy,
1095                                  getOrCreateType(BI->getType(), Unit),
1096                                  BaseOffset, BFlags);
1097     EltTys.push_back(DTy);
1098   }
1099 }
1100 
1101 /// CollectTemplateParams - A helper function to collect template parameters.
1102 llvm::DIArray CGDebugInfo::
1103 CollectTemplateParams(const TemplateParameterList *TPList,
1104                       const TemplateArgumentList &TAList,
1105                       llvm::DIFile Unit) {
1106   SmallVector<llvm::Value *, 16> TemplateParams;
1107   for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1108     const TemplateArgument &TA = TAList[i];
1109     const NamedDecl *ND = TPList->getParam(i);
1110     if (TA.getKind() == TemplateArgument::Type) {
1111       llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit);
1112       llvm::DITemplateTypeParameter TTP =
1113         DBuilder.createTemplateTypeParameter(TheCU, ND->getName(), TTy);
1114       TemplateParams.push_back(TTP);
1115     } else if (TA.getKind() == TemplateArgument::Integral) {
1116       llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit);
1117       llvm::DITemplateValueParameter TVP =
1118         DBuilder.createTemplateValueParameter(TheCU, ND->getName(), TTy,
1119                                              TA.getAsIntegral().getZExtValue());
1120       TemplateParams.push_back(TVP);
1121     }
1122   }
1123   return DBuilder.getOrCreateArray(TemplateParams);
1124 }
1125 
1126 /// CollectFunctionTemplateParams - A helper function to collect debug
1127 /// info for function template parameters.
1128 llvm::DIArray CGDebugInfo::
1129 CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) {
1130   if (FD->getTemplatedKind() ==
1131       FunctionDecl::TK_FunctionTemplateSpecialization) {
1132     const TemplateParameterList *TList =
1133       FD->getTemplateSpecializationInfo()->getTemplate()
1134       ->getTemplateParameters();
1135     return
1136       CollectTemplateParams(TList, *FD->getTemplateSpecializationArgs(), Unit);
1137   }
1138   return llvm::DIArray();
1139 }
1140 
1141 /// CollectCXXTemplateParams - A helper function to collect debug info for
1142 /// template parameters.
1143 llvm::DIArray CGDebugInfo::
1144 CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial,
1145                          llvm::DIFile Unit) {
1146   llvm::PointerUnion<ClassTemplateDecl *,
1147                      ClassTemplatePartialSpecializationDecl *>
1148     PU = TSpecial->getSpecializedTemplateOrPartial();
1149 
1150   TemplateParameterList *TPList = PU.is<ClassTemplateDecl *>() ?
1151     PU.get<ClassTemplateDecl *>()->getTemplateParameters() :
1152     PU.get<ClassTemplatePartialSpecializationDecl *>()->getTemplateParameters();
1153   const TemplateArgumentList &TAList = TSpecial->getTemplateInstantiationArgs();
1154   return CollectTemplateParams(TPList, TAList, Unit);
1155 }
1156 
1157 /// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
1158 llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
1159   if (VTablePtrType.isValid())
1160     return VTablePtrType;
1161 
1162   ASTContext &Context = CGM.getContext();
1163 
1164   /* Function type */
1165   llvm::Value *STy = getOrCreateType(Context.IntTy, Unit);
1166   llvm::DIArray SElements = DBuilder.getOrCreateArray(STy);
1167   llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements);
1168   unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1169   llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0,
1170                                                           "__vtbl_ptr_type");
1171   VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1172   return VTablePtrType;
1173 }
1174 
1175 /// getVTableName - Get vtable name for the given Class.
1176 StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
1177   // Construct gdb compatible name name.
1178   std::string Name = "_vptr$" + RD->getNameAsString();
1179 
1180   // Copy this name on the side and use its reference.
1181   char *StrPtr = DebugInfoNames.Allocate<char>(Name.length());
1182   memcpy(StrPtr, Name.data(), Name.length());
1183   return StringRef(StrPtr, Name.length());
1184 }
1185 
1186 
1187 /// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
1188 /// debug info entry in EltTys vector.
1189 void CGDebugInfo::
1190 CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
1191                   SmallVectorImpl<llvm::Value *> &EltTys) {
1192   const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1193 
1194   // If there is a primary base then it will hold vtable info.
1195   if (RL.getPrimaryBase())
1196     return;
1197 
1198   // If this class is not dynamic then there is not any vtable info to collect.
1199   if (!RD->isDynamicClass())
1200     return;
1201 
1202   unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1203   llvm::DIType VPTR
1204     = DBuilder.createMemberType(Unit, getVTableName(RD), Unit,
1205                                 0, Size, 0, 0, 0,
1206                                 getOrCreateVTablePtrType(Unit));
1207   EltTys.push_back(VPTR);
1208 }
1209 
1210 /// getOrCreateRecordType - Emit record type's standalone debug info.
1211 llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy,
1212                                                 SourceLocation Loc) {
1213   assert(CGM.getCodeGenOpts().DebugInfo >= CodeGenOptions::LimitedDebugInfo);
1214   llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc));
1215   return T;
1216 }
1217 
1218 /// getOrCreateInterfaceType - Emit an objective c interface type standalone
1219 /// debug info.
1220 llvm::DIType CGDebugInfo::getOrCreateInterfaceType(QualType D,
1221 						   SourceLocation Loc) {
1222   assert(CGM.getCodeGenOpts().DebugInfo >= CodeGenOptions::LimitedDebugInfo);
1223   llvm::DIType T = getOrCreateType(D, getOrCreateFile(Loc));
1224   DBuilder.retainType(T);
1225   return T;
1226 }
1227 
1228 /// CreateType - get structure or union type.
1229 llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty) {
1230   RecordDecl *RD = Ty->getDecl();
1231 
1232   // Get overall information about the record type for the debug info.
1233   llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1234 
1235   // Records and classes and unions can all be recursive.  To handle them, we
1236   // first generate a debug descriptor for the struct as a forward declaration.
1237   // Then (if it is a definition) we go through and get debug info for all of
1238   // its members.  Finally, we create a descriptor for the complete type (which
1239   // may refer to the forward decl if the struct is recursive) and replace all
1240   // uses of the forward declaration with the final definition.
1241 
1242   llvm::DIType FwdDecl = getOrCreateLimitedType(QualType(Ty, 0), DefUnit);
1243 
1244   if (FwdDecl.isForwardDecl())
1245     return FwdDecl;
1246 
1247   llvm::TrackingVH<llvm::MDNode> FwdDeclNode(FwdDecl);
1248 
1249   // Push the struct on region stack.
1250   LexicalBlockStack.push_back(FwdDeclNode);
1251   RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1252 
1253   // Add this to the completed types cache since we're completing it.
1254   CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1255 
1256   // Convert all the elements.
1257   SmallVector<llvm::Value *, 16> EltTys;
1258 
1259   // Note: The split of CXXDecl information here is intentional, the
1260   // gdb tests will depend on a certain ordering at printout. The debug
1261   // information offsets are still correct if we merge them all together
1262   // though.
1263   const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1264   if (CXXDecl) {
1265     CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1266     CollectVTableInfo(CXXDecl, DefUnit, EltTys);
1267   }
1268 
1269   // Collect static variables with initializers and other fields.
1270   CollectRecordStaticVars(RD, FwdDecl);
1271   CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
1272   llvm::DIArray TParamsArray;
1273   if (CXXDecl) {
1274     CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
1275     CollectCXXFriends(CXXDecl, DefUnit, EltTys, FwdDecl);
1276     if (const ClassTemplateSpecializationDecl *TSpecial
1277         = dyn_cast<ClassTemplateSpecializationDecl>(RD))
1278       TParamsArray = CollectCXXTemplateParams(TSpecial, DefUnit);
1279   }
1280 
1281   LexicalBlockStack.pop_back();
1282   RegionMap.erase(Ty->getDecl());
1283 
1284   llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
1285   // FIXME: Magic numbers ahoy! These should be changed when we
1286   // get some enums in llvm/Analysis/DebugInfo.h to refer to
1287   // them.
1288   if (RD->isUnion())
1289     FwdDeclNode->replaceOperandWith(10, Elements);
1290   else if (CXXDecl) {
1291     FwdDeclNode->replaceOperandWith(10, Elements);
1292     FwdDeclNode->replaceOperandWith(13, TParamsArray);
1293   } else
1294     FwdDeclNode->replaceOperandWith(10, Elements);
1295 
1296   RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDeclNode);
1297   return llvm::DIType(FwdDeclNode);
1298 }
1299 
1300 /// CreateType - get objective-c object type.
1301 llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1302                                      llvm::DIFile Unit) {
1303   // Ignore protocols.
1304   return getOrCreateType(Ty->getBaseType(), Unit);
1305 }
1306 
1307 /// CreateType - get objective-c interface type.
1308 llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1309                                      llvm::DIFile Unit) {
1310   ObjCInterfaceDecl *ID = Ty->getDecl();
1311   if (!ID)
1312     return llvm::DIType();
1313 
1314   // Get overall information about the record type for the debug info.
1315   llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1316   unsigned Line = getLineNumber(ID->getLocation());
1317   unsigned RuntimeLang = TheCU.getLanguage();
1318 
1319   // If this is just a forward declaration return a special forward-declaration
1320   // debug type since we won't be able to lay out the entire type.
1321   ObjCInterfaceDecl *Def = ID->getDefinition();
1322   if (!Def) {
1323     llvm::DIType FwdDecl =
1324       DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
1325 				 ID->getName(), TheCU, DefUnit, Line,
1326 				 RuntimeLang);
1327     return FwdDecl;
1328   }
1329 
1330   ID = Def;
1331 
1332   // Bit size, align and offset of the type.
1333   uint64_t Size = CGM.getContext().getTypeSize(Ty);
1334   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1335 
1336   unsigned Flags = 0;
1337   if (ID->getImplementation())
1338     Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
1339 
1340   llvm::DIType RealDecl =
1341     DBuilder.createStructType(Unit, ID->getName(), DefUnit,
1342                               Line, Size, Align, Flags,
1343                               llvm::DIArray(), RuntimeLang);
1344 
1345   // Otherwise, insert it into the CompletedTypeCache so that recursive uses
1346   // will find it and we're emitting the complete type.
1347   CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl;
1348   // Push the struct on region stack.
1349   llvm::TrackingVH<llvm::MDNode> FwdDeclNode(RealDecl);
1350 
1351   LexicalBlockStack.push_back(FwdDeclNode);
1352   RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1353 
1354   // Convert all the elements.
1355   SmallVector<llvm::Value *, 16> EltTys;
1356 
1357   ObjCInterfaceDecl *SClass = ID->getSuperClass();
1358   if (SClass) {
1359     llvm::DIType SClassTy =
1360       getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1361     if (!SClassTy.isValid())
1362       return llvm::DIType();
1363 
1364     llvm::DIType InhTag =
1365       DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
1366     EltTys.push_back(InhTag);
1367   }
1368 
1369   for (ObjCContainerDecl::prop_iterator I = ID->prop_begin(),
1370          E = ID->prop_end(); I != E; ++I) {
1371     const ObjCPropertyDecl *PD = *I;
1372     SourceLocation Loc = PD->getLocation();
1373     llvm::DIFile PUnit = getOrCreateFile(Loc);
1374     unsigned PLine = getLineNumber(Loc);
1375     ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1376     ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1377     llvm::MDNode *PropertyNode =
1378       DBuilder.createObjCProperty(PD->getName(),
1379 				  PUnit, PLine,
1380                                   (Getter && Getter->isImplicit()) ? "" :
1381                                   getSelectorName(PD->getGetterName()),
1382                                   (Setter && Setter->isImplicit()) ? "" :
1383                                   getSelectorName(PD->getSetterName()),
1384                                   PD->getPropertyAttributes(),
1385 				  getOrCreateType(PD->getType(), PUnit));
1386     EltTys.push_back(PropertyNode);
1387   }
1388 
1389   const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1390   unsigned FieldNo = 0;
1391   for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1392        Field = Field->getNextIvar(), ++FieldNo) {
1393     llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1394     if (!FieldTy.isValid())
1395       return llvm::DIType();
1396 
1397     StringRef FieldName = Field->getName();
1398 
1399     // Ignore unnamed fields.
1400     if (FieldName.empty())
1401       continue;
1402 
1403     // Get the location for the field.
1404     llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1405     unsigned FieldLine = getLineNumber(Field->getLocation());
1406     QualType FType = Field->getType();
1407     uint64_t FieldSize = 0;
1408     unsigned FieldAlign = 0;
1409 
1410     if (!FType->isIncompleteArrayType()) {
1411 
1412       // Bit size, align and offset of the type.
1413       FieldSize = Field->isBitField()
1414         ? Field->getBitWidthValue(CGM.getContext())
1415         : CGM.getContext().getTypeSize(FType);
1416       FieldAlign = CGM.getContext().getTypeAlign(FType);
1417     }
1418 
1419     // We can't know the offset of our ivar in the structure if we're using
1420     // the non-fragile abi and the debugger should ignore the value anyways.
1421     // Call it the FieldNo+1 due to how debuggers use the information,
1422     // e.g. negating the value when it needs a lookup in the dynamic table.
1423     uint64_t FieldOffset = CGM.getLangOpts().ObjCRuntime.isNonFragile()
1424                              ? FieldNo+1 : RL.getFieldOffset(FieldNo);
1425 
1426     unsigned Flags = 0;
1427     if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1428       Flags = llvm::DIDescriptor::FlagProtected;
1429     else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1430       Flags = llvm::DIDescriptor::FlagPrivate;
1431 
1432     llvm::MDNode *PropertyNode = NULL;
1433     if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
1434       if (ObjCPropertyImplDecl *PImpD =
1435           ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
1436         if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
1437 	  SourceLocation Loc = PD->getLocation();
1438 	  llvm::DIFile PUnit = getOrCreateFile(Loc);
1439 	  unsigned PLine = getLineNumber(Loc);
1440           ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1441           ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1442           PropertyNode =
1443             DBuilder.createObjCProperty(PD->getName(),
1444                                         PUnit, PLine,
1445                                         (Getter && Getter->isImplicit()) ? "" :
1446                                         getSelectorName(PD->getGetterName()),
1447                                         (Setter && Setter->isImplicit()) ? "" :
1448                                         getSelectorName(PD->getSetterName()),
1449                                         PD->getPropertyAttributes(),
1450                                         getOrCreateType(PD->getType(), PUnit));
1451         }
1452       }
1453     }
1454     FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
1455                                       FieldLine, FieldSize, FieldAlign,
1456                                       FieldOffset, Flags, FieldTy,
1457                                       PropertyNode);
1458     EltTys.push_back(FieldTy);
1459   }
1460 
1461   llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
1462   FwdDeclNode->replaceOperandWith(10, Elements);
1463 
1464   LexicalBlockStack.pop_back();
1465   return llvm::DIType(FwdDeclNode);
1466 }
1467 
1468 llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) {
1469   llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1470   int64_t NumElems = Ty->getNumElements();
1471   int64_t LowerBound = 0;
1472   if (NumElems == 0)
1473     // If number of elements are not known then this is an unbounded array.
1474     // Use Low = 1, Hi = 0 to express such arrays.
1475     LowerBound = 1;
1476   else
1477     --NumElems;
1478 
1479   llvm::Value *Subscript = DBuilder.getOrCreateSubrange(LowerBound, NumElems);
1480   llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1481 
1482   uint64_t Size = CGM.getContext().getTypeSize(Ty);
1483   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1484 
1485   return
1486     DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1487 }
1488 
1489 llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1490                                      llvm::DIFile Unit) {
1491   uint64_t Size;
1492   uint64_t Align;
1493 
1494   // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1495   if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1496     Size = 0;
1497     Align =
1498       CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1499   } else if (Ty->isIncompleteArrayType()) {
1500     Size = 0;
1501     if (Ty->getElementType()->isIncompleteType())
1502       Align = 0;
1503     else
1504       Align = CGM.getContext().getTypeAlign(Ty->getElementType());
1505   } else if (Ty->isDependentSizedArrayType() || Ty->isIncompleteType()) {
1506     Size = 0;
1507     Align = 0;
1508   } else {
1509     // Size and align of the whole array, not the element type.
1510     Size = CGM.getContext().getTypeSize(Ty);
1511     Align = CGM.getContext().getTypeAlign(Ty);
1512   }
1513 
1514   // Add the dimensions of the array.  FIXME: This loses CV qualifiers from
1515   // interior arrays, do we care?  Why aren't nested arrays represented the
1516   // obvious/recursive way?
1517   SmallVector<llvm::Value *, 8> Subscripts;
1518   QualType EltTy(Ty, 0);
1519   while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1520     int64_t UpperBound = 0;
1521     int64_t LowerBound = 0;
1522     if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty)) {
1523       if (CAT->getSize().getZExtValue())
1524         UpperBound = CAT->getSize().getZExtValue() - 1;
1525     } else
1526       // This is an unbounded array. Use Low = 1, Hi = 0 to express such
1527       // arrays.
1528       LowerBound = 1;
1529 
1530     // FIXME: Verify this is right for VLAs.
1531     Subscripts.push_back(DBuilder.getOrCreateSubrange(LowerBound,
1532                                                       UpperBound));
1533     EltTy = Ty->getElementType();
1534   }
1535 
1536   llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1537 
1538   llvm::DIType DbgTy =
1539     DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1540                              SubscriptArray);
1541   return DbgTy;
1542 }
1543 
1544 llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
1545                                      llvm::DIFile Unit) {
1546   return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
1547                                Ty, Ty->getPointeeType(), Unit);
1548 }
1549 
1550 llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
1551                                      llvm::DIFile Unit) {
1552   return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
1553                                Ty, Ty->getPointeeType(), Unit);
1554 }
1555 
1556 llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
1557                                      llvm::DIFile U) {
1558   QualType PointerDiffTy = CGM.getContext().getPointerDiffType();
1559   llvm::DIType PointerDiffDITy = getOrCreateType(PointerDiffTy, U);
1560 
1561   if (!Ty->getPointeeType()->isFunctionType()) {
1562     // We have a data member pointer type.
1563     return PointerDiffDITy;
1564   }
1565 
1566   // We have a member function pointer type. Treat it as a struct with two
1567   // ptrdiff_t members.
1568   std::pair<uint64_t, unsigned> Info = CGM.getContext().getTypeInfo(Ty);
1569 
1570   uint64_t FieldOffset = 0;
1571   llvm::Value *ElementTypes[2];
1572 
1573   // FIXME: This should be a DW_TAG_pointer_to_member type.
1574   ElementTypes[0] =
1575     DBuilder.createMemberType(U, "ptr", U, 0,
1576                               Info.first, Info.second, FieldOffset, 0,
1577                               PointerDiffDITy);
1578   FieldOffset += Info.first;
1579 
1580   ElementTypes[1] =
1581     DBuilder.createMemberType(U, "ptr", U, 0,
1582                               Info.first, Info.second, FieldOffset, 0,
1583                               PointerDiffDITy);
1584 
1585   llvm::DIArray Elements = DBuilder.getOrCreateArray(ElementTypes);
1586 
1587   return DBuilder.createStructType(U, StringRef("test"),
1588                                    U, 0, FieldOffset,
1589                                    0, 0, Elements);
1590 }
1591 
1592 llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty,
1593                                      llvm::DIFile U) {
1594   // Ignore the atomic wrapping
1595   // FIXME: What is the correct representation?
1596   return getOrCreateType(Ty->getValueType(), U);
1597 }
1598 
1599 /// CreateEnumType - get enumeration type.
1600 llvm::DIType CGDebugInfo::CreateEnumType(const EnumDecl *ED) {
1601   SmallVector<llvm::Value *, 16> Enumerators;
1602 
1603   // Create DIEnumerator elements for each enumerator.
1604   for (EnumDecl::enumerator_iterator
1605          Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
1606        Enum != EnumEnd; ++Enum) {
1607     Enumerators.push_back(
1608       DBuilder.createEnumerator(Enum->getName(),
1609                                 Enum->getInitVal().getZExtValue()));
1610   }
1611 
1612   // Return a CompositeType for the enum itself.
1613   llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1614 
1615   llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1616   unsigned Line = getLineNumber(ED->getLocation());
1617   uint64_t Size = 0;
1618   uint64_t Align = 0;
1619   if (!ED->getTypeForDecl()->isIncompleteType()) {
1620     Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1621     Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1622   }
1623   llvm::DIDescriptor EnumContext =
1624     getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1625   llvm::DIType ClassTy = ED->isScopedUsingClassTag() ?
1626     getOrCreateType(ED->getIntegerType(), DefUnit) : llvm::DIType();
1627   unsigned Flags = !ED->isCompleteDefinition() ? llvm::DIDescriptor::FlagFwdDecl : 0;
1628   llvm::DIType DbgTy =
1629     DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1630                                    Size, Align, EltArray,
1631                                    ClassTy, Flags);
1632   return DbgTy;
1633 }
1634 
1635 static QualType UnwrapTypeForDebugInfo(QualType T) {
1636   do {
1637     QualType LastT = T;
1638     switch (T->getTypeClass()) {
1639     default:
1640       return T;
1641     case Type::TemplateSpecialization:
1642       T = cast<TemplateSpecializationType>(T)->desugar();
1643       break;
1644     case Type::TypeOfExpr:
1645       T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1646       break;
1647     case Type::TypeOf:
1648       T = cast<TypeOfType>(T)->getUnderlyingType();
1649       break;
1650     case Type::Decltype:
1651       T = cast<DecltypeType>(T)->getUnderlyingType();
1652       break;
1653     case Type::UnaryTransform:
1654       T = cast<UnaryTransformType>(T)->getUnderlyingType();
1655       break;
1656     case Type::Attributed:
1657       T = cast<AttributedType>(T)->getEquivalentType();
1658       break;
1659     case Type::Elaborated:
1660       T = cast<ElaboratedType>(T)->getNamedType();
1661       break;
1662     case Type::Paren:
1663       T = cast<ParenType>(T)->getInnerType();
1664       break;
1665     case Type::SubstTemplateTypeParm: {
1666       // We need to keep the qualifiers handy since getReplacementType()
1667       // will strip them away.
1668       unsigned Quals = T.getLocalFastQualifiers();
1669       T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
1670       T.addFastQualifiers(Quals);
1671     }
1672       break;
1673     case Type::Auto:
1674       T = cast<AutoType>(T)->getDeducedType();
1675       break;
1676     }
1677 
1678     assert(T != LastT && "Type unwrapping failed to unwrap!");
1679     if (T == LastT)
1680       return T;
1681   } while (true);
1682 }
1683 
1684 /// getType - Get the type from the cache or return null type if it doesn't exist.
1685 llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) {
1686 
1687   // Unwrap the type as needed for debug information.
1688   Ty = UnwrapTypeForDebugInfo(Ty);
1689 
1690   // Check for existing entry.
1691   llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1692     TypeCache.find(Ty.getAsOpaquePtr());
1693   if (it != TypeCache.end()) {
1694     // Verify that the debug info still exists.
1695     if (llvm::Value *V = it->second)
1696       return llvm::DIType(cast<llvm::MDNode>(V));
1697   }
1698 
1699   return llvm::DIType();
1700 }
1701 
1702 /// getCompletedTypeOrNull - Get the type from the cache or return null if it
1703 /// doesn't exist.
1704 llvm::DIType CGDebugInfo::getCompletedTypeOrNull(QualType Ty) {
1705 
1706   // Unwrap the type as needed for debug information.
1707   Ty = UnwrapTypeForDebugInfo(Ty);
1708 
1709   // Check for existing entry.
1710   llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1711     CompletedTypeCache.find(Ty.getAsOpaquePtr());
1712   if (it != CompletedTypeCache.end()) {
1713     // Verify that the debug info still exists.
1714     if (llvm::Value *V = it->second)
1715       return llvm::DIType(cast<llvm::MDNode>(V));
1716   }
1717 
1718   return llvm::DIType();
1719 }
1720 
1721 
1722 /// getOrCreateType - Get the type from the cache or create a new
1723 /// one if necessary.
1724 llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit) {
1725   if (Ty.isNull())
1726     return llvm::DIType();
1727 
1728   // Unwrap the type as needed for debug information.
1729   Ty = UnwrapTypeForDebugInfo(Ty);
1730 
1731   llvm::DIType T = getCompletedTypeOrNull(Ty);
1732 
1733   if (T.Verify())
1734     return T;
1735 
1736   // Otherwise create the type.
1737   llvm::DIType Res = CreateTypeNode(Ty, Unit);
1738 
1739   llvm::DIType TC = getTypeOrNull(Ty);
1740   if (TC.Verify() && TC.isForwardDecl())
1741     ReplaceMap.push_back(std::make_pair(Ty.getAsOpaquePtr(),
1742                                         static_cast<llvm::Value*>(TC)));
1743 
1744   // And update the type cache.
1745   TypeCache[Ty.getAsOpaquePtr()] = Res;
1746 
1747   if (!Res.isForwardDecl())
1748     CompletedTypeCache[Ty.getAsOpaquePtr()] = Res;
1749 
1750   return Res;
1751 }
1752 
1753 /// CreateTypeNode - Create a new debug type node.
1754 llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit) {
1755   // Handle qualifiers, which recursively handles what they refer to.
1756   if (Ty.hasLocalQualifiers())
1757     return CreateQualifiedType(Ty, Unit);
1758 
1759   const char *Diag = 0;
1760 
1761   // Work out details of type.
1762   switch (Ty->getTypeClass()) {
1763 #define TYPE(Class, Base)
1764 #define ABSTRACT_TYPE(Class, Base)
1765 #define NON_CANONICAL_TYPE(Class, Base)
1766 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1767 #include "clang/AST/TypeNodes.def"
1768     llvm_unreachable("Dependent types cannot show up in debug information");
1769 
1770   case Type::ExtVector:
1771   case Type::Vector:
1772     return CreateType(cast<VectorType>(Ty), Unit);
1773   case Type::ObjCObjectPointer:
1774     return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
1775   case Type::ObjCObject:
1776     return CreateType(cast<ObjCObjectType>(Ty), Unit);
1777   case Type::ObjCInterface:
1778     return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
1779   case Type::Builtin:
1780     return CreateType(cast<BuiltinType>(Ty));
1781   case Type::Complex:
1782     return CreateType(cast<ComplexType>(Ty));
1783   case Type::Pointer:
1784     return CreateType(cast<PointerType>(Ty), Unit);
1785   case Type::BlockPointer:
1786     return CreateType(cast<BlockPointerType>(Ty), Unit);
1787   case Type::Typedef:
1788     return CreateType(cast<TypedefType>(Ty), Unit);
1789   case Type::Record:
1790     return CreateType(cast<RecordType>(Ty));
1791   case Type::Enum:
1792     return CreateEnumType(cast<EnumType>(Ty)->getDecl());
1793   case Type::FunctionProto:
1794   case Type::FunctionNoProto:
1795     return CreateType(cast<FunctionType>(Ty), Unit);
1796   case Type::ConstantArray:
1797   case Type::VariableArray:
1798   case Type::IncompleteArray:
1799     return CreateType(cast<ArrayType>(Ty), Unit);
1800 
1801   case Type::LValueReference:
1802     return CreateType(cast<LValueReferenceType>(Ty), Unit);
1803   case Type::RValueReference:
1804     return CreateType(cast<RValueReferenceType>(Ty), Unit);
1805 
1806   case Type::MemberPointer:
1807     return CreateType(cast<MemberPointerType>(Ty), Unit);
1808 
1809   case Type::Atomic:
1810     return CreateType(cast<AtomicType>(Ty), Unit);
1811 
1812   case Type::Attributed:
1813   case Type::TemplateSpecialization:
1814   case Type::Elaborated:
1815   case Type::Paren:
1816   case Type::SubstTemplateTypeParm:
1817   case Type::TypeOfExpr:
1818   case Type::TypeOf:
1819   case Type::Decltype:
1820   case Type::UnaryTransform:
1821   case Type::Auto:
1822     llvm_unreachable("type should have been unwrapped!");
1823   }
1824 
1825   assert(Diag && "Fall through without a diagnostic?");
1826   unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error,
1827                                "debug information for %0 is not yet supported");
1828   CGM.getDiags().Report(DiagID)
1829     << Diag;
1830   return llvm::DIType();
1831 }
1832 
1833 /// getOrCreateLimitedType - Get the type from the cache or create a new
1834 /// limited type if necessary.
1835 llvm::DIType CGDebugInfo::getOrCreateLimitedType(QualType Ty,
1836 						 llvm::DIFile Unit) {
1837   if (Ty.isNull())
1838     return llvm::DIType();
1839 
1840   // Unwrap the type as needed for debug information.
1841   Ty = UnwrapTypeForDebugInfo(Ty);
1842 
1843   llvm::DIType T = getTypeOrNull(Ty);
1844 
1845   // We may have cached a forward decl when we could have created
1846   // a non-forward decl. Go ahead and create a non-forward decl
1847   // now.
1848   if (T.Verify() && !T.isForwardDecl()) return T;
1849 
1850   // Otherwise create the type.
1851   llvm::DIType Res = CreateLimitedTypeNode(Ty, Unit);
1852 
1853   if (T.Verify() && T.isForwardDecl())
1854     ReplaceMap.push_back(std::make_pair(Ty.getAsOpaquePtr(),
1855                                         static_cast<llvm::Value*>(T)));
1856 
1857   // And update the type cache.
1858   TypeCache[Ty.getAsOpaquePtr()] = Res;
1859   return Res;
1860 }
1861 
1862 // TODO: Currently used for context chains when limiting debug info.
1863 llvm::DIType CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
1864   RecordDecl *RD = Ty->getDecl();
1865 
1866   // Get overall information about the record type for the debug info.
1867   llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1868   unsigned Line = getLineNumber(RD->getLocation());
1869   StringRef RDName = RD->getName();
1870 
1871   llvm::DIDescriptor RDContext;
1872   if (CGM.getCodeGenOpts().DebugInfo == CodeGenOptions::LimitedDebugInfo)
1873     RDContext = createContextChain(cast<Decl>(RD->getDeclContext()));
1874   else
1875     RDContext = getContextDescriptor(cast<Decl>(RD->getDeclContext()));
1876 
1877   // If this is just a forward declaration, construct an appropriately
1878   // marked node and just return it.
1879   if (!RD->getDefinition())
1880     return createRecordFwdDecl(RD, RDContext);
1881 
1882   uint64_t Size = CGM.getContext().getTypeSize(Ty);
1883   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1884   const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1885   llvm::TrackingVH<llvm::MDNode> RealDecl;
1886 
1887   if (RD->isUnion())
1888     RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
1889 					Size, Align, 0, llvm::DIArray());
1890   else if (CXXDecl) {
1891     RDName = getClassName(RD);
1892 
1893     // FIXME: This could be a struct type giving a default visibility different
1894     // than C++ class type, but needs llvm metadata changes first.
1895     RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
1896 					Size, Align, 0, 0, llvm::DIType(),
1897 					llvm::DIArray(), llvm::DIType(),
1898 					llvm::DIArray());
1899   } else
1900     RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line,
1901 					 Size, Align, 0, llvm::DIArray());
1902 
1903   RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1904   TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = llvm::DIType(RealDecl);
1905 
1906   if (CXXDecl) {
1907     // A class's primary base or the class itself contains the vtable.
1908     llvm::MDNode *ContainingType = NULL;
1909     const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1910     if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
1911       // Seek non virtual primary base root.
1912       while (1) {
1913 	const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
1914 	const CXXRecordDecl *PBT = BRL.getPrimaryBase();
1915 	if (PBT && !BRL.isPrimaryBaseVirtual())
1916 	  PBase = PBT;
1917 	else
1918 	  break;
1919       }
1920       ContainingType =
1921 	getOrCreateType(QualType(PBase->getTypeForDecl(), 0), DefUnit);
1922     }
1923     else if (CXXDecl->isDynamicClass())
1924       ContainingType = RealDecl;
1925 
1926     RealDecl->replaceOperandWith(12, ContainingType);
1927   }
1928   return llvm::DIType(RealDecl);
1929 }
1930 
1931 /// CreateLimitedTypeNode - Create a new debug type node, but only forward
1932 /// declare composite types that haven't been processed yet.
1933 llvm::DIType CGDebugInfo::CreateLimitedTypeNode(QualType Ty,llvm::DIFile Unit) {
1934 
1935   // Work out details of type.
1936   switch (Ty->getTypeClass()) {
1937 #define TYPE(Class, Base)
1938 #define ABSTRACT_TYPE(Class, Base)
1939 #define NON_CANONICAL_TYPE(Class, Base)
1940 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1941         #include "clang/AST/TypeNodes.def"
1942     llvm_unreachable("Dependent types cannot show up in debug information");
1943 
1944   case Type::Record:
1945     return CreateLimitedType(cast<RecordType>(Ty));
1946   default:
1947     return CreateTypeNode(Ty, Unit);
1948   }
1949 }
1950 
1951 /// CreateMemberType - Create new member and increase Offset by FType's size.
1952 llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
1953                                            StringRef Name,
1954                                            uint64_t *Offset) {
1955   llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1956   uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
1957   unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
1958   llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0,
1959                                               FieldSize, FieldAlign,
1960                                               *Offset, 0, FieldTy);
1961   *Offset += FieldSize;
1962   return Ty;
1963 }
1964 
1965 /// getFunctionDeclaration - Return debug info descriptor to describe method
1966 /// declaration for the given method definition.
1967 llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
1968   const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
1969   if (!FD) return llvm::DISubprogram();
1970 
1971   // Setup context.
1972   getContextDescriptor(cast<Decl>(D->getDeclContext()));
1973 
1974   llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
1975     MI = SPCache.find(FD->getCanonicalDecl());
1976   if (MI != SPCache.end()) {
1977     llvm::Value *V = MI->second;
1978     llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
1979     if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
1980       return SP;
1981   }
1982 
1983   for (FunctionDecl::redecl_iterator I = FD->redecls_begin(),
1984          E = FD->redecls_end(); I != E; ++I) {
1985     const FunctionDecl *NextFD = *I;
1986     llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
1987       MI = SPCache.find(NextFD->getCanonicalDecl());
1988     if (MI != SPCache.end()) {
1989       llvm::Value *V = MI->second;
1990       llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
1991       if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
1992         return SP;
1993     }
1994   }
1995   return llvm::DISubprogram();
1996 }
1997 
1998 // getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
1999 // implicit parameter "this".
2000 llvm::DIType CGDebugInfo::getOrCreateFunctionType(const Decl *D,
2001                                                   QualType FnType,
2002                                                   llvm::DIFile F) {
2003 
2004   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
2005     return getOrCreateMethodType(Method, F);
2006   if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
2007     // Add "self" and "_cmd"
2008     SmallVector<llvm::Value *, 16> Elts;
2009 
2010     // First element is always return type. For 'void' functions it is NULL.
2011     Elts.push_back(getOrCreateType(OMethod->getResultType(), F));
2012     // "self" pointer is always first argument.
2013     llvm::DIType SelfTy = getOrCreateType(OMethod->getSelfDecl()->getType(), F);
2014     Elts.push_back(DBuilder.createObjectPointerType(SelfTy));
2015     // "_cmd" pointer is always second argument.
2016     llvm::DIType CmdTy = getOrCreateType(OMethod->getCmdDecl()->getType(), F);
2017     Elts.push_back(DBuilder.createArtificialType(CmdTy));
2018     // Get rest of the arguments.
2019     for (ObjCMethodDecl::param_const_iterator PI = OMethod->param_begin(),
2020            PE = OMethod->param_end(); PI != PE; ++PI)
2021       Elts.push_back(getOrCreateType((*PI)->getType(), F));
2022 
2023     llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2024     return DBuilder.createSubroutineType(F, EltTypeArray);
2025   }
2026   return getOrCreateType(FnType, F);
2027 }
2028 
2029 /// EmitFunctionStart - Constructs the debug code for entering a function.
2030 void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
2031                                     llvm::Function *Fn,
2032                                     CGBuilderTy &Builder) {
2033 
2034   StringRef Name;
2035   StringRef LinkageName;
2036 
2037   FnBeginRegionCount.push_back(LexicalBlockStack.size());
2038 
2039   const Decl *D = GD.getDecl();
2040   // Use the location of the declaration.
2041   SourceLocation Loc = D->getLocation();
2042 
2043   unsigned Flags = 0;
2044   llvm::DIFile Unit = getOrCreateFile(Loc);
2045   llvm::DIDescriptor FDContext(Unit);
2046   llvm::DIArray TParamsArray;
2047   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2048     // If there is a DISubprogram for this function available then use it.
2049     llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2050       FI = SPCache.find(FD->getCanonicalDecl());
2051     if (FI != SPCache.end()) {
2052       llvm::Value *V = FI->second;
2053       llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(V));
2054       if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
2055         llvm::MDNode *SPN = SP;
2056         LexicalBlockStack.push_back(SPN);
2057         RegionMap[D] = llvm::WeakVH(SP);
2058         return;
2059       }
2060     }
2061     Name = getFunctionName(FD);
2062     // Use mangled name as linkage name for c/c++ functions.
2063     if (FD->hasPrototype()) {
2064       LinkageName = CGM.getMangledName(GD);
2065       Flags |= llvm::DIDescriptor::FlagPrototyped;
2066     }
2067     if (LinkageName == Name ||
2068         CGM.getCodeGenOpts().DebugInfo <= CodeGenOptions::DebugLineTablesOnly)
2069       LinkageName = StringRef();
2070 
2071     if (CGM.getCodeGenOpts().DebugInfo >= CodeGenOptions::LimitedDebugInfo) {
2072       if (const NamespaceDecl *NSDecl =
2073           dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
2074         FDContext = getOrCreateNameSpace(NSDecl);
2075       else if (const RecordDecl *RDecl =
2076                dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
2077         FDContext = getContextDescriptor(cast<Decl>(RDecl->getDeclContext()));
2078 
2079       // Collect template parameters.
2080       TParamsArray = CollectFunctionTemplateParams(FD, Unit);
2081     }
2082   } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
2083     Name = getObjCMethodName(OMD);
2084     Flags |= llvm::DIDescriptor::FlagPrototyped;
2085   } else {
2086     // Use llvm function name.
2087     Name = Fn->getName();
2088     Flags |= llvm::DIDescriptor::FlagPrototyped;
2089   }
2090   if (!Name.empty() && Name[0] == '\01')
2091     Name = Name.substr(1);
2092 
2093   unsigned LineNo = getLineNumber(Loc);
2094   if (D->isImplicit())
2095     Flags |= llvm::DIDescriptor::FlagArtificial;
2096 
2097   llvm::DIType DIFnType;
2098   llvm::DISubprogram SPDecl;
2099   if (CGM.getCodeGenOpts().DebugInfo >= CodeGenOptions::LimitedDebugInfo) {
2100     DIFnType = getOrCreateFunctionType(D, FnType, Unit);
2101     SPDecl = getFunctionDeclaration(D);
2102   } else {
2103     // Create fake but valid subroutine type. Otherwise
2104     // llvm::DISubprogram::Verify() would return false, and
2105     // subprogram DIE will miss DW_AT_decl_file and
2106     // DW_AT_decl_line fields.
2107     SmallVector<llvm::Value*, 16> Elts;
2108     llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2109     DIFnType = DBuilder.createSubroutineType(Unit, EltTypeArray);
2110   }
2111   llvm::DISubprogram SP;
2112   SP = DBuilder.createFunction(FDContext, Name, LinkageName, Unit,
2113                                LineNo, DIFnType,
2114                                Fn->hasInternalLinkage(), true/*definition*/,
2115                                getLineNumber(CurLoc), Flags,
2116                                CGM.getLangOpts().Optimize,
2117                                Fn, TParamsArray, SPDecl);
2118 
2119   // Push function on region stack.
2120   llvm::MDNode *SPN = SP;
2121   LexicalBlockStack.push_back(SPN);
2122   RegionMap[D] = llvm::WeakVH(SP);
2123 }
2124 
2125 /// EmitLocation - Emit metadata to indicate a change in line/column
2126 /// information in the source file.
2127 void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc) {
2128 
2129   // Update our current location
2130   setLocation(Loc);
2131 
2132   if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
2133 
2134   // Don't bother if things are the same as last time.
2135   SourceManager &SM = CGM.getContext().getSourceManager();
2136   if (CurLoc == PrevLoc ||
2137       SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc))
2138     // New Builder may not be in sync with CGDebugInfo.
2139     if (!Builder.getCurrentDebugLocation().isUnknown())
2140       return;
2141 
2142   // Update last state.
2143   PrevLoc = CurLoc;
2144 
2145   llvm::MDNode *Scope = LexicalBlockStack.back();
2146   Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(CurLoc),
2147                                                       getColumnNumber(CurLoc),
2148                                                       Scope));
2149 }
2150 
2151 /// CreateLexicalBlock - Creates a new lexical block node and pushes it on
2152 /// the stack.
2153 void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
2154   llvm::DIDescriptor D =
2155     DBuilder.createLexicalBlock(LexicalBlockStack.empty() ?
2156                                 llvm::DIDescriptor() :
2157                                 llvm::DIDescriptor(LexicalBlockStack.back()),
2158                                 getOrCreateFile(CurLoc),
2159                                 getLineNumber(CurLoc),
2160                                 getColumnNumber(CurLoc));
2161   llvm::MDNode *DN = D;
2162   LexicalBlockStack.push_back(DN);
2163 }
2164 
2165 /// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
2166 /// region - beginning of a DW_TAG_lexical_block.
2167 void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder, SourceLocation Loc) {
2168   // Set our current location.
2169   setLocation(Loc);
2170 
2171   // Create a new lexical block and push it on the stack.
2172   CreateLexicalBlock(Loc);
2173 
2174   // Emit a line table change for the current location inside the new scope.
2175   Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc),
2176                                   getColumnNumber(Loc),
2177                                   LexicalBlockStack.back()));
2178 }
2179 
2180 /// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative
2181 /// region - end of a DW_TAG_lexical_block.
2182 void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder, SourceLocation Loc) {
2183   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2184 
2185   // Provide an entry in the line table for the end of the block.
2186   EmitLocation(Builder, Loc);
2187 
2188   LexicalBlockStack.pop_back();
2189 }
2190 
2191 /// EmitFunctionEnd - Constructs the debug code for exiting a function.
2192 void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
2193   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2194   unsigned RCount = FnBeginRegionCount.back();
2195   assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
2196 
2197   // Pop all regions for this function.
2198   while (LexicalBlockStack.size() != RCount)
2199     EmitLexicalBlockEnd(Builder, CurLoc);
2200   FnBeginRegionCount.pop_back();
2201 }
2202 
2203 // EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
2204 // See BuildByRefType.
2205 llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const ValueDecl *VD,
2206                                                        uint64_t *XOffset) {
2207 
2208   SmallVector<llvm::Value *, 5> EltTys;
2209   QualType FType;
2210   uint64_t FieldSize, FieldOffset;
2211   unsigned FieldAlign;
2212 
2213   llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2214   QualType Type = VD->getType();
2215 
2216   FieldOffset = 0;
2217   FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2218   EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
2219   EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
2220   FType = CGM.getContext().IntTy;
2221   EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
2222   EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
2223 
2224   bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type);
2225   if (HasCopyAndDispose) {
2226     FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2227     EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
2228                                       &FieldOffset));
2229     EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
2230                                       &FieldOffset));
2231   }
2232 
2233   CharUnits Align = CGM.getContext().getDeclAlign(VD);
2234   if (Align > CGM.getContext().toCharUnitsFromBits(
2235         CGM.getContext().getTargetInfo().getPointerAlign(0))) {
2236     CharUnits FieldOffsetInBytes
2237       = CGM.getContext().toCharUnitsFromBits(FieldOffset);
2238     CharUnits AlignedOffsetInBytes
2239       = FieldOffsetInBytes.RoundUpToAlignment(Align);
2240     CharUnits NumPaddingBytes
2241       = AlignedOffsetInBytes - FieldOffsetInBytes;
2242 
2243     if (NumPaddingBytes.isPositive()) {
2244       llvm::APInt pad(32, NumPaddingBytes.getQuantity());
2245       FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
2246                                                     pad, ArrayType::Normal, 0);
2247       EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
2248     }
2249   }
2250 
2251   FType = Type;
2252   llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2253   FieldSize = CGM.getContext().getTypeSize(FType);
2254   FieldAlign = CGM.getContext().toBits(Align);
2255 
2256   *XOffset = FieldOffset;
2257   FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit,
2258                                       0, FieldSize, FieldAlign,
2259                                       FieldOffset, 0, FieldTy);
2260   EltTys.push_back(FieldTy);
2261   FieldOffset += FieldSize;
2262 
2263   llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
2264 
2265   unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
2266 
2267   return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
2268                                    Elements);
2269 }
2270 
2271 /// EmitDeclare - Emit local variable declaration debug info.
2272 void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
2273                               llvm::Value *Storage,
2274                               unsigned ArgNo, CGBuilderTy &Builder) {
2275   assert(CGM.getCodeGenOpts().DebugInfo >= CodeGenOptions::LimitedDebugInfo);
2276   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2277 
2278   llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2279   llvm::DIType Ty;
2280   uint64_t XOffset = 0;
2281   if (VD->hasAttr<BlocksAttr>())
2282     Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
2283   else
2284     Ty = getOrCreateType(VD->getType(), Unit);
2285 
2286   // If there is no debug info for this type then do not emit debug info
2287   // for this variable.
2288   if (!Ty)
2289     return;
2290 
2291   if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage)) {
2292     // If Storage is an aggregate returned as 'sret' then let debugger know
2293     // about this.
2294     if (Arg->hasStructRetAttr())
2295       Ty = DBuilder.createReferenceType(llvm::dwarf::DW_TAG_reference_type, Ty);
2296     else if (CXXRecordDecl *Record = VD->getType()->getAsCXXRecordDecl()) {
2297       // If an aggregate variable has non trivial destructor or non trivial copy
2298       // constructor than it is pass indirectly. Let debug info know about this
2299       // by using reference of the aggregate type as a argument type.
2300       if (!Record->hasTrivialCopyConstructor() ||
2301           !Record->hasTrivialDestructor())
2302         Ty = DBuilder.createReferenceType(llvm::dwarf::DW_TAG_reference_type, Ty);
2303     }
2304   }
2305 
2306   // Get location information.
2307   unsigned Line = getLineNumber(VD->getLocation());
2308   unsigned Column = getColumnNumber(VD->getLocation());
2309   unsigned Flags = 0;
2310   if (VD->isImplicit())
2311     Flags |= llvm::DIDescriptor::FlagArtificial;
2312   // If this is the first argument and it is implicit then
2313   // give it an object pointer flag.
2314   // FIXME: There has to be a better way to do this, but for static
2315   // functions there won't be an implicit param at arg1 and
2316   // otherwise it is 'self' or 'this'.
2317   if (isa<ImplicitParamDecl>(VD) && ArgNo == 1)
2318     Flags |= llvm::DIDescriptor::FlagObjectPointer;
2319 
2320   llvm::MDNode *Scope = LexicalBlockStack.back();
2321 
2322   StringRef Name = VD->getName();
2323   if (!Name.empty()) {
2324     if (VD->hasAttr<BlocksAttr>()) {
2325       CharUnits offset = CharUnits::fromQuantity(32);
2326       SmallVector<llvm::Value *, 9> addr;
2327       llvm::Type *Int64Ty = CGM.Int64Ty;
2328       addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2329       // offset of __forwarding field
2330       offset = CGM.getContext().toCharUnitsFromBits(
2331         CGM.getContext().getTargetInfo().getPointerWidth(0));
2332       addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2333       addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2334       addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2335       // offset of x field
2336       offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2337       addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2338 
2339       // Create the descriptor for the variable.
2340       llvm::DIVariable D =
2341         DBuilder.createComplexVariable(Tag,
2342                                        llvm::DIDescriptor(Scope),
2343                                        VD->getName(), Unit, Line, Ty,
2344                                        addr, ArgNo);
2345 
2346       // Insert an llvm.dbg.declare into the current block.
2347       llvm::Instruction *Call =
2348         DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2349       Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2350       return;
2351     } else if (isa<VariableArrayType>(VD->getType())) {
2352       // These are "complex" variables in that they need an op_deref.
2353       // Create the descriptor for the variable.
2354       llvm::Value *Addr = llvm::ConstantInt::get(CGM.Int64Ty,
2355                                                  llvm::DIBuilder::OpDeref);
2356       llvm::DIVariable D =
2357         DBuilder.createComplexVariable(Tag,
2358                                        llvm::DIDescriptor(Scope),
2359                                        Name, Unit, Line, Ty,
2360                                        Addr, ArgNo);
2361 
2362       // Insert an llvm.dbg.declare into the current block.
2363       llvm::Instruction *Call =
2364         DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2365       Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2366       return;
2367     }
2368 
2369     // Create the descriptor for the variable.
2370     llvm::DIVariable D =
2371       DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2372                                    Name, Unit, Line, Ty,
2373                                    CGM.getLangOpts().Optimize, Flags, ArgNo);
2374 
2375     // Insert an llvm.dbg.declare into the current block.
2376     llvm::Instruction *Call =
2377       DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2378     Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2379     return;
2380   }
2381 
2382   // If VD is an anonymous union then Storage represents value for
2383   // all union fields.
2384   if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2385     const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
2386     if (RD->isUnion()) {
2387       for (RecordDecl::field_iterator I = RD->field_begin(),
2388              E = RD->field_end();
2389            I != E; ++I) {
2390         FieldDecl *Field = *I;
2391         llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2392         StringRef FieldName = Field->getName();
2393 
2394         // Ignore unnamed fields. Do not ignore unnamed records.
2395         if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2396           continue;
2397 
2398         // Use VarDecl's Tag, Scope and Line number.
2399         llvm::DIVariable D =
2400           DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2401                                        FieldName, Unit, Line, FieldTy,
2402                                        CGM.getLangOpts().Optimize, Flags,
2403                                        ArgNo);
2404 
2405         // Insert an llvm.dbg.declare into the current block.
2406         llvm::Instruction *Call =
2407           DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2408         Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2409       }
2410     }
2411   }
2412 }
2413 
2414 void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2415                                             llvm::Value *Storage,
2416                                             CGBuilderTy &Builder) {
2417   assert(CGM.getCodeGenOpts().DebugInfo >= CodeGenOptions::LimitedDebugInfo);
2418   EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2419 }
2420 
2421 void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(
2422   const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder,
2423   const CGBlockInfo &blockInfo) {
2424   assert(CGM.getCodeGenOpts().DebugInfo >= CodeGenOptions::LimitedDebugInfo);
2425   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2426 
2427   if (Builder.GetInsertBlock() == 0)
2428     return;
2429 
2430   bool isByRef = VD->hasAttr<BlocksAttr>();
2431 
2432   uint64_t XOffset = 0;
2433   llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2434   llvm::DIType Ty;
2435   if (isByRef)
2436     Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
2437   else
2438     Ty = getOrCreateType(VD->getType(), Unit);
2439 
2440   // Get location information.
2441   unsigned Line = getLineNumber(VD->getLocation());
2442   unsigned Column = getColumnNumber(VD->getLocation());
2443 
2444   const llvm::TargetData &target = CGM.getTargetData();
2445 
2446   CharUnits offset = CharUnits::fromQuantity(
2447     target.getStructLayout(blockInfo.StructureType)
2448           ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2449 
2450   SmallVector<llvm::Value *, 9> addr;
2451   llvm::Type *Int64Ty = CGM.Int64Ty;
2452   addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2453   addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2454   if (isByRef) {
2455     addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2456     addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2457     // offset of __forwarding field
2458     offset = CGM.getContext()
2459                 .toCharUnitsFromBits(target.getPointerSizeInBits());
2460     addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2461     addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2462     addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2463     // offset of x field
2464     offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2465     addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2466   }
2467 
2468   // Create the descriptor for the variable.
2469   llvm::DIVariable D =
2470     DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable,
2471                                    llvm::DIDescriptor(LexicalBlockStack.back()),
2472                                    VD->getName(), Unit, Line, Ty, addr);
2473   // Insert an llvm.dbg.declare into the current block.
2474   llvm::Instruction *Call =
2475     DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
2476   Call->setDebugLoc(llvm::DebugLoc::get(Line, Column,
2477                                         LexicalBlockStack.back()));
2478 }
2479 
2480 /// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2481 /// variable declaration.
2482 void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2483                                            unsigned ArgNo,
2484                                            CGBuilderTy &Builder) {
2485   assert(CGM.getCodeGenOpts().DebugInfo >= CodeGenOptions::LimitedDebugInfo);
2486   EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2487 }
2488 
2489 namespace {
2490   struct BlockLayoutChunk {
2491     uint64_t OffsetInBits;
2492     const BlockDecl::Capture *Capture;
2493   };
2494   bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2495     return l.OffsetInBits < r.OffsetInBits;
2496   }
2497 }
2498 
2499 void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
2500                                                        llvm::Value *addr,
2501                                                        CGBuilderTy &Builder) {
2502   assert(CGM.getCodeGenOpts().DebugInfo >= CodeGenOptions::LimitedDebugInfo);
2503   ASTContext &C = CGM.getContext();
2504   const BlockDecl *blockDecl = block.getBlockDecl();
2505 
2506   // Collect some general information about the block's location.
2507   SourceLocation loc = blockDecl->getCaretLocation();
2508   llvm::DIFile tunit = getOrCreateFile(loc);
2509   unsigned line = getLineNumber(loc);
2510   unsigned column = getColumnNumber(loc);
2511 
2512   // Build the debug-info type for the block literal.
2513   getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
2514 
2515   const llvm::StructLayout *blockLayout =
2516     CGM.getTargetData().getStructLayout(block.StructureType);
2517 
2518   SmallVector<llvm::Value*, 16> fields;
2519   fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
2520                                    blockLayout->getElementOffsetInBits(0),
2521                                    tunit, tunit));
2522   fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
2523                                    blockLayout->getElementOffsetInBits(1),
2524                                    tunit, tunit));
2525   fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
2526                                    blockLayout->getElementOffsetInBits(2),
2527                                    tunit, tunit));
2528   fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
2529                                    blockLayout->getElementOffsetInBits(3),
2530                                    tunit, tunit));
2531   fields.push_back(createFieldType("__descriptor",
2532                                    C.getPointerType(block.NeedsCopyDispose ?
2533                                         C.getBlockDescriptorExtendedType() :
2534                                         C.getBlockDescriptorType()),
2535                                    0, loc, AS_public,
2536                                    blockLayout->getElementOffsetInBits(4),
2537                                    tunit, tunit));
2538 
2539   // We want to sort the captures by offset, not because DWARF
2540   // requires this, but because we're paranoid about debuggers.
2541   SmallVector<BlockLayoutChunk, 8> chunks;
2542 
2543   // 'this' capture.
2544   if (blockDecl->capturesCXXThis()) {
2545     BlockLayoutChunk chunk;
2546     chunk.OffsetInBits =
2547       blockLayout->getElementOffsetInBits(block.CXXThisIndex);
2548     chunk.Capture = 0;
2549     chunks.push_back(chunk);
2550   }
2551 
2552   // Variable captures.
2553   for (BlockDecl::capture_const_iterator
2554          i = blockDecl->capture_begin(), e = blockDecl->capture_end();
2555        i != e; ++i) {
2556     const BlockDecl::Capture &capture = *i;
2557     const VarDecl *variable = capture.getVariable();
2558     const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
2559 
2560     // Ignore constant captures.
2561     if (captureInfo.isConstant())
2562       continue;
2563 
2564     BlockLayoutChunk chunk;
2565     chunk.OffsetInBits =
2566       blockLayout->getElementOffsetInBits(captureInfo.getIndex());
2567     chunk.Capture = &capture;
2568     chunks.push_back(chunk);
2569   }
2570 
2571   // Sort by offset.
2572   llvm::array_pod_sort(chunks.begin(), chunks.end());
2573 
2574   for (SmallVectorImpl<BlockLayoutChunk>::iterator
2575          i = chunks.begin(), e = chunks.end(); i != e; ++i) {
2576     uint64_t offsetInBits = i->OffsetInBits;
2577     const BlockDecl::Capture *capture = i->Capture;
2578 
2579     // If we have a null capture, this must be the C++ 'this' capture.
2580     if (!capture) {
2581       const CXXMethodDecl *method =
2582         cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
2583       QualType type = method->getThisType(C);
2584 
2585       fields.push_back(createFieldType("this", type, 0, loc, AS_public,
2586                                        offsetInBits, tunit, tunit));
2587       continue;
2588     }
2589 
2590     const VarDecl *variable = capture->getVariable();
2591     StringRef name = variable->getName();
2592 
2593     llvm::DIType fieldType;
2594     if (capture->isByRef()) {
2595       std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
2596 
2597       // FIXME: this creates a second copy of this type!
2598       uint64_t xoffset;
2599       fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
2600       fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
2601       fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
2602                                             ptrInfo.first, ptrInfo.second,
2603                                             offsetInBits, 0, fieldType);
2604     } else {
2605       fieldType = createFieldType(name, variable->getType(), 0,
2606                                   loc, AS_public, offsetInBits, tunit, tunit);
2607     }
2608     fields.push_back(fieldType);
2609   }
2610 
2611   SmallString<36> typeName;
2612   llvm::raw_svector_ostream(typeName)
2613     << "__block_literal_" << CGM.getUniqueBlockCount();
2614 
2615   llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
2616 
2617   llvm::DIType type =
2618     DBuilder.createStructType(tunit, typeName.str(), tunit, line,
2619                               CGM.getContext().toBits(block.BlockSize),
2620                               CGM.getContext().toBits(block.BlockAlign),
2621                               0, fieldsArray);
2622   type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
2623 
2624   // Get overall information about the block.
2625   unsigned flags = llvm::DIDescriptor::FlagArtificial;
2626   llvm::MDNode *scope = LexicalBlockStack.back();
2627   StringRef name = ".block_descriptor";
2628 
2629   // Create the descriptor for the parameter.
2630   llvm::DIVariable debugVar =
2631     DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
2632                                  llvm::DIDescriptor(scope),
2633                                  name, tunit, line, type,
2634                                  CGM.getLangOpts().Optimize, flags,
2635                                  cast<llvm::Argument>(addr)->getArgNo() + 1);
2636 
2637   // Insert an llvm.dbg.value into the current block.
2638   llvm::Instruction *declare =
2639     DBuilder.insertDbgValueIntrinsic(addr, 0, debugVar,
2640                                      Builder.GetInsertBlock());
2641   declare->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
2642 }
2643 
2644 /// EmitGlobalVariable - Emit information about a global variable.
2645 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
2646                                      const VarDecl *D) {
2647   assert(CGM.getCodeGenOpts().DebugInfo >= CodeGenOptions::LimitedDebugInfo);
2648   // Create global variable debug descriptor.
2649   llvm::DIFile Unit = getOrCreateFile(D->getLocation());
2650   unsigned LineNo = getLineNumber(D->getLocation());
2651 
2652   setLocation(D->getLocation());
2653 
2654   QualType T = D->getType();
2655   if (T->isIncompleteArrayType()) {
2656 
2657     // CodeGen turns int[] into int[1] so we'll do the same here.
2658     llvm::APInt ConstVal(32, 1);
2659     QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
2660 
2661     T = CGM.getContext().getConstantArrayType(ET, ConstVal,
2662                                               ArrayType::Normal, 0);
2663   }
2664   StringRef DeclName = D->getName();
2665   StringRef LinkageName;
2666   if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext())
2667       && !isa<ObjCMethodDecl>(D->getDeclContext()))
2668     LinkageName = Var->getName();
2669   if (LinkageName == DeclName)
2670     LinkageName = StringRef();
2671   llvm::DIDescriptor DContext =
2672     getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
2673   DBuilder.createStaticVariable(DContext, DeclName, LinkageName,
2674                                 Unit, LineNo, getOrCreateType(T, Unit),
2675                                 Var->hasInternalLinkage(), Var);
2676 }
2677 
2678 /// EmitGlobalVariable - Emit information about an objective-c interface.
2679 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
2680                                      ObjCInterfaceDecl *ID) {
2681   assert(CGM.getCodeGenOpts().DebugInfo >= CodeGenOptions::LimitedDebugInfo);
2682   // Create global variable debug descriptor.
2683   llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
2684   unsigned LineNo = getLineNumber(ID->getLocation());
2685 
2686   StringRef Name = ID->getName();
2687 
2688   QualType T = CGM.getContext().getObjCInterfaceType(ID);
2689   if (T->isIncompleteArrayType()) {
2690 
2691     // CodeGen turns int[] into int[1] so we'll do the same here.
2692     llvm::APInt ConstVal(32, 1);
2693     QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
2694 
2695     T = CGM.getContext().getConstantArrayType(ET, ConstVal,
2696                                            ArrayType::Normal, 0);
2697   }
2698 
2699   DBuilder.createGlobalVariable(Name, Unit, LineNo,
2700                                 getOrCreateType(T, Unit),
2701                                 Var->hasInternalLinkage(), Var);
2702 }
2703 
2704 /// EmitGlobalVariable - Emit global variable's debug info.
2705 void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
2706                                      llvm::Constant *Init) {
2707   assert(CGM.getCodeGenOpts().DebugInfo >= CodeGenOptions::LimitedDebugInfo);
2708   // Create the descriptor for the variable.
2709   llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2710   StringRef Name = VD->getName();
2711   llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
2712   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
2713     const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext());
2714     assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
2715     Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
2716   }
2717   // Do not use DIGlobalVariable for enums.
2718   if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
2719     return;
2720   DBuilder.createStaticVariable(Unit, Name, Name, Unit,
2721                                 getLineNumber(VD->getLocation()),
2722                                 Ty, true, Init);
2723 }
2724 
2725 /// getOrCreateNamesSpace - Return namespace descriptor for the given
2726 /// namespace decl.
2727 llvm::DINameSpace
2728 CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
2729   llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
2730     NameSpaceCache.find(NSDecl);
2731   if (I != NameSpaceCache.end())
2732     return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
2733 
2734   unsigned LineNo = getLineNumber(NSDecl->getLocation());
2735   llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
2736   llvm::DIDescriptor Context =
2737     getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
2738   llvm::DINameSpace NS =
2739     DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
2740   NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
2741   return NS;
2742 }
2743 
2744 void CGDebugInfo::finalize(void) {
2745   for (std::vector<std::pair<void *, llvm::WeakVH> >::const_iterator VI
2746          = ReplaceMap.begin(), VE = ReplaceMap.end(); VI != VE; ++VI) {
2747     llvm::DIType Ty, RepTy;
2748     // Verify that the debug info still exists.
2749     if (llvm::Value *V = VI->second)
2750       Ty = llvm::DIType(cast<llvm::MDNode>(V));
2751 
2752     llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
2753       TypeCache.find(VI->first);
2754     if (it != TypeCache.end()) {
2755       // Verify that the debug info still exists.
2756       if (llvm::Value *V = it->second)
2757         RepTy = llvm::DIType(cast<llvm::MDNode>(V));
2758     }
2759 
2760     if (Ty.Verify() && Ty.isForwardDecl() && RepTy.Verify()) {
2761       Ty.replaceAllUsesWith(RepTy);
2762     }
2763   }
2764   DBuilder.finalize();
2765 }
2766