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