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