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