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