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