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 << ((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())
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       // TODO: Need to handle 'this' in some way by probably renaming the
797       // this of the lambda class and having a field member of 'this'.
798       if (C.capturesVariable()) {
799         VarDecl *V = C.getCapturedVar();
800         llvm::DIFile VUnit = getOrCreateFile(C.getLocation());
801         StringRef VName = V->getName();
802         uint64_t SizeInBitsOverride = 0;
803         if (Field->isBitField()) {
804           SizeInBitsOverride = Field->getBitWidthValue(CGM.getContext());
805           assert(SizeInBitsOverride && "found named 0-width bitfield");
806         }
807         llvm::DIType fieldType
808           = createFieldType(VName, Field->getType(), SizeInBitsOverride, C.getLocation(),
809                             Field->getAccess(), layout.getFieldOffset(fieldno),
810                             VUnit, RecordTy);
811         elements.push_back(fieldType);
812       }
813     }
814   } else {
815     bool IsMsStruct = record->hasAttr<MsStructAttr>();
816     const FieldDecl *LastFD = 0;
817     for (RecordDecl::field_iterator I = record->field_begin(),
818            E = record->field_end();
819          I != E; ++I, ++fieldNo) {
820       FieldDecl *field = *I;
821 
822       if (IsMsStruct) {
823         // Zero-length bitfields following non-bitfield members are ignored
824         if (CGM.getContext().ZeroBitfieldFollowsNonBitfield((field), LastFD)) {
825           --fieldNo;
826           continue;
827         }
828         LastFD = field;
829       }
830 
831       StringRef name = field->getName();
832       QualType type = field->getType();
833 
834       // Ignore unnamed fields unless they're anonymous structs/unions.
835       if (name.empty() && !type->isRecordType()) {
836         LastFD = field;
837         continue;
838       }
839 
840       uint64_t SizeInBitsOverride = 0;
841       if (field->isBitField()) {
842         SizeInBitsOverride = field->getBitWidthValue(CGM.getContext());
843         assert(SizeInBitsOverride && "found named 0-width bitfield");
844       }
845 
846       llvm::DIType fieldType
847         = createFieldType(name, type, SizeInBitsOverride,
848                           field->getLocation(), field->getAccess(),
849                           layout.getFieldOffset(fieldNo), tunit, RecordTy);
850 
851       elements.push_back(fieldType);
852     }
853   }
854 }
855 
856 /// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
857 /// function type is not updated to include implicit "this" pointer. Use this
858 /// routine to get a method type which includes "this" pointer.
859 llvm::DIType
860 CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
861                                    llvm::DIFile Unit) {
862   llvm::DIType FnTy
863     = getOrCreateType(QualType(Method->getType()->getAs<FunctionProtoType>(),
864                                0),
865                       Unit);
866 
867   // Add "this" pointer.
868   llvm::DIArray Args = llvm::DICompositeType(FnTy).getTypeArray();
869   assert (Args.getNumElements() && "Invalid number of arguments!");
870 
871   SmallVector<llvm::Value *, 16> Elts;
872 
873   // First element is always return type. For 'void' functions it is NULL.
874   Elts.push_back(Args.getElement(0));
875 
876   if (!Method->isStatic()) {
877     // "this" pointer is always first argument.
878     QualType ThisPtr = Method->getThisType(CGM.getContext());
879 
880     const CXXRecordDecl *RD = Method->getParent();
881     if (isa<ClassTemplateSpecializationDecl>(RD)) {
882       // Create pointer type directly in this case.
883       const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
884       QualType PointeeTy = ThisPtrTy->getPointeeType();
885       unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
886       uint64_t Size = CGM.getContext().getTargetInfo().getPointerWidth(AS);
887       uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy);
888       llvm::DIType PointeeType = getOrCreateType(PointeeTy, Unit);
889       llvm::DIType ThisPtrType = DBuilder.createPointerType(PointeeType, Size, Align);
890       TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
891       // TODO: This and the artificial type below are misleading, the
892       // types aren't artificial the argument is, but the current
893       // metadata doesn't represent that.
894       ThisPtrType = DBuilder.createArtificialType(ThisPtrType);
895       Elts.push_back(ThisPtrType);
896     } else {
897       llvm::DIType ThisPtrType = getOrCreateType(ThisPtr, Unit);
898       TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
899       ThisPtrType = DBuilder.createArtificialType(ThisPtrType);
900       Elts.push_back(ThisPtrType);
901     }
902   }
903 
904   // Copy rest of the arguments.
905   for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
906     Elts.push_back(Args.getElement(i));
907 
908   llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
909 
910   return DBuilder.createSubroutineType(Unit, EltTypeArray);
911 }
912 
913 /// isFunctionLocalClass - Return true if CXXRecordDecl is defined
914 /// inside a function.
915 static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
916   if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
917     return isFunctionLocalClass(NRD);
918   if (isa<FunctionDecl>(RD->getDeclContext()))
919     return true;
920   return false;
921 }
922 
923 /// CreateCXXMemberFunction - A helper function to create a DISubprogram for
924 /// a single member function GlobalDecl.
925 llvm::DISubprogram
926 CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
927                                      llvm::DIFile Unit,
928                                      llvm::DIType RecordTy) {
929   bool IsCtorOrDtor =
930     isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
931 
932   StringRef MethodName = getFunctionName(Method);
933   llvm::DIType MethodTy = getOrCreateMethodType(Method, Unit);
934 
935   // Since a single ctor/dtor corresponds to multiple functions, it doesn't
936   // make sense to give a single ctor/dtor a linkage name.
937   StringRef MethodLinkageName;
938   if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
939     MethodLinkageName = CGM.getMangledName(Method);
940 
941   // Get the location for the method.
942   llvm::DIFile MethodDefUnit = getOrCreateFile(Method->getLocation());
943   unsigned MethodLine = getLineNumber(Method->getLocation());
944 
945   // Collect virtual method info.
946   llvm::DIType ContainingType;
947   unsigned Virtuality = 0;
948   unsigned VIndex = 0;
949 
950   if (Method->isVirtual()) {
951     if (Method->isPure())
952       Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
953     else
954       Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
955 
956     // It doesn't make sense to give a virtual destructor a vtable index,
957     // since a single destructor has two entries in the vtable.
958     if (!isa<CXXDestructorDecl>(Method))
959       VIndex = CGM.getVTableContext().getMethodVTableIndex(Method);
960     ContainingType = RecordTy;
961   }
962 
963   unsigned Flags = 0;
964   if (Method->isImplicit())
965     Flags |= llvm::DIDescriptor::FlagArtificial;
966   AccessSpecifier Access = Method->getAccess();
967   if (Access == clang::AS_private)
968     Flags |= llvm::DIDescriptor::FlagPrivate;
969   else if (Access == clang::AS_protected)
970     Flags |= llvm::DIDescriptor::FlagProtected;
971   if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
972     if (CXXC->isExplicit())
973       Flags |= llvm::DIDescriptor::FlagExplicit;
974   } else if (const CXXConversionDecl *CXXC =
975              dyn_cast<CXXConversionDecl>(Method)) {
976     if (CXXC->isExplicit())
977       Flags |= llvm::DIDescriptor::FlagExplicit;
978   }
979   if (Method->hasPrototype())
980     Flags |= llvm::DIDescriptor::FlagPrototyped;
981 
982   llvm::DIArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
983   llvm::DISubprogram SP =
984     DBuilder.createMethod(RecordTy, MethodName, MethodLinkageName,
985                           MethodDefUnit, MethodLine,
986                           MethodTy, /*isLocalToUnit=*/false,
987                           /* isDefinition=*/ false,
988                           Virtuality, VIndex, ContainingType,
989                           Flags, CGM.getLangOpts().Optimize, NULL,
990                           TParamsArray);
991 
992   SPCache[Method->getCanonicalDecl()] = llvm::WeakVH(SP);
993 
994   return SP;
995 }
996 
997 /// CollectCXXMemberFunctions - A helper function to collect debug info for
998 /// C++ member functions. This is used while creating debug info entry for
999 /// a Record.
1000 void CGDebugInfo::
1001 CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
1002                           SmallVectorImpl<llvm::Value *> &EltTys,
1003                           llvm::DIType RecordTy) {
1004 
1005   // Since we want more than just the individual member decls if we
1006   // have templated functions iterate over every declaration to gather
1007   // the functions.
1008   for(DeclContext::decl_iterator I = RD->decls_begin(),
1009         E = RD->decls_end(); I != E; ++I) {
1010     Decl *D = *I;
1011     if (D->isImplicit() && !D->isUsed())
1012       continue;
1013 
1014     if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
1015       // Only emit debug information for user provided functions, we're
1016       // unlikely to want info for artificial functions.
1017       if (Method->isUserProvided())
1018         EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
1019     }
1020     else if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
1021       for (FunctionTemplateDecl::spec_iterator SI = FTD->spec_begin(),
1022              SE = FTD->spec_end(); SI != SE; ++SI)
1023         EltTys.push_back(CreateCXXMemberFunction(cast<CXXMethodDecl>(*SI), Unit,
1024                                                  RecordTy));
1025   }
1026 }
1027 
1028 /// CollectCXXFriends - A helper function to collect debug info for
1029 /// C++ base classes. This is used while creating debug info entry for
1030 /// a Record.
1031 void CGDebugInfo::
1032 CollectCXXFriends(const CXXRecordDecl *RD, llvm::DIFile Unit,
1033                 SmallVectorImpl<llvm::Value *> &EltTys,
1034                 llvm::DIType RecordTy) {
1035   for (CXXRecordDecl::friend_iterator BI = RD->friend_begin(),
1036          BE = RD->friend_end(); BI != BE; ++BI) {
1037     if ((*BI)->isUnsupportedFriend())
1038       continue;
1039     if (TypeSourceInfo *TInfo = (*BI)->getFriendType())
1040       EltTys.push_back(DBuilder.createFriend(RecordTy,
1041                                              getOrCreateType(TInfo->getType(),
1042                                                              Unit)));
1043   }
1044 }
1045 
1046 /// CollectCXXBases - A helper function to collect debug info for
1047 /// C++ base classes. This is used while creating debug info entry for
1048 /// a Record.
1049 void CGDebugInfo::
1050 CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
1051                 SmallVectorImpl<llvm::Value *> &EltTys,
1052                 llvm::DIType RecordTy) {
1053 
1054   const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1055   for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
1056          BE = RD->bases_end(); BI != BE; ++BI) {
1057     unsigned BFlags = 0;
1058     uint64_t BaseOffset;
1059 
1060     const CXXRecordDecl *Base =
1061       cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl());
1062 
1063     if (BI->isVirtual()) {
1064       // virtual base offset offset is -ve. The code generator emits dwarf
1065       // expression where it expects +ve number.
1066       BaseOffset =
1067         0 - CGM.getVTableContext()
1068                .getVirtualBaseOffsetOffset(RD, Base).getQuantity();
1069       BFlags = llvm::DIDescriptor::FlagVirtual;
1070     } else
1071       BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1072     // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1073     // BI->isVirtual() and bits when not.
1074 
1075     AccessSpecifier Access = BI->getAccessSpecifier();
1076     if (Access == clang::AS_private)
1077       BFlags |= llvm::DIDescriptor::FlagPrivate;
1078     else if (Access == clang::AS_protected)
1079       BFlags |= llvm::DIDescriptor::FlagProtected;
1080 
1081     llvm::DIType DTy =
1082       DBuilder.createInheritance(RecordTy,
1083                                  getOrCreateType(BI->getType(), Unit),
1084                                  BaseOffset, BFlags);
1085     EltTys.push_back(DTy);
1086   }
1087 }
1088 
1089 /// CollectTemplateParams - A helper function to collect template parameters.
1090 llvm::DIArray CGDebugInfo::
1091 CollectTemplateParams(const TemplateParameterList *TPList,
1092                       const TemplateArgumentList &TAList,
1093                       llvm::DIFile Unit) {
1094   SmallVector<llvm::Value *, 16> TemplateParams;
1095   for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1096     const TemplateArgument &TA = TAList[i];
1097     const NamedDecl *ND = TPList->getParam(i);
1098     if (TA.getKind() == TemplateArgument::Type) {
1099       llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit);
1100       llvm::DITemplateTypeParameter TTP =
1101         DBuilder.createTemplateTypeParameter(TheCU, ND->getName(), TTy);
1102       TemplateParams.push_back(TTP);
1103     } else if (TA.getKind() == TemplateArgument::Integral) {
1104       llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit);
1105       llvm::DITemplateValueParameter TVP =
1106         DBuilder.createTemplateValueParameter(TheCU, ND->getName(), TTy,
1107                                              TA.getAsIntegral().getZExtValue());
1108       TemplateParams.push_back(TVP);
1109     }
1110   }
1111   return DBuilder.getOrCreateArray(TemplateParams);
1112 }
1113 
1114 /// CollectFunctionTemplateParams - A helper function to collect debug
1115 /// info for function template parameters.
1116 llvm::DIArray CGDebugInfo::
1117 CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) {
1118   if (FD->getTemplatedKind() ==
1119       FunctionDecl::TK_FunctionTemplateSpecialization) {
1120     const TemplateParameterList *TList =
1121       FD->getTemplateSpecializationInfo()->getTemplate()
1122       ->getTemplateParameters();
1123     return
1124       CollectTemplateParams(TList, *FD->getTemplateSpecializationArgs(), Unit);
1125   }
1126   return llvm::DIArray();
1127 }
1128 
1129 /// CollectCXXTemplateParams - A helper function to collect debug info for
1130 /// template parameters.
1131 llvm::DIArray CGDebugInfo::
1132 CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial,
1133                          llvm::DIFile Unit) {
1134   llvm::PointerUnion<ClassTemplateDecl *,
1135                      ClassTemplatePartialSpecializationDecl *>
1136     PU = TSpecial->getSpecializedTemplateOrPartial();
1137 
1138   TemplateParameterList *TPList = PU.is<ClassTemplateDecl *>() ?
1139     PU.get<ClassTemplateDecl *>()->getTemplateParameters() :
1140     PU.get<ClassTemplatePartialSpecializationDecl *>()->getTemplateParameters();
1141   const TemplateArgumentList &TAList = TSpecial->getTemplateInstantiationArgs();
1142   return CollectTemplateParams(TPList, TAList, Unit);
1143 }
1144 
1145 /// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
1146 llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
1147   if (VTablePtrType.isValid())
1148     return VTablePtrType;
1149 
1150   ASTContext &Context = CGM.getContext();
1151 
1152   /* Function type */
1153   llvm::Value *STy = getOrCreateType(Context.IntTy, Unit);
1154   llvm::DIArray SElements = DBuilder.getOrCreateArray(STy);
1155   llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements);
1156   unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1157   llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0,
1158                                                           "__vtbl_ptr_type");
1159   VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1160   return VTablePtrType;
1161 }
1162 
1163 /// getVTableName - Get vtable name for the given Class.
1164 StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
1165   // Construct gdb compatible name name.
1166   std::string Name = "_vptr$" + RD->getNameAsString();
1167 
1168   // Copy this name on the side and use its reference.
1169   char *StrPtr = DebugInfoNames.Allocate<char>(Name.length());
1170   memcpy(StrPtr, Name.data(), Name.length());
1171   return StringRef(StrPtr, Name.length());
1172 }
1173 
1174 
1175 /// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
1176 /// debug info entry in EltTys vector.
1177 void CGDebugInfo::
1178 CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
1179                   SmallVectorImpl<llvm::Value *> &EltTys) {
1180   const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1181 
1182   // If there is a primary base then it will hold vtable info.
1183   if (RL.getPrimaryBase())
1184     return;
1185 
1186   // If this class is not dynamic then there is not any vtable info to collect.
1187   if (!RD->isDynamicClass())
1188     return;
1189 
1190   unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1191   llvm::DIType VPTR
1192     = DBuilder.createMemberType(Unit, getVTableName(RD), Unit,
1193                                 0, Size, 0, 0, 0,
1194                                 getOrCreateVTablePtrType(Unit));
1195   EltTys.push_back(VPTR);
1196 }
1197 
1198 /// getOrCreateRecordType - Emit record type's standalone debug info.
1199 llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy,
1200                                                 SourceLocation Loc) {
1201   assert(CGM.getCodeGenOpts().DebugInfo >= CodeGenOptions::LimitedDebugInfo);
1202   llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc));
1203   return T;
1204 }
1205 
1206 /// getOrCreateInterfaceType - Emit an objective c interface type standalone
1207 /// debug info.
1208 llvm::DIType CGDebugInfo::getOrCreateInterfaceType(QualType D,
1209 						   SourceLocation Loc) {
1210   assert(CGM.getCodeGenOpts().DebugInfo >= CodeGenOptions::LimitedDebugInfo);
1211   llvm::DIType T = getOrCreateType(D, getOrCreateFile(Loc));
1212   DBuilder.retainType(T);
1213   return T;
1214 }
1215 
1216 /// CreateType - get structure or union type.
1217 llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty) {
1218   RecordDecl *RD = Ty->getDecl();
1219 
1220   // Get overall information about the record type for the debug info.
1221   llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1222 
1223   // Records and classes and unions can all be recursive.  To handle them, we
1224   // first generate a debug descriptor for the struct as a forward declaration.
1225   // Then (if it is a definition) we go through and get debug info for all of
1226   // its members.  Finally, we create a descriptor for the complete type (which
1227   // may refer to the forward decl if the struct is recursive) and replace all
1228   // uses of the forward declaration with the final definition.
1229 
1230   llvm::DIType FwdDecl = getOrCreateLimitedType(QualType(Ty, 0), DefUnit);
1231 
1232   if (FwdDecl.isForwardDecl())
1233     return FwdDecl;
1234 
1235   llvm::TrackingVH<llvm::MDNode> FwdDeclNode(FwdDecl);
1236 
1237   // Push the struct on region stack.
1238   LexicalBlockStack.push_back(FwdDeclNode);
1239   RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1240 
1241   // Add this to the completed types cache since we're completing it.
1242   CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1243 
1244   // Convert all the elements.
1245   SmallVector<llvm::Value *, 16> EltTys;
1246 
1247   // Note: The split of CXXDecl information here is intentional, the
1248   // gdb tests will depend on a certain ordering at printout. The debug
1249   // information offsets are still correct if we merge them all together
1250   // though.
1251   const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1252   if (CXXDecl) {
1253     CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1254     CollectVTableInfo(CXXDecl, DefUnit, EltTys);
1255   }
1256 
1257   // Collect static variables with initializers and other fields.
1258   CollectRecordStaticVars(RD, FwdDecl);
1259   CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
1260   llvm::DIArray TParamsArray;
1261   if (CXXDecl) {
1262     CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
1263     CollectCXXFriends(CXXDecl, DefUnit, EltTys, FwdDecl);
1264     if (const ClassTemplateSpecializationDecl *TSpecial
1265         = dyn_cast<ClassTemplateSpecializationDecl>(RD))
1266       TParamsArray = CollectCXXTemplateParams(TSpecial, DefUnit);
1267   }
1268 
1269   LexicalBlockStack.pop_back();
1270   RegionMap.erase(Ty->getDecl());
1271 
1272   llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
1273   // FIXME: Magic numbers ahoy! These should be changed when we
1274   // get some enums in llvm/Analysis/DebugInfo.h to refer to
1275   // them.
1276   if (RD->isUnion())
1277     FwdDeclNode->replaceOperandWith(10, Elements);
1278   else if (CXXDecl) {
1279     FwdDeclNode->replaceOperandWith(10, Elements);
1280     FwdDeclNode->replaceOperandWith(13, TParamsArray);
1281   } else
1282     FwdDeclNode->replaceOperandWith(10, Elements);
1283 
1284   RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDeclNode);
1285   return llvm::DIType(FwdDeclNode);
1286 }
1287 
1288 /// CreateType - get objective-c object type.
1289 llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1290                                      llvm::DIFile Unit) {
1291   // Ignore protocols.
1292   return getOrCreateType(Ty->getBaseType(), Unit);
1293 }
1294 
1295 /// CreateType - get objective-c interface type.
1296 llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1297                                      llvm::DIFile Unit) {
1298   ObjCInterfaceDecl *ID = Ty->getDecl();
1299   if (!ID)
1300     return llvm::DIType();
1301 
1302   // Get overall information about the record type for the debug info.
1303   llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1304   unsigned Line = getLineNumber(ID->getLocation());
1305   unsigned RuntimeLang = TheCU.getLanguage();
1306 
1307   // If this is just a forward declaration return a special forward-declaration
1308   // debug type since we won't be able to lay out the entire type.
1309   ObjCInterfaceDecl *Def = ID->getDefinition();
1310   if (!Def) {
1311     llvm::DIType FwdDecl =
1312       DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
1313 				 ID->getName(), TheCU, DefUnit, Line,
1314 				 RuntimeLang);
1315     return FwdDecl;
1316   }
1317 
1318   ID = Def;
1319 
1320   // Bit size, align and offset of the type.
1321   uint64_t Size = CGM.getContext().getTypeSize(Ty);
1322   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1323 
1324   unsigned Flags = 0;
1325   if (ID->getImplementation())
1326     Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
1327 
1328   llvm::DIType RealDecl =
1329     DBuilder.createStructType(Unit, ID->getName(), DefUnit,
1330                               Line, Size, Align, Flags,
1331                               llvm::DIArray(), RuntimeLang);
1332 
1333   // Otherwise, insert it into the CompletedTypeCache so that recursive uses
1334   // will find it and we're emitting the complete type.
1335   CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl;
1336   // Push the struct on region stack.
1337   llvm::TrackingVH<llvm::MDNode> FwdDeclNode(RealDecl);
1338 
1339   LexicalBlockStack.push_back(FwdDeclNode);
1340   RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1341 
1342   // Convert all the elements.
1343   SmallVector<llvm::Value *, 16> EltTys;
1344 
1345   ObjCInterfaceDecl *SClass = ID->getSuperClass();
1346   if (SClass) {
1347     llvm::DIType SClassTy =
1348       getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1349     if (!SClassTy.isValid())
1350       return llvm::DIType();
1351 
1352     llvm::DIType InhTag =
1353       DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
1354     EltTys.push_back(InhTag);
1355   }
1356 
1357   for (ObjCContainerDecl::prop_iterator I = ID->prop_begin(),
1358          E = ID->prop_end(); I != E; ++I) {
1359     const ObjCPropertyDecl *PD = *I;
1360     SourceLocation Loc = PD->getLocation();
1361     llvm::DIFile PUnit = getOrCreateFile(Loc);
1362     unsigned PLine = getLineNumber(Loc);
1363     ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1364     ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1365     llvm::MDNode *PropertyNode =
1366       DBuilder.createObjCProperty(PD->getName(),
1367 				  PUnit, PLine,
1368                                   (Getter && Getter->isImplicit()) ? "" :
1369                                   getSelectorName(PD->getGetterName()),
1370                                   (Setter && Setter->isImplicit()) ? "" :
1371                                   getSelectorName(PD->getSetterName()),
1372                                   PD->getPropertyAttributes(),
1373 				  getOrCreateType(PD->getType(), PUnit));
1374     EltTys.push_back(PropertyNode);
1375   }
1376 
1377   const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1378   unsigned FieldNo = 0;
1379   for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1380        Field = Field->getNextIvar(), ++FieldNo) {
1381     llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1382     if (!FieldTy.isValid())
1383       return llvm::DIType();
1384 
1385     StringRef FieldName = Field->getName();
1386 
1387     // Ignore unnamed fields.
1388     if (FieldName.empty())
1389       continue;
1390 
1391     // Get the location for the field.
1392     llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1393     unsigned FieldLine = getLineNumber(Field->getLocation());
1394     QualType FType = Field->getType();
1395     uint64_t FieldSize = 0;
1396     unsigned FieldAlign = 0;
1397 
1398     if (!FType->isIncompleteArrayType()) {
1399 
1400       // Bit size, align and offset of the type.
1401       FieldSize = Field->isBitField()
1402         ? Field->getBitWidthValue(CGM.getContext())
1403         : CGM.getContext().getTypeSize(FType);
1404       FieldAlign = CGM.getContext().getTypeAlign(FType);
1405     }
1406 
1407     // We can't know the offset of our ivar in the structure if we're using
1408     // the non-fragile abi and the debugger should ignore the value anyways.
1409     // Call it the FieldNo+1 due to how debuggers use the information,
1410     // e.g. negating the value when it needs a lookup in the dynamic table.
1411     uint64_t FieldOffset = CGM.getLangOpts().ObjCRuntime.isNonFragile()
1412                              ? FieldNo+1 : RL.getFieldOffset(FieldNo);
1413 
1414     unsigned Flags = 0;
1415     if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1416       Flags = llvm::DIDescriptor::FlagProtected;
1417     else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1418       Flags = llvm::DIDescriptor::FlagPrivate;
1419 
1420     llvm::MDNode *PropertyNode = NULL;
1421     if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
1422       if (ObjCPropertyImplDecl *PImpD =
1423           ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
1424         if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
1425 	  SourceLocation Loc = PD->getLocation();
1426 	  llvm::DIFile PUnit = getOrCreateFile(Loc);
1427 	  unsigned PLine = getLineNumber(Loc);
1428           ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1429           ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1430           PropertyNode =
1431             DBuilder.createObjCProperty(PD->getName(),
1432                                         PUnit, PLine,
1433                                         (Getter && Getter->isImplicit()) ? "" :
1434                                         getSelectorName(PD->getGetterName()),
1435                                         (Setter && Setter->isImplicit()) ? "" :
1436                                         getSelectorName(PD->getSetterName()),
1437                                         PD->getPropertyAttributes(),
1438                                         getOrCreateType(PD->getType(), PUnit));
1439         }
1440       }
1441     }
1442     FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
1443                                       FieldLine, FieldSize, FieldAlign,
1444                                       FieldOffset, Flags, FieldTy,
1445                                       PropertyNode);
1446     EltTys.push_back(FieldTy);
1447   }
1448 
1449   llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
1450   FwdDeclNode->replaceOperandWith(10, Elements);
1451 
1452   LexicalBlockStack.pop_back();
1453   return llvm::DIType(FwdDeclNode);
1454 }
1455 
1456 llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) {
1457   llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1458   int64_t NumElems = Ty->getNumElements();
1459   int64_t LowerBound = 0;
1460   if (NumElems == 0)
1461     // If number of elements are not known then this is an unbounded array.
1462     // Use Low = 1, Hi = 0 to express such arrays.
1463     LowerBound = 1;
1464   else
1465     --NumElems;
1466 
1467   llvm::Value *Subscript = DBuilder.getOrCreateSubrange(LowerBound, NumElems);
1468   llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1469 
1470   uint64_t Size = CGM.getContext().getTypeSize(Ty);
1471   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1472 
1473   return
1474     DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1475 }
1476 
1477 llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1478                                      llvm::DIFile Unit) {
1479   uint64_t Size;
1480   uint64_t Align;
1481 
1482   // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1483   if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1484     Size = 0;
1485     Align =
1486       CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1487   } else if (Ty->isIncompleteArrayType()) {
1488     Size = 0;
1489     if (Ty->getElementType()->isIncompleteType())
1490       Align = 0;
1491     else
1492       Align = CGM.getContext().getTypeAlign(Ty->getElementType());
1493   } else if (Ty->isDependentSizedArrayType() || Ty->isIncompleteType()) {
1494     Size = 0;
1495     Align = 0;
1496   } else {
1497     // Size and align of the whole array, not the element type.
1498     Size = CGM.getContext().getTypeSize(Ty);
1499     Align = CGM.getContext().getTypeAlign(Ty);
1500   }
1501 
1502   // Add the dimensions of the array.  FIXME: This loses CV qualifiers from
1503   // interior arrays, do we care?  Why aren't nested arrays represented the
1504   // obvious/recursive way?
1505   SmallVector<llvm::Value *, 8> Subscripts;
1506   QualType EltTy(Ty, 0);
1507   while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1508     int64_t UpperBound = 0;
1509     int64_t LowerBound = 0;
1510     if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty)) {
1511       if (CAT->getSize().getZExtValue())
1512         UpperBound = CAT->getSize().getZExtValue() - 1;
1513     } else
1514       // This is an unbounded array. Use Low = 1, Hi = 0 to express such
1515       // arrays.
1516       LowerBound = 1;
1517 
1518     // FIXME: Verify this is right for VLAs.
1519     Subscripts.push_back(DBuilder.getOrCreateSubrange(LowerBound,
1520                                                       UpperBound));
1521     EltTy = Ty->getElementType();
1522   }
1523 
1524   llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1525 
1526   llvm::DIType DbgTy =
1527     DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1528                              SubscriptArray);
1529   return DbgTy;
1530 }
1531 
1532 llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
1533                                      llvm::DIFile Unit) {
1534   return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
1535                                Ty, Ty->getPointeeType(), Unit);
1536 }
1537 
1538 llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
1539                                      llvm::DIFile Unit) {
1540   return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
1541                                Ty, Ty->getPointeeType(), Unit);
1542 }
1543 
1544 llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
1545                                      llvm::DIFile U) {
1546   QualType PointerDiffTy = CGM.getContext().getPointerDiffType();
1547   llvm::DIType PointerDiffDITy = getOrCreateType(PointerDiffTy, U);
1548 
1549   if (!Ty->getPointeeType()->isFunctionType()) {
1550     // We have a data member pointer type.
1551     return PointerDiffDITy;
1552   }
1553 
1554   // We have a member function pointer type. Treat it as a struct with two
1555   // ptrdiff_t members.
1556   std::pair<uint64_t, unsigned> Info = CGM.getContext().getTypeInfo(Ty);
1557 
1558   uint64_t FieldOffset = 0;
1559   llvm::Value *ElementTypes[2];
1560 
1561   // FIXME: This should be a DW_TAG_pointer_to_member type.
1562   ElementTypes[0] =
1563     DBuilder.createMemberType(U, "ptr", U, 0,
1564                               Info.first, Info.second, FieldOffset, 0,
1565                               PointerDiffDITy);
1566   FieldOffset += Info.first;
1567 
1568   ElementTypes[1] =
1569     DBuilder.createMemberType(U, "ptr", U, 0,
1570                               Info.first, Info.second, FieldOffset, 0,
1571                               PointerDiffDITy);
1572 
1573   llvm::DIArray Elements = DBuilder.getOrCreateArray(ElementTypes);
1574 
1575   return DBuilder.createStructType(U, StringRef("test"),
1576                                    U, 0, FieldOffset,
1577                                    0, 0, Elements);
1578 }
1579 
1580 llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty,
1581                                      llvm::DIFile U) {
1582   // Ignore the atomic wrapping
1583   // FIXME: What is the correct representation?
1584   return getOrCreateType(Ty->getValueType(), U);
1585 }
1586 
1587 /// CreateEnumType - get enumeration type.
1588 llvm::DIType CGDebugInfo::CreateEnumType(const EnumDecl *ED) {
1589   SmallVector<llvm::Value *, 16> Enumerators;
1590 
1591   // Create DIEnumerator elements for each enumerator.
1592   for (EnumDecl::enumerator_iterator
1593          Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
1594        Enum != EnumEnd; ++Enum) {
1595     Enumerators.push_back(
1596       DBuilder.createEnumerator(Enum->getName(),
1597                                 Enum->getInitVal().getZExtValue()));
1598   }
1599 
1600   // Return a CompositeType for the enum itself.
1601   llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1602 
1603   llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1604   unsigned Line = getLineNumber(ED->getLocation());
1605   uint64_t Size = 0;
1606   uint64_t Align = 0;
1607   if (!ED->getTypeForDecl()->isIncompleteType()) {
1608     Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1609     Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1610   }
1611   llvm::DIDescriptor EnumContext =
1612     getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1613   llvm::DIType ClassTy = ED->isScopedUsingClassTag() ?
1614     getOrCreateType(ED->getIntegerType(), DefUnit) : llvm::DIType();
1615   unsigned Flags = !ED->isCompleteDefinition() ? llvm::DIDescriptor::FlagFwdDecl : 0;
1616   llvm::DIType DbgTy =
1617     DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1618                                    Size, Align, EltArray,
1619                                    ClassTy, Flags);
1620   return DbgTy;
1621 }
1622 
1623 static QualType UnwrapTypeForDebugInfo(QualType T) {
1624   do {
1625     QualType LastT = T;
1626     switch (T->getTypeClass()) {
1627     default:
1628       return T;
1629     case Type::TemplateSpecialization:
1630       T = cast<TemplateSpecializationType>(T)->desugar();
1631       break;
1632     case Type::TypeOfExpr:
1633       T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1634       break;
1635     case Type::TypeOf:
1636       T = cast<TypeOfType>(T)->getUnderlyingType();
1637       break;
1638     case Type::Decltype:
1639       T = cast<DecltypeType>(T)->getUnderlyingType();
1640       break;
1641     case Type::UnaryTransform:
1642       T = cast<UnaryTransformType>(T)->getUnderlyingType();
1643       break;
1644     case Type::Attributed:
1645       T = cast<AttributedType>(T)->getEquivalentType();
1646       break;
1647     case Type::Elaborated:
1648       T = cast<ElaboratedType>(T)->getNamedType();
1649       break;
1650     case Type::Paren:
1651       T = cast<ParenType>(T)->getInnerType();
1652       break;
1653     case Type::SubstTemplateTypeParm: {
1654       // We need to keep the qualifiers handy since getReplacementType()
1655       // will strip them away.
1656       unsigned Quals = T.getLocalFastQualifiers();
1657       T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
1658       T.addFastQualifiers(Quals);
1659     }
1660       break;
1661     case Type::Auto:
1662       T = cast<AutoType>(T)->getDeducedType();
1663       break;
1664     }
1665 
1666     assert(T != LastT && "Type unwrapping failed to unwrap!");
1667     if (T == LastT)
1668       return T;
1669   } while (true);
1670 }
1671 
1672 /// getType - Get the type from the cache or return null type if it doesn't exist.
1673 llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) {
1674 
1675   // Unwrap the type as needed for debug information.
1676   Ty = UnwrapTypeForDebugInfo(Ty);
1677 
1678   // Check for existing entry.
1679   llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1680     TypeCache.find(Ty.getAsOpaquePtr());
1681   if (it != TypeCache.end()) {
1682     // Verify that the debug info still exists.
1683     if (llvm::Value *V = it->second)
1684       return llvm::DIType(cast<llvm::MDNode>(V));
1685   }
1686 
1687   return llvm::DIType();
1688 }
1689 
1690 /// getCompletedTypeOrNull - Get the type from the cache or return null if it
1691 /// doesn't exist.
1692 llvm::DIType CGDebugInfo::getCompletedTypeOrNull(QualType Ty) {
1693 
1694   // Unwrap the type as needed for debug information.
1695   Ty = UnwrapTypeForDebugInfo(Ty);
1696 
1697   // Check for existing entry.
1698   llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1699     CompletedTypeCache.find(Ty.getAsOpaquePtr());
1700   if (it != CompletedTypeCache.end()) {
1701     // Verify that the debug info still exists.
1702     if (llvm::Value *V = it->second)
1703       return llvm::DIType(cast<llvm::MDNode>(V));
1704   }
1705 
1706   return llvm::DIType();
1707 }
1708 
1709 
1710 /// getOrCreateType - Get the type from the cache or create a new
1711 /// one if necessary.
1712 llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit) {
1713   if (Ty.isNull())
1714     return llvm::DIType();
1715 
1716   // Unwrap the type as needed for debug information.
1717   Ty = UnwrapTypeForDebugInfo(Ty);
1718 
1719   llvm::DIType T = getCompletedTypeOrNull(Ty);
1720 
1721   if (T.Verify())
1722     return T;
1723 
1724   // Otherwise create the type.
1725   llvm::DIType Res = CreateTypeNode(Ty, Unit);
1726 
1727   llvm::DIType TC = getTypeOrNull(Ty);
1728   if (TC.Verify() && TC.isForwardDecl())
1729     ReplaceMap.push_back(std::make_pair(Ty.getAsOpaquePtr(),
1730                                         static_cast<llvm::Value*>(TC)));
1731 
1732   // And update the type cache.
1733   TypeCache[Ty.getAsOpaquePtr()] = Res;
1734 
1735   if (!Res.isForwardDecl())
1736     CompletedTypeCache[Ty.getAsOpaquePtr()] = Res;
1737 
1738   return Res;
1739 }
1740 
1741 /// CreateTypeNode - Create a new debug type node.
1742 llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit) {
1743   // Handle qualifiers, which recursively handles what they refer to.
1744   if (Ty.hasLocalQualifiers())
1745     return CreateQualifiedType(Ty, Unit);
1746 
1747   const char *Diag = 0;
1748 
1749   // Work out details of type.
1750   switch (Ty->getTypeClass()) {
1751 #define TYPE(Class, Base)
1752 #define ABSTRACT_TYPE(Class, Base)
1753 #define NON_CANONICAL_TYPE(Class, Base)
1754 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1755 #include "clang/AST/TypeNodes.def"
1756     llvm_unreachable("Dependent types cannot show up in debug information");
1757 
1758   case Type::ExtVector:
1759   case Type::Vector:
1760     return CreateType(cast<VectorType>(Ty), Unit);
1761   case Type::ObjCObjectPointer:
1762     return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
1763   case Type::ObjCObject:
1764     return CreateType(cast<ObjCObjectType>(Ty), Unit);
1765   case Type::ObjCInterface:
1766     return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
1767   case Type::Builtin:
1768     return CreateType(cast<BuiltinType>(Ty));
1769   case Type::Complex:
1770     return CreateType(cast<ComplexType>(Ty));
1771   case Type::Pointer:
1772     return CreateType(cast<PointerType>(Ty), Unit);
1773   case Type::BlockPointer:
1774     return CreateType(cast<BlockPointerType>(Ty), Unit);
1775   case Type::Typedef:
1776     return CreateType(cast<TypedefType>(Ty), Unit);
1777   case Type::Record:
1778     return CreateType(cast<RecordType>(Ty));
1779   case Type::Enum:
1780     return CreateEnumType(cast<EnumType>(Ty)->getDecl());
1781   case Type::FunctionProto:
1782   case Type::FunctionNoProto:
1783     return CreateType(cast<FunctionType>(Ty), Unit);
1784   case Type::ConstantArray:
1785   case Type::VariableArray:
1786   case Type::IncompleteArray:
1787     return CreateType(cast<ArrayType>(Ty), Unit);
1788 
1789   case Type::LValueReference:
1790     return CreateType(cast<LValueReferenceType>(Ty), Unit);
1791   case Type::RValueReference:
1792     return CreateType(cast<RValueReferenceType>(Ty), Unit);
1793 
1794   case Type::MemberPointer:
1795     return CreateType(cast<MemberPointerType>(Ty), Unit);
1796 
1797   case Type::Atomic:
1798     return CreateType(cast<AtomicType>(Ty), Unit);
1799 
1800   case Type::Attributed:
1801   case Type::TemplateSpecialization:
1802   case Type::Elaborated:
1803   case Type::Paren:
1804   case Type::SubstTemplateTypeParm:
1805   case Type::TypeOfExpr:
1806   case Type::TypeOf:
1807   case Type::Decltype:
1808   case Type::UnaryTransform:
1809   case Type::Auto:
1810     llvm_unreachable("type should have been unwrapped!");
1811   }
1812 
1813   assert(Diag && "Fall through without a diagnostic?");
1814   unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error,
1815                                "debug information for %0 is not yet supported");
1816   CGM.getDiags().Report(DiagID)
1817     << Diag;
1818   return llvm::DIType();
1819 }
1820 
1821 /// getOrCreateLimitedType - Get the type from the cache or create a new
1822 /// limited type if necessary.
1823 llvm::DIType CGDebugInfo::getOrCreateLimitedType(QualType Ty,
1824 						 llvm::DIFile Unit) {
1825   if (Ty.isNull())
1826     return llvm::DIType();
1827 
1828   // Unwrap the type as needed for debug information.
1829   Ty = UnwrapTypeForDebugInfo(Ty);
1830 
1831   llvm::DIType T = getTypeOrNull(Ty);
1832 
1833   // We may have cached a forward decl when we could have created
1834   // a non-forward decl. Go ahead and create a non-forward decl
1835   // now.
1836   if (T.Verify() && !T.isForwardDecl()) return T;
1837 
1838   // Otherwise create the type.
1839   llvm::DIType Res = CreateLimitedTypeNode(Ty, Unit);
1840 
1841   if (T.Verify() && T.isForwardDecl())
1842     ReplaceMap.push_back(std::make_pair(Ty.getAsOpaquePtr(),
1843                                         static_cast<llvm::Value*>(T)));
1844 
1845   // And update the type cache.
1846   TypeCache[Ty.getAsOpaquePtr()] = Res;
1847   return Res;
1848 }
1849 
1850 // TODO: Currently used for context chains when limiting debug info.
1851 llvm::DIType CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
1852   RecordDecl *RD = Ty->getDecl();
1853 
1854   // Get overall information about the record type for the debug info.
1855   llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1856   unsigned Line = getLineNumber(RD->getLocation());
1857   StringRef RDName = RD->getName();
1858 
1859   llvm::DIDescriptor RDContext;
1860   if (CGM.getCodeGenOpts().DebugInfo == CodeGenOptions::LimitedDebugInfo)
1861     RDContext = createContextChain(cast<Decl>(RD->getDeclContext()));
1862   else
1863     RDContext = getContextDescriptor(cast<Decl>(RD->getDeclContext()));
1864 
1865   // If this is just a forward declaration, construct an appropriately
1866   // marked node and just return it.
1867   if (!RD->getDefinition())
1868     return createRecordFwdDecl(RD, RDContext);
1869 
1870   uint64_t Size = CGM.getContext().getTypeSize(Ty);
1871   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1872   const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1873   llvm::TrackingVH<llvm::MDNode> RealDecl;
1874 
1875   if (RD->isUnion())
1876     RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
1877 					Size, Align, 0, llvm::DIArray());
1878   else if (CXXDecl) {
1879     RDName = getClassName(RD);
1880 
1881     // FIXME: This could be a struct type giving a default visibility different
1882     // than C++ class type, but needs llvm metadata changes first.
1883     RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
1884 					Size, Align, 0, 0, llvm::DIType(),
1885 					llvm::DIArray(), llvm::DIType(),
1886 					llvm::DIArray());
1887   } else
1888     RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line,
1889 					 Size, Align, 0, llvm::DIArray());
1890 
1891   RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1892   TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = llvm::DIType(RealDecl);
1893 
1894   if (CXXDecl) {
1895     // A class's primary base or the class itself contains the vtable.
1896     llvm::MDNode *ContainingType = NULL;
1897     const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1898     if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
1899       // Seek non virtual primary base root.
1900       while (1) {
1901 	const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
1902 	const CXXRecordDecl *PBT = BRL.getPrimaryBase();
1903 	if (PBT && !BRL.isPrimaryBaseVirtual())
1904 	  PBase = PBT;
1905 	else
1906 	  break;
1907       }
1908       ContainingType =
1909 	getOrCreateType(QualType(PBase->getTypeForDecl(), 0), DefUnit);
1910     }
1911     else if (CXXDecl->isDynamicClass())
1912       ContainingType = RealDecl;
1913 
1914     RealDecl->replaceOperandWith(12, ContainingType);
1915   }
1916   return llvm::DIType(RealDecl);
1917 }
1918 
1919 /// CreateLimitedTypeNode - Create a new debug type node, but only forward
1920 /// declare composite types that haven't been processed yet.
1921 llvm::DIType CGDebugInfo::CreateLimitedTypeNode(QualType Ty,llvm::DIFile Unit) {
1922 
1923   // Work out details of type.
1924   switch (Ty->getTypeClass()) {
1925 #define TYPE(Class, Base)
1926 #define ABSTRACT_TYPE(Class, Base)
1927 #define NON_CANONICAL_TYPE(Class, Base)
1928 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1929         #include "clang/AST/TypeNodes.def"
1930     llvm_unreachable("Dependent types cannot show up in debug information");
1931 
1932   case Type::Record:
1933     return CreateLimitedType(cast<RecordType>(Ty));
1934   default:
1935     return CreateTypeNode(Ty, Unit);
1936   }
1937 }
1938 
1939 /// CreateMemberType - Create new member and increase Offset by FType's size.
1940 llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
1941                                            StringRef Name,
1942                                            uint64_t *Offset) {
1943   llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1944   uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
1945   unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
1946   llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0,
1947                                               FieldSize, FieldAlign,
1948                                               *Offset, 0, FieldTy);
1949   *Offset += FieldSize;
1950   return Ty;
1951 }
1952 
1953 /// getFunctionDeclaration - Return debug info descriptor to describe method
1954 /// declaration for the given method definition.
1955 llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
1956   const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
1957   if (!FD) return llvm::DISubprogram();
1958 
1959   // Setup context.
1960   getContextDescriptor(cast<Decl>(D->getDeclContext()));
1961 
1962   llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
1963     MI = SPCache.find(FD->getCanonicalDecl());
1964   if (MI != SPCache.end()) {
1965     llvm::Value *V = MI->second;
1966     llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
1967     if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
1968       return SP;
1969   }
1970 
1971   for (FunctionDecl::redecl_iterator I = FD->redecls_begin(),
1972          E = FD->redecls_end(); I != E; ++I) {
1973     const FunctionDecl *NextFD = *I;
1974     llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
1975       MI = SPCache.find(NextFD->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   return llvm::DISubprogram();
1984 }
1985 
1986 // getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
1987 // implicit parameter "this".
1988 llvm::DIType CGDebugInfo::getOrCreateFunctionType(const Decl * D,
1989                                                   QualType FnType,
1990                                                   llvm::DIFile F) {
1991 
1992   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1993     return getOrCreateMethodType(Method, F);
1994   if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
1995     // Add "self" and "_cmd"
1996     SmallVector<llvm::Value *, 16> Elts;
1997 
1998     // First element is always return type. For 'void' functions it is NULL.
1999     Elts.push_back(getOrCreateType(OMethod->getResultType(), F));
2000     // "self" pointer is always first argument.
2001     Elts.push_back(getOrCreateType(OMethod->getSelfDecl()->getType(), F));
2002     // "cmd" pointer is always second argument.
2003     Elts.push_back(getOrCreateType(OMethod->getCmdDecl()->getType(), F));
2004     // Get rest of the arguments.
2005     for (ObjCMethodDecl::param_const_iterator PI = OMethod->param_begin(),
2006            PE = OMethod->param_end(); PI != PE; ++PI)
2007       Elts.push_back(getOrCreateType((*PI)->getType(), F));
2008 
2009     llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2010     return DBuilder.createSubroutineType(F, EltTypeArray);
2011   }
2012   return getOrCreateType(FnType, F);
2013 }
2014 
2015 /// EmitFunctionStart - Constructs the debug code for entering a function.
2016 void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
2017                                     llvm::Function *Fn,
2018                                     CGBuilderTy &Builder) {
2019 
2020   StringRef Name;
2021   StringRef LinkageName;
2022 
2023   FnBeginRegionCount.push_back(LexicalBlockStack.size());
2024 
2025   const Decl *D = GD.getDecl();
2026   // Use the location of the declaration.
2027   SourceLocation Loc = D->getLocation();
2028 
2029   unsigned Flags = 0;
2030   llvm::DIFile Unit = getOrCreateFile(Loc);
2031   llvm::DIDescriptor FDContext(Unit);
2032   llvm::DIArray TParamsArray;
2033   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2034     // If there is a DISubprogram for this function available then use it.
2035     llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2036       FI = SPCache.find(FD->getCanonicalDecl());
2037     if (FI != SPCache.end()) {
2038       llvm::Value *V = FI->second;
2039       llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(V));
2040       if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
2041         llvm::MDNode *SPN = SP;
2042         LexicalBlockStack.push_back(SPN);
2043         RegionMap[D] = llvm::WeakVH(SP);
2044         return;
2045       }
2046     }
2047     Name = getFunctionName(FD);
2048     // Use mangled name as linkage name for c/c++ functions.
2049     if (FD->hasPrototype()) {
2050       LinkageName = CGM.getMangledName(GD);
2051       Flags |= llvm::DIDescriptor::FlagPrototyped;
2052     }
2053     if (LinkageName == Name ||
2054         CGM.getCodeGenOpts().DebugInfo <= CodeGenOptions::DebugLineTablesOnly)
2055       LinkageName = StringRef();
2056 
2057     if (CGM.getCodeGenOpts().DebugInfo >= CodeGenOptions::LimitedDebugInfo) {
2058       if (const NamespaceDecl *NSDecl =
2059           dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
2060         FDContext = getOrCreateNameSpace(NSDecl);
2061       else if (const RecordDecl *RDecl =
2062                dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
2063         FDContext = getContextDescriptor(cast<Decl>(RDecl->getDeclContext()));
2064 
2065       // Collect template parameters.
2066       TParamsArray = CollectFunctionTemplateParams(FD, Unit);
2067     }
2068   } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
2069     Name = getObjCMethodName(OMD);
2070     Flags |= llvm::DIDescriptor::FlagPrototyped;
2071   } else {
2072     // Use llvm function name.
2073     Name = Fn->getName();
2074     Flags |= llvm::DIDescriptor::FlagPrototyped;
2075   }
2076   if (!Name.empty() && Name[0] == '\01')
2077     Name = Name.substr(1);
2078 
2079   unsigned LineNo = getLineNumber(Loc);
2080   if (D->isImplicit())
2081     Flags |= llvm::DIDescriptor::FlagArtificial;
2082 
2083   llvm::DIType DIFnType;
2084   llvm::DISubprogram SPDecl;
2085   if (CGM.getCodeGenOpts().DebugInfo >= CodeGenOptions::LimitedDebugInfo) {
2086     DIFnType = getOrCreateFunctionType(D, FnType, Unit);
2087     SPDecl = getFunctionDeclaration(D);
2088   } else {
2089     // Create fake but valid subroutine type. Otherwise
2090     // llvm::DISubprogram::Verify() would return false, and
2091     // subprogram DIE will miss DW_AT_decl_file and
2092     // DW_AT_decl_line fields.
2093     SmallVector<llvm::Value*, 16> Elts;
2094     llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2095     DIFnType = DBuilder.createSubroutineType(Unit, EltTypeArray);
2096   }
2097   llvm::DISubprogram SP;
2098   SP = DBuilder.createFunction(FDContext, Name, LinkageName, Unit,
2099                                LineNo, DIFnType,
2100                                Fn->hasInternalLinkage(), true/*definition*/,
2101                                getLineNumber(CurLoc), Flags,
2102                                CGM.getLangOpts().Optimize,
2103                                Fn, TParamsArray, SPDecl);
2104 
2105   // Push function on region stack.
2106   llvm::MDNode *SPN = SP;
2107   LexicalBlockStack.push_back(SPN);
2108   RegionMap[D] = llvm::WeakVH(SP);
2109 }
2110 
2111 /// EmitLocation - Emit metadata to indicate a change in line/column
2112 /// information in the source file.
2113 void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc) {
2114 
2115   // Update our current location
2116   setLocation(Loc);
2117 
2118   if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
2119 
2120   // Don't bother if things are the same as last time.
2121   SourceManager &SM = CGM.getContext().getSourceManager();
2122   if (CurLoc == PrevLoc ||
2123       SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc))
2124     // New Builder may not be in sync with CGDebugInfo.
2125     if (!Builder.getCurrentDebugLocation().isUnknown())
2126       return;
2127 
2128   // Update last state.
2129   PrevLoc = CurLoc;
2130 
2131   llvm::MDNode *Scope = LexicalBlockStack.back();
2132   Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(CurLoc),
2133                                                       getColumnNumber(CurLoc),
2134                                                       Scope));
2135 }
2136 
2137 /// CreateLexicalBlock - Creates a new lexical block node and pushes it on
2138 /// the stack.
2139 void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
2140   llvm::DIDescriptor D =
2141     DBuilder.createLexicalBlock(LexicalBlockStack.empty() ?
2142                                 llvm::DIDescriptor() :
2143                                 llvm::DIDescriptor(LexicalBlockStack.back()),
2144                                 getOrCreateFile(CurLoc),
2145                                 getLineNumber(CurLoc),
2146                                 getColumnNumber(CurLoc));
2147   llvm::MDNode *DN = D;
2148   LexicalBlockStack.push_back(DN);
2149 }
2150 
2151 /// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
2152 /// region - beginning of a DW_TAG_lexical_block.
2153 void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder, SourceLocation Loc) {
2154   // Set our current location.
2155   setLocation(Loc);
2156 
2157   // Create a new lexical block and push it on the stack.
2158   CreateLexicalBlock(Loc);
2159 
2160   // Emit a line table change for the current location inside the new scope.
2161   Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc),
2162                                   getColumnNumber(Loc),
2163                                   LexicalBlockStack.back()));
2164 }
2165 
2166 /// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative
2167 /// region - end of a DW_TAG_lexical_block.
2168 void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder, SourceLocation Loc) {
2169   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2170 
2171   // Provide an entry in the line table for the end of the block.
2172   EmitLocation(Builder, Loc);
2173 
2174   LexicalBlockStack.pop_back();
2175 }
2176 
2177 /// EmitFunctionEnd - Constructs the debug code for exiting a function.
2178 void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
2179   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2180   unsigned RCount = FnBeginRegionCount.back();
2181   assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
2182 
2183   // Pop all regions for this function.
2184   while (LexicalBlockStack.size() != RCount)
2185     EmitLexicalBlockEnd(Builder, CurLoc);
2186   FnBeginRegionCount.pop_back();
2187 }
2188 
2189 // EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
2190 // See BuildByRefType.
2191 llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const ValueDecl *VD,
2192                                                        uint64_t *XOffset) {
2193 
2194   SmallVector<llvm::Value *, 5> EltTys;
2195   QualType FType;
2196   uint64_t FieldSize, FieldOffset;
2197   unsigned FieldAlign;
2198 
2199   llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2200   QualType Type = VD->getType();
2201 
2202   FieldOffset = 0;
2203   FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2204   EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
2205   EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
2206   FType = CGM.getContext().IntTy;
2207   EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
2208   EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
2209 
2210   bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type);
2211   if (HasCopyAndDispose) {
2212     FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2213     EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
2214                                       &FieldOffset));
2215     EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
2216                                       &FieldOffset));
2217   }
2218 
2219   CharUnits Align = CGM.getContext().getDeclAlign(VD);
2220   if (Align > CGM.getContext().toCharUnitsFromBits(
2221         CGM.getContext().getTargetInfo().getPointerAlign(0))) {
2222     CharUnits FieldOffsetInBytes
2223       = CGM.getContext().toCharUnitsFromBits(FieldOffset);
2224     CharUnits AlignedOffsetInBytes
2225       = FieldOffsetInBytes.RoundUpToAlignment(Align);
2226     CharUnits NumPaddingBytes
2227       = AlignedOffsetInBytes - FieldOffsetInBytes;
2228 
2229     if (NumPaddingBytes.isPositive()) {
2230       llvm::APInt pad(32, NumPaddingBytes.getQuantity());
2231       FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
2232                                                     pad, ArrayType::Normal, 0);
2233       EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
2234     }
2235   }
2236 
2237   FType = Type;
2238   llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2239   FieldSize = CGM.getContext().getTypeSize(FType);
2240   FieldAlign = CGM.getContext().toBits(Align);
2241 
2242   *XOffset = FieldOffset;
2243   FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit,
2244                                       0, FieldSize, FieldAlign,
2245                                       FieldOffset, 0, FieldTy);
2246   EltTys.push_back(FieldTy);
2247   FieldOffset += FieldSize;
2248 
2249   llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
2250 
2251   unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
2252 
2253   return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
2254                                    Elements);
2255 }
2256 
2257 /// EmitDeclare - Emit local variable declaration debug info.
2258 void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
2259                               llvm::Value *Storage,
2260                               unsigned ArgNo, CGBuilderTy &Builder) {
2261   assert(CGM.getCodeGenOpts().DebugInfo >= CodeGenOptions::LimitedDebugInfo);
2262   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2263 
2264   llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2265   llvm::DIType Ty;
2266   uint64_t XOffset = 0;
2267   if (VD->hasAttr<BlocksAttr>())
2268     Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
2269   else
2270     Ty = getOrCreateType(VD->getType(), Unit);
2271 
2272   // If there is not any debug info for type then do not emit debug info
2273   // for this variable.
2274   if (!Ty)
2275     return;
2276 
2277   if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage)) {
2278     // If Storage is an aggregate returned as 'sret' then let debugger know
2279     // about this.
2280     if (Arg->hasStructRetAttr())
2281       Ty = DBuilder.createReferenceType(llvm::dwarf::DW_TAG_reference_type, Ty);
2282     else if (CXXRecordDecl *Record = VD->getType()->getAsCXXRecordDecl()) {
2283       // If an aggregate variable has non trivial destructor or non trivial copy
2284       // constructor than it is pass indirectly. Let debug info know about this
2285       // by using reference of the aggregate type as a argument type.
2286       if (!Record->hasTrivialCopyConstructor() ||
2287           !Record->hasTrivialDestructor())
2288         Ty = DBuilder.createReferenceType(llvm::dwarf::DW_TAG_reference_type, Ty);
2289     }
2290   }
2291 
2292   // Get location information.
2293   unsigned Line = getLineNumber(VD->getLocation());
2294   unsigned Column = getColumnNumber(VD->getLocation());
2295   unsigned Flags = 0;
2296   if (VD->isImplicit())
2297     Flags |= llvm::DIDescriptor::FlagArtificial;
2298   llvm::MDNode *Scope = LexicalBlockStack.back();
2299 
2300   StringRef Name = VD->getName();
2301   if (!Name.empty()) {
2302     if (VD->hasAttr<BlocksAttr>()) {
2303       CharUnits offset = CharUnits::fromQuantity(32);
2304       SmallVector<llvm::Value *, 9> addr;
2305       llvm::Type *Int64Ty = CGM.Int64Ty;
2306       addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2307       // offset of __forwarding field
2308       offset = CGM.getContext().toCharUnitsFromBits(
2309         CGM.getContext().getTargetInfo().getPointerWidth(0));
2310       addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2311       addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2312       addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2313       // offset of x field
2314       offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2315       addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2316 
2317       // Create the descriptor for the variable.
2318       llvm::DIVariable D =
2319         DBuilder.createComplexVariable(Tag,
2320                                        llvm::DIDescriptor(Scope),
2321                                        VD->getName(), Unit, Line, Ty,
2322                                        addr, ArgNo);
2323 
2324       // Insert an llvm.dbg.declare into the current block.
2325       llvm::Instruction *Call =
2326         DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2327       Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2328       return;
2329     } else if (isa<VariableArrayType>(VD->getType())) {
2330       // These are "complex" variables in that they need an op_deref.
2331       // Create the descriptor for the variable.
2332       llvm::Value *Addr = llvm::ConstantInt::get(CGM.Int64Ty,
2333                                                  llvm::DIBuilder::OpDeref);
2334       llvm::DIVariable D =
2335         DBuilder.createComplexVariable(Tag,
2336                                        llvm::DIDescriptor(Scope),
2337                                        Name, Unit, Line, Ty,
2338                                        Addr, ArgNo);
2339 
2340       // Insert an llvm.dbg.declare into the current block.
2341       llvm::Instruction *Call =
2342         DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2343       Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2344       return;
2345     }
2346 
2347     // Create the descriptor for the variable.
2348     llvm::DIVariable D =
2349       DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2350                                    Name, Unit, Line, Ty,
2351                                    CGM.getLangOpts().Optimize, Flags, ArgNo);
2352 
2353     // Insert an llvm.dbg.declare into the current block.
2354     llvm::Instruction *Call =
2355       DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2356     Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2357     return;
2358   }
2359 
2360   // If VD is an anonymous union then Storage represents value for
2361   // all union fields.
2362   if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2363     const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
2364     if (RD->isUnion()) {
2365       for (RecordDecl::field_iterator I = RD->field_begin(),
2366              E = RD->field_end();
2367            I != E; ++I) {
2368         FieldDecl *Field = *I;
2369         llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2370         StringRef FieldName = Field->getName();
2371 
2372         // Ignore unnamed fields. Do not ignore unnamed records.
2373         if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2374           continue;
2375 
2376         // Use VarDecl's Tag, Scope and Line number.
2377         llvm::DIVariable D =
2378           DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2379                                        FieldName, Unit, Line, FieldTy,
2380                                        CGM.getLangOpts().Optimize, Flags,
2381                                        ArgNo);
2382 
2383         // Insert an llvm.dbg.declare into the current block.
2384         llvm::Instruction *Call =
2385           DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2386         Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2387       }
2388     }
2389   }
2390 }
2391 
2392 void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2393                                             llvm::Value *Storage,
2394                                             CGBuilderTy &Builder) {
2395   assert(CGM.getCodeGenOpts().DebugInfo >= CodeGenOptions::LimitedDebugInfo);
2396   EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2397 }
2398 
2399 void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(
2400   const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder,
2401   const CGBlockInfo &blockInfo) {
2402   assert(CGM.getCodeGenOpts().DebugInfo >= CodeGenOptions::LimitedDebugInfo);
2403   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2404 
2405   if (Builder.GetInsertBlock() == 0)
2406     return;
2407 
2408   bool isByRef = VD->hasAttr<BlocksAttr>();
2409 
2410   uint64_t XOffset = 0;
2411   llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2412   llvm::DIType Ty;
2413   if (isByRef)
2414     Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
2415   else
2416     Ty = getOrCreateType(VD->getType(), Unit);
2417 
2418   // Get location information.
2419   unsigned Line = getLineNumber(VD->getLocation());
2420   unsigned Column = getColumnNumber(VD->getLocation());
2421 
2422   const llvm::TargetData &target = CGM.getTargetData();
2423 
2424   CharUnits offset = CharUnits::fromQuantity(
2425     target.getStructLayout(blockInfo.StructureType)
2426           ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2427 
2428   SmallVector<llvm::Value *, 9> addr;
2429   llvm::Type *Int64Ty = CGM.Int64Ty;
2430   addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2431   addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2432   if (isByRef) {
2433     addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2434     addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2435     // offset of __forwarding field
2436     offset = CGM.getContext()
2437                 .toCharUnitsFromBits(target.getPointerSizeInBits());
2438     addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2439     addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2440     addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2441     // offset of x field
2442     offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2443     addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2444   }
2445 
2446   // Create the descriptor for the variable.
2447   llvm::DIVariable D =
2448     DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable,
2449                                    llvm::DIDescriptor(LexicalBlockStack.back()),
2450                                    VD->getName(), Unit, Line, Ty, addr);
2451   // Insert an llvm.dbg.declare into the current block.
2452   llvm::Instruction *Call =
2453     DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
2454   Call->setDebugLoc(llvm::DebugLoc::get(Line, Column,
2455                                         LexicalBlockStack.back()));
2456 }
2457 
2458 /// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2459 /// variable declaration.
2460 void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2461                                            unsigned ArgNo,
2462                                            CGBuilderTy &Builder) {
2463   assert(CGM.getCodeGenOpts().DebugInfo >= CodeGenOptions::LimitedDebugInfo);
2464   EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2465 }
2466 
2467 namespace {
2468   struct BlockLayoutChunk {
2469     uint64_t OffsetInBits;
2470     const BlockDecl::Capture *Capture;
2471   };
2472   bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2473     return l.OffsetInBits < r.OffsetInBits;
2474   }
2475 }
2476 
2477 void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
2478                                                        llvm::Value *addr,
2479                                                        CGBuilderTy &Builder) {
2480   assert(CGM.getCodeGenOpts().DebugInfo >= CodeGenOptions::LimitedDebugInfo);
2481   ASTContext &C = CGM.getContext();
2482   const BlockDecl *blockDecl = block.getBlockDecl();
2483 
2484   // Collect some general information about the block's location.
2485   SourceLocation loc = blockDecl->getCaretLocation();
2486   llvm::DIFile tunit = getOrCreateFile(loc);
2487   unsigned line = getLineNumber(loc);
2488   unsigned column = getColumnNumber(loc);
2489 
2490   // Build the debug-info type for the block literal.
2491   getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
2492 
2493   const llvm::StructLayout *blockLayout =
2494     CGM.getTargetData().getStructLayout(block.StructureType);
2495 
2496   SmallVector<llvm::Value*, 16> fields;
2497   fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
2498                                    blockLayout->getElementOffsetInBits(0),
2499                                    tunit, tunit));
2500   fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
2501                                    blockLayout->getElementOffsetInBits(1),
2502                                    tunit, tunit));
2503   fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
2504                                    blockLayout->getElementOffsetInBits(2),
2505                                    tunit, tunit));
2506   fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
2507                                    blockLayout->getElementOffsetInBits(3),
2508                                    tunit, tunit));
2509   fields.push_back(createFieldType("__descriptor",
2510                                    C.getPointerType(block.NeedsCopyDispose ?
2511                                         C.getBlockDescriptorExtendedType() :
2512                                         C.getBlockDescriptorType()),
2513                                    0, loc, AS_public,
2514                                    blockLayout->getElementOffsetInBits(4),
2515                                    tunit, tunit));
2516 
2517   // We want to sort the captures by offset, not because DWARF
2518   // requires this, but because we're paranoid about debuggers.
2519   SmallVector<BlockLayoutChunk, 8> chunks;
2520 
2521   // 'this' capture.
2522   if (blockDecl->capturesCXXThis()) {
2523     BlockLayoutChunk chunk;
2524     chunk.OffsetInBits =
2525       blockLayout->getElementOffsetInBits(block.CXXThisIndex);
2526     chunk.Capture = 0;
2527     chunks.push_back(chunk);
2528   }
2529 
2530   // Variable captures.
2531   for (BlockDecl::capture_const_iterator
2532          i = blockDecl->capture_begin(), e = blockDecl->capture_end();
2533        i != e; ++i) {
2534     const BlockDecl::Capture &capture = *i;
2535     const VarDecl *variable = capture.getVariable();
2536     const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
2537 
2538     // Ignore constant captures.
2539     if (captureInfo.isConstant())
2540       continue;
2541 
2542     BlockLayoutChunk chunk;
2543     chunk.OffsetInBits =
2544       blockLayout->getElementOffsetInBits(captureInfo.getIndex());
2545     chunk.Capture = &capture;
2546     chunks.push_back(chunk);
2547   }
2548 
2549   // Sort by offset.
2550   llvm::array_pod_sort(chunks.begin(), chunks.end());
2551 
2552   for (SmallVectorImpl<BlockLayoutChunk>::iterator
2553          i = chunks.begin(), e = chunks.end(); i != e; ++i) {
2554     uint64_t offsetInBits = i->OffsetInBits;
2555     const BlockDecl::Capture *capture = i->Capture;
2556 
2557     // If we have a null capture, this must be the C++ 'this' capture.
2558     if (!capture) {
2559       const CXXMethodDecl *method =
2560         cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
2561       QualType type = method->getThisType(C);
2562 
2563       fields.push_back(createFieldType("this", type, 0, loc, AS_public,
2564                                        offsetInBits, tunit, tunit));
2565       continue;
2566     }
2567 
2568     const VarDecl *variable = capture->getVariable();
2569     StringRef name = variable->getName();
2570 
2571     llvm::DIType fieldType;
2572     if (capture->isByRef()) {
2573       std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
2574 
2575       // FIXME: this creates a second copy of this type!
2576       uint64_t xoffset;
2577       fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
2578       fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
2579       fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
2580                                             ptrInfo.first, ptrInfo.second,
2581                                             offsetInBits, 0, fieldType);
2582     } else {
2583       fieldType = createFieldType(name, variable->getType(), 0,
2584                                   loc, AS_public, offsetInBits, tunit, tunit);
2585     }
2586     fields.push_back(fieldType);
2587   }
2588 
2589   SmallString<36> typeName;
2590   llvm::raw_svector_ostream(typeName)
2591     << "__block_literal_" << CGM.getUniqueBlockCount();
2592 
2593   llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
2594 
2595   llvm::DIType type =
2596     DBuilder.createStructType(tunit, typeName.str(), tunit, line,
2597                               CGM.getContext().toBits(block.BlockSize),
2598                               CGM.getContext().toBits(block.BlockAlign),
2599                               0, fieldsArray);
2600   type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
2601 
2602   // Get overall information about the block.
2603   unsigned flags = llvm::DIDescriptor::FlagArtificial;
2604   llvm::MDNode *scope = LexicalBlockStack.back();
2605   StringRef name = ".block_descriptor";
2606 
2607   // Create the descriptor for the parameter.
2608   llvm::DIVariable debugVar =
2609     DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
2610                                  llvm::DIDescriptor(scope),
2611                                  name, tunit, line, type,
2612                                  CGM.getLangOpts().Optimize, flags,
2613                                  cast<llvm::Argument>(addr)->getArgNo() + 1);
2614 
2615   // Insert an llvm.dbg.value into the current block.
2616   llvm::Instruction *declare =
2617     DBuilder.insertDbgValueIntrinsic(addr, 0, debugVar,
2618                                      Builder.GetInsertBlock());
2619   declare->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
2620 }
2621 
2622 /// EmitGlobalVariable - Emit information about a global variable.
2623 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
2624                                      const VarDecl *D) {
2625   assert(CGM.getCodeGenOpts().DebugInfo >= CodeGenOptions::LimitedDebugInfo);
2626   // Create global variable debug descriptor.
2627   llvm::DIFile Unit = getOrCreateFile(D->getLocation());
2628   unsigned LineNo = getLineNumber(D->getLocation());
2629 
2630   setLocation(D->getLocation());
2631 
2632   QualType T = D->getType();
2633   if (T->isIncompleteArrayType()) {
2634 
2635     // CodeGen turns int[] into int[1] so we'll do the same here.
2636     llvm::APInt ConstVal(32, 1);
2637     QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
2638 
2639     T = CGM.getContext().getConstantArrayType(ET, ConstVal,
2640                                               ArrayType::Normal, 0);
2641   }
2642   StringRef DeclName = D->getName();
2643   StringRef LinkageName;
2644   if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext())
2645       && !isa<ObjCMethodDecl>(D->getDeclContext()))
2646     LinkageName = Var->getName();
2647   if (LinkageName == DeclName)
2648     LinkageName = StringRef();
2649   llvm::DIDescriptor DContext =
2650     getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
2651   DBuilder.createStaticVariable(DContext, DeclName, LinkageName,
2652                                 Unit, LineNo, getOrCreateType(T, Unit),
2653                                 Var->hasInternalLinkage(), Var);
2654 }
2655 
2656 /// EmitGlobalVariable - Emit information about an objective-c interface.
2657 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
2658                                      ObjCInterfaceDecl *ID) {
2659   assert(CGM.getCodeGenOpts().DebugInfo >= CodeGenOptions::LimitedDebugInfo);
2660   // Create global variable debug descriptor.
2661   llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
2662   unsigned LineNo = getLineNumber(ID->getLocation());
2663 
2664   StringRef Name = ID->getName();
2665 
2666   QualType T = CGM.getContext().getObjCInterfaceType(ID);
2667   if (T->isIncompleteArrayType()) {
2668 
2669     // CodeGen turns int[] into int[1] so we'll do the same here.
2670     llvm::APInt ConstVal(32, 1);
2671     QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
2672 
2673     T = CGM.getContext().getConstantArrayType(ET, ConstVal,
2674                                            ArrayType::Normal, 0);
2675   }
2676 
2677   DBuilder.createGlobalVariable(Name, Unit, LineNo,
2678                                 getOrCreateType(T, Unit),
2679                                 Var->hasInternalLinkage(), Var);
2680 }
2681 
2682 /// EmitGlobalVariable - Emit global variable's debug info.
2683 void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
2684                                      llvm::Constant *Init) {
2685   assert(CGM.getCodeGenOpts().DebugInfo >= CodeGenOptions::LimitedDebugInfo);
2686   // Create the descriptor for the variable.
2687   llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2688   StringRef Name = VD->getName();
2689   llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
2690   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
2691     const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext());
2692     assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
2693     Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
2694   }
2695   // Do not use DIGlobalVariable for enums.
2696   if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
2697     return;
2698   DBuilder.createStaticVariable(Unit, Name, Name, Unit,
2699                                 getLineNumber(VD->getLocation()),
2700                                 Ty, true, Init);
2701 }
2702 
2703 /// getOrCreateNamesSpace - Return namespace descriptor for the given
2704 /// namespace decl.
2705 llvm::DINameSpace
2706 CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
2707   llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
2708     NameSpaceCache.find(NSDecl);
2709   if (I != NameSpaceCache.end())
2710     return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
2711 
2712   unsigned LineNo = getLineNumber(NSDecl->getLocation());
2713   llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
2714   llvm::DIDescriptor Context =
2715     getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
2716   llvm::DINameSpace NS =
2717     DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
2718   NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
2719   return NS;
2720 }
2721 
2722 void CGDebugInfo::finalize(void) {
2723   for (std::vector<std::pair<void *, llvm::WeakVH> >::const_iterator VI
2724          = ReplaceMap.begin(), VE = ReplaceMap.end(); VI != VE; ++VI) {
2725     llvm::DIType Ty, RepTy;
2726     // Verify that the debug info still exists.
2727     if (llvm::Value *V = VI->second)
2728       Ty = llvm::DIType(cast<llvm::MDNode>(V));
2729 
2730     llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
2731       TypeCache.find(VI->first);
2732     if (it != TypeCache.end()) {
2733       // Verify that the debug info still exists.
2734       if (llvm::Value *V = it->second)
2735         RepTy = llvm::DIType(cast<llvm::MDNode>(V));
2736     }
2737 
2738     if (Ty.Verify() && Ty.isForwardDecl() && RepTy.Verify()) {
2739       Ty.replaceAllUsesWith(RepTy);
2740     }
2741   }
2742   DBuilder.finalize();
2743 }
2744