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