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