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