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