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