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