1 //===--- CGDebugInfo.cpp - Emit Debug Information for a Module ------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This coordinates the debug information generation while generating code.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "CGDebugInfo.h"
14 #include "CGBlocks.h"
15 #include "CGCXXABI.h"
16 #include "CGObjCRuntime.h"
17 #include "CGRecordLayout.h"
18 #include "CodeGenFunction.h"
19 #include "CodeGenModule.h"
20 #include "ConstantEmitter.h"
21 #include "clang/AST/ASTContext.h"
22 #include "clang/AST/Attr.h"
23 #include "clang/AST/DeclFriend.h"
24 #include "clang/AST/DeclObjC.h"
25 #include "clang/AST/DeclTemplate.h"
26 #include "clang/AST/Expr.h"
27 #include "clang/AST/RecordLayout.h"
28 #include "clang/AST/RecursiveASTVisitor.h"
29 #include "clang/Basic/CodeGenOptions.h"
30 #include "clang/Basic/FileManager.h"
31 #include "clang/Basic/SourceManager.h"
32 #include "clang/Basic/Version.h"
33 #include "clang/Frontend/FrontendOptions.h"
34 #include "clang/Lex/HeaderSearchOptions.h"
35 #include "clang/Lex/ModuleMap.h"
36 #include "clang/Lex/PreprocessorOptions.h"
37 #include "llvm/ADT/DenseSet.h"
38 #include "llvm/ADT/SmallVector.h"
39 #include "llvm/ADT/StringExtras.h"
40 #include "llvm/IR/Constants.h"
41 #include "llvm/IR/DataLayout.h"
42 #include "llvm/IR/DerivedTypes.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/Intrinsics.h"
45 #include "llvm/IR/Metadata.h"
46 #include "llvm/IR/Module.h"
47 #include "llvm/Support/FileSystem.h"
48 #include "llvm/Support/MD5.h"
49 #include "llvm/Support/Path.h"
50 #include "llvm/Support/TimeProfiler.h"
51 using namespace clang;
52 using namespace clang::CodeGen;
53 
54 static uint32_t getTypeAlignIfRequired(const Type *Ty, const ASTContext &Ctx) {
55   auto TI = Ctx.getTypeInfo(Ty);
56   return TI.isAlignRequired() ? TI.Align : 0;
57 }
58 
59 static uint32_t getTypeAlignIfRequired(QualType Ty, const ASTContext &Ctx) {
60   return getTypeAlignIfRequired(Ty.getTypePtr(), Ctx);
61 }
62 
63 static uint32_t getDeclAlignIfRequired(const Decl *D, const ASTContext &Ctx) {
64   return D->hasAttr<AlignedAttr>() ? D->getMaxAlignment() : 0;
65 }
66 
67 CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
68     : CGM(CGM), DebugKind(CGM.getCodeGenOpts().getDebugInfo()),
69       DebugTypeExtRefs(CGM.getCodeGenOpts().DebugTypeExtRefs),
70       DBuilder(CGM.getModule()) {
71   for (const auto &KV : CGM.getCodeGenOpts().DebugPrefixMap)
72     DebugPrefixMap[KV.first] = KV.second;
73   CreateCompileUnit();
74 }
75 
76 CGDebugInfo::~CGDebugInfo() {
77   assert(LexicalBlockStack.empty() &&
78          "Region stack mismatch, stack not empty!");
79 }
80 
81 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF,
82                                        SourceLocation TemporaryLocation)
83     : CGF(&CGF) {
84   init(TemporaryLocation);
85 }
86 
87 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF,
88                                        bool DefaultToEmpty,
89                                        SourceLocation TemporaryLocation)
90     : CGF(&CGF) {
91   init(TemporaryLocation, DefaultToEmpty);
92 }
93 
94 void ApplyDebugLocation::init(SourceLocation TemporaryLocation,
95                               bool DefaultToEmpty) {
96   auto *DI = CGF->getDebugInfo();
97   if (!DI) {
98     CGF = nullptr;
99     return;
100   }
101 
102   OriginalLocation = CGF->Builder.getCurrentDebugLocation();
103 
104   if (OriginalLocation && !DI->CGM.getExpressionLocationsEnabled())
105     return;
106 
107   if (TemporaryLocation.isValid()) {
108     DI->EmitLocation(CGF->Builder, TemporaryLocation);
109     return;
110   }
111 
112   if (DefaultToEmpty) {
113     CGF->Builder.SetCurrentDebugLocation(llvm::DebugLoc());
114     return;
115   }
116 
117   // Construct a location that has a valid scope, but no line info.
118   assert(!DI->LexicalBlockStack.empty());
119   CGF->Builder.SetCurrentDebugLocation(
120       llvm::DILocation::get(DI->LexicalBlockStack.back()->getContext(), 0, 0,
121                             DI->LexicalBlockStack.back(), DI->getInlinedAt()));
122 }
123 
124 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, const Expr *E)
125     : CGF(&CGF) {
126   init(E->getExprLoc());
127 }
128 
129 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, llvm::DebugLoc Loc)
130     : CGF(&CGF) {
131   if (!CGF.getDebugInfo()) {
132     this->CGF = nullptr;
133     return;
134   }
135   OriginalLocation = CGF.Builder.getCurrentDebugLocation();
136   if (Loc)
137     CGF.Builder.SetCurrentDebugLocation(std::move(Loc));
138 }
139 
140 ApplyDebugLocation::~ApplyDebugLocation() {
141   // Query CGF so the location isn't overwritten when location updates are
142   // temporarily disabled (for C++ default function arguments)
143   if (CGF)
144     CGF->Builder.SetCurrentDebugLocation(std::move(OriginalLocation));
145 }
146 
147 ApplyInlineDebugLocation::ApplyInlineDebugLocation(CodeGenFunction &CGF,
148                                                    GlobalDecl InlinedFn)
149     : CGF(&CGF) {
150   if (!CGF.getDebugInfo()) {
151     this->CGF = nullptr;
152     return;
153   }
154   auto &DI = *CGF.getDebugInfo();
155   SavedLocation = DI.getLocation();
156   assert((DI.getInlinedAt() ==
157           CGF.Builder.getCurrentDebugLocation()->getInlinedAt()) &&
158          "CGDebugInfo and IRBuilder are out of sync");
159 
160   DI.EmitInlineFunctionStart(CGF.Builder, InlinedFn);
161 }
162 
163 ApplyInlineDebugLocation::~ApplyInlineDebugLocation() {
164   if (!CGF)
165     return;
166   auto &DI = *CGF->getDebugInfo();
167   DI.EmitInlineFunctionEnd(CGF->Builder);
168   DI.EmitLocation(CGF->Builder, SavedLocation);
169 }
170 
171 void CGDebugInfo::setLocation(SourceLocation Loc) {
172   // If the new location isn't valid return.
173   if (Loc.isInvalid())
174     return;
175 
176   CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc);
177 
178   // If we've changed files in the middle of a lexical scope go ahead
179   // and create a new lexical scope with file node if it's different
180   // from the one in the scope.
181   if (LexicalBlockStack.empty())
182     return;
183 
184   SourceManager &SM = CGM.getContext().getSourceManager();
185   auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
186   PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
187   if (PCLoc.isInvalid() || Scope->getFile() == getOrCreateFile(CurLoc))
188     return;
189 
190   if (auto *LBF = dyn_cast<llvm::DILexicalBlockFile>(Scope)) {
191     LexicalBlockStack.pop_back();
192     LexicalBlockStack.emplace_back(DBuilder.createLexicalBlockFile(
193         LBF->getScope(), getOrCreateFile(CurLoc)));
194   } else if (isa<llvm::DILexicalBlock>(Scope) ||
195              isa<llvm::DISubprogram>(Scope)) {
196     LexicalBlockStack.pop_back();
197     LexicalBlockStack.emplace_back(
198         DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc)));
199   }
200 }
201 
202 llvm::DIScope *CGDebugInfo::getDeclContextDescriptor(const Decl *D) {
203   llvm::DIScope *Mod = getParentModuleOrNull(D);
204   return getContextDescriptor(cast<Decl>(D->getDeclContext()),
205                               Mod ? Mod : TheCU);
206 }
207 
208 llvm::DIScope *CGDebugInfo::getContextDescriptor(const Decl *Context,
209                                                  llvm::DIScope *Default) {
210   if (!Context)
211     return Default;
212 
213   auto I = RegionMap.find(Context);
214   if (I != RegionMap.end()) {
215     llvm::Metadata *V = I->second;
216     return dyn_cast_or_null<llvm::DIScope>(V);
217   }
218 
219   // Check namespace.
220   if (const auto *NSDecl = dyn_cast<NamespaceDecl>(Context))
221     return getOrCreateNamespace(NSDecl);
222 
223   if (const auto *RDecl = dyn_cast<RecordDecl>(Context))
224     if (!RDecl->isDependentType())
225       return getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
226                              TheCU->getFile());
227   return Default;
228 }
229 
230 PrintingPolicy CGDebugInfo::getPrintingPolicy() const {
231   PrintingPolicy PP = CGM.getContext().getPrintingPolicy();
232 
233   // If we're emitting codeview, it's important to try to match MSVC's naming so
234   // that visualizers written for MSVC will trigger for our class names. In
235   // particular, we can't have spaces between arguments of standard templates
236   // like basic_string and vector, but we must have spaces between consecutive
237   // angle brackets that close nested template argument lists.
238   if (CGM.getCodeGenOpts().EmitCodeView) {
239     PP.MSVCFormatting = true;
240     PP.SplitTemplateClosers = true;
241   } else {
242     // For DWARF, printing rules are underspecified.
243     // SplitTemplateClosers yields better interop with GCC and GDB (PR46052).
244     PP.SplitTemplateClosers = true;
245   }
246 
247   PP.SuppressInlineNamespace = false;
248   PP.PrintCanonicalTypes = true;
249   PP.UsePreferredNames = false;
250   PP.AlwaysIncludeTypeForTemplateArgument = true;
251   PP.UseEnumerators = false;
252 
253   // Apply -fdebug-prefix-map.
254   PP.Callbacks = &PrintCB;
255   return PP;
256 }
257 
258 StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
259   return internString(GetName(FD));
260 }
261 
262 StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
263   SmallString<256> MethodName;
264   llvm::raw_svector_ostream OS(MethodName);
265   OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
266   const DeclContext *DC = OMD->getDeclContext();
267   if (const auto *OID = dyn_cast<ObjCImplementationDecl>(DC)) {
268     OS << OID->getName();
269   } else if (const auto *OID = dyn_cast<ObjCInterfaceDecl>(DC)) {
270     OS << OID->getName();
271   } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(DC)) {
272     if (OC->IsClassExtension()) {
273       OS << OC->getClassInterface()->getName();
274     } else {
275       OS << OC->getIdentifier()->getNameStart() << '('
276          << OC->getIdentifier()->getNameStart() << ')';
277     }
278   } else if (const auto *OCD = dyn_cast<ObjCCategoryImplDecl>(DC)) {
279     OS << OCD->getClassInterface()->getName() << '(' << OCD->getName() << ')';
280   }
281   OS << ' ' << OMD->getSelector().getAsString() << ']';
282 
283   return internString(OS.str());
284 }
285 
286 StringRef CGDebugInfo::getSelectorName(Selector S) {
287   return internString(S.getAsString());
288 }
289 
290 StringRef CGDebugInfo::getClassName(const RecordDecl *RD) {
291   if (isa<ClassTemplateSpecializationDecl>(RD)) {
292     // Copy this name on the side and use its reference.
293     return internString(GetName(RD));
294   }
295 
296   // quick optimization to avoid having to intern strings that are already
297   // stored reliably elsewhere
298   if (const IdentifierInfo *II = RD->getIdentifier())
299     return II->getName();
300 
301   // The CodeView printer in LLVM wants to see the names of unnamed types
302   // because they need to have a unique identifier.
303   // These names are used to reconstruct the fully qualified type names.
304   if (CGM.getCodeGenOpts().EmitCodeView) {
305     if (const TypedefNameDecl *D = RD->getTypedefNameForAnonDecl()) {
306       assert(RD->getDeclContext() == D->getDeclContext() &&
307              "Typedef should not be in another decl context!");
308       assert(D->getDeclName().getAsIdentifierInfo() &&
309              "Typedef was not named!");
310       return D->getDeclName().getAsIdentifierInfo()->getName();
311     }
312 
313     if (CGM.getLangOpts().CPlusPlus) {
314       StringRef Name;
315 
316       ASTContext &Context = CGM.getContext();
317       if (const DeclaratorDecl *DD = Context.getDeclaratorForUnnamedTagDecl(RD))
318         // Anonymous types without a name for linkage purposes have their
319         // declarator mangled in if they have one.
320         Name = DD->getName();
321       else if (const TypedefNameDecl *TND =
322                    Context.getTypedefNameForUnnamedTagDecl(RD))
323         // Anonymous types without a name for linkage purposes have their
324         // associate typedef mangled in if they have one.
325         Name = TND->getName();
326 
327       // Give lambdas a display name based on their name mangling.
328       if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
329         if (CXXRD->isLambda())
330           return internString(
331               CGM.getCXXABI().getMangleContext().getLambdaString(CXXRD));
332 
333       if (!Name.empty()) {
334         SmallString<256> UnnamedType("<unnamed-type-");
335         UnnamedType += Name;
336         UnnamedType += '>';
337         return internString(UnnamedType);
338       }
339     }
340   }
341 
342   return StringRef();
343 }
344 
345 Optional<llvm::DIFile::ChecksumKind>
346 CGDebugInfo::computeChecksum(FileID FID, SmallString<32> &Checksum) const {
347   Checksum.clear();
348 
349   if (!CGM.getCodeGenOpts().EmitCodeView &&
350       CGM.getCodeGenOpts().DwarfVersion < 5)
351     return None;
352 
353   SourceManager &SM = CGM.getContext().getSourceManager();
354   Optional<llvm::MemoryBufferRef> MemBuffer = SM.getBufferOrNone(FID);
355   if (!MemBuffer)
356     return None;
357 
358   llvm::toHex(
359       llvm::MD5::hash(llvm::arrayRefFromStringRef(MemBuffer->getBuffer())),
360       /*LowerCase*/ true, Checksum);
361   return llvm::DIFile::CSK_MD5;
362 }
363 
364 Optional<StringRef> CGDebugInfo::getSource(const SourceManager &SM,
365                                            FileID FID) {
366   if (!CGM.getCodeGenOpts().EmbedSource)
367     return None;
368 
369   bool SourceInvalid = false;
370   StringRef Source = SM.getBufferData(FID, &SourceInvalid);
371 
372   if (SourceInvalid)
373     return None;
374 
375   return Source;
376 }
377 
378 llvm::DIFile *CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
379   SourceManager &SM = CGM.getContext().getSourceManager();
380   StringRef FileName;
381   FileID FID;
382 
383   if (Loc.isInvalid()) {
384     // The DIFile used by the CU is distinct from the main source file. Call
385     // createFile() below for canonicalization if the source file was specified
386     // with an absolute path.
387     FileName = TheCU->getFile()->getFilename();
388   } else {
389     PresumedLoc PLoc = SM.getPresumedLoc(Loc);
390     FileName = PLoc.getFilename();
391 
392     if (FileName.empty()) {
393       FileName = TheCU->getFile()->getFilename();
394     } else {
395       FileName = PLoc.getFilename();
396     }
397     FID = PLoc.getFileID();
398   }
399 
400   // Cache the results.
401   auto It = DIFileCache.find(FileName.data());
402   if (It != DIFileCache.end()) {
403     // Verify that the information still exists.
404     if (llvm::Metadata *V = It->second)
405       return cast<llvm::DIFile>(V);
406   }
407 
408   SmallString<32> Checksum;
409 
410   Optional<llvm::DIFile::ChecksumKind> CSKind = computeChecksum(FID, Checksum);
411   Optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo;
412   if (CSKind)
413     CSInfo.emplace(*CSKind, Checksum);
414   return createFile(FileName, CSInfo, getSource(SM, SM.getFileID(Loc)));
415 }
416 
417 llvm::DIFile *
418 CGDebugInfo::createFile(StringRef FileName,
419                         Optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo,
420                         Optional<StringRef> Source) {
421   StringRef Dir;
422   StringRef File;
423   std::string RemappedFile = remapDIPath(FileName);
424   std::string CurDir = remapDIPath(getCurrentDirname());
425   SmallString<128> DirBuf;
426   SmallString<128> FileBuf;
427   if (llvm::sys::path::is_absolute(RemappedFile)) {
428     // Strip the common prefix (if it is more than just "/" or "C:\") from
429     // current directory and FileName for a more space-efficient encoding.
430     auto FileIt = llvm::sys::path::begin(RemappedFile);
431     auto FileE = llvm::sys::path::end(RemappedFile);
432     auto CurDirIt = llvm::sys::path::begin(CurDir);
433     auto CurDirE = llvm::sys::path::end(CurDir);
434     for (; CurDirIt != CurDirE && *CurDirIt == *FileIt; ++CurDirIt, ++FileIt)
435       llvm::sys::path::append(DirBuf, *CurDirIt);
436     if (llvm::sys::path::root_path(DirBuf) == DirBuf) {
437       // Don't strip the common prefix if it is only the root ("/" or "C:\")
438       // since that would make LLVM diagnostic locations confusing.
439       Dir = {};
440       File = RemappedFile;
441     } else {
442       for (; FileIt != FileE; ++FileIt)
443         llvm::sys::path::append(FileBuf, *FileIt);
444       Dir = DirBuf;
445       File = FileBuf;
446     }
447   } else {
448     if (!llvm::sys::path::is_absolute(FileName))
449       Dir = CurDir;
450     File = RemappedFile;
451   }
452   llvm::DIFile *F = DBuilder.createFile(File, Dir, CSInfo, Source);
453   DIFileCache[FileName.data()].reset(F);
454   return F;
455 }
456 
457 std::string CGDebugInfo::remapDIPath(StringRef Path) const {
458   if (DebugPrefixMap.empty())
459     return Path.str();
460 
461   SmallString<256> P = Path;
462   for (const auto &Entry : DebugPrefixMap)
463     if (llvm::sys::path::replace_path_prefix(P, Entry.first, Entry.second))
464       break;
465   return P.str().str();
466 }
467 
468 unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
469   if (Loc.isInvalid())
470     return 0;
471   SourceManager &SM = CGM.getContext().getSourceManager();
472   return SM.getPresumedLoc(Loc).getLine();
473 }
474 
475 unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {
476   // We may not want column information at all.
477   if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo)
478     return 0;
479 
480   // If the location is invalid then use the current column.
481   if (Loc.isInvalid() && CurLoc.isInvalid())
482     return 0;
483   SourceManager &SM = CGM.getContext().getSourceManager();
484   PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
485   return PLoc.isValid() ? PLoc.getColumn() : 0;
486 }
487 
488 StringRef CGDebugInfo::getCurrentDirname() {
489   if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
490     return CGM.getCodeGenOpts().DebugCompilationDir;
491 
492   if (!CWDName.empty())
493     return CWDName;
494   SmallString<256> CWD;
495   llvm::sys::fs::current_path(CWD);
496   return CWDName = internString(CWD);
497 }
498 
499 void CGDebugInfo::CreateCompileUnit() {
500   SmallString<32> Checksum;
501   Optional<llvm::DIFile::ChecksumKind> CSKind;
502   Optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo;
503 
504   // Should we be asking the SourceManager for the main file name, instead of
505   // accepting it as an argument? This just causes the main file name to
506   // mismatch with source locations and create extra lexical scopes or
507   // mismatched debug info (a CU with a DW_AT_file of "-", because that's what
508   // the driver passed, but functions/other things have DW_AT_file of "<stdin>"
509   // because that's what the SourceManager says)
510 
511   // Get absolute path name.
512   SourceManager &SM = CGM.getContext().getSourceManager();
513   std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
514   if (MainFileName.empty())
515     MainFileName = "<stdin>";
516 
517   // The main file name provided via the "-main-file-name" option contains just
518   // the file name itself with no path information. This file name may have had
519   // a relative path, so we look into the actual file entry for the main
520   // file to determine the real absolute path for the file.
521   std::string MainFileDir;
522   if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
523     MainFileDir = std::string(MainFile->getDir()->getName());
524     if (!llvm::sys::path::is_absolute(MainFileName)) {
525       llvm::SmallString<1024> MainFileDirSS(MainFileDir);
526       llvm::sys::path::append(MainFileDirSS, MainFileName);
527       MainFileName =
528           std::string(llvm::sys::path::remove_leading_dotslash(MainFileDirSS));
529     }
530     // If the main file name provided is identical to the input file name, and
531     // if the input file is a preprocessed source, use the module name for
532     // debug info. The module name comes from the name specified in the first
533     // linemarker if the input is a preprocessed source.
534     if (MainFile->getName() == MainFileName &&
535         FrontendOptions::getInputKindForExtension(
536             MainFile->getName().rsplit('.').second)
537             .isPreprocessed())
538       MainFileName = CGM.getModule().getName().str();
539 
540     CSKind = computeChecksum(SM.getMainFileID(), Checksum);
541   }
542 
543   llvm::dwarf::SourceLanguage LangTag;
544   const LangOptions &LO = CGM.getLangOpts();
545   if (LO.CPlusPlus) {
546     if (LO.ObjC)
547       LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
548     else if (LO.CPlusPlus14 && (!CGM.getCodeGenOpts().DebugStrictDwarf ||
549                                 CGM.getCodeGenOpts().DwarfVersion >= 5))
550       LangTag = llvm::dwarf::DW_LANG_C_plus_plus_14;
551     else if (LO.CPlusPlus11 && (!CGM.getCodeGenOpts().DebugStrictDwarf ||
552                                 CGM.getCodeGenOpts().DwarfVersion >= 5))
553       LangTag = llvm::dwarf::DW_LANG_C_plus_plus_11;
554     else
555       LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
556   } else if (LO.ObjC) {
557     LangTag = llvm::dwarf::DW_LANG_ObjC;
558   } else if (LO.OpenCL && (!CGM.getCodeGenOpts().DebugStrictDwarf ||
559                            CGM.getCodeGenOpts().DwarfVersion >= 5)) {
560     LangTag = llvm::dwarf::DW_LANG_OpenCL;
561   } else if (LO.RenderScript) {
562     LangTag = llvm::dwarf::DW_LANG_GOOGLE_RenderScript;
563   } else if (LO.C99) {
564     LangTag = llvm::dwarf::DW_LANG_C99;
565   } else {
566     LangTag = llvm::dwarf::DW_LANG_C89;
567   }
568 
569   std::string Producer = getClangFullVersion();
570 
571   // Figure out which version of the ObjC runtime we have.
572   unsigned RuntimeVers = 0;
573   if (LO.ObjC)
574     RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
575 
576   llvm::DICompileUnit::DebugEmissionKind EmissionKind;
577   switch (DebugKind) {
578   case codegenoptions::NoDebugInfo:
579   case codegenoptions::LocTrackingOnly:
580     EmissionKind = llvm::DICompileUnit::NoDebug;
581     break;
582   case codegenoptions::DebugLineTablesOnly:
583     EmissionKind = llvm::DICompileUnit::LineTablesOnly;
584     break;
585   case codegenoptions::DebugDirectivesOnly:
586     EmissionKind = llvm::DICompileUnit::DebugDirectivesOnly;
587     break;
588   case codegenoptions::DebugInfoConstructor:
589   case codegenoptions::LimitedDebugInfo:
590   case codegenoptions::FullDebugInfo:
591   case codegenoptions::UnusedTypeInfo:
592     EmissionKind = llvm::DICompileUnit::FullDebug;
593     break;
594   }
595 
596   uint64_t DwoId = 0;
597   auto &CGOpts = CGM.getCodeGenOpts();
598   // The DIFile used by the CU is distinct from the main source
599   // file. Its directory part specifies what becomes the
600   // DW_AT_comp_dir (the compilation directory), even if the source
601   // file was specified with an absolute path.
602   if (CSKind)
603     CSInfo.emplace(*CSKind, Checksum);
604   llvm::DIFile *CUFile = DBuilder.createFile(
605       remapDIPath(MainFileName), remapDIPath(getCurrentDirname()), CSInfo,
606       getSource(SM, SM.getMainFileID()));
607 
608   StringRef Sysroot, SDK;
609   if (CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB) {
610     Sysroot = CGM.getHeaderSearchOpts().Sysroot;
611     auto B = llvm::sys::path::rbegin(Sysroot);
612     auto E = llvm::sys::path::rend(Sysroot);
613     auto It = std::find_if(B, E, [](auto SDK) { return SDK.endswith(".sdk"); });
614     if (It != E)
615       SDK = *It;
616   }
617 
618   // Create new compile unit.
619   TheCU = DBuilder.createCompileUnit(
620       LangTag, CUFile, CGOpts.EmitVersionIdentMetadata ? Producer : "",
621       LO.Optimize || CGOpts.PrepareForLTO || CGOpts.PrepareForThinLTO,
622       CGOpts.DwarfDebugFlags, RuntimeVers, CGOpts.SplitDwarfFile, EmissionKind,
623       DwoId, CGOpts.SplitDwarfInlining, CGOpts.DebugInfoForProfiling,
624       CGM.getTarget().getTriple().isNVPTX()
625           ? llvm::DICompileUnit::DebugNameTableKind::None
626           : static_cast<llvm::DICompileUnit::DebugNameTableKind>(
627                 CGOpts.DebugNameTable),
628       CGOpts.DebugRangesBaseAddress, remapDIPath(Sysroot), SDK);
629 }
630 
631 llvm::DIType *CGDebugInfo::CreateType(const BuiltinType *BT) {
632   llvm::dwarf::TypeKind Encoding;
633   StringRef BTName;
634   switch (BT->getKind()) {
635 #define BUILTIN_TYPE(Id, SingletonId)
636 #define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
637 #include "clang/AST/BuiltinTypes.def"
638   case BuiltinType::Dependent:
639     llvm_unreachable("Unexpected builtin type");
640   case BuiltinType::NullPtr:
641     return DBuilder.createNullPtrType();
642   case BuiltinType::Void:
643     return nullptr;
644   case BuiltinType::ObjCClass:
645     if (!ClassTy)
646       ClassTy =
647           DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
648                                      "objc_class", TheCU, TheCU->getFile(), 0);
649     return ClassTy;
650   case BuiltinType::ObjCId: {
651     // typedef struct objc_class *Class;
652     // typedef struct objc_object {
653     //  Class isa;
654     // } *id;
655 
656     if (ObjTy)
657       return ObjTy;
658 
659     if (!ClassTy)
660       ClassTy =
661           DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
662                                      "objc_class", TheCU, TheCU->getFile(), 0);
663 
664     unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
665 
666     auto *ISATy = DBuilder.createPointerType(ClassTy, Size);
667 
668     ObjTy = DBuilder.createStructType(TheCU, "objc_object", TheCU->getFile(), 0,
669                                       0, 0, llvm::DINode::FlagZero, nullptr,
670                                       llvm::DINodeArray());
671 
672     DBuilder.replaceArrays(
673         ObjTy, DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
674                    ObjTy, "isa", TheCU->getFile(), 0, Size, 0, 0,
675                    llvm::DINode::FlagZero, ISATy)));
676     return ObjTy;
677   }
678   case BuiltinType::ObjCSel: {
679     if (!SelTy)
680       SelTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
681                                          "objc_selector", TheCU,
682                                          TheCU->getFile(), 0);
683     return SelTy;
684   }
685 
686 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix)                   \
687   case BuiltinType::Id:                                                        \
688     return getOrCreateStructPtrType("opencl_" #ImgType "_" #Suffix "_t",       \
689                                     SingletonId);
690 #include "clang/Basic/OpenCLImageTypes.def"
691   case BuiltinType::OCLSampler:
692     return getOrCreateStructPtrType("opencl_sampler_t", OCLSamplerDITy);
693   case BuiltinType::OCLEvent:
694     return getOrCreateStructPtrType("opencl_event_t", OCLEventDITy);
695   case BuiltinType::OCLClkEvent:
696     return getOrCreateStructPtrType("opencl_clk_event_t", OCLClkEventDITy);
697   case BuiltinType::OCLQueue:
698     return getOrCreateStructPtrType("opencl_queue_t", OCLQueueDITy);
699   case BuiltinType::OCLReserveID:
700     return getOrCreateStructPtrType("opencl_reserve_id_t", OCLReserveIDDITy);
701 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
702   case BuiltinType::Id: \
703     return getOrCreateStructPtrType("opencl_" #ExtType, Id##Ty);
704 #include "clang/Basic/OpenCLExtensionTypes.def"
705 
706 #define SVE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
707 #include "clang/Basic/AArch64SVEACLETypes.def"
708     {
709       ASTContext::BuiltinVectorTypeInfo Info =
710           CGM.getContext().getBuiltinVectorTypeInfo(BT);
711       unsigned NumElemsPerVG = (Info.EC.getKnownMinValue() * Info.NumVectors) / 2;
712 
713       // Debuggers can't extract 1bit from a vector, so will display a
714       // bitpattern for svbool_t instead.
715       if (Info.ElementType == CGM.getContext().BoolTy) {
716         NumElemsPerVG /= 8;
717         Info.ElementType = CGM.getContext().UnsignedCharTy;
718       }
719 
720       auto *LowerBound =
721           llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
722               llvm::Type::getInt64Ty(CGM.getLLVMContext()), 0));
723       SmallVector<uint64_t, 9> Expr(
724           {llvm::dwarf::DW_OP_constu, NumElemsPerVG, llvm::dwarf::DW_OP_bregx,
725            /* AArch64::VG */ 46, 0, llvm::dwarf::DW_OP_mul,
726            llvm::dwarf::DW_OP_constu, 1, llvm::dwarf::DW_OP_minus});
727       auto *UpperBound = DBuilder.createExpression(Expr);
728 
729       llvm::Metadata *Subscript = DBuilder.getOrCreateSubrange(
730           /*count*/ nullptr, LowerBound, UpperBound, /*stride*/ nullptr);
731       llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
732       llvm::DIType *ElemTy =
733           getOrCreateType(Info.ElementType, TheCU->getFile());
734       auto Align = getTypeAlignIfRequired(BT, CGM.getContext());
735       return DBuilder.createVectorType(/*Size*/ 0, Align, ElemTy,
736                                        SubscriptArray);
737     }
738   // It doesn't make sense to generate debug info for PowerPC MMA vector types.
739   // So we return a safe type here to avoid generating an error.
740 #define PPC_VECTOR_TYPE(Name, Id, size) \
741   case BuiltinType::Id:
742 #include "clang/Basic/PPCTypes.def"
743     return CreateType(cast<const BuiltinType>(CGM.getContext().IntTy));
744 
745 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
746 #include "clang/Basic/RISCVVTypes.def"
747     {
748       ASTContext::BuiltinVectorTypeInfo Info =
749           CGM.getContext().getBuiltinVectorTypeInfo(BT);
750 
751       unsigned ElementCount = Info.EC.getKnownMinValue();
752       unsigned SEW = CGM.getContext().getTypeSize(Info.ElementType);
753 
754       bool Fractional = false;
755       unsigned LMUL;
756       unsigned FixedSize = ElementCount * SEW;
757       if (Info.ElementType == CGM.getContext().BoolTy) {
758         // Mask type only occupies one vector register.
759         LMUL = 1;
760       } else if (FixedSize < 64) {
761         // In RVV scalable vector types, we encode 64 bits in the fixed part.
762         Fractional = true;
763         LMUL = 64 / FixedSize;
764       } else {
765         LMUL = FixedSize / 64;
766       }
767 
768       // Element count = (VLENB / SEW) x LMUL
769       SmallVector<uint64_t, 12> Expr(
770           // The DW_OP_bregx operation has two operands: a register which is
771           // specified by an unsigned LEB128 number, followed by a signed LEB128
772           // offset.
773           {llvm::dwarf::DW_OP_bregx, // Read the contents of a register.
774            4096 + 0xC22,             // RISC-V VLENB CSR register.
775            0, // Offset for DW_OP_bregx. It is dummy here.
776            llvm::dwarf::DW_OP_constu,
777            SEW / 8, // SEW is in bits.
778            llvm::dwarf::DW_OP_div, llvm::dwarf::DW_OP_constu, LMUL});
779       if (Fractional)
780         Expr.push_back(llvm::dwarf::DW_OP_div);
781       else
782         Expr.push_back(llvm::dwarf::DW_OP_mul);
783       // Element max index = count - 1
784       Expr.append({llvm::dwarf::DW_OP_constu, 1, llvm::dwarf::DW_OP_minus});
785 
786       auto *LowerBound =
787           llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
788               llvm::Type::getInt64Ty(CGM.getLLVMContext()), 0));
789       auto *UpperBound = DBuilder.createExpression(Expr);
790       llvm::Metadata *Subscript = DBuilder.getOrCreateSubrange(
791           /*count*/ nullptr, LowerBound, UpperBound, /*stride*/ nullptr);
792       llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
793       llvm::DIType *ElemTy =
794           getOrCreateType(Info.ElementType, TheCU->getFile());
795 
796       auto Align = getTypeAlignIfRequired(BT, CGM.getContext());
797       return DBuilder.createVectorType(/*Size=*/0, Align, ElemTy,
798                                        SubscriptArray);
799     }
800   case BuiltinType::UChar:
801   case BuiltinType::Char_U:
802     Encoding = llvm::dwarf::DW_ATE_unsigned_char;
803     break;
804   case BuiltinType::Char_S:
805   case BuiltinType::SChar:
806     Encoding = llvm::dwarf::DW_ATE_signed_char;
807     break;
808   case BuiltinType::Char8:
809   case BuiltinType::Char16:
810   case BuiltinType::Char32:
811     Encoding = llvm::dwarf::DW_ATE_UTF;
812     break;
813   case BuiltinType::UShort:
814   case BuiltinType::UInt:
815   case BuiltinType::UInt128:
816   case BuiltinType::ULong:
817   case BuiltinType::WChar_U:
818   case BuiltinType::ULongLong:
819     Encoding = llvm::dwarf::DW_ATE_unsigned;
820     break;
821   case BuiltinType::Short:
822   case BuiltinType::Int:
823   case BuiltinType::Int128:
824   case BuiltinType::Long:
825   case BuiltinType::WChar_S:
826   case BuiltinType::LongLong:
827     Encoding = llvm::dwarf::DW_ATE_signed;
828     break;
829   case BuiltinType::Bool:
830     Encoding = llvm::dwarf::DW_ATE_boolean;
831     break;
832   case BuiltinType::Half:
833   case BuiltinType::Float:
834   case BuiltinType::LongDouble:
835   case BuiltinType::Float16:
836   case BuiltinType::BFloat16:
837   case BuiltinType::Float128:
838   case BuiltinType::Double:
839   case BuiltinType::Ibm128:
840     // FIXME: For targets where long double, __ibm128 and __float128 have the
841     // same size, they are currently indistinguishable in the debugger without
842     // some special treatment. However, there is currently no consensus on
843     // encoding and this should be updated once a DWARF encoding exists for
844     // distinct floating point types of the same size.
845     Encoding = llvm::dwarf::DW_ATE_float;
846     break;
847   case BuiltinType::ShortAccum:
848   case BuiltinType::Accum:
849   case BuiltinType::LongAccum:
850   case BuiltinType::ShortFract:
851   case BuiltinType::Fract:
852   case BuiltinType::LongFract:
853   case BuiltinType::SatShortFract:
854   case BuiltinType::SatFract:
855   case BuiltinType::SatLongFract:
856   case BuiltinType::SatShortAccum:
857   case BuiltinType::SatAccum:
858   case BuiltinType::SatLongAccum:
859     Encoding = llvm::dwarf::DW_ATE_signed_fixed;
860     break;
861   case BuiltinType::UShortAccum:
862   case BuiltinType::UAccum:
863   case BuiltinType::ULongAccum:
864   case BuiltinType::UShortFract:
865   case BuiltinType::UFract:
866   case BuiltinType::ULongFract:
867   case BuiltinType::SatUShortAccum:
868   case BuiltinType::SatUAccum:
869   case BuiltinType::SatULongAccum:
870   case BuiltinType::SatUShortFract:
871   case BuiltinType::SatUFract:
872   case BuiltinType::SatULongFract:
873     Encoding = llvm::dwarf::DW_ATE_unsigned_fixed;
874     break;
875   }
876 
877   BTName = BT->getName(CGM.getLangOpts());
878   // Bit size and offset of the type.
879   uint64_t Size = CGM.getContext().getTypeSize(BT);
880   return DBuilder.createBasicType(BTName, Size, Encoding);
881 }
882 
883 llvm::DIType *CGDebugInfo::CreateType(const AutoType *Ty) {
884   return DBuilder.createUnspecifiedType("auto");
885 }
886 
887 llvm::DIType *CGDebugInfo::CreateType(const BitIntType *Ty) {
888 
889   StringRef Name = Ty->isUnsigned() ? "unsigned _BitInt" : "_BitInt";
890   llvm::dwarf::TypeKind Encoding = Ty->isUnsigned()
891                                        ? llvm::dwarf::DW_ATE_unsigned
892                                        : llvm::dwarf::DW_ATE_signed;
893 
894   return DBuilder.createBasicType(Name, CGM.getContext().getTypeSize(Ty),
895                                   Encoding);
896 }
897 
898 llvm::DIType *CGDebugInfo::CreateType(const ComplexType *Ty) {
899   // Bit size and offset of the type.
900   llvm::dwarf::TypeKind Encoding = llvm::dwarf::DW_ATE_complex_float;
901   if (Ty->isComplexIntegerType())
902     Encoding = llvm::dwarf::DW_ATE_lo_user;
903 
904   uint64_t Size = CGM.getContext().getTypeSize(Ty);
905   return DBuilder.createBasicType("complex", Size, Encoding);
906 }
907 
908 static void stripUnusedQualifiers(Qualifiers &Q) {
909   // Ignore these qualifiers for now.
910   Q.removeObjCGCAttr();
911   Q.removeAddressSpace();
912   Q.removeObjCLifetime();
913   Q.removeUnaligned();
914 }
915 
916 static llvm::dwarf::Tag getNextQualifier(Qualifiers &Q) {
917   if (Q.hasConst()) {
918     Q.removeConst();
919     return llvm::dwarf::DW_TAG_const_type;
920   }
921   if (Q.hasVolatile()) {
922     Q.removeVolatile();
923     return llvm::dwarf::DW_TAG_volatile_type;
924   }
925   if (Q.hasRestrict()) {
926     Q.removeRestrict();
927     return llvm::dwarf::DW_TAG_restrict_type;
928   }
929   return (llvm::dwarf::Tag)0;
930 }
931 
932 llvm::DIType *CGDebugInfo::CreateQualifiedType(QualType Ty,
933                                                llvm::DIFile *Unit) {
934   QualifierCollector Qc;
935   const Type *T = Qc.strip(Ty);
936 
937   stripUnusedQualifiers(Qc);
938 
939   // We will create one Derived type for one qualifier and recurse to handle any
940   // additional ones.
941   llvm::dwarf::Tag Tag = getNextQualifier(Qc);
942   if (!Tag) {
943     assert(Qc.empty() && "Unknown type qualifier for debug info");
944     return getOrCreateType(QualType(T, 0), Unit);
945   }
946 
947   auto *FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
948 
949   // No need to fill in the Name, Line, Size, Alignment, Offset in case of
950   // CVR derived types.
951   return DBuilder.createQualifiedType(Tag, FromTy);
952 }
953 
954 llvm::DIType *CGDebugInfo::CreateQualifiedType(const FunctionProtoType *F,
955                                                llvm::DIFile *Unit) {
956   FunctionProtoType::ExtProtoInfo EPI = F->getExtProtoInfo();
957   Qualifiers &Q = EPI.TypeQuals;
958   stripUnusedQualifiers(Q);
959 
960   // We will create one Derived type for one qualifier and recurse to handle any
961   // additional ones.
962   llvm::dwarf::Tag Tag = getNextQualifier(Q);
963   if (!Tag) {
964     assert(Q.empty() && "Unknown type qualifier for debug info");
965     return nullptr;
966   }
967 
968   auto *FromTy =
969       getOrCreateType(CGM.getContext().getFunctionType(F->getReturnType(),
970                                                        F->getParamTypes(), EPI),
971                       Unit);
972 
973   // No need to fill in the Name, Line, Size, Alignment, Offset in case of
974   // CVR derived types.
975   return DBuilder.createQualifiedType(Tag, FromTy);
976 }
977 
978 llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
979                                       llvm::DIFile *Unit) {
980 
981   // The frontend treats 'id' as a typedef to an ObjCObjectType,
982   // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
983   // debug info, we want to emit 'id' in both cases.
984   if (Ty->isObjCQualifiedIdType())
985     return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
986 
987   return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
988                                Ty->getPointeeType(), Unit);
989 }
990 
991 llvm::DIType *CGDebugInfo::CreateType(const PointerType *Ty,
992                                       llvm::DIFile *Unit) {
993   return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
994                                Ty->getPointeeType(), Unit);
995 }
996 
997 /// \return whether a C++ mangling exists for the type defined by TD.
998 static bool hasCXXMangling(const TagDecl *TD, llvm::DICompileUnit *TheCU) {
999   switch (TheCU->getSourceLanguage()) {
1000   case llvm::dwarf::DW_LANG_C_plus_plus:
1001   case llvm::dwarf::DW_LANG_C_plus_plus_11:
1002   case llvm::dwarf::DW_LANG_C_plus_plus_14:
1003     return true;
1004   case llvm::dwarf::DW_LANG_ObjC_plus_plus:
1005     return isa<CXXRecordDecl>(TD) || isa<EnumDecl>(TD);
1006   default:
1007     return false;
1008   }
1009 }
1010 
1011 // Determines if the debug info for this tag declaration needs a type
1012 // identifier. The purpose of the unique identifier is to deduplicate type
1013 // information for identical types across TUs. Because of the C++ one definition
1014 // rule (ODR), it is valid to assume that the type is defined the same way in
1015 // every TU and its debug info is equivalent.
1016 //
1017 // C does not have the ODR, and it is common for codebases to contain multiple
1018 // different definitions of a struct with the same name in different TUs.
1019 // Therefore, if the type doesn't have a C++ mangling, don't give it an
1020 // identifer. Type information in C is smaller and simpler than C++ type
1021 // information, so the increase in debug info size is negligible.
1022 //
1023 // If the type is not externally visible, it should be unique to the current TU,
1024 // and should not need an identifier to participate in type deduplication.
1025 // However, when emitting CodeView, the format internally uses these
1026 // unique type name identifers for references between debug info. For example,
1027 // the method of a class in an anonymous namespace uses the identifer to refer
1028 // to its parent class. The Microsoft C++ ABI attempts to provide unique names
1029 // for such types, so when emitting CodeView, always use identifiers for C++
1030 // types. This may create problems when attempting to emit CodeView when the MS
1031 // C++ ABI is not in use.
1032 static bool needsTypeIdentifier(const TagDecl *TD, CodeGenModule &CGM,
1033                                 llvm::DICompileUnit *TheCU) {
1034   // We only add a type identifier for types with C++ name mangling.
1035   if (!hasCXXMangling(TD, TheCU))
1036     return false;
1037 
1038   // Externally visible types with C++ mangling need a type identifier.
1039   if (TD->isExternallyVisible())
1040     return true;
1041 
1042   // CodeView types with C++ mangling need a type identifier.
1043   if (CGM.getCodeGenOpts().EmitCodeView)
1044     return true;
1045 
1046   return false;
1047 }
1048 
1049 // Returns a unique type identifier string if one exists, or an empty string.
1050 static SmallString<256> getTypeIdentifier(const TagType *Ty, CodeGenModule &CGM,
1051                                           llvm::DICompileUnit *TheCU) {
1052   SmallString<256> Identifier;
1053   const TagDecl *TD = Ty->getDecl();
1054 
1055   if (!needsTypeIdentifier(TD, CGM, TheCU))
1056     return Identifier;
1057   if (const auto *RD = dyn_cast<CXXRecordDecl>(TD))
1058     if (RD->getDefinition())
1059       if (RD->isDynamicClass() &&
1060           CGM.getVTableLinkage(RD) == llvm::GlobalValue::ExternalLinkage)
1061         return Identifier;
1062 
1063   // TODO: This is using the RTTI name. Is there a better way to get
1064   // a unique string for a type?
1065   llvm::raw_svector_ostream Out(Identifier);
1066   CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(QualType(Ty, 0), Out);
1067   return Identifier;
1068 }
1069 
1070 /// \return the appropriate DWARF tag for a composite type.
1071 static llvm::dwarf::Tag getTagForRecord(const RecordDecl *RD) {
1072   llvm::dwarf::Tag Tag;
1073   if (RD->isStruct() || RD->isInterface())
1074     Tag = llvm::dwarf::DW_TAG_structure_type;
1075   else if (RD->isUnion())
1076     Tag = llvm::dwarf::DW_TAG_union_type;
1077   else {
1078     // FIXME: This could be a struct type giving a default visibility different
1079     // than C++ class type, but needs llvm metadata changes first.
1080     assert(RD->isClass());
1081     Tag = llvm::dwarf::DW_TAG_class_type;
1082   }
1083   return Tag;
1084 }
1085 
1086 llvm::DICompositeType *
1087 CGDebugInfo::getOrCreateRecordFwdDecl(const RecordType *Ty,
1088                                       llvm::DIScope *Ctx) {
1089   const RecordDecl *RD = Ty->getDecl();
1090   if (llvm::DIType *T = getTypeOrNull(CGM.getContext().getRecordType(RD)))
1091     return cast<llvm::DICompositeType>(T);
1092   llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
1093   const unsigned Line =
1094       getLineNumber(RD->getLocation().isValid() ? RD->getLocation() : CurLoc);
1095   StringRef RDName = getClassName(RD);
1096 
1097   uint64_t Size = 0;
1098   uint32_t Align = 0;
1099 
1100   const RecordDecl *D = RD->getDefinition();
1101   if (D && D->isCompleteDefinition())
1102     Size = CGM.getContext().getTypeSize(Ty);
1103 
1104   llvm::DINode::DIFlags Flags = llvm::DINode::FlagFwdDecl;
1105 
1106   // Add flag to nontrivial forward declarations. To be consistent with MSVC,
1107   // add the flag if a record has no definition because we don't know whether
1108   // it will be trivial or not.
1109   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1110     if (!CXXRD->hasDefinition() ||
1111         (CXXRD->hasDefinition() && !CXXRD->isTrivial()))
1112       Flags |= llvm::DINode::FlagNonTrivial;
1113 
1114   // Create the type.
1115   SmallString<256> Identifier;
1116   // Don't include a linkage name in line tables only.
1117   if (CGM.getCodeGenOpts().hasReducedDebugInfo())
1118     Identifier = getTypeIdentifier(Ty, CGM, TheCU);
1119   llvm::DICompositeType *RetTy = DBuilder.createReplaceableCompositeType(
1120       getTagForRecord(RD), RDName, Ctx, DefUnit, Line, 0, Size, Align, Flags,
1121       Identifier);
1122   if (CGM.getCodeGenOpts().DebugFwdTemplateParams)
1123     if (auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD))
1124       DBuilder.replaceArrays(RetTy, llvm::DINodeArray(),
1125                              CollectCXXTemplateParams(TSpecial, DefUnit));
1126   ReplaceMap.emplace_back(
1127       std::piecewise_construct, std::make_tuple(Ty),
1128       std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
1129   return RetTy;
1130 }
1131 
1132 llvm::DIType *CGDebugInfo::CreatePointerLikeType(llvm::dwarf::Tag Tag,
1133                                                  const Type *Ty,
1134                                                  QualType PointeeTy,
1135                                                  llvm::DIFile *Unit) {
1136   // Bit size, align and offset of the type.
1137   // Size is always the size of a pointer. We can't use getTypeSize here
1138   // because that does not return the correct value for references.
1139   unsigned AddressSpace = CGM.getContext().getTargetAddressSpace(PointeeTy);
1140   uint64_t Size = CGM.getTarget().getPointerWidth(AddressSpace);
1141   auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
1142   Optional<unsigned> DWARFAddressSpace =
1143       CGM.getTarget().getDWARFAddressSpace(AddressSpace);
1144 
1145   SmallVector<llvm::Metadata *, 4> Annots;
1146   auto *BTFAttrTy = dyn_cast<BTFTagAttributedType>(PointeeTy);
1147   while (BTFAttrTy) {
1148     StringRef Tag = BTFAttrTy->getAttr()->getBTFTypeTag();
1149     if (!Tag.empty()) {
1150       llvm::Metadata *Ops[2] = {
1151           llvm::MDString::get(CGM.getLLVMContext(), StringRef("btf_type_tag")),
1152           llvm::MDString::get(CGM.getLLVMContext(), Tag)};
1153       Annots.insert(Annots.begin(),
1154                     llvm::MDNode::get(CGM.getLLVMContext(), Ops));
1155     }
1156     BTFAttrTy = dyn_cast<BTFTagAttributedType>(BTFAttrTy->getWrappedType());
1157   }
1158 
1159   llvm::DINodeArray Annotations = nullptr;
1160   if (Annots.size() > 0)
1161     Annotations = DBuilder.getOrCreateArray(Annots);
1162 
1163   if (Tag == llvm::dwarf::DW_TAG_reference_type ||
1164       Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
1165     return DBuilder.createReferenceType(Tag, getOrCreateType(PointeeTy, Unit),
1166                                         Size, Align, DWARFAddressSpace);
1167   else
1168     return DBuilder.createPointerType(getOrCreateType(PointeeTy, Unit), Size,
1169                                       Align, DWARFAddressSpace, StringRef(),
1170                                       Annotations);
1171 }
1172 
1173 llvm::DIType *CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
1174                                                     llvm::DIType *&Cache) {
1175   if (Cache)
1176     return Cache;
1177   Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
1178                                      TheCU, TheCU->getFile(), 0);
1179   unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1180   Cache = DBuilder.createPointerType(Cache, Size);
1181   return Cache;
1182 }
1183 
1184 uint64_t CGDebugInfo::collectDefaultElementTypesForBlockPointer(
1185     const BlockPointerType *Ty, llvm::DIFile *Unit, llvm::DIDerivedType *DescTy,
1186     unsigned LineNo, SmallVectorImpl<llvm::Metadata *> &EltTys) {
1187   QualType FType;
1188 
1189   // Advanced by calls to CreateMemberType in increments of FType, then
1190   // returned as the overall size of the default elements.
1191   uint64_t FieldOffset = 0;
1192 
1193   // Blocks in OpenCL have unique constraints which make the standard fields
1194   // redundant while requiring size and align fields for enqueue_kernel. See
1195   // initializeForBlockHeader in CGBlocks.cpp
1196   if (CGM.getLangOpts().OpenCL) {
1197     FType = CGM.getContext().IntTy;
1198     EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
1199     EltTys.push_back(CreateMemberType(Unit, FType, "__align", &FieldOffset));
1200   } else {
1201     FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1202     EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
1203     FType = CGM.getContext().IntTy;
1204     EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
1205     EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
1206     FType = CGM.getContext().getPointerType(Ty->getPointeeType());
1207     EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
1208     FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1209     uint64_t FieldSize = CGM.getContext().getTypeSize(Ty);
1210     uint32_t FieldAlign = CGM.getContext().getTypeAlign(Ty);
1211     EltTys.push_back(DBuilder.createMemberType(
1212         Unit, "__descriptor", nullptr, LineNo, FieldSize, FieldAlign,
1213         FieldOffset, llvm::DINode::FlagZero, DescTy));
1214     FieldOffset += FieldSize;
1215   }
1216 
1217   return FieldOffset;
1218 }
1219 
1220 llvm::DIType *CGDebugInfo::CreateType(const BlockPointerType *Ty,
1221                                       llvm::DIFile *Unit) {
1222   SmallVector<llvm::Metadata *, 8> EltTys;
1223   QualType FType;
1224   uint64_t FieldOffset;
1225   llvm::DINodeArray Elements;
1226 
1227   FieldOffset = 0;
1228   FType = CGM.getContext().UnsignedLongTy;
1229   EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
1230   EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
1231 
1232   Elements = DBuilder.getOrCreateArray(EltTys);
1233   EltTys.clear();
1234 
1235   llvm::DINode::DIFlags Flags = llvm::DINode::FlagAppleBlock;
1236 
1237   auto *EltTy =
1238       DBuilder.createStructType(Unit, "__block_descriptor", nullptr, 0,
1239                                 FieldOffset, 0, Flags, nullptr, Elements);
1240 
1241   // Bit size, align and offset of the type.
1242   uint64_t Size = CGM.getContext().getTypeSize(Ty);
1243 
1244   auto *DescTy = DBuilder.createPointerType(EltTy, Size);
1245 
1246   FieldOffset = collectDefaultElementTypesForBlockPointer(Ty, Unit, DescTy,
1247                                                           0, EltTys);
1248 
1249   Elements = DBuilder.getOrCreateArray(EltTys);
1250 
1251   // The __block_literal_generic structs are marked with a special
1252   // DW_AT_APPLE_BLOCK attribute and are an implementation detail only
1253   // the debugger needs to know about. To allow type uniquing, emit
1254   // them without a name or a location.
1255   EltTy = DBuilder.createStructType(Unit, "", nullptr, 0, FieldOffset, 0,
1256                                     Flags, nullptr, Elements);
1257 
1258   return DBuilder.createPointerType(EltTy, Size);
1259 }
1260 
1261 llvm::DIType *CGDebugInfo::CreateType(const TemplateSpecializationType *Ty,
1262                                       llvm::DIFile *Unit) {
1263   assert(Ty->isTypeAlias());
1264   llvm::DIType *Src = getOrCreateType(Ty->getAliasedType(), Unit);
1265 
1266   auto *AliasDecl =
1267       cast<TypeAliasTemplateDecl>(Ty->getTemplateName().getAsTemplateDecl())
1268           ->getTemplatedDecl();
1269 
1270   if (AliasDecl->hasAttr<NoDebugAttr>())
1271     return Src;
1272 
1273   SmallString<128> NS;
1274   llvm::raw_svector_ostream OS(NS);
1275   Ty->getTemplateName().print(OS, getPrintingPolicy(),
1276                               TemplateName::Qualified::None);
1277   printTemplateArgumentList(OS, Ty->template_arguments(), getPrintingPolicy());
1278 
1279   SourceLocation Loc = AliasDecl->getLocation();
1280   return DBuilder.createTypedef(Src, OS.str(), getOrCreateFile(Loc),
1281                                 getLineNumber(Loc),
1282                                 getDeclContextDescriptor(AliasDecl));
1283 }
1284 
1285 llvm::DIType *CGDebugInfo::CreateType(const TypedefType *Ty,
1286                                       llvm::DIFile *Unit) {
1287   llvm::DIType *Underlying =
1288       getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
1289 
1290   if (Ty->getDecl()->hasAttr<NoDebugAttr>())
1291     return Underlying;
1292 
1293   // We don't set size information, but do specify where the typedef was
1294   // declared.
1295   SourceLocation Loc = Ty->getDecl()->getLocation();
1296 
1297   uint32_t Align = getDeclAlignIfRequired(Ty->getDecl(), CGM.getContext());
1298   // Typedefs are derived from some other type.
1299   llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(Ty->getDecl());
1300   return DBuilder.createTypedef(Underlying, Ty->getDecl()->getName(),
1301                                 getOrCreateFile(Loc), getLineNumber(Loc),
1302                                 getDeclContextDescriptor(Ty->getDecl()), Align,
1303                                 Annotations);
1304 }
1305 
1306 static unsigned getDwarfCC(CallingConv CC) {
1307   switch (CC) {
1308   case CC_C:
1309     // Avoid emitting DW_AT_calling_convention if the C convention was used.
1310     return 0;
1311 
1312   case CC_X86StdCall:
1313     return llvm::dwarf::DW_CC_BORLAND_stdcall;
1314   case CC_X86FastCall:
1315     return llvm::dwarf::DW_CC_BORLAND_msfastcall;
1316   case CC_X86ThisCall:
1317     return llvm::dwarf::DW_CC_BORLAND_thiscall;
1318   case CC_X86VectorCall:
1319     return llvm::dwarf::DW_CC_LLVM_vectorcall;
1320   case CC_X86Pascal:
1321     return llvm::dwarf::DW_CC_BORLAND_pascal;
1322   case CC_Win64:
1323     return llvm::dwarf::DW_CC_LLVM_Win64;
1324   case CC_X86_64SysV:
1325     return llvm::dwarf::DW_CC_LLVM_X86_64SysV;
1326   case CC_AAPCS:
1327   case CC_AArch64VectorCall:
1328     return llvm::dwarf::DW_CC_LLVM_AAPCS;
1329   case CC_AAPCS_VFP:
1330     return llvm::dwarf::DW_CC_LLVM_AAPCS_VFP;
1331   case CC_IntelOclBicc:
1332     return llvm::dwarf::DW_CC_LLVM_IntelOclBicc;
1333   case CC_SpirFunction:
1334     return llvm::dwarf::DW_CC_LLVM_SpirFunction;
1335   case CC_OpenCLKernel:
1336     return llvm::dwarf::DW_CC_LLVM_OpenCLKernel;
1337   case CC_Swift:
1338     return llvm::dwarf::DW_CC_LLVM_Swift;
1339   case CC_SwiftAsync:
1340     // [FIXME: swiftasynccc] Update to SwiftAsync once LLVM support lands.
1341     return llvm::dwarf::DW_CC_LLVM_Swift;
1342   case CC_PreserveMost:
1343     return llvm::dwarf::DW_CC_LLVM_PreserveMost;
1344   case CC_PreserveAll:
1345     return llvm::dwarf::DW_CC_LLVM_PreserveAll;
1346   case CC_X86RegCall:
1347     return llvm::dwarf::DW_CC_LLVM_X86RegCall;
1348   }
1349   return 0;
1350 }
1351 
1352 static llvm::DINode::DIFlags getRefFlags(const FunctionProtoType *Func) {
1353   llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
1354   if (Func->getExtProtoInfo().RefQualifier == RQ_LValue)
1355     Flags |= llvm::DINode::FlagLValueReference;
1356   if (Func->getExtProtoInfo().RefQualifier == RQ_RValue)
1357     Flags |= llvm::DINode::FlagRValueReference;
1358   return Flags;
1359 }
1360 
1361 llvm::DIType *CGDebugInfo::CreateType(const FunctionType *Ty,
1362                                       llvm::DIFile *Unit) {
1363   const auto *FPT = dyn_cast<FunctionProtoType>(Ty);
1364   if (FPT) {
1365     if (llvm::DIType *QTy = CreateQualifiedType(FPT, Unit))
1366       return QTy;
1367   }
1368 
1369   // Create the type without any qualifiers
1370 
1371   SmallVector<llvm::Metadata *, 16> EltTys;
1372 
1373   // Add the result type at least.
1374   EltTys.push_back(getOrCreateType(Ty->getReturnType(), Unit));
1375 
1376   llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
1377   // Set up remainder of arguments if there is a prototype.
1378   // otherwise emit it as a variadic function.
1379   if (!FPT) {
1380     EltTys.push_back(DBuilder.createUnspecifiedParameter());
1381   } else {
1382     Flags = getRefFlags(FPT);
1383     for (const QualType &ParamType : FPT->param_types())
1384       EltTys.push_back(getOrCreateType(ParamType, Unit));
1385     if (FPT->isVariadic())
1386       EltTys.push_back(DBuilder.createUnspecifiedParameter());
1387   }
1388 
1389   llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
1390   llvm::DIType *F = DBuilder.createSubroutineType(
1391       EltTypeArray, Flags, getDwarfCC(Ty->getCallConv()));
1392   return F;
1393 }
1394 
1395 /// Convert an AccessSpecifier into the corresponding DINode flag.
1396 /// As an optimization, return 0 if the access specifier equals the
1397 /// default for the containing type.
1398 static llvm::DINode::DIFlags getAccessFlag(AccessSpecifier Access,
1399                                            const RecordDecl *RD) {
1400   AccessSpecifier Default = clang::AS_none;
1401   if (RD && RD->isClass())
1402     Default = clang::AS_private;
1403   else if (RD && (RD->isStruct() || RD->isUnion()))
1404     Default = clang::AS_public;
1405 
1406   if (Access == Default)
1407     return llvm::DINode::FlagZero;
1408 
1409   switch (Access) {
1410   case clang::AS_private:
1411     return llvm::DINode::FlagPrivate;
1412   case clang::AS_protected:
1413     return llvm::DINode::FlagProtected;
1414   case clang::AS_public:
1415     return llvm::DINode::FlagPublic;
1416   case clang::AS_none:
1417     return llvm::DINode::FlagZero;
1418   }
1419   llvm_unreachable("unexpected access enumerator");
1420 }
1421 
1422 llvm::DIType *CGDebugInfo::createBitFieldType(const FieldDecl *BitFieldDecl,
1423                                               llvm::DIScope *RecordTy,
1424                                               const RecordDecl *RD) {
1425   StringRef Name = BitFieldDecl->getName();
1426   QualType Ty = BitFieldDecl->getType();
1427   SourceLocation Loc = BitFieldDecl->getLocation();
1428   llvm::DIFile *VUnit = getOrCreateFile(Loc);
1429   llvm::DIType *DebugType = getOrCreateType(Ty, VUnit);
1430 
1431   // Get the location for the field.
1432   llvm::DIFile *File = getOrCreateFile(Loc);
1433   unsigned Line = getLineNumber(Loc);
1434 
1435   const CGBitFieldInfo &BitFieldInfo =
1436       CGM.getTypes().getCGRecordLayout(RD).getBitFieldInfo(BitFieldDecl);
1437   uint64_t SizeInBits = BitFieldInfo.Size;
1438   assert(SizeInBits > 0 && "found named 0-width bitfield");
1439   uint64_t StorageOffsetInBits =
1440       CGM.getContext().toBits(BitFieldInfo.StorageOffset);
1441   uint64_t Offset = BitFieldInfo.Offset;
1442   // The bit offsets for big endian machines are reversed for big
1443   // endian target, compensate for that as the DIDerivedType requires
1444   // un-reversed offsets.
1445   if (CGM.getDataLayout().isBigEndian())
1446     Offset = BitFieldInfo.StorageSize - BitFieldInfo.Size - Offset;
1447   uint64_t OffsetInBits = StorageOffsetInBits + Offset;
1448   llvm::DINode::DIFlags Flags = getAccessFlag(BitFieldDecl->getAccess(), RD);
1449   llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(BitFieldDecl);
1450   return DBuilder.createBitFieldMemberType(
1451       RecordTy, Name, File, Line, SizeInBits, OffsetInBits, StorageOffsetInBits,
1452       Flags, DebugType, Annotations);
1453 }
1454 
1455 llvm::DIType *CGDebugInfo::createFieldType(
1456     StringRef name, QualType type, SourceLocation loc, AccessSpecifier AS,
1457     uint64_t offsetInBits, uint32_t AlignInBits, llvm::DIFile *tunit,
1458     llvm::DIScope *scope, const RecordDecl *RD, llvm::DINodeArray Annotations) {
1459   llvm::DIType *debugType = getOrCreateType(type, tunit);
1460 
1461   // Get the location for the field.
1462   llvm::DIFile *file = getOrCreateFile(loc);
1463   const unsigned line = getLineNumber(loc.isValid() ? loc : CurLoc);
1464 
1465   uint64_t SizeInBits = 0;
1466   auto Align = AlignInBits;
1467   if (!type->isIncompleteArrayType()) {
1468     TypeInfo TI = CGM.getContext().getTypeInfo(type);
1469     SizeInBits = TI.Width;
1470     if (!Align)
1471       Align = getTypeAlignIfRequired(type, CGM.getContext());
1472   }
1473 
1474   llvm::DINode::DIFlags flags = getAccessFlag(AS, RD);
1475   return DBuilder.createMemberType(scope, name, file, line, SizeInBits, Align,
1476                                    offsetInBits, flags, debugType, Annotations);
1477 }
1478 
1479 void CGDebugInfo::CollectRecordLambdaFields(
1480     const CXXRecordDecl *CXXDecl, SmallVectorImpl<llvm::Metadata *> &elements,
1481     llvm::DIType *RecordTy) {
1482   // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
1483   // has the name and the location of the variable so we should iterate over
1484   // both concurrently.
1485   const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
1486   RecordDecl::field_iterator Field = CXXDecl->field_begin();
1487   unsigned fieldno = 0;
1488   for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
1489                                              E = CXXDecl->captures_end();
1490        I != E; ++I, ++Field, ++fieldno) {
1491     const LambdaCapture &C = *I;
1492     if (C.capturesVariable()) {
1493       SourceLocation Loc = C.getLocation();
1494       assert(!Field->isBitField() && "lambdas don't have bitfield members!");
1495       VarDecl *V = C.getCapturedVar();
1496       StringRef VName = V->getName();
1497       llvm::DIFile *VUnit = getOrCreateFile(Loc);
1498       auto Align = getDeclAlignIfRequired(V, CGM.getContext());
1499       llvm::DIType *FieldType = createFieldType(
1500           VName, Field->getType(), Loc, Field->getAccess(),
1501           layout.getFieldOffset(fieldno), Align, VUnit, RecordTy, CXXDecl);
1502       elements.push_back(FieldType);
1503     } else if (C.capturesThis()) {
1504       // TODO: Need to handle 'this' in some way by probably renaming the
1505       // this of the lambda class and having a field member of 'this' or
1506       // by using AT_object_pointer for the function and having that be
1507       // used as 'this' for semantic references.
1508       FieldDecl *f = *Field;
1509       llvm::DIFile *VUnit = getOrCreateFile(f->getLocation());
1510       QualType type = f->getType();
1511       llvm::DIType *fieldType = createFieldType(
1512           "this", type, f->getLocation(), f->getAccess(),
1513           layout.getFieldOffset(fieldno), VUnit, RecordTy, CXXDecl);
1514 
1515       elements.push_back(fieldType);
1516     }
1517   }
1518 }
1519 
1520 llvm::DIDerivedType *
1521 CGDebugInfo::CreateRecordStaticField(const VarDecl *Var, llvm::DIType *RecordTy,
1522                                      const RecordDecl *RD) {
1523   // Create the descriptor for the static variable, with or without
1524   // constant initializers.
1525   Var = Var->getCanonicalDecl();
1526   llvm::DIFile *VUnit = getOrCreateFile(Var->getLocation());
1527   llvm::DIType *VTy = getOrCreateType(Var->getType(), VUnit);
1528 
1529   unsigned LineNumber = getLineNumber(Var->getLocation());
1530   StringRef VName = Var->getName();
1531   llvm::Constant *C = nullptr;
1532   if (Var->getInit()) {
1533     const APValue *Value = Var->evaluateValue();
1534     if (Value) {
1535       if (Value->isInt())
1536         C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
1537       if (Value->isFloat())
1538         C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
1539     }
1540   }
1541 
1542   llvm::DINode::DIFlags Flags = getAccessFlag(Var->getAccess(), RD);
1543   auto Align = getDeclAlignIfRequired(Var, CGM.getContext());
1544   llvm::DIDerivedType *GV = DBuilder.createStaticMemberType(
1545       RecordTy, VName, VUnit, LineNumber, VTy, Flags, C, Align);
1546   StaticDataMemberCache[Var->getCanonicalDecl()].reset(GV);
1547   return GV;
1548 }
1549 
1550 void CGDebugInfo::CollectRecordNormalField(
1551     const FieldDecl *field, uint64_t OffsetInBits, llvm::DIFile *tunit,
1552     SmallVectorImpl<llvm::Metadata *> &elements, llvm::DIType *RecordTy,
1553     const RecordDecl *RD) {
1554   StringRef name = field->getName();
1555   QualType type = field->getType();
1556 
1557   // Ignore unnamed fields unless they're anonymous structs/unions.
1558   if (name.empty() && !type->isRecordType())
1559     return;
1560 
1561   llvm::DIType *FieldType;
1562   if (field->isBitField()) {
1563     FieldType = createBitFieldType(field, RecordTy, RD);
1564   } else {
1565     auto Align = getDeclAlignIfRequired(field, CGM.getContext());
1566     llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(field);
1567     FieldType =
1568         createFieldType(name, type, field->getLocation(), field->getAccess(),
1569                         OffsetInBits, Align, tunit, RecordTy, RD, Annotations);
1570   }
1571 
1572   elements.push_back(FieldType);
1573 }
1574 
1575 void CGDebugInfo::CollectRecordNestedType(
1576     const TypeDecl *TD, SmallVectorImpl<llvm::Metadata *> &elements) {
1577   QualType Ty = CGM.getContext().getTypeDeclType(TD);
1578   // Injected class names are not considered nested records.
1579   if (isa<InjectedClassNameType>(Ty))
1580     return;
1581   SourceLocation Loc = TD->getLocation();
1582   llvm::DIType *nestedType = getOrCreateType(Ty, getOrCreateFile(Loc));
1583   elements.push_back(nestedType);
1584 }
1585 
1586 void CGDebugInfo::CollectRecordFields(
1587     const RecordDecl *record, llvm::DIFile *tunit,
1588     SmallVectorImpl<llvm::Metadata *> &elements,
1589     llvm::DICompositeType *RecordTy) {
1590   const auto *CXXDecl = dyn_cast<CXXRecordDecl>(record);
1591 
1592   if (CXXDecl && CXXDecl->isLambda())
1593     CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
1594   else {
1595     const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
1596 
1597     // Field number for non-static fields.
1598     unsigned fieldNo = 0;
1599 
1600     // Static and non-static members should appear in the same order as
1601     // the corresponding declarations in the source program.
1602     for (const auto *I : record->decls())
1603       if (const auto *V = dyn_cast<VarDecl>(I)) {
1604         if (V->hasAttr<NoDebugAttr>())
1605           continue;
1606 
1607         // Skip variable template specializations when emitting CodeView. MSVC
1608         // doesn't emit them.
1609         if (CGM.getCodeGenOpts().EmitCodeView &&
1610             isa<VarTemplateSpecializationDecl>(V))
1611           continue;
1612 
1613         if (isa<VarTemplatePartialSpecializationDecl>(V))
1614           continue;
1615 
1616         // Reuse the existing static member declaration if one exists
1617         auto MI = StaticDataMemberCache.find(V->getCanonicalDecl());
1618         if (MI != StaticDataMemberCache.end()) {
1619           assert(MI->second &&
1620                  "Static data member declaration should still exist");
1621           elements.push_back(MI->second);
1622         } else {
1623           auto Field = CreateRecordStaticField(V, RecordTy, record);
1624           elements.push_back(Field);
1625         }
1626       } else if (const auto *field = dyn_cast<FieldDecl>(I)) {
1627         CollectRecordNormalField(field, layout.getFieldOffset(fieldNo), tunit,
1628                                  elements, RecordTy, record);
1629 
1630         // Bump field number for next field.
1631         ++fieldNo;
1632       } else if (CGM.getCodeGenOpts().EmitCodeView) {
1633         // Debug info for nested types is included in the member list only for
1634         // CodeView.
1635         if (const auto *nestedType = dyn_cast<TypeDecl>(I))
1636           if (!nestedType->isImplicit() &&
1637               nestedType->getDeclContext() == record)
1638             CollectRecordNestedType(nestedType, elements);
1639       }
1640   }
1641 }
1642 
1643 llvm::DISubroutineType *
1644 CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
1645                                    llvm::DIFile *Unit, bool decl) {
1646   const auto *Func = Method->getType()->castAs<FunctionProtoType>();
1647   if (Method->isStatic())
1648     return cast_or_null<llvm::DISubroutineType>(
1649         getOrCreateType(QualType(Func, 0), Unit));
1650   return getOrCreateInstanceMethodType(Method->getThisType(), Func, Unit, decl);
1651 }
1652 
1653 llvm::DISubroutineType *
1654 CGDebugInfo::getOrCreateInstanceMethodType(QualType ThisPtr,
1655                                            const FunctionProtoType *Func,
1656                                            llvm::DIFile *Unit, bool decl) {
1657   FunctionProtoType::ExtProtoInfo EPI = Func->getExtProtoInfo();
1658   Qualifiers &Qc = EPI.TypeQuals;
1659   Qc.removeConst();
1660   Qc.removeVolatile();
1661   Qc.removeRestrict();
1662   Qc.removeUnaligned();
1663   // Keep the removed qualifiers in sync with
1664   // CreateQualifiedType(const FunctionPrototype*, DIFile *Unit)
1665   // On a 'real' member function type, these qualifiers are carried on the type
1666   // of the first parameter, not as separate DW_TAG_const_type (etc) decorator
1667   // tags around them. (But, in the raw function types with qualifiers, they have
1668   // to use wrapper types.)
1669 
1670   // Add "this" pointer.
1671   const auto *OriginalFunc = cast<llvm::DISubroutineType>(
1672       getOrCreateType(CGM.getContext().getFunctionType(
1673                           Func->getReturnType(), Func->getParamTypes(), EPI),
1674                       Unit));
1675   llvm::DITypeRefArray Args = OriginalFunc->getTypeArray();
1676   assert(Args.size() && "Invalid number of arguments!");
1677 
1678   SmallVector<llvm::Metadata *, 16> Elts;
1679   // First element is always return type. For 'void' functions it is NULL.
1680   QualType temp = Func->getReturnType();
1681   if (temp->getTypeClass() == Type::Auto && decl)
1682     Elts.push_back(CreateType(cast<AutoType>(temp)));
1683   else
1684     Elts.push_back(Args[0]);
1685 
1686   // "this" pointer is always first argument.
1687   const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
1688   if (isa<ClassTemplateSpecializationDecl>(RD)) {
1689     // Create pointer type directly in this case.
1690     const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
1691     QualType PointeeTy = ThisPtrTy->getPointeeType();
1692     unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
1693     uint64_t Size = CGM.getTarget().getPointerWidth(AS);
1694     auto Align = getTypeAlignIfRequired(ThisPtrTy, CGM.getContext());
1695     llvm::DIType *PointeeType = getOrCreateType(PointeeTy, Unit);
1696     llvm::DIType *ThisPtrType =
1697         DBuilder.createPointerType(PointeeType, Size, Align);
1698     TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
1699     // TODO: This and the artificial type below are misleading, the
1700     // types aren't artificial the argument is, but the current
1701     // metadata doesn't represent that.
1702     ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1703     Elts.push_back(ThisPtrType);
1704   } else {
1705     llvm::DIType *ThisPtrType = getOrCreateType(ThisPtr, Unit);
1706     TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
1707     ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1708     Elts.push_back(ThisPtrType);
1709   }
1710 
1711   // Copy rest of the arguments.
1712   for (unsigned i = 1, e = Args.size(); i != e; ++i)
1713     Elts.push_back(Args[i]);
1714 
1715   llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
1716 
1717   return DBuilder.createSubroutineType(EltTypeArray, OriginalFunc->getFlags(),
1718                                        getDwarfCC(Func->getCallConv()));
1719 }
1720 
1721 /// isFunctionLocalClass - Return true if CXXRecordDecl is defined
1722 /// inside a function.
1723 static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
1724   if (const auto *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
1725     return isFunctionLocalClass(NRD);
1726   if (isa<FunctionDecl>(RD->getDeclContext()))
1727     return true;
1728   return false;
1729 }
1730 
1731 llvm::DISubprogram *CGDebugInfo::CreateCXXMemberFunction(
1732     const CXXMethodDecl *Method, llvm::DIFile *Unit, llvm::DIType *RecordTy) {
1733   bool IsCtorOrDtor =
1734       isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
1735 
1736   StringRef MethodName = getFunctionName(Method);
1737   llvm::DISubroutineType *MethodTy = getOrCreateMethodType(Method, Unit, true);
1738 
1739   // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1740   // make sense to give a single ctor/dtor a linkage name.
1741   StringRef MethodLinkageName;
1742   // FIXME: 'isFunctionLocalClass' seems like an arbitrary/unintentional
1743   // property to use here. It may've been intended to model "is non-external
1744   // type" but misses cases of non-function-local but non-external classes such
1745   // as those in anonymous namespaces as well as the reverse - external types
1746   // that are function local, such as those in (non-local) inline functions.
1747   if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1748     MethodLinkageName = CGM.getMangledName(Method);
1749 
1750   // Get the location for the method.
1751   llvm::DIFile *MethodDefUnit = nullptr;
1752   unsigned MethodLine = 0;
1753   if (!Method->isImplicit()) {
1754     MethodDefUnit = getOrCreateFile(Method->getLocation());
1755     MethodLine = getLineNumber(Method->getLocation());
1756   }
1757 
1758   // Collect virtual method info.
1759   llvm::DIType *ContainingType = nullptr;
1760   unsigned VIndex = 0;
1761   llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
1762   llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
1763   int ThisAdjustment = 0;
1764 
1765   if (Method->isVirtual()) {
1766     if (Method->isPure())
1767       SPFlags |= llvm::DISubprogram::SPFlagPureVirtual;
1768     else
1769       SPFlags |= llvm::DISubprogram::SPFlagVirtual;
1770 
1771     if (CGM.getTarget().getCXXABI().isItaniumFamily()) {
1772       // It doesn't make sense to give a virtual destructor a vtable index,
1773       // since a single destructor has two entries in the vtable.
1774       if (!isa<CXXDestructorDecl>(Method))
1775         VIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(Method);
1776     } else {
1777       // Emit MS ABI vftable information.  There is only one entry for the
1778       // deleting dtor.
1779       const auto *DD = dyn_cast<CXXDestructorDecl>(Method);
1780       GlobalDecl GD = DD ? GlobalDecl(DD, Dtor_Deleting) : GlobalDecl(Method);
1781       MethodVFTableLocation ML =
1782           CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD);
1783       VIndex = ML.Index;
1784 
1785       // CodeView only records the vftable offset in the class that introduces
1786       // the virtual method. This is possible because, unlike Itanium, the MS
1787       // C++ ABI does not include all virtual methods from non-primary bases in
1788       // the vtable for the most derived class. For example, if C inherits from
1789       // A and B, C's primary vftable will not include B's virtual methods.
1790       if (Method->size_overridden_methods() == 0)
1791         Flags |= llvm::DINode::FlagIntroducedVirtual;
1792 
1793       // The 'this' adjustment accounts for both the virtual and non-virtual
1794       // portions of the adjustment. Presumably the debugger only uses it when
1795       // it knows the dynamic type of an object.
1796       ThisAdjustment = CGM.getCXXABI()
1797                            .getVirtualFunctionPrologueThisAdjustment(GD)
1798                            .getQuantity();
1799     }
1800     ContainingType = RecordTy;
1801   }
1802 
1803   // We're checking for deleted C++ special member functions
1804   // [Ctors,Dtors, Copy/Move]
1805   auto checkAttrDeleted = [&](const auto *Method) {
1806     if (Method->getCanonicalDecl()->isDeleted())
1807       SPFlags |= llvm::DISubprogram::SPFlagDeleted;
1808   };
1809 
1810   switch (Method->getKind()) {
1811 
1812   case Decl::CXXConstructor:
1813   case Decl::CXXDestructor:
1814     checkAttrDeleted(Method);
1815     break;
1816   case Decl::CXXMethod:
1817     if (Method->isCopyAssignmentOperator() ||
1818         Method->isMoveAssignmentOperator())
1819       checkAttrDeleted(Method);
1820     break;
1821   default:
1822     break;
1823   }
1824 
1825   if (Method->isNoReturn())
1826     Flags |= llvm::DINode::FlagNoReturn;
1827 
1828   if (Method->isStatic())
1829     Flags |= llvm::DINode::FlagStaticMember;
1830   if (Method->isImplicit())
1831     Flags |= llvm::DINode::FlagArtificial;
1832   Flags |= getAccessFlag(Method->getAccess(), Method->getParent());
1833   if (const auto *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1834     if (CXXC->isExplicit())
1835       Flags |= llvm::DINode::FlagExplicit;
1836   } else if (const auto *CXXC = dyn_cast<CXXConversionDecl>(Method)) {
1837     if (CXXC->isExplicit())
1838       Flags |= llvm::DINode::FlagExplicit;
1839   }
1840   if (Method->hasPrototype())
1841     Flags |= llvm::DINode::FlagPrototyped;
1842   if (Method->getRefQualifier() == RQ_LValue)
1843     Flags |= llvm::DINode::FlagLValueReference;
1844   if (Method->getRefQualifier() == RQ_RValue)
1845     Flags |= llvm::DINode::FlagRValueReference;
1846   if (!Method->isExternallyVisible())
1847     SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;
1848   if (CGM.getLangOpts().Optimize)
1849     SPFlags |= llvm::DISubprogram::SPFlagOptimized;
1850 
1851   // In this debug mode, emit type info for a class when its constructor type
1852   // info is emitted.
1853   if (DebugKind == codegenoptions::DebugInfoConstructor)
1854     if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
1855       completeUnusedClass(*CD->getParent());
1856 
1857   llvm::DINodeArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1858   llvm::DISubprogram *SP = DBuilder.createMethod(
1859       RecordTy, MethodName, MethodLinkageName, MethodDefUnit, MethodLine,
1860       MethodTy, VIndex, ThisAdjustment, ContainingType, Flags, SPFlags,
1861       TParamsArray.get());
1862 
1863   SPCache[Method->getCanonicalDecl()].reset(SP);
1864 
1865   return SP;
1866 }
1867 
1868 void CGDebugInfo::CollectCXXMemberFunctions(
1869     const CXXRecordDecl *RD, llvm::DIFile *Unit,
1870     SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy) {
1871 
1872   // Since we want more than just the individual member decls if we
1873   // have templated functions iterate over every declaration to gather
1874   // the functions.
1875   for (const auto *I : RD->decls()) {
1876     const auto *Method = dyn_cast<CXXMethodDecl>(I);
1877     // If the member is implicit, don't add it to the member list. This avoids
1878     // the member being added to type units by LLVM, while still allowing it
1879     // to be emitted into the type declaration/reference inside the compile
1880     // unit.
1881     // Ditto 'nodebug' methods, for consistency with CodeGenFunction.cpp.
1882     // FIXME: Handle Using(Shadow?)Decls here to create
1883     // DW_TAG_imported_declarations inside the class for base decls brought into
1884     // derived classes. GDB doesn't seem to notice/leverage these when I tried
1885     // it, so I'm not rushing to fix this. (GCC seems to produce them, if
1886     // referenced)
1887     if (!Method || Method->isImplicit() || Method->hasAttr<NoDebugAttr>())
1888       continue;
1889 
1890     if (Method->getType()->castAs<FunctionProtoType>()->getContainedAutoType())
1891       continue;
1892 
1893     // Reuse the existing member function declaration if it exists.
1894     // It may be associated with the declaration of the type & should be
1895     // reused as we're building the definition.
1896     //
1897     // This situation can arise in the vtable-based debug info reduction where
1898     // implicit members are emitted in a non-vtable TU.
1899     auto MI = SPCache.find(Method->getCanonicalDecl());
1900     EltTys.push_back(MI == SPCache.end()
1901                          ? CreateCXXMemberFunction(Method, Unit, RecordTy)
1902                          : static_cast<llvm::Metadata *>(MI->second));
1903   }
1904 }
1905 
1906 void CGDebugInfo::CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile *Unit,
1907                                   SmallVectorImpl<llvm::Metadata *> &EltTys,
1908                                   llvm::DIType *RecordTy) {
1909   llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> SeenTypes;
1910   CollectCXXBasesAux(RD, Unit, EltTys, RecordTy, RD->bases(), SeenTypes,
1911                      llvm::DINode::FlagZero);
1912 
1913   // If we are generating CodeView debug info, we also need to emit records for
1914   // indirect virtual base classes.
1915   if (CGM.getCodeGenOpts().EmitCodeView) {
1916     CollectCXXBasesAux(RD, Unit, EltTys, RecordTy, RD->vbases(), SeenTypes,
1917                        llvm::DINode::FlagIndirectVirtualBase);
1918   }
1919 }
1920 
1921 void CGDebugInfo::CollectCXXBasesAux(
1922     const CXXRecordDecl *RD, llvm::DIFile *Unit,
1923     SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy,
1924     const CXXRecordDecl::base_class_const_range &Bases,
1925     llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> &SeenTypes,
1926     llvm::DINode::DIFlags StartingFlags) {
1927   const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1928   for (const auto &BI : Bases) {
1929     const auto *Base =
1930         cast<CXXRecordDecl>(BI.getType()->castAs<RecordType>()->getDecl());
1931     if (!SeenTypes.insert(Base).second)
1932       continue;
1933     auto *BaseTy = getOrCreateType(BI.getType(), Unit);
1934     llvm::DINode::DIFlags BFlags = StartingFlags;
1935     uint64_t BaseOffset;
1936     uint32_t VBPtrOffset = 0;
1937 
1938     if (BI.isVirtual()) {
1939       if (CGM.getTarget().getCXXABI().isItaniumFamily()) {
1940         // virtual base offset offset is -ve. The code generator emits dwarf
1941         // expression where it expects +ve number.
1942         BaseOffset = 0 - CGM.getItaniumVTableContext()
1943                              .getVirtualBaseOffsetOffset(RD, Base)
1944                              .getQuantity();
1945       } else {
1946         // In the MS ABI, store the vbtable offset, which is analogous to the
1947         // vbase offset offset in Itanium.
1948         BaseOffset =
1949             4 * CGM.getMicrosoftVTableContext().getVBTableIndex(RD, Base);
1950         VBPtrOffset = CGM.getContext()
1951                           .getASTRecordLayout(RD)
1952                           .getVBPtrOffset()
1953                           .getQuantity();
1954       }
1955       BFlags |= llvm::DINode::FlagVirtual;
1956     } else
1957       BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1958     // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1959     // BI->isVirtual() and bits when not.
1960 
1961     BFlags |= getAccessFlag(BI.getAccessSpecifier(), RD);
1962     llvm::DIType *DTy = DBuilder.createInheritance(RecordTy, BaseTy, BaseOffset,
1963                                                    VBPtrOffset, BFlags);
1964     EltTys.push_back(DTy);
1965   }
1966 }
1967 
1968 llvm::DINodeArray
1969 CGDebugInfo::CollectTemplateParams(Optional<TemplateArgs> OArgs,
1970                                    llvm::DIFile *Unit) {
1971   if (!OArgs)
1972     return llvm::DINodeArray();
1973   TemplateArgs &Args = *OArgs;
1974   SmallVector<llvm::Metadata *, 16> TemplateParams;
1975   for (unsigned i = 0, e = Args.Args.size(); i != e; ++i) {
1976     const TemplateArgument &TA = Args.Args[i];
1977     StringRef Name;
1978     bool defaultParameter = false;
1979     if (Args.TList)
1980       Name = Args.TList->getParam(i)->getName();
1981     switch (TA.getKind()) {
1982     case TemplateArgument::Type: {
1983       llvm::DIType *TTy = getOrCreateType(TA.getAsType(), Unit);
1984 
1985       if (Args.TList)
1986         if (auto *templateType =
1987                 dyn_cast_or_null<TemplateTypeParmDecl>(Args.TList->getParam(i)))
1988           if (templateType->hasDefaultArgument())
1989             defaultParameter =
1990                 templateType->getDefaultArgument() == TA.getAsType();
1991 
1992       TemplateParams.push_back(DBuilder.createTemplateTypeParameter(
1993           TheCU, Name, TTy, defaultParameter));
1994 
1995     } break;
1996     case TemplateArgument::Integral: {
1997       llvm::DIType *TTy = getOrCreateType(TA.getIntegralType(), Unit);
1998       if (Args.TList && CGM.getCodeGenOpts().DwarfVersion >= 5)
1999         if (auto *templateType = dyn_cast_or_null<NonTypeTemplateParmDecl>(
2000                 Args.TList->getParam(i)))
2001           if (templateType->hasDefaultArgument() &&
2002               !templateType->getDefaultArgument()->isValueDependent())
2003             defaultParameter = llvm::APSInt::isSameValue(
2004                 templateType->getDefaultArgument()->EvaluateKnownConstInt(
2005                     CGM.getContext()),
2006                 TA.getAsIntegral());
2007 
2008       TemplateParams.push_back(DBuilder.createTemplateValueParameter(
2009           TheCU, Name, TTy, defaultParameter,
2010           llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral())));
2011     } break;
2012     case TemplateArgument::Declaration: {
2013       const ValueDecl *D = TA.getAsDecl();
2014       QualType T = TA.getParamTypeForDecl().getDesugaredType(CGM.getContext());
2015       llvm::DIType *TTy = getOrCreateType(T, Unit);
2016       llvm::Constant *V = nullptr;
2017       // Skip retrieve the value if that template parameter has cuda device
2018       // attribute, i.e. that value is not available at the host side.
2019       if (!CGM.getLangOpts().CUDA || CGM.getLangOpts().CUDAIsDevice ||
2020           !D->hasAttr<CUDADeviceAttr>()) {
2021         const CXXMethodDecl *MD;
2022         // Variable pointer template parameters have a value that is the address
2023         // of the variable.
2024         if (const auto *VD = dyn_cast<VarDecl>(D))
2025           V = CGM.GetAddrOfGlobalVar(VD);
2026         // Member function pointers have special support for building them,
2027         // though this is currently unsupported in LLVM CodeGen.
2028         else if ((MD = dyn_cast<CXXMethodDecl>(D)) && MD->isInstance())
2029           V = CGM.getCXXABI().EmitMemberFunctionPointer(MD);
2030         else if (const auto *FD = dyn_cast<FunctionDecl>(D))
2031           V = CGM.GetAddrOfFunction(FD);
2032         // Member data pointers have special handling too to compute the fixed
2033         // offset within the object.
2034         else if (const auto *MPT =
2035                      dyn_cast<MemberPointerType>(T.getTypePtr())) {
2036           // These five lines (& possibly the above member function pointer
2037           // handling) might be able to be refactored to use similar code in
2038           // CodeGenModule::getMemberPointerConstant
2039           uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
2040           CharUnits chars =
2041               CGM.getContext().toCharUnitsFromBits((int64_t)fieldOffset);
2042           V = CGM.getCXXABI().EmitMemberDataPointer(MPT, chars);
2043         } else if (const auto *GD = dyn_cast<MSGuidDecl>(D)) {
2044           V = CGM.GetAddrOfMSGuidDecl(GD).getPointer();
2045         } else if (const auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
2046           if (T->isRecordType())
2047             V = ConstantEmitter(CGM).emitAbstract(
2048                 SourceLocation(), TPO->getValue(), TPO->getType());
2049           else
2050             V = CGM.GetAddrOfTemplateParamObject(TPO).getPointer();
2051         }
2052         assert(V && "Failed to find template parameter pointer");
2053         V = V->stripPointerCasts();
2054       }
2055       TemplateParams.push_back(DBuilder.createTemplateValueParameter(
2056           TheCU, Name, TTy, defaultParameter, cast_or_null<llvm::Constant>(V)));
2057     } break;
2058     case TemplateArgument::NullPtr: {
2059       QualType T = TA.getNullPtrType();
2060       llvm::DIType *TTy = getOrCreateType(T, Unit);
2061       llvm::Constant *V = nullptr;
2062       // Special case member data pointer null values since they're actually -1
2063       // instead of zero.
2064       if (const auto *MPT = dyn_cast<MemberPointerType>(T.getTypePtr()))
2065         // But treat member function pointers as simple zero integers because
2066         // it's easier than having a special case in LLVM's CodeGen. If LLVM
2067         // CodeGen grows handling for values of non-null member function
2068         // pointers then perhaps we could remove this special case and rely on
2069         // EmitNullMemberPointer for member function pointers.
2070         if (MPT->isMemberDataPointer())
2071           V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
2072       if (!V)
2073         V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
2074       TemplateParams.push_back(DBuilder.createTemplateValueParameter(
2075           TheCU, Name, TTy, defaultParameter, V));
2076     } break;
2077     case TemplateArgument::Template: {
2078       std::string QualName;
2079       llvm::raw_string_ostream OS(QualName);
2080       TA.getAsTemplate().getAsTemplateDecl()->printQualifiedName(
2081           OS, getPrintingPolicy());
2082       TemplateParams.push_back(DBuilder.createTemplateTemplateParameter(
2083           TheCU, Name, nullptr, OS.str()));
2084       break;
2085     }
2086     case TemplateArgument::Pack:
2087       TemplateParams.push_back(DBuilder.createTemplateParameterPack(
2088           TheCU, Name, nullptr,
2089           CollectTemplateParams({{nullptr, TA.getPackAsArray()}}, Unit)));
2090       break;
2091     case TemplateArgument::Expression: {
2092       const Expr *E = TA.getAsExpr();
2093       QualType T = E->getType();
2094       if (E->isGLValue())
2095         T = CGM.getContext().getLValueReferenceType(T);
2096       llvm::Constant *V = ConstantEmitter(CGM).emitAbstract(E, T);
2097       assert(V && "Expression in template argument isn't constant");
2098       llvm::DIType *TTy = getOrCreateType(T, Unit);
2099       TemplateParams.push_back(DBuilder.createTemplateValueParameter(
2100           TheCU, Name, TTy, defaultParameter, V->stripPointerCasts()));
2101     } break;
2102     // And the following should never occur:
2103     case TemplateArgument::TemplateExpansion:
2104     case TemplateArgument::Null:
2105       llvm_unreachable(
2106           "These argument types shouldn't exist in concrete types");
2107     }
2108   }
2109   return DBuilder.getOrCreateArray(TemplateParams);
2110 }
2111 
2112 Optional<CGDebugInfo::TemplateArgs>
2113 CGDebugInfo::GetTemplateArgs(const FunctionDecl *FD) const {
2114   if (FD->getTemplatedKind() ==
2115       FunctionDecl::TK_FunctionTemplateSpecialization) {
2116     const TemplateParameterList *TList = FD->getTemplateSpecializationInfo()
2117                                              ->getTemplate()
2118                                              ->getTemplateParameters();
2119     return {{TList, FD->getTemplateSpecializationArgs()->asArray()}};
2120   }
2121   return None;
2122 }
2123 Optional<CGDebugInfo::TemplateArgs>
2124 CGDebugInfo::GetTemplateArgs(const VarDecl *VD) const {
2125   // Always get the full list of parameters, not just the ones from the
2126   // specialization. A partial specialization may have fewer parameters than
2127   // there are arguments.
2128   auto *TS = dyn_cast<VarTemplateSpecializationDecl>(VD);
2129   if (!TS)
2130     return None;
2131   VarTemplateDecl *T = TS->getSpecializedTemplate();
2132   const TemplateParameterList *TList = T->getTemplateParameters();
2133   auto TA = TS->getTemplateArgs().asArray();
2134   return {{TList, TA}};
2135 }
2136 Optional<CGDebugInfo::TemplateArgs>
2137 CGDebugInfo::GetTemplateArgs(const RecordDecl *RD) const {
2138   if (auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
2139     // Always get the full list of parameters, not just the ones from the
2140     // specialization. A partial specialization may have fewer parameters than
2141     // there are arguments.
2142     TemplateParameterList *TPList =
2143         TSpecial->getSpecializedTemplate()->getTemplateParameters();
2144     const TemplateArgumentList &TAList = TSpecial->getTemplateArgs();
2145     return {{TPList, TAList.asArray()}};
2146   }
2147   return None;
2148 }
2149 
2150 llvm::DINodeArray
2151 CGDebugInfo::CollectFunctionTemplateParams(const FunctionDecl *FD,
2152                                            llvm::DIFile *Unit) {
2153   return CollectTemplateParams(GetTemplateArgs(FD), Unit);
2154 }
2155 
2156 llvm::DINodeArray CGDebugInfo::CollectVarTemplateParams(const VarDecl *VL,
2157                                                         llvm::DIFile *Unit) {
2158   return CollectTemplateParams(GetTemplateArgs(VL), Unit);
2159 }
2160 
2161 llvm::DINodeArray CGDebugInfo::CollectCXXTemplateParams(const RecordDecl *RD,
2162                                                         llvm::DIFile *Unit) {
2163   return CollectTemplateParams(GetTemplateArgs(RD), Unit);
2164 }
2165 
2166 llvm::DINodeArray CGDebugInfo::CollectBTFDeclTagAnnotations(const Decl *D) {
2167   if (!D->hasAttr<BTFDeclTagAttr>())
2168     return nullptr;
2169 
2170   SmallVector<llvm::Metadata *, 4> Annotations;
2171   for (const auto *I : D->specific_attrs<BTFDeclTagAttr>()) {
2172     llvm::Metadata *Ops[2] = {
2173         llvm::MDString::get(CGM.getLLVMContext(), StringRef("btf_decl_tag")),
2174         llvm::MDString::get(CGM.getLLVMContext(), I->getBTFDeclTag())};
2175     Annotations.push_back(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2176   }
2177   return DBuilder.getOrCreateArray(Annotations);
2178 }
2179 
2180 llvm::DIType *CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile *Unit) {
2181   if (VTablePtrType)
2182     return VTablePtrType;
2183 
2184   ASTContext &Context = CGM.getContext();
2185 
2186   /* Function type */
2187   llvm::Metadata *STy = getOrCreateType(Context.IntTy, Unit);
2188   llvm::DITypeRefArray SElements = DBuilder.getOrCreateTypeArray(STy);
2189   llvm::DIType *SubTy = DBuilder.createSubroutineType(SElements);
2190   unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
2191   unsigned VtblPtrAddressSpace = CGM.getTarget().getVtblPtrAddressSpace();
2192   Optional<unsigned> DWARFAddressSpace =
2193       CGM.getTarget().getDWARFAddressSpace(VtblPtrAddressSpace);
2194 
2195   llvm::DIType *vtbl_ptr_type = DBuilder.createPointerType(
2196       SubTy, Size, 0, DWARFAddressSpace, "__vtbl_ptr_type");
2197   VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
2198   return VTablePtrType;
2199 }
2200 
2201 StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
2202   // Copy the gdb compatible name on the side and use its reference.
2203   return internString("_vptr$", RD->getNameAsString());
2204 }
2205 
2206 StringRef CGDebugInfo::getDynamicInitializerName(const VarDecl *VD,
2207                                                  DynamicInitKind StubKind,
2208                                                  llvm::Function *InitFn) {
2209   // If we're not emitting codeview, use the mangled name. For Itanium, this is
2210   // arbitrary.
2211   if (!CGM.getCodeGenOpts().EmitCodeView ||
2212       StubKind == DynamicInitKind::GlobalArrayDestructor)
2213     return InitFn->getName();
2214 
2215   // Print the normal qualified name for the variable, then break off the last
2216   // NNS, and add the appropriate other text. Clang always prints the global
2217   // variable name without template arguments, so we can use rsplit("::") and
2218   // then recombine the pieces.
2219   SmallString<128> QualifiedGV;
2220   StringRef Quals;
2221   StringRef GVName;
2222   {
2223     llvm::raw_svector_ostream OS(QualifiedGV);
2224     VD->printQualifiedName(OS, getPrintingPolicy());
2225     std::tie(Quals, GVName) = OS.str().rsplit("::");
2226     if (GVName.empty())
2227       std::swap(Quals, GVName);
2228   }
2229 
2230   SmallString<128> InitName;
2231   llvm::raw_svector_ostream OS(InitName);
2232   if (!Quals.empty())
2233     OS << Quals << "::";
2234 
2235   switch (StubKind) {
2236   case DynamicInitKind::NoStub:
2237   case DynamicInitKind::GlobalArrayDestructor:
2238     llvm_unreachable("not an initializer");
2239   case DynamicInitKind::Initializer:
2240     OS << "`dynamic initializer for '";
2241     break;
2242   case DynamicInitKind::AtExit:
2243     OS << "`dynamic atexit destructor for '";
2244     break;
2245   }
2246 
2247   OS << GVName;
2248 
2249   // Add any template specialization args.
2250   if (const auto *VTpl = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
2251     printTemplateArgumentList(OS, VTpl->getTemplateArgs().asArray(),
2252                               getPrintingPolicy());
2253   }
2254 
2255   OS << '\'';
2256 
2257   return internString(OS.str());
2258 }
2259 
2260 void CGDebugInfo::CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile *Unit,
2261                                     SmallVectorImpl<llvm::Metadata *> &EltTys) {
2262   // If this class is not dynamic then there is not any vtable info to collect.
2263   if (!RD->isDynamicClass())
2264     return;
2265 
2266   // Don't emit any vtable shape or vptr info if this class doesn't have an
2267   // extendable vfptr. This can happen if the class doesn't have virtual
2268   // methods, or in the MS ABI if those virtual methods only come from virtually
2269   // inherited bases.
2270   const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2271   if (!RL.hasExtendableVFPtr())
2272     return;
2273 
2274   // CodeView needs to know how large the vtable of every dynamic class is, so
2275   // emit a special named pointer type into the element list. The vptr type
2276   // points to this type as well.
2277   llvm::DIType *VPtrTy = nullptr;
2278   bool NeedVTableShape = CGM.getCodeGenOpts().EmitCodeView &&
2279                          CGM.getTarget().getCXXABI().isMicrosoft();
2280   if (NeedVTableShape) {
2281     uint64_t PtrWidth =
2282         CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
2283     const VTableLayout &VFTLayout =
2284         CGM.getMicrosoftVTableContext().getVFTableLayout(RD, CharUnits::Zero());
2285     unsigned VSlotCount =
2286         VFTLayout.vtable_components().size() - CGM.getLangOpts().RTTIData;
2287     unsigned VTableWidth = PtrWidth * VSlotCount;
2288     unsigned VtblPtrAddressSpace = CGM.getTarget().getVtblPtrAddressSpace();
2289     Optional<unsigned> DWARFAddressSpace =
2290         CGM.getTarget().getDWARFAddressSpace(VtblPtrAddressSpace);
2291 
2292     // Create a very wide void* type and insert it directly in the element list.
2293     llvm::DIType *VTableType = DBuilder.createPointerType(
2294         nullptr, VTableWidth, 0, DWARFAddressSpace, "__vtbl_ptr_type");
2295     EltTys.push_back(VTableType);
2296 
2297     // The vptr is a pointer to this special vtable type.
2298     VPtrTy = DBuilder.createPointerType(VTableType, PtrWidth);
2299   }
2300 
2301   // If there is a primary base then the artificial vptr member lives there.
2302   if (RL.getPrimaryBase())
2303     return;
2304 
2305   if (!VPtrTy)
2306     VPtrTy = getOrCreateVTablePtrType(Unit);
2307 
2308   unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
2309   llvm::DIType *VPtrMember =
2310       DBuilder.createMemberType(Unit, getVTableName(RD), Unit, 0, Size, 0, 0,
2311                                 llvm::DINode::FlagArtificial, VPtrTy);
2312   EltTys.push_back(VPtrMember);
2313 }
2314 
2315 llvm::DIType *CGDebugInfo::getOrCreateRecordType(QualType RTy,
2316                                                  SourceLocation Loc) {
2317   assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
2318   llvm::DIType *T = getOrCreateType(RTy, getOrCreateFile(Loc));
2319   return T;
2320 }
2321 
2322 llvm::DIType *CGDebugInfo::getOrCreateInterfaceType(QualType D,
2323                                                     SourceLocation Loc) {
2324   return getOrCreateStandaloneType(D, Loc);
2325 }
2326 
2327 llvm::DIType *CGDebugInfo::getOrCreateStandaloneType(QualType D,
2328                                                      SourceLocation Loc) {
2329   assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
2330   assert(!D.isNull() && "null type");
2331   llvm::DIType *T = getOrCreateType(D, getOrCreateFile(Loc));
2332   assert(T && "could not create debug info for type");
2333 
2334   RetainedTypes.push_back(D.getAsOpaquePtr());
2335   return T;
2336 }
2337 
2338 void CGDebugInfo::addHeapAllocSiteMetadata(llvm::CallBase *CI,
2339                                            QualType AllocatedTy,
2340                                            SourceLocation Loc) {
2341   if (CGM.getCodeGenOpts().getDebugInfo() <=
2342       codegenoptions::DebugLineTablesOnly)
2343     return;
2344   llvm::MDNode *node;
2345   if (AllocatedTy->isVoidType())
2346     node = llvm::MDNode::get(CGM.getLLVMContext(), None);
2347   else
2348     node = getOrCreateType(AllocatedTy, getOrCreateFile(Loc));
2349 
2350   CI->setMetadata("heapallocsite", node);
2351 }
2352 
2353 void CGDebugInfo::completeType(const EnumDecl *ED) {
2354   if (DebugKind <= codegenoptions::DebugLineTablesOnly)
2355     return;
2356   QualType Ty = CGM.getContext().getEnumType(ED);
2357   void *TyPtr = Ty.getAsOpaquePtr();
2358   auto I = TypeCache.find(TyPtr);
2359   if (I == TypeCache.end() || !cast<llvm::DIType>(I->second)->isForwardDecl())
2360     return;
2361   llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<EnumType>());
2362   assert(!Res->isForwardDecl());
2363   TypeCache[TyPtr].reset(Res);
2364 }
2365 
2366 void CGDebugInfo::completeType(const RecordDecl *RD) {
2367   if (DebugKind > codegenoptions::LimitedDebugInfo ||
2368       !CGM.getLangOpts().CPlusPlus)
2369     completeRequiredType(RD);
2370 }
2371 
2372 /// Return true if the class or any of its methods are marked dllimport.
2373 static bool isClassOrMethodDLLImport(const CXXRecordDecl *RD) {
2374   if (RD->hasAttr<DLLImportAttr>())
2375     return true;
2376   for (const CXXMethodDecl *MD : RD->methods())
2377     if (MD->hasAttr<DLLImportAttr>())
2378       return true;
2379   return false;
2380 }
2381 
2382 /// Does a type definition exist in an imported clang module?
2383 static bool isDefinedInClangModule(const RecordDecl *RD) {
2384   // Only definitions that where imported from an AST file come from a module.
2385   if (!RD || !RD->isFromASTFile())
2386     return false;
2387   // Anonymous entities cannot be addressed. Treat them as not from module.
2388   if (!RD->isExternallyVisible() && RD->getName().empty())
2389     return false;
2390   if (auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD)) {
2391     if (!CXXDecl->isCompleteDefinition())
2392       return false;
2393     // Check wether RD is a template.
2394     auto TemplateKind = CXXDecl->getTemplateSpecializationKind();
2395     if (TemplateKind != TSK_Undeclared) {
2396       // Unfortunately getOwningModule() isn't accurate enough to find the
2397       // owning module of a ClassTemplateSpecializationDecl that is inside a
2398       // namespace spanning multiple modules.
2399       bool Explicit = false;
2400       if (auto *TD = dyn_cast<ClassTemplateSpecializationDecl>(CXXDecl))
2401         Explicit = TD->isExplicitInstantiationOrSpecialization();
2402       if (!Explicit && CXXDecl->getEnclosingNamespaceContext())
2403         return false;
2404       // This is a template, check the origin of the first member.
2405       if (CXXDecl->field_begin() == CXXDecl->field_end())
2406         return TemplateKind == TSK_ExplicitInstantiationDeclaration;
2407       if (!CXXDecl->field_begin()->isFromASTFile())
2408         return false;
2409     }
2410   }
2411   return true;
2412 }
2413 
2414 void CGDebugInfo::completeClassData(const RecordDecl *RD) {
2415   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
2416     if (CXXRD->isDynamicClass() &&
2417         CGM.getVTableLinkage(CXXRD) ==
2418             llvm::GlobalValue::AvailableExternallyLinkage &&
2419         !isClassOrMethodDLLImport(CXXRD))
2420       return;
2421 
2422   if (DebugTypeExtRefs && isDefinedInClangModule(RD->getDefinition()))
2423     return;
2424 
2425   completeClass(RD);
2426 }
2427 
2428 void CGDebugInfo::completeClass(const RecordDecl *RD) {
2429   if (DebugKind <= codegenoptions::DebugLineTablesOnly)
2430     return;
2431   QualType Ty = CGM.getContext().getRecordType(RD);
2432   void *TyPtr = Ty.getAsOpaquePtr();
2433   auto I = TypeCache.find(TyPtr);
2434   if (I != TypeCache.end() && !cast<llvm::DIType>(I->second)->isForwardDecl())
2435     return;
2436   llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<RecordType>());
2437   assert(!Res->isForwardDecl());
2438   TypeCache[TyPtr].reset(Res);
2439 }
2440 
2441 static bool hasExplicitMemberDefinition(CXXRecordDecl::method_iterator I,
2442                                         CXXRecordDecl::method_iterator End) {
2443   for (CXXMethodDecl *MD : llvm::make_range(I, End))
2444     if (FunctionDecl *Tmpl = MD->getInstantiatedFromMemberFunction())
2445       if (!Tmpl->isImplicit() && Tmpl->isThisDeclarationADefinition() &&
2446           !MD->getMemberSpecializationInfo()->isExplicitSpecialization())
2447         return true;
2448   return false;
2449 }
2450 
2451 static bool canUseCtorHoming(const CXXRecordDecl *RD) {
2452   // Constructor homing can be used for classes that cannnot be constructed
2453   // without emitting code for one of their constructors. This is classes that
2454   // don't have trivial or constexpr constructors, or can be created from
2455   // aggregate initialization. Also skip lambda objects because they don't call
2456   // constructors.
2457 
2458   // Skip this optimization if the class or any of its methods are marked
2459   // dllimport.
2460   if (isClassOrMethodDLLImport(RD))
2461     return false;
2462 
2463   return !RD->isLambda() && !RD->isAggregate() &&
2464          !RD->hasTrivialDefaultConstructor() &&
2465          !RD->hasConstexprNonCopyMoveConstructor();
2466 }
2467 
2468 static bool shouldOmitDefinition(codegenoptions::DebugInfoKind DebugKind,
2469                                  bool DebugTypeExtRefs, const RecordDecl *RD,
2470                                  const LangOptions &LangOpts) {
2471   if (DebugTypeExtRefs && isDefinedInClangModule(RD->getDefinition()))
2472     return true;
2473 
2474   if (auto *ES = RD->getASTContext().getExternalSource())
2475     if (ES->hasExternalDefinitions(RD) == ExternalASTSource::EK_Always)
2476       return true;
2477 
2478   // Only emit forward declarations in line tables only to keep debug info size
2479   // small. This only applies to CodeView, since we don't emit types in DWARF
2480   // line tables only.
2481   if (DebugKind == codegenoptions::DebugLineTablesOnly)
2482     return true;
2483 
2484   if (DebugKind > codegenoptions::LimitedDebugInfo ||
2485       RD->hasAttr<StandaloneDebugAttr>())
2486     return false;
2487 
2488   if (!LangOpts.CPlusPlus)
2489     return false;
2490 
2491   if (!RD->isCompleteDefinitionRequired())
2492     return true;
2493 
2494   const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
2495 
2496   if (!CXXDecl)
2497     return false;
2498 
2499   // Only emit complete debug info for a dynamic class when its vtable is
2500   // emitted.  However, Microsoft debuggers don't resolve type information
2501   // across DLL boundaries, so skip this optimization if the class or any of its
2502   // methods are marked dllimport. This isn't a complete solution, since objects
2503   // without any dllimport methods can be used in one DLL and constructed in
2504   // another, but it is the current behavior of LimitedDebugInfo.
2505   if (CXXDecl->hasDefinition() && CXXDecl->isDynamicClass() &&
2506       !isClassOrMethodDLLImport(CXXDecl))
2507     return true;
2508 
2509   TemplateSpecializationKind Spec = TSK_Undeclared;
2510   if (const auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD))
2511     Spec = SD->getSpecializationKind();
2512 
2513   if (Spec == TSK_ExplicitInstantiationDeclaration &&
2514       hasExplicitMemberDefinition(CXXDecl->method_begin(),
2515                                   CXXDecl->method_end()))
2516     return true;
2517 
2518   // In constructor homing mode, only emit complete debug info for a class
2519   // when its constructor is emitted.
2520   if ((DebugKind == codegenoptions::DebugInfoConstructor) &&
2521       canUseCtorHoming(CXXDecl))
2522     return true;
2523 
2524   return false;
2525 }
2526 
2527 void CGDebugInfo::completeRequiredType(const RecordDecl *RD) {
2528   if (shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD, CGM.getLangOpts()))
2529     return;
2530 
2531   QualType Ty = CGM.getContext().getRecordType(RD);
2532   llvm::DIType *T = getTypeOrNull(Ty);
2533   if (T && T->isForwardDecl())
2534     completeClassData(RD);
2535 }
2536 
2537 llvm::DIType *CGDebugInfo::CreateType(const RecordType *Ty) {
2538   RecordDecl *RD = Ty->getDecl();
2539   llvm::DIType *T = cast_or_null<llvm::DIType>(getTypeOrNull(QualType(Ty, 0)));
2540   if (T || shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD,
2541                                 CGM.getLangOpts())) {
2542     if (!T)
2543       T = getOrCreateRecordFwdDecl(Ty, getDeclContextDescriptor(RD));
2544     return T;
2545   }
2546 
2547   return CreateTypeDefinition(Ty);
2548 }
2549 
2550 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {
2551   RecordDecl *RD = Ty->getDecl();
2552 
2553   // Get overall information about the record type for the debug info.
2554   llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
2555 
2556   // Records and classes and unions can all be recursive.  To handle them, we
2557   // first generate a debug descriptor for the struct as a forward declaration.
2558   // Then (if it is a definition) we go through and get debug info for all of
2559   // its members.  Finally, we create a descriptor for the complete type (which
2560   // may refer to the forward decl if the struct is recursive) and replace all
2561   // uses of the forward declaration with the final definition.
2562   llvm::DICompositeType *FwdDecl = getOrCreateLimitedType(Ty);
2563 
2564   const RecordDecl *D = RD->getDefinition();
2565   if (!D || !D->isCompleteDefinition())
2566     return FwdDecl;
2567 
2568   if (const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
2569     CollectContainingType(CXXDecl, FwdDecl);
2570 
2571   // Push the struct on region stack.
2572   LexicalBlockStack.emplace_back(&*FwdDecl);
2573   RegionMap[Ty->getDecl()].reset(FwdDecl);
2574 
2575   // Convert all the elements.
2576   SmallVector<llvm::Metadata *, 16> EltTys;
2577   // what about nested types?
2578 
2579   // Note: The split of CXXDecl information here is intentional, the
2580   // gdb tests will depend on a certain ordering at printout. The debug
2581   // information offsets are still correct if we merge them all together
2582   // though.
2583   const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
2584   if (CXXDecl) {
2585     CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
2586     CollectVTableInfo(CXXDecl, DefUnit, EltTys);
2587   }
2588 
2589   // Collect data fields (including static variables and any initializers).
2590   CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
2591   if (CXXDecl)
2592     CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
2593 
2594   LexicalBlockStack.pop_back();
2595   RegionMap.erase(Ty->getDecl());
2596 
2597   llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
2598   DBuilder.replaceArrays(FwdDecl, Elements);
2599 
2600   if (FwdDecl->isTemporary())
2601     FwdDecl =
2602         llvm::MDNode::replaceWithPermanent(llvm::TempDICompositeType(FwdDecl));
2603 
2604   RegionMap[Ty->getDecl()].reset(FwdDecl);
2605   return FwdDecl;
2606 }
2607 
2608 llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectType *Ty,
2609                                       llvm::DIFile *Unit) {
2610   // Ignore protocols.
2611   return getOrCreateType(Ty->getBaseType(), Unit);
2612 }
2613 
2614 llvm::DIType *CGDebugInfo::CreateType(const ObjCTypeParamType *Ty,
2615                                       llvm::DIFile *Unit) {
2616   // Ignore protocols.
2617   SourceLocation Loc = Ty->getDecl()->getLocation();
2618 
2619   // Use Typedefs to represent ObjCTypeParamType.
2620   return DBuilder.createTypedef(
2621       getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit),
2622       Ty->getDecl()->getName(), getOrCreateFile(Loc), getLineNumber(Loc),
2623       getDeclContextDescriptor(Ty->getDecl()));
2624 }
2625 
2626 /// \return true if Getter has the default name for the property PD.
2627 static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
2628                                  const ObjCMethodDecl *Getter) {
2629   assert(PD);
2630   if (!Getter)
2631     return true;
2632 
2633   assert(Getter->getDeclName().isObjCZeroArgSelector());
2634   return PD->getName() ==
2635          Getter->getDeclName().getObjCSelector().getNameForSlot(0);
2636 }
2637 
2638 /// \return true if Setter has the default name for the property PD.
2639 static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
2640                                  const ObjCMethodDecl *Setter) {
2641   assert(PD);
2642   if (!Setter)
2643     return true;
2644 
2645   assert(Setter->getDeclName().isObjCOneArgSelector());
2646   return SelectorTable::constructSetterName(PD->getName()) ==
2647          Setter->getDeclName().getObjCSelector().getNameForSlot(0);
2648 }
2649 
2650 llvm::DIType *CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
2651                                       llvm::DIFile *Unit) {
2652   ObjCInterfaceDecl *ID = Ty->getDecl();
2653   if (!ID)
2654     return nullptr;
2655 
2656   // Return a forward declaration if this type was imported from a clang module,
2657   // and this is not the compile unit with the implementation of the type (which
2658   // may contain hidden ivars).
2659   if (DebugTypeExtRefs && ID->isFromASTFile() && ID->getDefinition() &&
2660       !ID->getImplementation())
2661     return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
2662                                       ID->getName(),
2663                                       getDeclContextDescriptor(ID), Unit, 0);
2664 
2665   // Get overall information about the record type for the debug info.
2666   llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
2667   unsigned Line = getLineNumber(ID->getLocation());
2668   auto RuntimeLang =
2669       static_cast<llvm::dwarf::SourceLanguage>(TheCU->getSourceLanguage());
2670 
2671   // If this is just a forward declaration return a special forward-declaration
2672   // debug type since we won't be able to lay out the entire type.
2673   ObjCInterfaceDecl *Def = ID->getDefinition();
2674   if (!Def || !Def->getImplementation()) {
2675     llvm::DIScope *Mod = getParentModuleOrNull(ID);
2676     llvm::DIType *FwdDecl = DBuilder.createReplaceableCompositeType(
2677         llvm::dwarf::DW_TAG_structure_type, ID->getName(), Mod ? Mod : TheCU,
2678         DefUnit, Line, RuntimeLang);
2679     ObjCInterfaceCache.push_back(ObjCInterfaceCacheEntry(Ty, FwdDecl, Unit));
2680     return FwdDecl;
2681   }
2682 
2683   return CreateTypeDefinition(Ty, Unit);
2684 }
2685 
2686 llvm::DIModule *CGDebugInfo::getOrCreateModuleRef(ASTSourceDescriptor Mod,
2687                                                   bool CreateSkeletonCU) {
2688   // Use the Module pointer as the key into the cache. This is a
2689   // nullptr if the "Module" is a PCH, which is safe because we don't
2690   // support chained PCH debug info, so there can only be a single PCH.
2691   const Module *M = Mod.getModuleOrNull();
2692   auto ModRef = ModuleCache.find(M);
2693   if (ModRef != ModuleCache.end())
2694     return cast<llvm::DIModule>(ModRef->second);
2695 
2696   // Macro definitions that were defined with "-D" on the command line.
2697   SmallString<128> ConfigMacros;
2698   {
2699     llvm::raw_svector_ostream OS(ConfigMacros);
2700     const auto &PPOpts = CGM.getPreprocessorOpts();
2701     unsigned I = 0;
2702     // Translate the macro definitions back into a command line.
2703     for (auto &M : PPOpts.Macros) {
2704       if (++I > 1)
2705         OS << " ";
2706       const std::string &Macro = M.first;
2707       bool Undef = M.second;
2708       OS << "\"-" << (Undef ? 'U' : 'D');
2709       for (char c : Macro)
2710         switch (c) {
2711         case '\\':
2712           OS << "\\\\";
2713           break;
2714         case '"':
2715           OS << "\\\"";
2716           break;
2717         default:
2718           OS << c;
2719         }
2720       OS << '\"';
2721     }
2722   }
2723 
2724   bool IsRootModule = M ? !M->Parent : true;
2725   // When a module name is specified as -fmodule-name, that module gets a
2726   // clang::Module object, but it won't actually be built or imported; it will
2727   // be textual.
2728   if (CreateSkeletonCU && IsRootModule && Mod.getASTFile().empty() && M)
2729     assert(StringRef(M->Name).startswith(CGM.getLangOpts().ModuleName) &&
2730            "clang module without ASTFile must be specified by -fmodule-name");
2731 
2732   // Return a StringRef to the remapped Path.
2733   auto RemapPath = [this](StringRef Path) -> std::string {
2734     std::string Remapped = remapDIPath(Path);
2735     StringRef Relative(Remapped);
2736     StringRef CompDir = TheCU->getDirectory();
2737     if (Relative.consume_front(CompDir))
2738       Relative.consume_front(llvm::sys::path::get_separator());
2739 
2740     return Relative.str();
2741   };
2742 
2743   if (CreateSkeletonCU && IsRootModule && !Mod.getASTFile().empty()) {
2744     // PCH files don't have a signature field in the control block,
2745     // but LLVM detects skeleton CUs by looking for a non-zero DWO id.
2746     // We use the lower 64 bits for debug info.
2747 
2748     uint64_t Signature = 0;
2749     if (const auto &ModSig = Mod.getSignature())
2750       Signature = ModSig.truncatedValue();
2751     else
2752       Signature = ~1ULL;
2753 
2754     llvm::DIBuilder DIB(CGM.getModule());
2755     SmallString<0> PCM;
2756     if (!llvm::sys::path::is_absolute(Mod.getASTFile()))
2757       PCM = Mod.getPath();
2758     llvm::sys::path::append(PCM, Mod.getASTFile());
2759     DIB.createCompileUnit(
2760         TheCU->getSourceLanguage(),
2761         // TODO: Support "Source" from external AST providers?
2762         DIB.createFile(Mod.getModuleName(), TheCU->getDirectory()),
2763         TheCU->getProducer(), false, StringRef(), 0, RemapPath(PCM),
2764         llvm::DICompileUnit::FullDebug, Signature);
2765     DIB.finalize();
2766   }
2767 
2768   llvm::DIModule *Parent =
2769       IsRootModule ? nullptr
2770                    : getOrCreateModuleRef(ASTSourceDescriptor(*M->Parent),
2771                                           CreateSkeletonCU);
2772   std::string IncludePath = Mod.getPath().str();
2773   llvm::DIModule *DIMod =
2774       DBuilder.createModule(Parent, Mod.getModuleName(), ConfigMacros,
2775                             RemapPath(IncludePath));
2776   ModuleCache[M].reset(DIMod);
2777   return DIMod;
2778 }
2779 
2780 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const ObjCInterfaceType *Ty,
2781                                                 llvm::DIFile *Unit) {
2782   ObjCInterfaceDecl *ID = Ty->getDecl();
2783   llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
2784   unsigned Line = getLineNumber(ID->getLocation());
2785   unsigned RuntimeLang = TheCU->getSourceLanguage();
2786 
2787   // Bit size, align and offset of the type.
2788   uint64_t Size = CGM.getContext().getTypeSize(Ty);
2789   auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
2790 
2791   llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
2792   if (ID->getImplementation())
2793     Flags |= llvm::DINode::FlagObjcClassComplete;
2794 
2795   llvm::DIScope *Mod = getParentModuleOrNull(ID);
2796   llvm::DICompositeType *RealDecl = DBuilder.createStructType(
2797       Mod ? Mod : Unit, ID->getName(), DefUnit, Line, Size, Align, Flags,
2798       nullptr, llvm::DINodeArray(), RuntimeLang);
2799 
2800   QualType QTy(Ty, 0);
2801   TypeCache[QTy.getAsOpaquePtr()].reset(RealDecl);
2802 
2803   // Push the struct on region stack.
2804   LexicalBlockStack.emplace_back(RealDecl);
2805   RegionMap[Ty->getDecl()].reset(RealDecl);
2806 
2807   // Convert all the elements.
2808   SmallVector<llvm::Metadata *, 16> EltTys;
2809 
2810   ObjCInterfaceDecl *SClass = ID->getSuperClass();
2811   if (SClass) {
2812     llvm::DIType *SClassTy =
2813         getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
2814     if (!SClassTy)
2815       return nullptr;
2816 
2817     llvm::DIType *InhTag = DBuilder.createInheritance(RealDecl, SClassTy, 0, 0,
2818                                                       llvm::DINode::FlagZero);
2819     EltTys.push_back(InhTag);
2820   }
2821 
2822   // Create entries for all of the properties.
2823   auto AddProperty = [&](const ObjCPropertyDecl *PD) {
2824     SourceLocation Loc = PD->getLocation();
2825     llvm::DIFile *PUnit = getOrCreateFile(Loc);
2826     unsigned PLine = getLineNumber(Loc);
2827     ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
2828     ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
2829     llvm::MDNode *PropertyNode = DBuilder.createObjCProperty(
2830         PD->getName(), PUnit, PLine,
2831         hasDefaultGetterName(PD, Getter) ? ""
2832                                          : getSelectorName(PD->getGetterName()),
2833         hasDefaultSetterName(PD, Setter) ? ""
2834                                          : getSelectorName(PD->getSetterName()),
2835         PD->getPropertyAttributes(), getOrCreateType(PD->getType(), PUnit));
2836     EltTys.push_back(PropertyNode);
2837   };
2838   {
2839     // Use 'char' for the isClassProperty bit as DenseSet requires space for
2840     // empty/tombstone keys in the data type (and bool is too small for that).
2841     typedef std::pair<char, const IdentifierInfo *> IsClassAndIdent;
2842     /// List of already emitted properties. Two distinct class and instance
2843     /// properties can share the same identifier (but not two instance
2844     /// properties or two class properties).
2845     llvm::DenseSet<IsClassAndIdent> PropertySet;
2846     /// Returns the IsClassAndIdent key for the given property.
2847     auto GetIsClassAndIdent = [](const ObjCPropertyDecl *PD) {
2848       return std::make_pair(PD->isClassProperty(), PD->getIdentifier());
2849     };
2850     for (const ObjCCategoryDecl *ClassExt : ID->known_extensions())
2851       for (auto *PD : ClassExt->properties()) {
2852         PropertySet.insert(GetIsClassAndIdent(PD));
2853         AddProperty(PD);
2854       }
2855     for (const auto *PD : ID->properties()) {
2856       // Don't emit duplicate metadata for properties that were already in a
2857       // class extension.
2858       if (!PropertySet.insert(GetIsClassAndIdent(PD)).second)
2859         continue;
2860       AddProperty(PD);
2861     }
2862   }
2863 
2864   const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
2865   unsigned FieldNo = 0;
2866   for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
2867        Field = Field->getNextIvar(), ++FieldNo) {
2868     llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
2869     if (!FieldTy)
2870       return nullptr;
2871 
2872     StringRef FieldName = Field->getName();
2873 
2874     // Ignore unnamed fields.
2875     if (FieldName.empty())
2876       continue;
2877 
2878     // Get the location for the field.
2879     llvm::DIFile *FieldDefUnit = getOrCreateFile(Field->getLocation());
2880     unsigned FieldLine = getLineNumber(Field->getLocation());
2881     QualType FType = Field->getType();
2882     uint64_t FieldSize = 0;
2883     uint32_t FieldAlign = 0;
2884 
2885     if (!FType->isIncompleteArrayType()) {
2886 
2887       // Bit size, align and offset of the type.
2888       FieldSize = Field->isBitField()
2889                       ? Field->getBitWidthValue(CGM.getContext())
2890                       : CGM.getContext().getTypeSize(FType);
2891       FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext());
2892     }
2893 
2894     uint64_t FieldOffset;
2895     if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
2896       // We don't know the runtime offset of an ivar if we're using the
2897       // non-fragile ABI.  For bitfields, use the bit offset into the first
2898       // byte of storage of the bitfield.  For other fields, use zero.
2899       if (Field->isBitField()) {
2900         FieldOffset =
2901             CGM.getObjCRuntime().ComputeBitfieldBitOffset(CGM, ID, Field);
2902         FieldOffset %= CGM.getContext().getCharWidth();
2903       } else {
2904         FieldOffset = 0;
2905       }
2906     } else {
2907       FieldOffset = RL.getFieldOffset(FieldNo);
2908     }
2909 
2910     llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
2911     if (Field->getAccessControl() == ObjCIvarDecl::Protected)
2912       Flags = llvm::DINode::FlagProtected;
2913     else if (Field->getAccessControl() == ObjCIvarDecl::Private)
2914       Flags = llvm::DINode::FlagPrivate;
2915     else if (Field->getAccessControl() == ObjCIvarDecl::Public)
2916       Flags = llvm::DINode::FlagPublic;
2917 
2918     llvm::MDNode *PropertyNode = nullptr;
2919     if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
2920       if (ObjCPropertyImplDecl *PImpD =
2921               ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
2922         if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
2923           SourceLocation Loc = PD->getLocation();
2924           llvm::DIFile *PUnit = getOrCreateFile(Loc);
2925           unsigned PLine = getLineNumber(Loc);
2926           ObjCMethodDecl *Getter = PImpD->getGetterMethodDecl();
2927           ObjCMethodDecl *Setter = PImpD->getSetterMethodDecl();
2928           PropertyNode = DBuilder.createObjCProperty(
2929               PD->getName(), PUnit, PLine,
2930               hasDefaultGetterName(PD, Getter)
2931                   ? ""
2932                   : getSelectorName(PD->getGetterName()),
2933               hasDefaultSetterName(PD, Setter)
2934                   ? ""
2935                   : getSelectorName(PD->getSetterName()),
2936               PD->getPropertyAttributes(),
2937               getOrCreateType(PD->getType(), PUnit));
2938         }
2939       }
2940     }
2941     FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit, FieldLine,
2942                                       FieldSize, FieldAlign, FieldOffset, Flags,
2943                                       FieldTy, PropertyNode);
2944     EltTys.push_back(FieldTy);
2945   }
2946 
2947   llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
2948   DBuilder.replaceArrays(RealDecl, Elements);
2949 
2950   LexicalBlockStack.pop_back();
2951   return RealDecl;
2952 }
2953 
2954 llvm::DIType *CGDebugInfo::CreateType(const VectorType *Ty,
2955                                       llvm::DIFile *Unit) {
2956   if (Ty->isExtVectorBoolType()) {
2957     // Boolean ext_vector_type(N) are special because their real element type
2958     // (bits of bit size) is not their Clang element type (_Bool of size byte).
2959     // For now, we pretend the boolean vector were actually a vector of bytes
2960     // (where each byte represents 8 bits of the actual vector).
2961     // FIXME Debug info should actually represent this proper as a vector mask
2962     // type.
2963     auto &Ctx = CGM.getContext();
2964     uint64_t Size = CGM.getContext().getTypeSize(Ty);
2965     uint64_t NumVectorBytes = Size / Ctx.getCharWidth();
2966 
2967     // Construct the vector of 'char' type.
2968     QualType CharVecTy = Ctx.getVectorType(Ctx.CharTy, NumVectorBytes,
2969                                            VectorType::GenericVector);
2970     return CreateType(CharVecTy->getAs<VectorType>(), Unit);
2971   }
2972 
2973   llvm::DIType *ElementTy = getOrCreateType(Ty->getElementType(), Unit);
2974   int64_t Count = Ty->getNumElements();
2975 
2976   llvm::Metadata *Subscript;
2977   QualType QTy(Ty, 0);
2978   auto SizeExpr = SizeExprCache.find(QTy);
2979   if (SizeExpr != SizeExprCache.end())
2980     Subscript = DBuilder.getOrCreateSubrange(
2981         SizeExpr->getSecond() /*count*/, nullptr /*lowerBound*/,
2982         nullptr /*upperBound*/, nullptr /*stride*/);
2983   else {
2984     auto *CountNode =
2985         llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
2986             llvm::Type::getInt64Ty(CGM.getLLVMContext()), Count ? Count : -1));
2987     Subscript = DBuilder.getOrCreateSubrange(
2988         CountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
2989         nullptr /*stride*/);
2990   }
2991   llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
2992 
2993   uint64_t Size = CGM.getContext().getTypeSize(Ty);
2994   auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
2995 
2996   return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
2997 }
2998 
2999 llvm::DIType *CGDebugInfo::CreateType(const ConstantMatrixType *Ty,
3000                                       llvm::DIFile *Unit) {
3001   // FIXME: Create another debug type for matrices
3002   // For the time being, it treats it like a nested ArrayType.
3003 
3004   llvm::DIType *ElementTy = getOrCreateType(Ty->getElementType(), Unit);
3005   uint64_t Size = CGM.getContext().getTypeSize(Ty);
3006   uint32_t Align = getTypeAlignIfRequired(Ty, CGM.getContext());
3007 
3008   // Create ranges for both dimensions.
3009   llvm::SmallVector<llvm::Metadata *, 2> Subscripts;
3010   auto *ColumnCountNode =
3011       llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
3012           llvm::Type::getInt64Ty(CGM.getLLVMContext()), Ty->getNumColumns()));
3013   auto *RowCountNode =
3014       llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
3015           llvm::Type::getInt64Ty(CGM.getLLVMContext()), Ty->getNumRows()));
3016   Subscripts.push_back(DBuilder.getOrCreateSubrange(
3017       ColumnCountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
3018       nullptr /*stride*/));
3019   Subscripts.push_back(DBuilder.getOrCreateSubrange(
3020       RowCountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
3021       nullptr /*stride*/));
3022   llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
3023   return DBuilder.createArrayType(Size, Align, ElementTy, SubscriptArray);
3024 }
3025 
3026 llvm::DIType *CGDebugInfo::CreateType(const ArrayType *Ty, llvm::DIFile *Unit) {
3027   uint64_t Size;
3028   uint32_t Align;
3029 
3030   // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
3031   if (const auto *VAT = dyn_cast<VariableArrayType>(Ty)) {
3032     Size = 0;
3033     Align = getTypeAlignIfRequired(CGM.getContext().getBaseElementType(VAT),
3034                                    CGM.getContext());
3035   } else if (Ty->isIncompleteArrayType()) {
3036     Size = 0;
3037     if (Ty->getElementType()->isIncompleteType())
3038       Align = 0;
3039     else
3040       Align = getTypeAlignIfRequired(Ty->getElementType(), CGM.getContext());
3041   } else if (Ty->isIncompleteType()) {
3042     Size = 0;
3043     Align = 0;
3044   } else {
3045     // Size and align of the whole array, not the element type.
3046     Size = CGM.getContext().getTypeSize(Ty);
3047     Align = getTypeAlignIfRequired(Ty, CGM.getContext());
3048   }
3049 
3050   // Add the dimensions of the array.  FIXME: This loses CV qualifiers from
3051   // interior arrays, do we care?  Why aren't nested arrays represented the
3052   // obvious/recursive way?
3053   SmallVector<llvm::Metadata *, 8> Subscripts;
3054   QualType EltTy(Ty, 0);
3055   while ((Ty = dyn_cast<ArrayType>(EltTy))) {
3056     // If the number of elements is known, then count is that number. Otherwise,
3057     // it's -1. This allows us to represent a subrange with an array of 0
3058     // elements, like this:
3059     //
3060     //   struct foo {
3061     //     int x[0];
3062     //   };
3063     int64_t Count = -1; // Count == -1 is an unbounded array.
3064     if (const auto *CAT = dyn_cast<ConstantArrayType>(Ty))
3065       Count = CAT->getSize().getZExtValue();
3066     else if (const auto *VAT = dyn_cast<VariableArrayType>(Ty)) {
3067       if (Expr *Size = VAT->getSizeExpr()) {
3068         Expr::EvalResult Result;
3069         if (Size->EvaluateAsInt(Result, CGM.getContext()))
3070           Count = Result.Val.getInt().getExtValue();
3071       }
3072     }
3073 
3074     auto SizeNode = SizeExprCache.find(EltTy);
3075     if (SizeNode != SizeExprCache.end())
3076       Subscripts.push_back(DBuilder.getOrCreateSubrange(
3077           SizeNode->getSecond() /*count*/, nullptr /*lowerBound*/,
3078           nullptr /*upperBound*/, nullptr /*stride*/));
3079     else {
3080       auto *CountNode =
3081           llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
3082               llvm::Type::getInt64Ty(CGM.getLLVMContext()), Count));
3083       Subscripts.push_back(DBuilder.getOrCreateSubrange(
3084           CountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
3085           nullptr /*stride*/));
3086     }
3087     EltTy = Ty->getElementType();
3088   }
3089 
3090   llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
3091 
3092   return DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
3093                                   SubscriptArray);
3094 }
3095 
3096 llvm::DIType *CGDebugInfo::CreateType(const LValueReferenceType *Ty,
3097                                       llvm::DIFile *Unit) {
3098   return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type, Ty,
3099                                Ty->getPointeeType(), Unit);
3100 }
3101 
3102 llvm::DIType *CGDebugInfo::CreateType(const RValueReferenceType *Ty,
3103                                       llvm::DIFile *Unit) {
3104   llvm::dwarf::Tag Tag = llvm::dwarf::DW_TAG_rvalue_reference_type;
3105   // DW_TAG_rvalue_reference_type was introduced in DWARF 4.
3106   if (CGM.getCodeGenOpts().DebugStrictDwarf &&
3107       CGM.getCodeGenOpts().DwarfVersion < 4)
3108     Tag = llvm::dwarf::DW_TAG_reference_type;
3109 
3110   return CreatePointerLikeType(Tag, Ty, Ty->getPointeeType(), Unit);
3111 }
3112 
3113 llvm::DIType *CGDebugInfo::CreateType(const MemberPointerType *Ty,
3114                                       llvm::DIFile *U) {
3115   llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3116   uint64_t Size = 0;
3117 
3118   if (!Ty->isIncompleteType()) {
3119     Size = CGM.getContext().getTypeSize(Ty);
3120 
3121     // Set the MS inheritance model. There is no flag for the unspecified model.
3122     if (CGM.getTarget().getCXXABI().isMicrosoft()) {
3123       switch (Ty->getMostRecentCXXRecordDecl()->getMSInheritanceModel()) {
3124       case MSInheritanceModel::Single:
3125         Flags |= llvm::DINode::FlagSingleInheritance;
3126         break;
3127       case MSInheritanceModel::Multiple:
3128         Flags |= llvm::DINode::FlagMultipleInheritance;
3129         break;
3130       case MSInheritanceModel::Virtual:
3131         Flags |= llvm::DINode::FlagVirtualInheritance;
3132         break;
3133       case MSInheritanceModel::Unspecified:
3134         break;
3135       }
3136     }
3137   }
3138 
3139   llvm::DIType *ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
3140   if (Ty->isMemberDataPointerType())
3141     return DBuilder.createMemberPointerType(
3142         getOrCreateType(Ty->getPointeeType(), U), ClassType, Size, /*Align=*/0,
3143         Flags);
3144 
3145   const FunctionProtoType *FPT =
3146       Ty->getPointeeType()->getAs<FunctionProtoType>();
3147   return DBuilder.createMemberPointerType(
3148       getOrCreateInstanceMethodType(
3149           CXXMethodDecl::getThisType(FPT, Ty->getMostRecentCXXRecordDecl()),
3150           FPT, U, false),
3151       ClassType, Size, /*Align=*/0, Flags);
3152 }
3153 
3154 llvm::DIType *CGDebugInfo::CreateType(const AtomicType *Ty, llvm::DIFile *U) {
3155   auto *FromTy = getOrCreateType(Ty->getValueType(), U);
3156   return DBuilder.createQualifiedType(llvm::dwarf::DW_TAG_atomic_type, FromTy);
3157 }
3158 
3159 llvm::DIType *CGDebugInfo::CreateType(const PipeType *Ty, llvm::DIFile *U) {
3160   return getOrCreateType(Ty->getElementType(), U);
3161 }
3162 
3163 llvm::DIType *CGDebugInfo::CreateEnumType(const EnumType *Ty) {
3164   const EnumDecl *ED = Ty->getDecl();
3165 
3166   uint64_t Size = 0;
3167   uint32_t Align = 0;
3168   if (!ED->getTypeForDecl()->isIncompleteType()) {
3169     Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
3170     Align = getDeclAlignIfRequired(ED, CGM.getContext());
3171   }
3172 
3173   SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
3174 
3175   bool isImportedFromModule =
3176       DebugTypeExtRefs && ED->isFromASTFile() && ED->getDefinition();
3177 
3178   // If this is just a forward declaration, construct an appropriately
3179   // marked node and just return it.
3180   if (isImportedFromModule || !ED->getDefinition()) {
3181     // Note that it is possible for enums to be created as part of
3182     // their own declcontext. In this case a FwdDecl will be created
3183     // twice. This doesn't cause a problem because both FwdDecls are
3184     // entered into the ReplaceMap: finalize() will replace the first
3185     // FwdDecl with the second and then replace the second with
3186     // complete type.
3187     llvm::DIScope *EDContext = getDeclContextDescriptor(ED);
3188     llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
3189     llvm::TempDIScope TmpContext(DBuilder.createReplaceableCompositeType(
3190         llvm::dwarf::DW_TAG_enumeration_type, "", TheCU, DefUnit, 0));
3191 
3192     unsigned Line = getLineNumber(ED->getLocation());
3193     StringRef EDName = ED->getName();
3194     llvm::DIType *RetTy = DBuilder.createReplaceableCompositeType(
3195         llvm::dwarf::DW_TAG_enumeration_type, EDName, EDContext, DefUnit, Line,
3196         0, Size, Align, llvm::DINode::FlagFwdDecl, Identifier);
3197 
3198     ReplaceMap.emplace_back(
3199         std::piecewise_construct, std::make_tuple(Ty),
3200         std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
3201     return RetTy;
3202   }
3203 
3204   return CreateTypeDefinition(Ty);
3205 }
3206 
3207 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const EnumType *Ty) {
3208   const EnumDecl *ED = Ty->getDecl();
3209   uint64_t Size = 0;
3210   uint32_t Align = 0;
3211   if (!ED->getTypeForDecl()->isIncompleteType()) {
3212     Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
3213     Align = getDeclAlignIfRequired(ED, CGM.getContext());
3214   }
3215 
3216   SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
3217 
3218   SmallVector<llvm::Metadata *, 16> Enumerators;
3219   ED = ED->getDefinition();
3220   for (const auto *Enum : ED->enumerators()) {
3221     Enumerators.push_back(
3222         DBuilder.createEnumerator(Enum->getName(), Enum->getInitVal()));
3223   }
3224 
3225   // Return a CompositeType for the enum itself.
3226   llvm::DINodeArray EltArray = DBuilder.getOrCreateArray(Enumerators);
3227 
3228   llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
3229   unsigned Line = getLineNumber(ED->getLocation());
3230   llvm::DIScope *EnumContext = getDeclContextDescriptor(ED);
3231   llvm::DIType *ClassTy = getOrCreateType(ED->getIntegerType(), DefUnit);
3232   return DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit,
3233                                         Line, Size, Align, EltArray, ClassTy,
3234                                         Identifier, ED->isScoped());
3235 }
3236 
3237 llvm::DIMacro *CGDebugInfo::CreateMacro(llvm::DIMacroFile *Parent,
3238                                         unsigned MType, SourceLocation LineLoc,
3239                                         StringRef Name, StringRef Value) {
3240   unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(LineLoc);
3241   return DBuilder.createMacro(Parent, Line, MType, Name, Value);
3242 }
3243 
3244 llvm::DIMacroFile *CGDebugInfo::CreateTempMacroFile(llvm::DIMacroFile *Parent,
3245                                                     SourceLocation LineLoc,
3246                                                     SourceLocation FileLoc) {
3247   llvm::DIFile *FName = getOrCreateFile(FileLoc);
3248   unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(LineLoc);
3249   return DBuilder.createTempMacroFile(Parent, Line, FName);
3250 }
3251 
3252 static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
3253   Qualifiers Quals;
3254   do {
3255     Qualifiers InnerQuals = T.getLocalQualifiers();
3256     // Qualifiers::operator+() doesn't like it if you add a Qualifier
3257     // that is already there.
3258     Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals);
3259     Quals += InnerQuals;
3260     QualType LastT = T;
3261     switch (T->getTypeClass()) {
3262     default:
3263       return C.getQualifiedType(T.getTypePtr(), Quals);
3264     case Type::TemplateSpecialization: {
3265       const auto *Spec = cast<TemplateSpecializationType>(T);
3266       if (Spec->isTypeAlias())
3267         return C.getQualifiedType(T.getTypePtr(), Quals);
3268       T = Spec->desugar();
3269       break;
3270     }
3271     case Type::TypeOfExpr:
3272       T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
3273       break;
3274     case Type::TypeOf:
3275       T = cast<TypeOfType>(T)->getUnderlyingType();
3276       break;
3277     case Type::Decltype:
3278       T = cast<DecltypeType>(T)->getUnderlyingType();
3279       break;
3280     case Type::UnaryTransform:
3281       T = cast<UnaryTransformType>(T)->getUnderlyingType();
3282       break;
3283     case Type::Attributed:
3284       T = cast<AttributedType>(T)->getEquivalentType();
3285       break;
3286     case Type::BTFTagAttributed:
3287       T = cast<BTFTagAttributedType>(T)->getWrappedType();
3288       break;
3289     case Type::Elaborated:
3290       T = cast<ElaboratedType>(T)->getNamedType();
3291       break;
3292     case Type::Using:
3293       T = cast<UsingType>(T)->getUnderlyingType();
3294       break;
3295     case Type::Paren:
3296       T = cast<ParenType>(T)->getInnerType();
3297       break;
3298     case Type::MacroQualified:
3299       T = cast<MacroQualifiedType>(T)->getUnderlyingType();
3300       break;
3301     case Type::SubstTemplateTypeParm:
3302       T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
3303       break;
3304     case Type::Auto:
3305     case Type::DeducedTemplateSpecialization: {
3306       QualType DT = cast<DeducedType>(T)->getDeducedType();
3307       assert(!DT.isNull() && "Undeduced types shouldn't reach here.");
3308       T = DT;
3309       break;
3310     }
3311     case Type::Adjusted:
3312     case Type::Decayed:
3313       // Decayed and adjusted types use the adjusted type in LLVM and DWARF.
3314       T = cast<AdjustedType>(T)->getAdjustedType();
3315       break;
3316     }
3317 
3318     assert(T != LastT && "Type unwrapping failed to unwrap!");
3319     (void)LastT;
3320   } while (true);
3321 }
3322 
3323 llvm::DIType *CGDebugInfo::getTypeOrNull(QualType Ty) {
3324   assert(Ty == UnwrapTypeForDebugInfo(Ty, CGM.getContext()));
3325   auto It = TypeCache.find(Ty.getAsOpaquePtr());
3326   if (It != TypeCache.end()) {
3327     // Verify that the debug info still exists.
3328     if (llvm::Metadata *V = It->second)
3329       return cast<llvm::DIType>(V);
3330   }
3331 
3332   return nullptr;
3333 }
3334 
3335 void CGDebugInfo::completeTemplateDefinition(
3336     const ClassTemplateSpecializationDecl &SD) {
3337   completeUnusedClass(SD);
3338 }
3339 
3340 void CGDebugInfo::completeUnusedClass(const CXXRecordDecl &D) {
3341   if (DebugKind <= codegenoptions::DebugLineTablesOnly)
3342     return;
3343 
3344   completeClassData(&D);
3345   // In case this type has no member function definitions being emitted, ensure
3346   // it is retained
3347   RetainedTypes.push_back(CGM.getContext().getRecordType(&D).getAsOpaquePtr());
3348 }
3349 
3350 llvm::DIType *CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile *Unit) {
3351   if (Ty.isNull())
3352     return nullptr;
3353 
3354   llvm::TimeTraceScope TimeScope("DebugType", [&]() {
3355     std::string Name;
3356     llvm::raw_string_ostream OS(Name);
3357     Ty.print(OS, getPrintingPolicy());
3358     return Name;
3359   });
3360 
3361   // Unwrap the type as needed for debug information.
3362   Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
3363 
3364   if (auto *T = getTypeOrNull(Ty))
3365     return T;
3366 
3367   llvm::DIType *Res = CreateTypeNode(Ty, Unit);
3368   void *TyPtr = Ty.getAsOpaquePtr();
3369 
3370   // And update the type cache.
3371   TypeCache[TyPtr].reset(Res);
3372 
3373   return Res;
3374 }
3375 
3376 llvm::DIModule *CGDebugInfo::getParentModuleOrNull(const Decl *D) {
3377   // A forward declaration inside a module header does not belong to the module.
3378   if (isa<RecordDecl>(D) && !cast<RecordDecl>(D)->getDefinition())
3379     return nullptr;
3380   if (DebugTypeExtRefs && D->isFromASTFile()) {
3381     // Record a reference to an imported clang module or precompiled header.
3382     auto *Reader = CGM.getContext().getExternalSource();
3383     auto Idx = D->getOwningModuleID();
3384     auto Info = Reader->getSourceDescriptor(Idx);
3385     if (Info)
3386       return getOrCreateModuleRef(*Info, /*SkeletonCU=*/true);
3387   } else if (ClangModuleMap) {
3388     // We are building a clang module or a precompiled header.
3389     //
3390     // TODO: When D is a CXXRecordDecl or a C++ Enum, the ODR applies
3391     // and it wouldn't be necessary to specify the parent scope
3392     // because the type is already unique by definition (it would look
3393     // like the output of -fno-standalone-debug). On the other hand,
3394     // the parent scope helps a consumer to quickly locate the object
3395     // file where the type's definition is located, so it might be
3396     // best to make this behavior a command line or debugger tuning
3397     // option.
3398     if (Module *M = D->getOwningModule()) {
3399       // This is a (sub-)module.
3400       auto Info = ASTSourceDescriptor(*M);
3401       return getOrCreateModuleRef(Info, /*SkeletonCU=*/false);
3402     } else {
3403       // This the precompiled header being built.
3404       return getOrCreateModuleRef(PCHDescriptor, /*SkeletonCU=*/false);
3405     }
3406   }
3407 
3408   return nullptr;
3409 }
3410 
3411 llvm::DIType *CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile *Unit) {
3412   // Handle qualifiers, which recursively handles what they refer to.
3413   if (Ty.hasLocalQualifiers())
3414     return CreateQualifiedType(Ty, Unit);
3415 
3416   // Work out details of type.
3417   switch (Ty->getTypeClass()) {
3418 #define TYPE(Class, Base)
3419 #define ABSTRACT_TYPE(Class, Base)
3420 #define NON_CANONICAL_TYPE(Class, Base)
3421 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3422 #include "clang/AST/TypeNodes.inc"
3423     llvm_unreachable("Dependent types cannot show up in debug information");
3424 
3425   case Type::ExtVector:
3426   case Type::Vector:
3427     return CreateType(cast<VectorType>(Ty), Unit);
3428   case Type::ConstantMatrix:
3429     return CreateType(cast<ConstantMatrixType>(Ty), Unit);
3430   case Type::ObjCObjectPointer:
3431     return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
3432   case Type::ObjCObject:
3433     return CreateType(cast<ObjCObjectType>(Ty), Unit);
3434   case Type::ObjCTypeParam:
3435     return CreateType(cast<ObjCTypeParamType>(Ty), Unit);
3436   case Type::ObjCInterface:
3437     return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
3438   case Type::Builtin:
3439     return CreateType(cast<BuiltinType>(Ty));
3440   case Type::Complex:
3441     return CreateType(cast<ComplexType>(Ty));
3442   case Type::Pointer:
3443     return CreateType(cast<PointerType>(Ty), Unit);
3444   case Type::BlockPointer:
3445     return CreateType(cast<BlockPointerType>(Ty), Unit);
3446   case Type::Typedef:
3447     return CreateType(cast<TypedefType>(Ty), Unit);
3448   case Type::Record:
3449     return CreateType(cast<RecordType>(Ty));
3450   case Type::Enum:
3451     return CreateEnumType(cast<EnumType>(Ty));
3452   case Type::FunctionProto:
3453   case Type::FunctionNoProto:
3454     return CreateType(cast<FunctionType>(Ty), Unit);
3455   case Type::ConstantArray:
3456   case Type::VariableArray:
3457   case Type::IncompleteArray:
3458     return CreateType(cast<ArrayType>(Ty), Unit);
3459 
3460   case Type::LValueReference:
3461     return CreateType(cast<LValueReferenceType>(Ty), Unit);
3462   case Type::RValueReference:
3463     return CreateType(cast<RValueReferenceType>(Ty), Unit);
3464 
3465   case Type::MemberPointer:
3466     return CreateType(cast<MemberPointerType>(Ty), Unit);
3467 
3468   case Type::Atomic:
3469     return CreateType(cast<AtomicType>(Ty), Unit);
3470 
3471   case Type::BitInt:
3472     return CreateType(cast<BitIntType>(Ty));
3473   case Type::Pipe:
3474     return CreateType(cast<PipeType>(Ty), Unit);
3475 
3476   case Type::TemplateSpecialization:
3477     return CreateType(cast<TemplateSpecializationType>(Ty), Unit);
3478 
3479   case Type::Auto:
3480   case Type::Attributed:
3481   case Type::BTFTagAttributed:
3482   case Type::Adjusted:
3483   case Type::Decayed:
3484   case Type::DeducedTemplateSpecialization:
3485   case Type::Elaborated:
3486   case Type::Using:
3487   case Type::Paren:
3488   case Type::MacroQualified:
3489   case Type::SubstTemplateTypeParm:
3490   case Type::TypeOfExpr:
3491   case Type::TypeOf:
3492   case Type::Decltype:
3493   case Type::UnaryTransform:
3494     break;
3495   }
3496 
3497   llvm_unreachable("type should have been unwrapped!");
3498 }
3499 
3500 llvm::DICompositeType *
3501 CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty) {
3502   QualType QTy(Ty, 0);
3503 
3504   auto *T = cast_or_null<llvm::DICompositeType>(getTypeOrNull(QTy));
3505 
3506   // We may have cached a forward decl when we could have created
3507   // a non-forward decl. Go ahead and create a non-forward decl
3508   // now.
3509   if (T && !T->isForwardDecl())
3510     return T;
3511 
3512   // Otherwise create the type.
3513   llvm::DICompositeType *Res = CreateLimitedType(Ty);
3514 
3515   // Propagate members from the declaration to the definition
3516   // CreateType(const RecordType*) will overwrite this with the members in the
3517   // correct order if the full type is needed.
3518   DBuilder.replaceArrays(Res, T ? T->getElements() : llvm::DINodeArray());
3519 
3520   // And update the type cache.
3521   TypeCache[QTy.getAsOpaquePtr()].reset(Res);
3522   return Res;
3523 }
3524 
3525 // TODO: Currently used for context chains when limiting debug info.
3526 llvm::DICompositeType *CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
3527   RecordDecl *RD = Ty->getDecl();
3528 
3529   // Get overall information about the record type for the debug info.
3530   StringRef RDName = getClassName(RD);
3531   const SourceLocation Loc = RD->getLocation();
3532   llvm::DIFile *DefUnit = nullptr;
3533   unsigned Line = 0;
3534   if (Loc.isValid()) {
3535     DefUnit = getOrCreateFile(Loc);
3536     Line = getLineNumber(Loc);
3537   }
3538 
3539   llvm::DIScope *RDContext = getDeclContextDescriptor(RD);
3540 
3541   // If we ended up creating the type during the context chain construction,
3542   // just return that.
3543   auto *T = cast_or_null<llvm::DICompositeType>(
3544       getTypeOrNull(CGM.getContext().getRecordType(RD)));
3545   if (T && (!T->isForwardDecl() || !RD->getDefinition()))
3546     return T;
3547 
3548   // If this is just a forward or incomplete declaration, construct an
3549   // appropriately marked node and just return it.
3550   const RecordDecl *D = RD->getDefinition();
3551   if (!D || !D->isCompleteDefinition())
3552     return getOrCreateRecordFwdDecl(Ty, RDContext);
3553 
3554   uint64_t Size = CGM.getContext().getTypeSize(Ty);
3555   auto Align = getDeclAlignIfRequired(D, CGM.getContext());
3556 
3557   SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
3558 
3559   // Explicitly record the calling convention and export symbols for C++
3560   // records.
3561   auto Flags = llvm::DINode::FlagZero;
3562   if (auto CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3563     if (CGM.getCXXABI().getRecordArgABI(CXXRD) == CGCXXABI::RAA_Indirect)
3564       Flags |= llvm::DINode::FlagTypePassByReference;
3565     else
3566       Flags |= llvm::DINode::FlagTypePassByValue;
3567 
3568     // Record if a C++ record is non-trivial type.
3569     if (!CXXRD->isTrivial())
3570       Flags |= llvm::DINode::FlagNonTrivial;
3571 
3572     // Record exports it symbols to the containing structure.
3573     if (CXXRD->isAnonymousStructOrUnion())
3574         Flags |= llvm::DINode::FlagExportSymbols;
3575 
3576     Flags |= getAccessFlag(CXXRD->getAccess(),
3577                            dyn_cast<CXXRecordDecl>(CXXRD->getDeclContext()));
3578   }
3579 
3580   llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(D);
3581   llvm::DICompositeType *RealDecl = DBuilder.createReplaceableCompositeType(
3582       getTagForRecord(RD), RDName, RDContext, DefUnit, Line, 0, Size, Align,
3583       Flags, Identifier, Annotations);
3584 
3585   // Elements of composite types usually have back to the type, creating
3586   // uniquing cycles.  Distinct nodes are more efficient.
3587   switch (RealDecl->getTag()) {
3588   default:
3589     llvm_unreachable("invalid composite type tag");
3590 
3591   case llvm::dwarf::DW_TAG_array_type:
3592   case llvm::dwarf::DW_TAG_enumeration_type:
3593     // Array elements and most enumeration elements don't have back references,
3594     // so they don't tend to be involved in uniquing cycles and there is some
3595     // chance of merging them when linking together two modules.  Only make
3596     // them distinct if they are ODR-uniqued.
3597     if (Identifier.empty())
3598       break;
3599     LLVM_FALLTHROUGH;
3600 
3601   case llvm::dwarf::DW_TAG_structure_type:
3602   case llvm::dwarf::DW_TAG_union_type:
3603   case llvm::dwarf::DW_TAG_class_type:
3604     // Immediately resolve to a distinct node.
3605     RealDecl =
3606         llvm::MDNode::replaceWithDistinct(llvm::TempDICompositeType(RealDecl));
3607     break;
3608   }
3609 
3610   RegionMap[Ty->getDecl()].reset(RealDecl);
3611   TypeCache[QualType(Ty, 0).getAsOpaquePtr()].reset(RealDecl);
3612 
3613   if (const auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD))
3614     DBuilder.replaceArrays(RealDecl, llvm::DINodeArray(),
3615                            CollectCXXTemplateParams(TSpecial, DefUnit));
3616   return RealDecl;
3617 }
3618 
3619 void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,
3620                                         llvm::DICompositeType *RealDecl) {
3621   // A class's primary base or the class itself contains the vtable.
3622   llvm::DICompositeType *ContainingType = nullptr;
3623   const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
3624   if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
3625     // Seek non-virtual primary base root.
3626     while (true) {
3627       const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
3628       const CXXRecordDecl *PBT = BRL.getPrimaryBase();
3629       if (PBT && !BRL.isPrimaryBaseVirtual())
3630         PBase = PBT;
3631       else
3632         break;
3633     }
3634     ContainingType = cast<llvm::DICompositeType>(
3635         getOrCreateType(QualType(PBase->getTypeForDecl(), 0),
3636                         getOrCreateFile(RD->getLocation())));
3637   } else if (RD->isDynamicClass())
3638     ContainingType = RealDecl;
3639 
3640   DBuilder.replaceVTableHolder(RealDecl, ContainingType);
3641 }
3642 
3643 llvm::DIType *CGDebugInfo::CreateMemberType(llvm::DIFile *Unit, QualType FType,
3644                                             StringRef Name, uint64_t *Offset) {
3645   llvm::DIType *FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
3646   uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
3647   auto FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext());
3648   llvm::DIType *Ty =
3649       DBuilder.createMemberType(Unit, Name, Unit, 0, FieldSize, FieldAlign,
3650                                 *Offset, llvm::DINode::FlagZero, FieldTy);
3651   *Offset += FieldSize;
3652   return Ty;
3653 }
3654 
3655 void CGDebugInfo::collectFunctionDeclProps(GlobalDecl GD, llvm::DIFile *Unit,
3656                                            StringRef &Name,
3657                                            StringRef &LinkageName,
3658                                            llvm::DIScope *&FDContext,
3659                                            llvm::DINodeArray &TParamsArray,
3660                                            llvm::DINode::DIFlags &Flags) {
3661   const auto *FD = cast<FunctionDecl>(GD.getCanonicalDecl().getDecl());
3662   Name = getFunctionName(FD);
3663   // Use mangled name as linkage name for C/C++ functions.
3664   if (FD->getType()->getAs<FunctionProtoType>())
3665     LinkageName = CGM.getMangledName(GD);
3666   if (FD->hasPrototype())
3667     Flags |= llvm::DINode::FlagPrototyped;
3668   // No need to replicate the linkage name if it isn't different from the
3669   // subprogram name, no need to have it at all unless coverage is enabled or
3670   // debug is set to more than just line tables or extra debug info is needed.
3671   if (LinkageName == Name || (!CGM.getCodeGenOpts().EmitGcovArcs &&
3672                               !CGM.getCodeGenOpts().EmitGcovNotes &&
3673                               !CGM.getCodeGenOpts().DebugInfoForProfiling &&
3674                               !CGM.getCodeGenOpts().PseudoProbeForProfiling &&
3675                               DebugKind <= codegenoptions::DebugLineTablesOnly))
3676     LinkageName = StringRef();
3677 
3678   // Emit the function scope in line tables only mode (if CodeView) to
3679   // differentiate between function names.
3680   if (CGM.getCodeGenOpts().hasReducedDebugInfo() ||
3681       (DebugKind == codegenoptions::DebugLineTablesOnly &&
3682        CGM.getCodeGenOpts().EmitCodeView)) {
3683     if (const NamespaceDecl *NSDecl =
3684             dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
3685       FDContext = getOrCreateNamespace(NSDecl);
3686     else if (const RecordDecl *RDecl =
3687                  dyn_cast_or_null<RecordDecl>(FD->getDeclContext())) {
3688       llvm::DIScope *Mod = getParentModuleOrNull(RDecl);
3689       FDContext = getContextDescriptor(RDecl, Mod ? Mod : TheCU);
3690     }
3691   }
3692   if (CGM.getCodeGenOpts().hasReducedDebugInfo()) {
3693     // Check if it is a noreturn-marked function
3694     if (FD->isNoReturn())
3695       Flags |= llvm::DINode::FlagNoReturn;
3696     // Collect template parameters.
3697     TParamsArray = CollectFunctionTemplateParams(FD, Unit);
3698   }
3699 }
3700 
3701 void CGDebugInfo::collectVarDeclProps(const VarDecl *VD, llvm::DIFile *&Unit,
3702                                       unsigned &LineNo, QualType &T,
3703                                       StringRef &Name, StringRef &LinkageName,
3704                                       llvm::MDTuple *&TemplateParameters,
3705                                       llvm::DIScope *&VDContext) {
3706   Unit = getOrCreateFile(VD->getLocation());
3707   LineNo = getLineNumber(VD->getLocation());
3708 
3709   setLocation(VD->getLocation());
3710 
3711   T = VD->getType();
3712   if (T->isIncompleteArrayType()) {
3713     // CodeGen turns int[] into int[1] so we'll do the same here.
3714     llvm::APInt ConstVal(32, 1);
3715     QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3716 
3717     T = CGM.getContext().getConstantArrayType(ET, ConstVal, nullptr,
3718                                               ArrayType::Normal, 0);
3719   }
3720 
3721   Name = VD->getName();
3722   if (VD->getDeclContext() && !isa<FunctionDecl>(VD->getDeclContext()) &&
3723       !isa<ObjCMethodDecl>(VD->getDeclContext()))
3724     LinkageName = CGM.getMangledName(VD);
3725   if (LinkageName == Name)
3726     LinkageName = StringRef();
3727 
3728   if (isa<VarTemplateSpecializationDecl>(VD)) {
3729     llvm::DINodeArray parameterNodes = CollectVarTemplateParams(VD, &*Unit);
3730     TemplateParameters = parameterNodes.get();
3731   } else {
3732     TemplateParameters = nullptr;
3733   }
3734 
3735   // Since we emit declarations (DW_AT_members) for static members, place the
3736   // definition of those static members in the namespace they were declared in
3737   // in the source code (the lexical decl context).
3738   // FIXME: Generalize this for even non-member global variables where the
3739   // declaration and definition may have different lexical decl contexts, once
3740   // we have support for emitting declarations of (non-member) global variables.
3741   const DeclContext *DC = VD->isStaticDataMember() ? VD->getLexicalDeclContext()
3742                                                    : VD->getDeclContext();
3743   // When a record type contains an in-line initialization of a static data
3744   // member, and the record type is marked as __declspec(dllexport), an implicit
3745   // definition of the member will be created in the record context.  DWARF
3746   // doesn't seem to have a nice way to describe this in a form that consumers
3747   // are likely to understand, so fake the "normal" situation of a definition
3748   // outside the class by putting it in the global scope.
3749   if (DC->isRecord())
3750     DC = CGM.getContext().getTranslationUnitDecl();
3751 
3752   llvm::DIScope *Mod = getParentModuleOrNull(VD);
3753   VDContext = getContextDescriptor(cast<Decl>(DC), Mod ? Mod : TheCU);
3754 }
3755 
3756 llvm::DISubprogram *CGDebugInfo::getFunctionFwdDeclOrStub(GlobalDecl GD,
3757                                                           bool Stub) {
3758   llvm::DINodeArray TParamsArray;
3759   StringRef Name, LinkageName;
3760   llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3761   llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
3762   SourceLocation Loc = GD.getDecl()->getLocation();
3763   llvm::DIFile *Unit = getOrCreateFile(Loc);
3764   llvm::DIScope *DContext = Unit;
3765   unsigned Line = getLineNumber(Loc);
3766   collectFunctionDeclProps(GD, Unit, Name, LinkageName, DContext, TParamsArray,
3767                            Flags);
3768   auto *FD = cast<FunctionDecl>(GD.getDecl());
3769 
3770   // Build function type.
3771   SmallVector<QualType, 16> ArgTypes;
3772   for (const ParmVarDecl *Parm : FD->parameters())
3773     ArgTypes.push_back(Parm->getType());
3774 
3775   CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
3776   QualType FnType = CGM.getContext().getFunctionType(
3777       FD->getReturnType(), ArgTypes, FunctionProtoType::ExtProtoInfo(CC));
3778   if (!FD->isExternallyVisible())
3779     SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;
3780   if (CGM.getLangOpts().Optimize)
3781     SPFlags |= llvm::DISubprogram::SPFlagOptimized;
3782 
3783   if (Stub) {
3784     Flags |= getCallSiteRelatedAttrs();
3785     SPFlags |= llvm::DISubprogram::SPFlagDefinition;
3786     return DBuilder.createFunction(
3787         DContext, Name, LinkageName, Unit, Line,
3788         getOrCreateFunctionType(GD.getDecl(), FnType, Unit), 0, Flags, SPFlags,
3789         TParamsArray.get(), getFunctionDeclaration(FD));
3790   }
3791 
3792   llvm::DISubprogram *SP = DBuilder.createTempFunctionFwdDecl(
3793       DContext, Name, LinkageName, Unit, Line,
3794       getOrCreateFunctionType(GD.getDecl(), FnType, Unit), 0, Flags, SPFlags,
3795       TParamsArray.get(), getFunctionDeclaration(FD));
3796   const FunctionDecl *CanonDecl = FD->getCanonicalDecl();
3797   FwdDeclReplaceMap.emplace_back(std::piecewise_construct,
3798                                  std::make_tuple(CanonDecl),
3799                                  std::make_tuple(SP));
3800   return SP;
3801 }
3802 
3803 llvm::DISubprogram *CGDebugInfo::getFunctionForwardDeclaration(GlobalDecl GD) {
3804   return getFunctionFwdDeclOrStub(GD, /* Stub = */ false);
3805 }
3806 
3807 llvm::DISubprogram *CGDebugInfo::getFunctionStub(GlobalDecl GD) {
3808   return getFunctionFwdDeclOrStub(GD, /* Stub = */ true);
3809 }
3810 
3811 llvm::DIGlobalVariable *
3812 CGDebugInfo::getGlobalVariableForwardDeclaration(const VarDecl *VD) {
3813   QualType T;
3814   StringRef Name, LinkageName;
3815   SourceLocation Loc = VD->getLocation();
3816   llvm::DIFile *Unit = getOrCreateFile(Loc);
3817   llvm::DIScope *DContext = Unit;
3818   unsigned Line = getLineNumber(Loc);
3819   llvm::MDTuple *TemplateParameters = nullptr;
3820 
3821   collectVarDeclProps(VD, Unit, Line, T, Name, LinkageName, TemplateParameters,
3822                       DContext);
3823   auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
3824   auto *GV = DBuilder.createTempGlobalVariableFwdDecl(
3825       DContext, Name, LinkageName, Unit, Line, getOrCreateType(T, Unit),
3826       !VD->isExternallyVisible(), nullptr, TemplateParameters, Align);
3827   FwdDeclReplaceMap.emplace_back(
3828       std::piecewise_construct,
3829       std::make_tuple(cast<VarDecl>(VD->getCanonicalDecl())),
3830       std::make_tuple(static_cast<llvm::Metadata *>(GV)));
3831   return GV;
3832 }
3833 
3834 llvm::DINode *CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
3835   // We only need a declaration (not a definition) of the type - so use whatever
3836   // we would otherwise do to get a type for a pointee. (forward declarations in
3837   // limited debug info, full definitions (if the type definition is available)
3838   // in unlimited debug info)
3839   if (const auto *TD = dyn_cast<TypeDecl>(D))
3840     return getOrCreateType(CGM.getContext().getTypeDeclType(TD),
3841                            getOrCreateFile(TD->getLocation()));
3842   auto I = DeclCache.find(D->getCanonicalDecl());
3843 
3844   if (I != DeclCache.end()) {
3845     auto N = I->second;
3846     if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(N))
3847       return GVE->getVariable();
3848     return cast<llvm::DINode>(N);
3849   }
3850 
3851   // Search imported declaration cache if it is already defined
3852   // as imported declaration.
3853   auto IE = ImportedDeclCache.find(D->getCanonicalDecl());
3854 
3855   if (IE != ImportedDeclCache.end()) {
3856     auto N = IE->second;
3857     if (auto *GVE = dyn_cast_or_null<llvm::DIImportedEntity>(N))
3858       return cast<llvm::DINode>(GVE);
3859     return dyn_cast_or_null<llvm::DINode>(N);
3860   }
3861 
3862   // No definition for now. Emit a forward definition that might be
3863   // merged with a potential upcoming definition.
3864   if (const auto *FD = dyn_cast<FunctionDecl>(D))
3865     return getFunctionForwardDeclaration(FD);
3866   else if (const auto *VD = dyn_cast<VarDecl>(D))
3867     return getGlobalVariableForwardDeclaration(VD);
3868 
3869   return nullptr;
3870 }
3871 
3872 llvm::DISubprogram *CGDebugInfo::getFunctionDeclaration(const Decl *D) {
3873   if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly)
3874     return nullptr;
3875 
3876   const auto *FD = dyn_cast<FunctionDecl>(D);
3877   if (!FD)
3878     return nullptr;
3879 
3880   // Setup context.
3881   auto *S = getDeclContextDescriptor(D);
3882 
3883   auto MI = SPCache.find(FD->getCanonicalDecl());
3884   if (MI == SPCache.end()) {
3885     if (const auto *MD = dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
3886       return CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()),
3887                                      cast<llvm::DICompositeType>(S));
3888     }
3889   }
3890   if (MI != SPCache.end()) {
3891     auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
3892     if (SP && !SP->isDefinition())
3893       return SP;
3894   }
3895 
3896   for (auto NextFD : FD->redecls()) {
3897     auto MI = SPCache.find(NextFD->getCanonicalDecl());
3898     if (MI != SPCache.end()) {
3899       auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
3900       if (SP && !SP->isDefinition())
3901         return SP;
3902     }
3903   }
3904   return nullptr;
3905 }
3906 
3907 llvm::DISubprogram *CGDebugInfo::getObjCMethodDeclaration(
3908     const Decl *D, llvm::DISubroutineType *FnType, unsigned LineNo,
3909     llvm::DINode::DIFlags Flags, llvm::DISubprogram::DISPFlags SPFlags) {
3910   if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly)
3911     return nullptr;
3912 
3913   const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
3914   if (!OMD)
3915     return nullptr;
3916 
3917   if (CGM.getCodeGenOpts().DwarfVersion < 5 && !OMD->isDirectMethod())
3918     return nullptr;
3919 
3920   if (OMD->isDirectMethod())
3921     SPFlags |= llvm::DISubprogram::SPFlagObjCDirect;
3922 
3923   // Starting with DWARF V5 method declarations are emitted as children of
3924   // the interface type.
3925   auto *ID = dyn_cast_or_null<ObjCInterfaceDecl>(D->getDeclContext());
3926   if (!ID)
3927     ID = OMD->getClassInterface();
3928   if (!ID)
3929     return nullptr;
3930   QualType QTy(ID->getTypeForDecl(), 0);
3931   auto It = TypeCache.find(QTy.getAsOpaquePtr());
3932   if (It == TypeCache.end())
3933     return nullptr;
3934   auto *InterfaceType = cast<llvm::DICompositeType>(It->second);
3935   llvm::DISubprogram *FD = DBuilder.createFunction(
3936       InterfaceType, getObjCMethodName(OMD), StringRef(),
3937       InterfaceType->getFile(), LineNo, FnType, LineNo, Flags, SPFlags);
3938   DBuilder.finalizeSubprogram(FD);
3939   ObjCMethodCache[ID].push_back({FD, OMD->isDirectMethod()});
3940   return FD;
3941 }
3942 
3943 // getOrCreateFunctionType - Construct type. If it is a c++ method, include
3944 // implicit parameter "this".
3945 llvm::DISubroutineType *CGDebugInfo::getOrCreateFunctionType(const Decl *D,
3946                                                              QualType FnType,
3947                                                              llvm::DIFile *F) {
3948   // In CodeView, we emit the function types in line tables only because the
3949   // only way to distinguish between functions is by display name and type.
3950   if (!D || (DebugKind <= codegenoptions::DebugLineTablesOnly &&
3951              !CGM.getCodeGenOpts().EmitCodeView))
3952     // Create fake but valid subroutine type. Otherwise -verify would fail, and
3953     // subprogram DIE will miss DW_AT_decl_file and DW_AT_decl_line fields.
3954     return DBuilder.createSubroutineType(DBuilder.getOrCreateTypeArray(None));
3955 
3956   if (const auto *Method = dyn_cast<CXXMethodDecl>(D))
3957     return getOrCreateMethodType(Method, F, false);
3958 
3959   const auto *FTy = FnType->getAs<FunctionType>();
3960   CallingConv CC = FTy ? FTy->getCallConv() : CallingConv::CC_C;
3961 
3962   if (const auto *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
3963     // Add "self" and "_cmd"
3964     SmallVector<llvm::Metadata *, 16> Elts;
3965 
3966     // First element is always return type. For 'void' functions it is NULL.
3967     QualType ResultTy = OMethod->getReturnType();
3968 
3969     // Replace the instancetype keyword with the actual type.
3970     if (ResultTy == CGM.getContext().getObjCInstanceType())
3971       ResultTy = CGM.getContext().getPointerType(
3972           QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
3973 
3974     Elts.push_back(getOrCreateType(ResultTy, F));
3975     // "self" pointer is always first argument.
3976     QualType SelfDeclTy;
3977     if (auto *SelfDecl = OMethod->getSelfDecl())
3978       SelfDeclTy = SelfDecl->getType();
3979     else if (auto *FPT = dyn_cast<FunctionProtoType>(FnType))
3980       if (FPT->getNumParams() > 1)
3981         SelfDeclTy = FPT->getParamType(0);
3982     if (!SelfDeclTy.isNull())
3983       Elts.push_back(
3984           CreateSelfType(SelfDeclTy, getOrCreateType(SelfDeclTy, F)));
3985     // "_cmd" pointer is always second argument.
3986     Elts.push_back(DBuilder.createArtificialType(
3987         getOrCreateType(CGM.getContext().getObjCSelType(), F)));
3988     // Get rest of the arguments.
3989     for (const auto *PI : OMethod->parameters())
3990       Elts.push_back(getOrCreateType(PI->getType(), F));
3991     // Variadic methods need a special marker at the end of the type list.
3992     if (OMethod->isVariadic())
3993       Elts.push_back(DBuilder.createUnspecifiedParameter());
3994 
3995     llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
3996     return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
3997                                          getDwarfCC(CC));
3998   }
3999 
4000   // Handle variadic function types; they need an additional
4001   // unspecified parameter.
4002   if (const auto *FD = dyn_cast<FunctionDecl>(D))
4003     if (FD->isVariadic()) {
4004       SmallVector<llvm::Metadata *, 16> EltTys;
4005       EltTys.push_back(getOrCreateType(FD->getReturnType(), F));
4006       if (const auto *FPT = dyn_cast<FunctionProtoType>(FnType))
4007         for (QualType ParamType : FPT->param_types())
4008           EltTys.push_back(getOrCreateType(ParamType, F));
4009       EltTys.push_back(DBuilder.createUnspecifiedParameter());
4010       llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
4011       return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
4012                                            getDwarfCC(CC));
4013     }
4014 
4015   return cast<llvm::DISubroutineType>(getOrCreateType(FnType, F));
4016 }
4017 
4018 QualType
4019 CGDebugInfo::getFunctionType(const FunctionDecl *FD, QualType RetTy,
4020                              const SmallVectorImpl<const VarDecl *> &Args) {
4021   CallingConv CC = CallingConv::CC_C;
4022   if (FD)
4023     if (const auto *SrcFnTy = FD->getType()->getAs<FunctionType>())
4024       CC = SrcFnTy->getCallConv();
4025   SmallVector<QualType, 16> ArgTypes;
4026   for (const VarDecl *VD : Args)
4027     ArgTypes.push_back(VD->getType());
4028   return CGM.getContext().getFunctionType(RetTy, ArgTypes,
4029                                           FunctionProtoType::ExtProtoInfo(CC));
4030 }
4031 
4032 void CGDebugInfo::emitFunctionStart(GlobalDecl GD, SourceLocation Loc,
4033                                     SourceLocation ScopeLoc, QualType FnType,
4034                                     llvm::Function *Fn, bool CurFuncIsThunk) {
4035   StringRef Name;
4036   StringRef LinkageName;
4037 
4038   FnBeginRegionCount.push_back(LexicalBlockStack.size());
4039 
4040   const Decl *D = GD.getDecl();
4041   bool HasDecl = (D != nullptr);
4042 
4043   llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
4044   llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
4045   llvm::DIFile *Unit = getOrCreateFile(Loc);
4046   llvm::DIScope *FDContext = Unit;
4047   llvm::DINodeArray TParamsArray;
4048   if (!HasDecl) {
4049     // Use llvm function name.
4050     LinkageName = Fn->getName();
4051   } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
4052     // If there is a subprogram for this function available then use it.
4053     auto FI = SPCache.find(FD->getCanonicalDecl());
4054     if (FI != SPCache.end()) {
4055       auto *SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
4056       if (SP && SP->isDefinition()) {
4057         LexicalBlockStack.emplace_back(SP);
4058         RegionMap[D].reset(SP);
4059         return;
4060       }
4061     }
4062     collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
4063                              TParamsArray, Flags);
4064   } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) {
4065     Name = getObjCMethodName(OMD);
4066     Flags |= llvm::DINode::FlagPrototyped;
4067   } else if (isa<VarDecl>(D) &&
4068              GD.getDynamicInitKind() != DynamicInitKind::NoStub) {
4069     // This is a global initializer or atexit destructor for a global variable.
4070     Name = getDynamicInitializerName(cast<VarDecl>(D), GD.getDynamicInitKind(),
4071                                      Fn);
4072   } else {
4073     Name = Fn->getName();
4074 
4075     if (isa<BlockDecl>(D))
4076       LinkageName = Name;
4077 
4078     Flags |= llvm::DINode::FlagPrototyped;
4079   }
4080   if (Name.startswith("\01"))
4081     Name = Name.substr(1);
4082 
4083   if (!HasDecl || D->isImplicit() || D->hasAttr<ArtificialAttr>() ||
4084       (isa<VarDecl>(D) && GD.getDynamicInitKind() != DynamicInitKind::NoStub)) {
4085     Flags |= llvm::DINode::FlagArtificial;
4086     // Artificial functions should not silently reuse CurLoc.
4087     CurLoc = SourceLocation();
4088   }
4089 
4090   if (CurFuncIsThunk)
4091     Flags |= llvm::DINode::FlagThunk;
4092 
4093   if (Fn->hasLocalLinkage())
4094     SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;
4095   if (CGM.getLangOpts().Optimize)
4096     SPFlags |= llvm::DISubprogram::SPFlagOptimized;
4097 
4098   llvm::DINode::DIFlags FlagsForDef = Flags | getCallSiteRelatedAttrs();
4099   llvm::DISubprogram::DISPFlags SPFlagsForDef =
4100       SPFlags | llvm::DISubprogram::SPFlagDefinition;
4101 
4102   const unsigned LineNo = getLineNumber(Loc.isValid() ? Loc : CurLoc);
4103   unsigned ScopeLine = getLineNumber(ScopeLoc);
4104   llvm::DISubroutineType *DIFnType = getOrCreateFunctionType(D, FnType, Unit);
4105   llvm::DISubprogram *Decl = nullptr;
4106   llvm::DINodeArray Annotations = nullptr;
4107   if (D) {
4108     Decl = isa<ObjCMethodDecl>(D)
4109                ? getObjCMethodDeclaration(D, DIFnType, LineNo, Flags, SPFlags)
4110                : getFunctionDeclaration(D);
4111     Annotations = CollectBTFDeclTagAnnotations(D);
4112   }
4113 
4114   // FIXME: The function declaration we're constructing here is mostly reusing
4115   // declarations from CXXMethodDecl and not constructing new ones for arbitrary
4116   // FunctionDecls. When/if we fix this we can have FDContext be TheCU/null for
4117   // all subprograms instead of the actual context since subprogram definitions
4118   // are emitted as CU level entities by the backend.
4119   llvm::DISubprogram *SP = DBuilder.createFunction(
4120       FDContext, Name, LinkageName, Unit, LineNo, DIFnType, ScopeLine,
4121       FlagsForDef, SPFlagsForDef, TParamsArray.get(), Decl, nullptr,
4122       Annotations);
4123   Fn->setSubprogram(SP);
4124   // We might get here with a VarDecl in the case we're generating
4125   // code for the initialization of globals. Do not record these decls
4126   // as they will overwrite the actual VarDecl Decl in the cache.
4127   if (HasDecl && isa<FunctionDecl>(D))
4128     DeclCache[D->getCanonicalDecl()].reset(SP);
4129 
4130   // Push the function onto the lexical block stack.
4131   LexicalBlockStack.emplace_back(SP);
4132 
4133   if (HasDecl)
4134     RegionMap[D].reset(SP);
4135 }
4136 
4137 void CGDebugInfo::EmitFunctionDecl(GlobalDecl GD, SourceLocation Loc,
4138                                    QualType FnType, llvm::Function *Fn) {
4139   StringRef Name;
4140   StringRef LinkageName;
4141 
4142   const Decl *D = GD.getDecl();
4143   if (!D)
4144     return;
4145 
4146   llvm::TimeTraceScope TimeScope("DebugFunction", [&]() {
4147     return GetName(D, true);
4148   });
4149 
4150   llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
4151   llvm::DIFile *Unit = getOrCreateFile(Loc);
4152   bool IsDeclForCallSite = Fn ? true : false;
4153   llvm::DIScope *FDContext =
4154       IsDeclForCallSite ? Unit : getDeclContextDescriptor(D);
4155   llvm::DINodeArray TParamsArray;
4156   if (isa<FunctionDecl>(D)) {
4157     // If there is a DISubprogram for this function available then use it.
4158     collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
4159                              TParamsArray, Flags);
4160   } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) {
4161     Name = getObjCMethodName(OMD);
4162     Flags |= llvm::DINode::FlagPrototyped;
4163   } else {
4164     llvm_unreachable("not a function or ObjC method");
4165   }
4166   if (!Name.empty() && Name[0] == '\01')
4167     Name = Name.substr(1);
4168 
4169   if (D->isImplicit()) {
4170     Flags |= llvm::DINode::FlagArtificial;
4171     // Artificial functions without a location should not silently reuse CurLoc.
4172     if (Loc.isInvalid())
4173       CurLoc = SourceLocation();
4174   }
4175   unsigned LineNo = getLineNumber(Loc);
4176   unsigned ScopeLine = 0;
4177   llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
4178   if (CGM.getLangOpts().Optimize)
4179     SPFlags |= llvm::DISubprogram::SPFlagOptimized;
4180 
4181   llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(D);
4182   llvm::DISubprogram *SP = DBuilder.createFunction(
4183       FDContext, Name, LinkageName, Unit, LineNo,
4184       getOrCreateFunctionType(D, FnType, Unit), ScopeLine, Flags, SPFlags,
4185       TParamsArray.get(), getFunctionDeclaration(D), nullptr, Annotations);
4186 
4187   if (IsDeclForCallSite)
4188     Fn->setSubprogram(SP);
4189 
4190   DBuilder.finalizeSubprogram(SP);
4191 }
4192 
4193 void CGDebugInfo::EmitFuncDeclForCallSite(llvm::CallBase *CallOrInvoke,
4194                                           QualType CalleeType,
4195                                           const FunctionDecl *CalleeDecl) {
4196   if (!CallOrInvoke)
4197     return;
4198   auto *Func = CallOrInvoke->getCalledFunction();
4199   if (!Func)
4200     return;
4201   if (Func->getSubprogram())
4202     return;
4203 
4204   // Do not emit a declaration subprogram for a builtin, a function with nodebug
4205   // attribute, or if call site info isn't required. Also, elide declarations
4206   // for functions with reserved names, as call site-related features aren't
4207   // interesting in this case (& also, the compiler may emit calls to these
4208   // functions without debug locations, which makes the verifier complain).
4209   if (CalleeDecl->getBuiltinID() != 0 || CalleeDecl->hasAttr<NoDebugAttr>() ||
4210       getCallSiteRelatedAttrs() == llvm::DINode::FlagZero)
4211     return;
4212   if (CalleeDecl->isReserved(CGM.getLangOpts()) !=
4213       ReservedIdentifierStatus::NotReserved)
4214     return;
4215 
4216   // If there is no DISubprogram attached to the function being called,
4217   // create the one describing the function in order to have complete
4218   // call site debug info.
4219   if (!CalleeDecl->isStatic() && !CalleeDecl->isInlined())
4220     EmitFunctionDecl(CalleeDecl, CalleeDecl->getLocation(), CalleeType, Func);
4221 }
4222 
4223 void CGDebugInfo::EmitInlineFunctionStart(CGBuilderTy &Builder, GlobalDecl GD) {
4224   const auto *FD = cast<FunctionDecl>(GD.getDecl());
4225   // If there is a subprogram for this function available then use it.
4226   auto FI = SPCache.find(FD->getCanonicalDecl());
4227   llvm::DISubprogram *SP = nullptr;
4228   if (FI != SPCache.end())
4229     SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
4230   if (!SP || !SP->isDefinition())
4231     SP = getFunctionStub(GD);
4232   FnBeginRegionCount.push_back(LexicalBlockStack.size());
4233   LexicalBlockStack.emplace_back(SP);
4234   setInlinedAt(Builder.getCurrentDebugLocation());
4235   EmitLocation(Builder, FD->getLocation());
4236 }
4237 
4238 void CGDebugInfo::EmitInlineFunctionEnd(CGBuilderTy &Builder) {
4239   assert(CurInlinedAt && "unbalanced inline scope stack");
4240   EmitFunctionEnd(Builder, nullptr);
4241   setInlinedAt(llvm::DebugLoc(CurInlinedAt).getInlinedAt());
4242 }
4243 
4244 void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc) {
4245   // Update our current location
4246   setLocation(Loc);
4247 
4248   if (CurLoc.isInvalid() || CurLoc.isMacroID() || LexicalBlockStack.empty())
4249     return;
4250 
4251   llvm::MDNode *Scope = LexicalBlockStack.back();
4252   Builder.SetCurrentDebugLocation(
4253       llvm::DILocation::get(CGM.getLLVMContext(), getLineNumber(CurLoc),
4254                             getColumnNumber(CurLoc), Scope, CurInlinedAt));
4255 }
4256 
4257 void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
4258   llvm::MDNode *Back = nullptr;
4259   if (!LexicalBlockStack.empty())
4260     Back = LexicalBlockStack.back().get();
4261   LexicalBlockStack.emplace_back(DBuilder.createLexicalBlock(
4262       cast<llvm::DIScope>(Back), getOrCreateFile(CurLoc), getLineNumber(CurLoc),
4263       getColumnNumber(CurLoc)));
4264 }
4265 
4266 void CGDebugInfo::AppendAddressSpaceXDeref(
4267     unsigned AddressSpace, SmallVectorImpl<uint64_t> &Expr) const {
4268   Optional<unsigned> DWARFAddressSpace =
4269       CGM.getTarget().getDWARFAddressSpace(AddressSpace);
4270   if (!DWARFAddressSpace)
4271     return;
4272 
4273   Expr.push_back(llvm::dwarf::DW_OP_constu);
4274   Expr.push_back(DWARFAddressSpace.getValue());
4275   Expr.push_back(llvm::dwarf::DW_OP_swap);
4276   Expr.push_back(llvm::dwarf::DW_OP_xderef);
4277 }
4278 
4279 void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
4280                                         SourceLocation Loc) {
4281   // Set our current location.
4282   setLocation(Loc);
4283 
4284   // Emit a line table change for the current location inside the new scope.
4285   Builder.SetCurrentDebugLocation(llvm::DILocation::get(
4286       CGM.getLLVMContext(), getLineNumber(Loc), getColumnNumber(Loc),
4287       LexicalBlockStack.back(), CurInlinedAt));
4288 
4289   if (DebugKind <= codegenoptions::DebugLineTablesOnly)
4290     return;
4291 
4292   // Create a new lexical block and push it on the stack.
4293   CreateLexicalBlock(Loc);
4294 }
4295 
4296 void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
4297                                       SourceLocation Loc) {
4298   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4299 
4300   // Provide an entry in the line table for the end of the block.
4301   EmitLocation(Builder, Loc);
4302 
4303   if (DebugKind <= codegenoptions::DebugLineTablesOnly)
4304     return;
4305 
4306   LexicalBlockStack.pop_back();
4307 }
4308 
4309 void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder, llvm::Function *Fn) {
4310   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4311   unsigned RCount = FnBeginRegionCount.back();
4312   assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
4313 
4314   // Pop all regions for this function.
4315   while (LexicalBlockStack.size() != RCount) {
4316     // Provide an entry in the line table for the end of the block.
4317     EmitLocation(Builder, CurLoc);
4318     LexicalBlockStack.pop_back();
4319   }
4320   FnBeginRegionCount.pop_back();
4321 
4322   if (Fn && Fn->getSubprogram())
4323     DBuilder.finalizeSubprogram(Fn->getSubprogram());
4324 }
4325 
4326 CGDebugInfo::BlockByRefType
4327 CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
4328                                           uint64_t *XOffset) {
4329   SmallVector<llvm::Metadata *, 5> EltTys;
4330   QualType FType;
4331   uint64_t FieldSize, FieldOffset;
4332   uint32_t FieldAlign;
4333 
4334   llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
4335   QualType Type = VD->getType();
4336 
4337   FieldOffset = 0;
4338   FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
4339   EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
4340   EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
4341   FType = CGM.getContext().IntTy;
4342   EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
4343   EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
4344 
4345   bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
4346   if (HasCopyAndDispose) {
4347     FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
4348     EltTys.push_back(
4349         CreateMemberType(Unit, FType, "__copy_helper", &FieldOffset));
4350     EltTys.push_back(
4351         CreateMemberType(Unit, FType, "__destroy_helper", &FieldOffset));
4352   }
4353   bool HasByrefExtendedLayout;
4354   Qualifiers::ObjCLifetime Lifetime;
4355   if (CGM.getContext().getByrefLifetime(Type, Lifetime,
4356                                         HasByrefExtendedLayout) &&
4357       HasByrefExtendedLayout) {
4358     FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
4359     EltTys.push_back(
4360         CreateMemberType(Unit, FType, "__byref_variable_layout", &FieldOffset));
4361   }
4362 
4363   CharUnits Align = CGM.getContext().getDeclAlign(VD);
4364   if (Align > CGM.getContext().toCharUnitsFromBits(
4365                   CGM.getTarget().getPointerAlign(0))) {
4366     CharUnits FieldOffsetInBytes =
4367         CGM.getContext().toCharUnitsFromBits(FieldOffset);
4368     CharUnits AlignedOffsetInBytes = FieldOffsetInBytes.alignTo(Align);
4369     CharUnits NumPaddingBytes = AlignedOffsetInBytes - FieldOffsetInBytes;
4370 
4371     if (NumPaddingBytes.isPositive()) {
4372       llvm::APInt pad(32, NumPaddingBytes.getQuantity());
4373       FType = CGM.getContext().getConstantArrayType(
4374           CGM.getContext().CharTy, pad, nullptr, ArrayType::Normal, 0);
4375       EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
4376     }
4377   }
4378 
4379   FType = Type;
4380   llvm::DIType *WrappedTy = getOrCreateType(FType, Unit);
4381   FieldSize = CGM.getContext().getTypeSize(FType);
4382   FieldAlign = CGM.getContext().toBits(Align);
4383 
4384   *XOffset = FieldOffset;
4385   llvm::DIType *FieldTy = DBuilder.createMemberType(
4386       Unit, VD->getName(), Unit, 0, FieldSize, FieldAlign, FieldOffset,
4387       llvm::DINode::FlagZero, WrappedTy);
4388   EltTys.push_back(FieldTy);
4389   FieldOffset += FieldSize;
4390 
4391   llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
4392   return {DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0,
4393                                     llvm::DINode::FlagZero, nullptr, Elements),
4394           WrappedTy};
4395 }
4396 
4397 llvm::DILocalVariable *CGDebugInfo::EmitDeclare(const VarDecl *VD,
4398                                                 llvm::Value *Storage,
4399                                                 llvm::Optional<unsigned> ArgNo,
4400                                                 CGBuilderTy &Builder,
4401                                                 const bool UsePointerValue) {
4402   assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4403   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4404   if (VD->hasAttr<NoDebugAttr>())
4405     return nullptr;
4406 
4407   bool Unwritten =
4408       VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) &&
4409                            cast<Decl>(VD->getDeclContext())->isImplicit());
4410   llvm::DIFile *Unit = nullptr;
4411   if (!Unwritten)
4412     Unit = getOrCreateFile(VD->getLocation());
4413   llvm::DIType *Ty;
4414   uint64_t XOffset = 0;
4415   if (VD->hasAttr<BlocksAttr>())
4416     Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset).WrappedType;
4417   else
4418     Ty = getOrCreateType(VD->getType(), Unit);
4419 
4420   // If there is no debug info for this type then do not emit debug info
4421   // for this variable.
4422   if (!Ty)
4423     return nullptr;
4424 
4425   // Get location information.
4426   unsigned Line = 0;
4427   unsigned Column = 0;
4428   if (!Unwritten) {
4429     Line = getLineNumber(VD->getLocation());
4430     Column = getColumnNumber(VD->getLocation());
4431   }
4432   SmallVector<uint64_t, 13> Expr;
4433   llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
4434   if (VD->isImplicit())
4435     Flags |= llvm::DINode::FlagArtificial;
4436 
4437   auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
4438 
4439   unsigned AddressSpace = CGM.getContext().getTargetAddressSpace(VD->getType());
4440   AppendAddressSpaceXDeref(AddressSpace, Expr);
4441 
4442   // If this is implicit parameter of CXXThis or ObjCSelf kind, then give it an
4443   // object pointer flag.
4444   if (const auto *IPD = dyn_cast<ImplicitParamDecl>(VD)) {
4445     if (IPD->getParameterKind() == ImplicitParamDecl::CXXThis ||
4446         IPD->getParameterKind() == ImplicitParamDecl::ObjCSelf)
4447       Flags |= llvm::DINode::FlagObjectPointer;
4448   }
4449 
4450   // Note: Older versions of clang used to emit byval references with an extra
4451   // DW_OP_deref, because they referenced the IR arg directly instead of
4452   // referencing an alloca. Newer versions of LLVM don't treat allocas
4453   // differently from other function arguments when used in a dbg.declare.
4454   auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
4455   StringRef Name = VD->getName();
4456   if (!Name.empty()) {
4457     // __block vars are stored on the heap if they are captured by a block that
4458     // can escape the local scope.
4459     if (VD->isEscapingByref()) {
4460       // Here, we need an offset *into* the alloca.
4461       CharUnits offset = CharUnits::fromQuantity(32);
4462       Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4463       // offset of __forwarding field
4464       offset = CGM.getContext().toCharUnitsFromBits(
4465           CGM.getTarget().getPointerWidth(0));
4466       Expr.push_back(offset.getQuantity());
4467       Expr.push_back(llvm::dwarf::DW_OP_deref);
4468       Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4469       // offset of x field
4470       offset = CGM.getContext().toCharUnitsFromBits(XOffset);
4471       Expr.push_back(offset.getQuantity());
4472     }
4473   } else if (const auto *RT = dyn_cast<RecordType>(VD->getType())) {
4474     // If VD is an anonymous union then Storage represents value for
4475     // all union fields.
4476     const RecordDecl *RD = RT->getDecl();
4477     if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
4478       // GDB has trouble finding local variables in anonymous unions, so we emit
4479       // artificial local variables for each of the members.
4480       //
4481       // FIXME: Remove this code as soon as GDB supports this.
4482       // The debug info verifier in LLVM operates based on the assumption that a
4483       // variable has the same size as its storage and we had to disable the
4484       // check for artificial variables.
4485       for (const auto *Field : RD->fields()) {
4486         llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
4487         StringRef FieldName = Field->getName();
4488 
4489         // Ignore unnamed fields. Do not ignore unnamed records.
4490         if (FieldName.empty() && !isa<RecordType>(Field->getType()))
4491           continue;
4492 
4493         // Use VarDecl's Tag, Scope and Line number.
4494         auto FieldAlign = getDeclAlignIfRequired(Field, CGM.getContext());
4495         auto *D = DBuilder.createAutoVariable(
4496             Scope, FieldName, Unit, Line, FieldTy, CGM.getLangOpts().Optimize,
4497             Flags | llvm::DINode::FlagArtificial, FieldAlign);
4498 
4499         // Insert an llvm.dbg.declare into the current block.
4500         DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
4501                                llvm::DILocation::get(CGM.getLLVMContext(), Line,
4502                                                      Column, Scope,
4503                                                      CurInlinedAt),
4504                                Builder.GetInsertBlock());
4505       }
4506     }
4507   }
4508 
4509   // Clang stores the sret pointer provided by the caller in a static alloca.
4510   // Use DW_OP_deref to tell the debugger to load the pointer and treat it as
4511   // the address of the variable.
4512   if (UsePointerValue) {
4513     assert(!llvm::is_contained(Expr, llvm::dwarf::DW_OP_deref) &&
4514            "Debug info already contains DW_OP_deref.");
4515     Expr.push_back(llvm::dwarf::DW_OP_deref);
4516   }
4517 
4518   // Create the descriptor for the variable.
4519   llvm::DILocalVariable *D = nullptr;
4520   if (ArgNo) {
4521     llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(VD);
4522     D = DBuilder.createParameterVariable(Scope, Name, *ArgNo, Unit, Line, Ty,
4523                                          CGM.getLangOpts().Optimize, Flags,
4524                                          Annotations);
4525   } else {
4526     // For normal local variable, we will try to find out whether 'VD' is the
4527     // copy parameter of coroutine.
4528     // If yes, we are going to use DIVariable of the origin parameter instead
4529     // of creating the new one.
4530     // If no, it might be a normal alloc, we just create a new one for it.
4531 
4532     // Check whether the VD is move parameters.
4533     auto RemapCoroArgToLocalVar = [&]() -> llvm::DILocalVariable * {
4534       // The scope of parameter and move-parameter should be distinct
4535       // DISubprogram.
4536       if (!isa<llvm::DISubprogram>(Scope) || !Scope->isDistinct())
4537         return nullptr;
4538 
4539       auto Iter = llvm::find_if(CoroutineParameterMappings, [&](auto &Pair) {
4540         Stmt *StmtPtr = const_cast<Stmt *>(Pair.second);
4541         if (DeclStmt *DeclStmtPtr = dyn_cast<DeclStmt>(StmtPtr)) {
4542           DeclGroupRef DeclGroup = DeclStmtPtr->getDeclGroup();
4543           Decl *Decl = DeclGroup.getSingleDecl();
4544           if (VD == dyn_cast_or_null<VarDecl>(Decl))
4545             return true;
4546         }
4547         return false;
4548       });
4549 
4550       if (Iter != CoroutineParameterMappings.end()) {
4551         ParmVarDecl *PD = const_cast<ParmVarDecl *>(Iter->first);
4552         auto Iter2 = llvm::find_if(ParamDbgMappings, [&](auto &DbgPair) {
4553           return DbgPair.first == PD && DbgPair.second->getScope() == Scope;
4554         });
4555         if (Iter2 != ParamDbgMappings.end())
4556           return const_cast<llvm::DILocalVariable *>(Iter2->second);
4557       }
4558       return nullptr;
4559     };
4560 
4561     // If we couldn't find a move param DIVariable, create a new one.
4562     D = RemapCoroArgToLocalVar();
4563     // Or we will create a new DIVariable for this Decl if D dose not exists.
4564     if (!D)
4565       D = DBuilder.createAutoVariable(Scope, Name, Unit, Line, Ty,
4566                                       CGM.getLangOpts().Optimize, Flags, Align);
4567   }
4568   // Insert an llvm.dbg.declare into the current block.
4569   DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
4570                          llvm::DILocation::get(CGM.getLLVMContext(), Line,
4571                                                Column, Scope, CurInlinedAt),
4572                          Builder.GetInsertBlock());
4573 
4574   return D;
4575 }
4576 
4577 llvm::DILocalVariable *CGDebugInfo::EmitDeclare(const BindingDecl *BD,
4578                                                 llvm::Value *Storage,
4579                                                 llvm::Optional<unsigned> ArgNo,
4580                                                 CGBuilderTy &Builder,
4581                                                 const bool UsePointerValue) {
4582   assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4583   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4584   if (BD->hasAttr<NoDebugAttr>())
4585     return nullptr;
4586 
4587   // Skip the tuple like case, we don't handle that here
4588   if (isa<DeclRefExpr>(BD->getBinding()))
4589     return nullptr;
4590 
4591   llvm::DIFile *Unit = getOrCreateFile(BD->getLocation());
4592   llvm::DIType *Ty = getOrCreateType(BD->getType(), Unit);
4593 
4594   // If there is no debug info for this type then do not emit debug info
4595   // for this variable.
4596   if (!Ty)
4597     return nullptr;
4598 
4599   auto Align = getDeclAlignIfRequired(BD, CGM.getContext());
4600   unsigned AddressSpace = CGM.getContext().getTargetAddressSpace(BD->getType());
4601 
4602   SmallVector<uint64_t, 3> Expr;
4603   AppendAddressSpaceXDeref(AddressSpace, Expr);
4604 
4605   // Clang stores the sret pointer provided by the caller in a static alloca.
4606   // Use DW_OP_deref to tell the debugger to load the pointer and treat it as
4607   // the address of the variable.
4608   if (UsePointerValue) {
4609     assert(!llvm::is_contained(Expr, llvm::dwarf::DW_OP_deref) &&
4610            "Debug info already contains DW_OP_deref.");
4611     Expr.push_back(llvm::dwarf::DW_OP_deref);
4612   }
4613 
4614   unsigned Line = getLineNumber(BD->getLocation());
4615   unsigned Column = getColumnNumber(BD->getLocation());
4616   StringRef Name = BD->getName();
4617   auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
4618   // Create the descriptor for the variable.
4619   llvm::DILocalVariable *D = DBuilder.createAutoVariable(
4620       Scope, Name, Unit, Line, Ty, CGM.getLangOpts().Optimize,
4621       llvm::DINode::FlagZero, Align);
4622 
4623   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BD->getBinding())) {
4624     if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
4625       const unsigned fieldIndex = FD->getFieldIndex();
4626       const clang::CXXRecordDecl *parent =
4627           (const CXXRecordDecl *)FD->getParent();
4628       const ASTRecordLayout &layout =
4629           CGM.getContext().getASTRecordLayout(parent);
4630       const uint64_t fieldOffset = layout.getFieldOffset(fieldIndex);
4631 
4632       if (fieldOffset != 0) {
4633         Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4634         Expr.push_back(
4635             CGM.getContext().toCharUnitsFromBits(fieldOffset).getQuantity());
4636       }
4637     }
4638   } else if (const ArraySubscriptExpr *ASE =
4639                  dyn_cast<ArraySubscriptExpr>(BD->getBinding())) {
4640     if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(ASE->getIdx())) {
4641       const uint64_t value = IL->getValue().getZExtValue();
4642       const uint64_t typeSize = CGM.getContext().getTypeSize(BD->getType());
4643 
4644       if (value != 0) {
4645         Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4646         Expr.push_back(CGM.getContext()
4647                            .toCharUnitsFromBits(value * typeSize)
4648                            .getQuantity());
4649       }
4650     }
4651   }
4652 
4653   // Insert an llvm.dbg.declare into the current block.
4654   DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
4655                          llvm::DILocation::get(CGM.getLLVMContext(), Line,
4656                                                Column, Scope, CurInlinedAt),
4657                          Builder.GetInsertBlock());
4658 
4659   return D;
4660 }
4661 
4662 llvm::DILocalVariable *
4663 CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD, llvm::Value *Storage,
4664                                        CGBuilderTy &Builder,
4665                                        const bool UsePointerValue) {
4666   assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4667 
4668   if (auto *DD = dyn_cast<DecompositionDecl>(VD))
4669     for (auto *B : DD->bindings()) {
4670       EmitDeclare(B, Storage, llvm::None, Builder,
4671                   VD->getType()->isReferenceType());
4672     }
4673 
4674   return EmitDeclare(VD, Storage, llvm::None, Builder, UsePointerValue);
4675 }
4676 
4677 void CGDebugInfo::EmitLabel(const LabelDecl *D, CGBuilderTy &Builder) {
4678   assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4679   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4680 
4681   if (D->hasAttr<NoDebugAttr>())
4682     return;
4683 
4684   auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
4685   llvm::DIFile *Unit = getOrCreateFile(D->getLocation());
4686 
4687   // Get location information.
4688   unsigned Line = getLineNumber(D->getLocation());
4689   unsigned Column = getColumnNumber(D->getLocation());
4690 
4691   StringRef Name = D->getName();
4692 
4693   // Create the descriptor for the label.
4694   auto *L =
4695       DBuilder.createLabel(Scope, Name, Unit, Line, CGM.getLangOpts().Optimize);
4696 
4697   // Insert an llvm.dbg.label into the current block.
4698   DBuilder.insertLabel(L,
4699                        llvm::DILocation::get(CGM.getLLVMContext(), Line, Column,
4700                                              Scope, CurInlinedAt),
4701                        Builder.GetInsertBlock());
4702 }
4703 
4704 llvm::DIType *CGDebugInfo::CreateSelfType(const QualType &QualTy,
4705                                           llvm::DIType *Ty) {
4706   llvm::DIType *CachedTy = getTypeOrNull(QualTy);
4707   if (CachedTy)
4708     Ty = CachedTy;
4709   return DBuilder.createObjectPointerType(Ty);
4710 }
4711 
4712 void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(
4713     const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder,
4714     const CGBlockInfo &blockInfo, llvm::Instruction *InsertPoint) {
4715   assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4716   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4717 
4718   if (Builder.GetInsertBlock() == nullptr)
4719     return;
4720   if (VD->hasAttr<NoDebugAttr>())
4721     return;
4722 
4723   bool isByRef = VD->hasAttr<BlocksAttr>();
4724 
4725   uint64_t XOffset = 0;
4726   llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
4727   llvm::DIType *Ty;
4728   if (isByRef)
4729     Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset).WrappedType;
4730   else
4731     Ty = getOrCreateType(VD->getType(), Unit);
4732 
4733   // Self is passed along as an implicit non-arg variable in a
4734   // block. Mark it as the object pointer.
4735   if (const auto *IPD = dyn_cast<ImplicitParamDecl>(VD))
4736     if (IPD->getParameterKind() == ImplicitParamDecl::ObjCSelf)
4737       Ty = CreateSelfType(VD->getType(), Ty);
4738 
4739   // Get location information.
4740   const unsigned Line =
4741       getLineNumber(VD->getLocation().isValid() ? VD->getLocation() : CurLoc);
4742   unsigned Column = getColumnNumber(VD->getLocation());
4743 
4744   const llvm::DataLayout &target = CGM.getDataLayout();
4745 
4746   CharUnits offset = CharUnits::fromQuantity(
4747       target.getStructLayout(blockInfo.StructureType)
4748           ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
4749 
4750   SmallVector<uint64_t, 9> addr;
4751   addr.push_back(llvm::dwarf::DW_OP_deref);
4752   addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4753   addr.push_back(offset.getQuantity());
4754   if (isByRef) {
4755     addr.push_back(llvm::dwarf::DW_OP_deref);
4756     addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4757     // offset of __forwarding field
4758     offset =
4759         CGM.getContext().toCharUnitsFromBits(target.getPointerSizeInBits(0));
4760     addr.push_back(offset.getQuantity());
4761     addr.push_back(llvm::dwarf::DW_OP_deref);
4762     addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4763     // offset of x field
4764     offset = CGM.getContext().toCharUnitsFromBits(XOffset);
4765     addr.push_back(offset.getQuantity());
4766   }
4767 
4768   // Create the descriptor for the variable.
4769   auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
4770   auto *D = DBuilder.createAutoVariable(
4771       cast<llvm::DILocalScope>(LexicalBlockStack.back()), VD->getName(), Unit,
4772       Line, Ty, false, llvm::DINode::FlagZero, Align);
4773 
4774   // Insert an llvm.dbg.declare into the current block.
4775   auto DL = llvm::DILocation::get(CGM.getLLVMContext(), Line, Column,
4776                                   LexicalBlockStack.back(), CurInlinedAt);
4777   auto *Expr = DBuilder.createExpression(addr);
4778   if (InsertPoint)
4779     DBuilder.insertDeclare(Storage, D, Expr, DL, InsertPoint);
4780   else
4781     DBuilder.insertDeclare(Storage, D, Expr, DL, Builder.GetInsertBlock());
4782 }
4783 
4784 llvm::DILocalVariable *
4785 CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
4786                                       unsigned ArgNo, CGBuilderTy &Builder) {
4787   assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4788   return EmitDeclare(VD, AI, ArgNo, Builder);
4789 }
4790 
4791 namespace {
4792 struct BlockLayoutChunk {
4793   uint64_t OffsetInBits;
4794   const BlockDecl::Capture *Capture;
4795 };
4796 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
4797   return l.OffsetInBits < r.OffsetInBits;
4798 }
4799 } // namespace
4800 
4801 void CGDebugInfo::collectDefaultFieldsForBlockLiteralDeclare(
4802     const CGBlockInfo &Block, const ASTContext &Context, SourceLocation Loc,
4803     const llvm::StructLayout &BlockLayout, llvm::DIFile *Unit,
4804     SmallVectorImpl<llvm::Metadata *> &Fields) {
4805   // Blocks in OpenCL have unique constraints which make the standard fields
4806   // redundant while requiring size and align fields for enqueue_kernel. See
4807   // initializeForBlockHeader in CGBlocks.cpp
4808   if (CGM.getLangOpts().OpenCL) {
4809     Fields.push_back(createFieldType("__size", Context.IntTy, Loc, AS_public,
4810                                      BlockLayout.getElementOffsetInBits(0),
4811                                      Unit, Unit));
4812     Fields.push_back(createFieldType("__align", Context.IntTy, Loc, AS_public,
4813                                      BlockLayout.getElementOffsetInBits(1),
4814                                      Unit, Unit));
4815   } else {
4816     Fields.push_back(createFieldType("__isa", Context.VoidPtrTy, Loc, AS_public,
4817                                      BlockLayout.getElementOffsetInBits(0),
4818                                      Unit, Unit));
4819     Fields.push_back(createFieldType("__flags", Context.IntTy, Loc, AS_public,
4820                                      BlockLayout.getElementOffsetInBits(1),
4821                                      Unit, Unit));
4822     Fields.push_back(
4823         createFieldType("__reserved", Context.IntTy, Loc, AS_public,
4824                         BlockLayout.getElementOffsetInBits(2), Unit, Unit));
4825     auto *FnTy = Block.getBlockExpr()->getFunctionType();
4826     auto FnPtrType = CGM.getContext().getPointerType(FnTy->desugar());
4827     Fields.push_back(createFieldType("__FuncPtr", FnPtrType, Loc, AS_public,
4828                                      BlockLayout.getElementOffsetInBits(3),
4829                                      Unit, Unit));
4830     Fields.push_back(createFieldType(
4831         "__descriptor",
4832         Context.getPointerType(Block.NeedsCopyDispose
4833                                    ? Context.getBlockDescriptorExtendedType()
4834                                    : Context.getBlockDescriptorType()),
4835         Loc, AS_public, BlockLayout.getElementOffsetInBits(4), Unit, Unit));
4836   }
4837 }
4838 
4839 void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
4840                                                        StringRef Name,
4841                                                        unsigned ArgNo,
4842                                                        llvm::AllocaInst *Alloca,
4843                                                        CGBuilderTy &Builder) {
4844   assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4845   ASTContext &C = CGM.getContext();
4846   const BlockDecl *blockDecl = block.getBlockDecl();
4847 
4848   // Collect some general information about the block's location.
4849   SourceLocation loc = blockDecl->getCaretLocation();
4850   llvm::DIFile *tunit = getOrCreateFile(loc);
4851   unsigned line = getLineNumber(loc);
4852   unsigned column = getColumnNumber(loc);
4853 
4854   // Build the debug-info type for the block literal.
4855   getDeclContextDescriptor(blockDecl);
4856 
4857   const llvm::StructLayout *blockLayout =
4858       CGM.getDataLayout().getStructLayout(block.StructureType);
4859 
4860   SmallVector<llvm::Metadata *, 16> fields;
4861   collectDefaultFieldsForBlockLiteralDeclare(block, C, loc, *blockLayout, tunit,
4862                                              fields);
4863 
4864   // We want to sort the captures by offset, not because DWARF
4865   // requires this, but because we're paranoid about debuggers.
4866   SmallVector<BlockLayoutChunk, 8> chunks;
4867 
4868   // 'this' capture.
4869   if (blockDecl->capturesCXXThis()) {
4870     BlockLayoutChunk chunk;
4871     chunk.OffsetInBits =
4872         blockLayout->getElementOffsetInBits(block.CXXThisIndex);
4873     chunk.Capture = nullptr;
4874     chunks.push_back(chunk);
4875   }
4876 
4877   // Variable captures.
4878   for (const auto &capture : blockDecl->captures()) {
4879     const VarDecl *variable = capture.getVariable();
4880     const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
4881 
4882     // Ignore constant captures.
4883     if (captureInfo.isConstant())
4884       continue;
4885 
4886     BlockLayoutChunk chunk;
4887     chunk.OffsetInBits =
4888         blockLayout->getElementOffsetInBits(captureInfo.getIndex());
4889     chunk.Capture = &capture;
4890     chunks.push_back(chunk);
4891   }
4892 
4893   // Sort by offset.
4894   llvm::array_pod_sort(chunks.begin(), chunks.end());
4895 
4896   for (const BlockLayoutChunk &Chunk : chunks) {
4897     uint64_t offsetInBits = Chunk.OffsetInBits;
4898     const BlockDecl::Capture *capture = Chunk.Capture;
4899 
4900     // If we have a null capture, this must be the C++ 'this' capture.
4901     if (!capture) {
4902       QualType type;
4903       if (auto *Method =
4904               cast_or_null<CXXMethodDecl>(blockDecl->getNonClosureContext()))
4905         type = Method->getThisType();
4906       else if (auto *RDecl = dyn_cast<CXXRecordDecl>(blockDecl->getParent()))
4907         type = QualType(RDecl->getTypeForDecl(), 0);
4908       else
4909         llvm_unreachable("unexpected block declcontext");
4910 
4911       fields.push_back(createFieldType("this", type, loc, AS_public,
4912                                        offsetInBits, tunit, tunit));
4913       continue;
4914     }
4915 
4916     const VarDecl *variable = capture->getVariable();
4917     StringRef name = variable->getName();
4918 
4919     llvm::DIType *fieldType;
4920     if (capture->isByRef()) {
4921       TypeInfo PtrInfo = C.getTypeInfo(C.VoidPtrTy);
4922       auto Align = PtrInfo.isAlignRequired() ? PtrInfo.Align : 0;
4923       // FIXME: This recomputes the layout of the BlockByRefWrapper.
4924       uint64_t xoffset;
4925       fieldType =
4926           EmitTypeForVarWithBlocksAttr(variable, &xoffset).BlockByRefWrapper;
4927       fieldType = DBuilder.createPointerType(fieldType, PtrInfo.Width);
4928       fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
4929                                             PtrInfo.Width, Align, offsetInBits,
4930                                             llvm::DINode::FlagZero, fieldType);
4931     } else {
4932       auto Align = getDeclAlignIfRequired(variable, CGM.getContext());
4933       fieldType = createFieldType(name, variable->getType(), loc, AS_public,
4934                                   offsetInBits, Align, tunit, tunit);
4935     }
4936     fields.push_back(fieldType);
4937   }
4938 
4939   SmallString<36> typeName;
4940   llvm::raw_svector_ostream(typeName)
4941       << "__block_literal_" << CGM.getUniqueBlockCount();
4942 
4943   llvm::DINodeArray fieldsArray = DBuilder.getOrCreateArray(fields);
4944 
4945   llvm::DIType *type =
4946       DBuilder.createStructType(tunit, typeName.str(), tunit, line,
4947                                 CGM.getContext().toBits(block.BlockSize), 0,
4948                                 llvm::DINode::FlagZero, nullptr, fieldsArray);
4949   type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
4950 
4951   // Get overall information about the block.
4952   llvm::DINode::DIFlags flags = llvm::DINode::FlagArtificial;
4953   auto *scope = cast<llvm::DILocalScope>(LexicalBlockStack.back());
4954 
4955   // Create the descriptor for the parameter.
4956   auto *debugVar = DBuilder.createParameterVariable(
4957       scope, Name, ArgNo, tunit, line, type, CGM.getLangOpts().Optimize, flags);
4958 
4959   // Insert an llvm.dbg.declare into the current block.
4960   DBuilder.insertDeclare(Alloca, debugVar, DBuilder.createExpression(),
4961                          llvm::DILocation::get(CGM.getLLVMContext(), line,
4962                                                column, scope, CurInlinedAt),
4963                          Builder.GetInsertBlock());
4964 }
4965 
4966 llvm::DIDerivedType *
4967 CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {
4968   if (!D || !D->isStaticDataMember())
4969     return nullptr;
4970 
4971   auto MI = StaticDataMemberCache.find(D->getCanonicalDecl());
4972   if (MI != StaticDataMemberCache.end()) {
4973     assert(MI->second && "Static data member declaration should still exist");
4974     return MI->second;
4975   }
4976 
4977   // If the member wasn't found in the cache, lazily construct and add it to the
4978   // type (used when a limited form of the type is emitted).
4979   auto DC = D->getDeclContext();
4980   auto *Ctxt = cast<llvm::DICompositeType>(getDeclContextDescriptor(D));
4981   return CreateRecordStaticField(D, Ctxt, cast<RecordDecl>(DC));
4982 }
4983 
4984 llvm::DIGlobalVariableExpression *CGDebugInfo::CollectAnonRecordDecls(
4985     const RecordDecl *RD, llvm::DIFile *Unit, unsigned LineNo,
4986     StringRef LinkageName, llvm::GlobalVariable *Var, llvm::DIScope *DContext) {
4987   llvm::DIGlobalVariableExpression *GVE = nullptr;
4988 
4989   for (const auto *Field : RD->fields()) {
4990     llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
4991     StringRef FieldName = Field->getName();
4992 
4993     // Ignore unnamed fields, but recurse into anonymous records.
4994     if (FieldName.empty()) {
4995       if (const auto *RT = dyn_cast<RecordType>(Field->getType()))
4996         GVE = CollectAnonRecordDecls(RT->getDecl(), Unit, LineNo, LinkageName,
4997                                      Var, DContext);
4998       continue;
4999     }
5000     // Use VarDecl's Tag, Scope and Line number.
5001     GVE = DBuilder.createGlobalVariableExpression(
5002         DContext, FieldName, LinkageName, Unit, LineNo, FieldTy,
5003         Var->hasLocalLinkage());
5004     Var->addDebugInfo(GVE);
5005   }
5006   return GVE;
5007 }
5008 
5009 static bool ReferencesAnonymousEntity(ArrayRef<TemplateArgument> Args);
5010 static bool ReferencesAnonymousEntity(RecordType *RT) {
5011   // Unnamed classes/lambdas can't be reconstituted due to a lack of column
5012   // info we produce in the DWARF, so we can't get Clang's full name back.
5013   // But so long as it's not one of those, it doesn't matter if some sub-type
5014   // of the record (a template parameter) can't be reconstituted - because the
5015   // un-reconstitutable type itself will carry its own name.
5016   const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
5017   if (!RD)
5018     return false;
5019   if (!RD->getIdentifier())
5020     return true;
5021   auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD);
5022   if (!TSpecial)
5023     return false;
5024   return ReferencesAnonymousEntity(TSpecial->getTemplateArgs().asArray());
5025 }
5026 static bool ReferencesAnonymousEntity(ArrayRef<TemplateArgument> Args) {
5027   return llvm::any_of(Args, [&](const TemplateArgument &TA) {
5028     switch (TA.getKind()) {
5029     case TemplateArgument::Pack:
5030       return ReferencesAnonymousEntity(TA.getPackAsArray());
5031     case TemplateArgument::Type: {
5032       struct ReferencesAnonymous
5033           : public RecursiveASTVisitor<ReferencesAnonymous> {
5034         bool RefAnon = false;
5035         bool VisitRecordType(RecordType *RT) {
5036           if (ReferencesAnonymousEntity(RT)) {
5037             RefAnon = true;
5038             return false;
5039           }
5040           return true;
5041         }
5042       };
5043       ReferencesAnonymous RT;
5044       RT.TraverseType(TA.getAsType());
5045       if (RT.RefAnon)
5046         return true;
5047       break;
5048     }
5049     default:
5050       break;
5051     }
5052     return false;
5053   });
5054 }
5055 namespace {
5056 struct ReconstitutableType : public RecursiveASTVisitor<ReconstitutableType> {
5057   bool Reconstitutable = true;
5058   bool VisitVectorType(VectorType *FT) {
5059     Reconstitutable = false;
5060     return false;
5061   }
5062   bool VisitAtomicType(AtomicType *FT) {
5063     Reconstitutable = false;
5064     return false;
5065   }
5066   bool VisitType(Type *T) {
5067     // _BitInt(N) isn't reconstitutable because the bit width isn't encoded in
5068     // the DWARF, only the byte width.
5069     if (T->isBitIntType()) {
5070       Reconstitutable = false;
5071       return false;
5072     }
5073     return true;
5074   }
5075   bool TraverseEnumType(EnumType *ET) {
5076     // Unnamed enums can't be reconstituted due to a lack of column info we
5077     // produce in the DWARF, so we can't get Clang's full name back.
5078     if (const auto *ED = dyn_cast<EnumDecl>(ET->getDecl())) {
5079       if (!ED->getIdentifier()) {
5080         Reconstitutable = false;
5081         return false;
5082       }
5083       if (!ED->isExternallyVisible()) {
5084         Reconstitutable = false;
5085         return false;
5086       }
5087     }
5088     return true;
5089   }
5090   bool VisitFunctionProtoType(FunctionProtoType *FT) {
5091     // noexcept is not encoded in DWARF, so the reversi
5092     Reconstitutable &= !isNoexceptExceptionSpec(FT->getExceptionSpecType());
5093     Reconstitutable &= !FT->getNoReturnAttr();
5094     return Reconstitutable;
5095   }
5096   bool VisitRecordType(RecordType *RT) {
5097     if (ReferencesAnonymousEntity(RT)) {
5098       Reconstitutable = false;
5099       return false;
5100     }
5101     return true;
5102   }
5103 };
5104 } // anonymous namespace
5105 
5106 // Test whether a type name could be rebuilt from emitted debug info.
5107 static bool IsReconstitutableType(QualType QT) {
5108   ReconstitutableType T;
5109   T.TraverseType(QT);
5110   return T.Reconstitutable;
5111 }
5112 
5113 std::string CGDebugInfo::GetName(const Decl *D, bool Qualified) const {
5114   std::string Name;
5115   llvm::raw_string_ostream OS(Name);
5116   const NamedDecl *ND = dyn_cast<NamedDecl>(D);
5117   if (!ND)
5118     return Name;
5119   codegenoptions::DebugTemplateNamesKind TemplateNamesKind =
5120       CGM.getCodeGenOpts().getDebugSimpleTemplateNames();
5121 
5122   if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
5123     TemplateNamesKind = codegenoptions::DebugTemplateNamesKind::Full;
5124 
5125   Optional<TemplateArgs> Args;
5126 
5127   bool IsOperatorOverload = false; // isa<CXXConversionDecl>(ND);
5128   if (auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
5129     Args = GetTemplateArgs(RD);
5130   } else if (auto *FD = dyn_cast<FunctionDecl>(ND)) {
5131     Args = GetTemplateArgs(FD);
5132     auto NameKind = ND->getDeclName().getNameKind();
5133     IsOperatorOverload |=
5134         NameKind == DeclarationName::CXXOperatorName ||
5135         NameKind == DeclarationName::CXXConversionFunctionName;
5136   } else if (auto *VD = dyn_cast<VarDecl>(ND)) {
5137     Args = GetTemplateArgs(VD);
5138   }
5139   std::function<bool(ArrayRef<TemplateArgument>)> HasReconstitutableArgs =
5140       [&](ArrayRef<TemplateArgument> Args) {
5141         return llvm::all_of(Args, [&](const TemplateArgument &TA) {
5142           switch (TA.getKind()) {
5143           case TemplateArgument::Template:
5144             // Easy to reconstitute - the value of the parameter in the debug
5145             // info is the string name of the template. (so the template name
5146             // itself won't benefit from any name rebuilding, but that's a
5147             // representational limitation - maybe DWARF could be
5148             // changed/improved to use some more structural representation)
5149             return true;
5150           case TemplateArgument::Declaration:
5151             // Reference and pointer non-type template parameters point to
5152             // variables, functions, etc and their value is, at best (for
5153             // variables) represented as an address - not a reference to the
5154             // DWARF describing the variable/function/etc. This makes it hard,
5155             // possibly impossible to rebuild the original name - looking up the
5156             // address in the executable file's symbol table would be needed.
5157             return false;
5158           case TemplateArgument::NullPtr:
5159             // These could be rebuilt, but figured they're close enough to the
5160             // declaration case, and not worth rebuilding.
5161             return false;
5162           case TemplateArgument::Pack:
5163             // A pack is invalid if any of the elements of the pack are invalid.
5164             return HasReconstitutableArgs(TA.getPackAsArray());
5165           case TemplateArgument::Integral:
5166             // Larger integers get encoded as DWARF blocks which are a bit
5167             // harder to parse back into a large integer, etc - so punting on
5168             // this for now. Re-parsing the integers back into APInt is probably
5169             // feasible some day.
5170             return TA.getAsIntegral().getBitWidth() <= 64 &&
5171                    IsReconstitutableType(TA.getIntegralType());
5172           case TemplateArgument::Type:
5173             return IsReconstitutableType(TA.getAsType());
5174           default:
5175             llvm_unreachable("Other, unresolved, template arguments should "
5176                              "not be seen here");
5177           }
5178         });
5179       };
5180   // A conversion operator presents complications/ambiguity if there's a
5181   // conversion to class template that is itself a template, eg:
5182   // template<typename T>
5183   // operator ns::t1<T, int>();
5184   // This should be named, eg: "operator ns::t1<float, int><float>"
5185   // (ignoring clang bug that means this is currently "operator t1<float>")
5186   // but if the arguments were stripped, the consumer couldn't differentiate
5187   // whether the template argument list for the conversion type was the
5188   // function's argument list (& no reconstitution was needed) or not.
5189   // This could be handled if reconstitutable names had a separate attribute
5190   // annotating them as such - this would remove the ambiguity.
5191   //
5192   // Alternatively the template argument list could be parsed enough to check
5193   // whether there's one list or two, then compare that with the DWARF
5194   // description of the return type and the template argument lists to determine
5195   // how many lists there should be and if one is missing it could be assumed(?)
5196   // to be the function's template argument list  & then be rebuilt.
5197   //
5198   // Other operator overloads that aren't conversion operators could be
5199   // reconstituted but would require a bit more nuance about detecting the
5200   // difference between these different operators during that rebuilding.
5201   bool Reconstitutable =
5202       Args && HasReconstitutableArgs(Args->Args) && !IsOperatorOverload;
5203 
5204   PrintingPolicy PP = getPrintingPolicy();
5205 
5206   if (TemplateNamesKind == codegenoptions::DebugTemplateNamesKind::Full ||
5207       !Reconstitutable) {
5208     ND->getNameForDiagnostic(OS, PP, Qualified);
5209   } else {
5210     bool Mangled =
5211         TemplateNamesKind == codegenoptions::DebugTemplateNamesKind::Mangled;
5212     // check if it's a template
5213     if (Mangled)
5214       OS << "_STN|";
5215 
5216     OS << ND->getDeclName();
5217     std::string EncodedOriginalName;
5218     llvm::raw_string_ostream EncodedOriginalNameOS(EncodedOriginalName);
5219     EncodedOriginalNameOS << ND->getDeclName();
5220 
5221     if (Mangled) {
5222       OS << "|";
5223       printTemplateArgumentList(OS, Args->Args, PP);
5224       printTemplateArgumentList(EncodedOriginalNameOS, Args->Args, PP);
5225 #ifndef NDEBUG
5226       std::string CanonicalOriginalName;
5227       llvm::raw_string_ostream OriginalOS(CanonicalOriginalName);
5228       ND->getNameForDiagnostic(OriginalOS, PP, Qualified);
5229       assert(EncodedOriginalNameOS.str() == OriginalOS.str());
5230 #endif
5231     }
5232   }
5233   return Name;
5234 }
5235 
5236 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
5237                                      const VarDecl *D) {
5238   assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
5239   if (D->hasAttr<NoDebugAttr>())
5240     return;
5241 
5242   llvm::TimeTraceScope TimeScope("DebugGlobalVariable", [&]() {
5243     return GetName(D, true);
5244   });
5245 
5246   // If we already created a DIGlobalVariable for this declaration, just attach
5247   // it to the llvm::GlobalVariable.
5248   auto Cached = DeclCache.find(D->getCanonicalDecl());
5249   if (Cached != DeclCache.end())
5250     return Var->addDebugInfo(
5251         cast<llvm::DIGlobalVariableExpression>(Cached->second));
5252 
5253   // Create global variable debug descriptor.
5254   llvm::DIFile *Unit = nullptr;
5255   llvm::DIScope *DContext = nullptr;
5256   unsigned LineNo;
5257   StringRef DeclName, LinkageName;
5258   QualType T;
5259   llvm::MDTuple *TemplateParameters = nullptr;
5260   collectVarDeclProps(D, Unit, LineNo, T, DeclName, LinkageName,
5261                       TemplateParameters, DContext);
5262 
5263   // Attempt to store one global variable for the declaration - even if we
5264   // emit a lot of fields.
5265   llvm::DIGlobalVariableExpression *GVE = nullptr;
5266 
5267   // If this is an anonymous union then we'll want to emit a global
5268   // variable for each member of the anonymous union so that it's possible
5269   // to find the name of any field in the union.
5270   if (T->isUnionType() && DeclName.empty()) {
5271     const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
5272     assert(RD->isAnonymousStructOrUnion() &&
5273            "unnamed non-anonymous struct or union?");
5274     GVE = CollectAnonRecordDecls(RD, Unit, LineNo, LinkageName, Var, DContext);
5275   } else {
5276     auto Align = getDeclAlignIfRequired(D, CGM.getContext());
5277 
5278     SmallVector<uint64_t, 4> Expr;
5279     unsigned AddressSpace =
5280         CGM.getContext().getTargetAddressSpace(D->getType());
5281     if (CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) {
5282       if (D->hasAttr<CUDASharedAttr>())
5283         AddressSpace =
5284             CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared);
5285       else if (D->hasAttr<CUDAConstantAttr>())
5286         AddressSpace =
5287             CGM.getContext().getTargetAddressSpace(LangAS::cuda_constant);
5288     }
5289     AppendAddressSpaceXDeref(AddressSpace, Expr);
5290 
5291     llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(D);
5292     GVE = DBuilder.createGlobalVariableExpression(
5293         DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
5294         Var->hasLocalLinkage(), true,
5295         Expr.empty() ? nullptr : DBuilder.createExpression(Expr),
5296         getOrCreateStaticDataMemberDeclarationOrNull(D), TemplateParameters,
5297         Align, Annotations);
5298     Var->addDebugInfo(GVE);
5299   }
5300   DeclCache[D->getCanonicalDecl()].reset(GVE);
5301 }
5302 
5303 void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD, const APValue &Init) {
5304   assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
5305   if (VD->hasAttr<NoDebugAttr>())
5306     return;
5307   llvm::TimeTraceScope TimeScope("DebugConstGlobalVariable", [&]() {
5308     return GetName(VD, true);
5309   });
5310 
5311   auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
5312   // Create the descriptor for the variable.
5313   llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
5314   StringRef Name = VD->getName();
5315   llvm::DIType *Ty = getOrCreateType(VD->getType(), Unit);
5316 
5317   if (const auto *ECD = dyn_cast<EnumConstantDecl>(VD)) {
5318     const auto *ED = cast<EnumDecl>(ECD->getDeclContext());
5319     assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
5320 
5321     if (CGM.getCodeGenOpts().EmitCodeView) {
5322       // If CodeView, emit enums as global variables, unless they are defined
5323       // inside a class. We do this because MSVC doesn't emit S_CONSTANTs for
5324       // enums in classes, and because it is difficult to attach this scope
5325       // information to the global variable.
5326       if (isa<RecordDecl>(ED->getDeclContext()))
5327         return;
5328     } else {
5329       // If not CodeView, emit DW_TAG_enumeration_type if necessary. For
5330       // example: for "enum { ZERO };", a DW_TAG_enumeration_type is created the
5331       // first time `ZERO` is referenced in a function.
5332       llvm::DIType *EDTy =
5333           getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
5334       assert (EDTy->getTag() == llvm::dwarf::DW_TAG_enumeration_type);
5335       (void)EDTy;
5336       return;
5337     }
5338   }
5339 
5340   // Do not emit separate definitions for function local consts.
5341   if (isa<FunctionDecl>(VD->getDeclContext()))
5342     return;
5343 
5344   VD = cast<ValueDecl>(VD->getCanonicalDecl());
5345   auto *VarD = dyn_cast<VarDecl>(VD);
5346   if (VarD && VarD->isStaticDataMember()) {
5347     auto *RD = cast<RecordDecl>(VarD->getDeclContext());
5348     getDeclContextDescriptor(VarD);
5349     // Ensure that the type is retained even though it's otherwise unreferenced.
5350     //
5351     // FIXME: This is probably unnecessary, since Ty should reference RD
5352     // through its scope.
5353     RetainedTypes.push_back(
5354         CGM.getContext().getRecordType(RD).getAsOpaquePtr());
5355 
5356     return;
5357   }
5358   llvm::DIScope *DContext = getDeclContextDescriptor(VD);
5359 
5360   auto &GV = DeclCache[VD];
5361   if (GV)
5362     return;
5363   llvm::DIExpression *InitExpr = nullptr;
5364   if (CGM.getContext().getTypeSize(VD->getType()) <= 64) {
5365     // FIXME: Add a representation for integer constants wider than 64 bits.
5366     if (Init.isInt())
5367       InitExpr =
5368           DBuilder.createConstantValueExpression(Init.getInt().getExtValue());
5369     else if (Init.isFloat())
5370       InitExpr = DBuilder.createConstantValueExpression(
5371           Init.getFloat().bitcastToAPInt().getZExtValue());
5372   }
5373 
5374   llvm::MDTuple *TemplateParameters = nullptr;
5375 
5376   if (isa<VarTemplateSpecializationDecl>(VD))
5377     if (VarD) {
5378       llvm::DINodeArray parameterNodes = CollectVarTemplateParams(VarD, &*Unit);
5379       TemplateParameters = parameterNodes.get();
5380     }
5381 
5382   GV.reset(DBuilder.createGlobalVariableExpression(
5383       DContext, Name, StringRef(), Unit, getLineNumber(VD->getLocation()), Ty,
5384       true, true, InitExpr, getOrCreateStaticDataMemberDeclarationOrNull(VarD),
5385       TemplateParameters, Align));
5386 }
5387 
5388 void CGDebugInfo::EmitExternalVariable(llvm::GlobalVariable *Var,
5389                                        const VarDecl *D) {
5390   assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
5391   if (D->hasAttr<NoDebugAttr>())
5392     return;
5393 
5394   auto Align = getDeclAlignIfRequired(D, CGM.getContext());
5395   llvm::DIFile *Unit = getOrCreateFile(D->getLocation());
5396   StringRef Name = D->getName();
5397   llvm::DIType *Ty = getOrCreateType(D->getType(), Unit);
5398 
5399   llvm::DIScope *DContext = getDeclContextDescriptor(D);
5400   llvm::DIGlobalVariableExpression *GVE =
5401       DBuilder.createGlobalVariableExpression(
5402           DContext, Name, StringRef(), Unit, getLineNumber(D->getLocation()),
5403           Ty, false, false, nullptr, nullptr, nullptr, Align);
5404   Var->addDebugInfo(GVE);
5405 }
5406 
5407 void CGDebugInfo::EmitGlobalAlias(const llvm::GlobalValue *GV,
5408                                   const GlobalDecl GD) {
5409 
5410   assert(GV);
5411 
5412   if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
5413     return;
5414 
5415   const auto *D = cast<ValueDecl>(GD.getDecl());
5416   if (D->hasAttr<NoDebugAttr>())
5417     return;
5418 
5419   auto AliaseeDecl = CGM.getMangledNameDecl(GV->getName());
5420   llvm::DINode *DI;
5421 
5422   if (!AliaseeDecl)
5423     // FIXME: Aliasee not declared yet - possibly declared later
5424     // For example,
5425     //
5426     //   1 extern int newname __attribute__((alias("oldname")));
5427     //   2 int oldname = 1;
5428     //
5429     // No debug info would be generated for 'newname' in this case.
5430     //
5431     // Fix compiler to generate "newname" as imported_declaration
5432     // pointing to the DIE of "oldname".
5433     return;
5434   if (!(DI = getDeclarationOrDefinition(
5435             AliaseeDecl.getCanonicalDecl().getDecl())))
5436     return;
5437 
5438   llvm::DIScope *DContext = getDeclContextDescriptor(D);
5439   auto Loc = D->getLocation();
5440 
5441   llvm::DIImportedEntity *ImportDI = DBuilder.createImportedDeclaration(
5442       DContext, DI, getOrCreateFile(Loc), getLineNumber(Loc), D->getName());
5443 
5444   // Record this DIE in the cache for nested declaration reference.
5445   ImportedDeclCache[GD.getCanonicalDecl().getDecl()].reset(ImportDI);
5446 }
5447 
5448 llvm::DIScope *CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
5449   if (!LexicalBlockStack.empty())
5450     return LexicalBlockStack.back();
5451   llvm::DIScope *Mod = getParentModuleOrNull(D);
5452   return getContextDescriptor(D, Mod ? Mod : TheCU);
5453 }
5454 
5455 void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
5456   if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
5457     return;
5458   const NamespaceDecl *NSDecl = UD.getNominatedNamespace();
5459   if (!NSDecl->isAnonymousNamespace() ||
5460       CGM.getCodeGenOpts().DebugExplicitImport) {
5461     auto Loc = UD.getLocation();
5462     if (!Loc.isValid())
5463       Loc = CurLoc;
5464     DBuilder.createImportedModule(
5465         getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
5466         getOrCreateNamespace(NSDecl), getOrCreateFile(Loc), getLineNumber(Loc));
5467   }
5468 }
5469 
5470 void CGDebugInfo::EmitUsingShadowDecl(const UsingShadowDecl &USD) {
5471   if (llvm::DINode *Target =
5472           getDeclarationOrDefinition(USD.getUnderlyingDecl())) {
5473     auto Loc = USD.getLocation();
5474     DBuilder.createImportedDeclaration(
5475         getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
5476         getOrCreateFile(Loc), getLineNumber(Loc));
5477   }
5478 }
5479 
5480 void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
5481   if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
5482     return;
5483   assert(UD.shadow_size() &&
5484          "We shouldn't be codegening an invalid UsingDecl containing no decls");
5485 
5486   for (const auto *USD : UD.shadows()) {
5487     // FIXME: Skip functions with undeduced auto return type for now since we
5488     // don't currently have the plumbing for separate declarations & definitions
5489     // of free functions and mismatched types (auto in the declaration, concrete
5490     // return type in the definition)
5491     if (const auto *FD = dyn_cast<FunctionDecl>(USD->getUnderlyingDecl()))
5492       if (const auto *AT = FD->getType()
5493                                ->castAs<FunctionProtoType>()
5494                                ->getContainedAutoType())
5495         if (AT->getDeducedType().isNull())
5496           continue;
5497 
5498     EmitUsingShadowDecl(*USD);
5499     // Emitting one decl is sufficient - debuggers can detect that this is an
5500     // overloaded name & provide lookup for all the overloads.
5501     break;
5502   }
5503 }
5504 
5505 void CGDebugInfo::EmitUsingEnumDecl(const UsingEnumDecl &UD) {
5506   if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
5507     return;
5508   assert(UD.shadow_size() &&
5509          "We shouldn't be codegening an invalid UsingEnumDecl"
5510          " containing no decls");
5511 
5512   for (const auto *USD : UD.shadows())
5513     EmitUsingShadowDecl(*USD);
5514 }
5515 
5516 void CGDebugInfo::EmitImportDecl(const ImportDecl &ID) {
5517   if (CGM.getCodeGenOpts().getDebuggerTuning() != llvm::DebuggerKind::LLDB)
5518     return;
5519   if (Module *M = ID.getImportedModule()) {
5520     auto Info = ASTSourceDescriptor(*M);
5521     auto Loc = ID.getLocation();
5522     DBuilder.createImportedDeclaration(
5523         getCurrentContextDescriptor(cast<Decl>(ID.getDeclContext())),
5524         getOrCreateModuleRef(Info, DebugTypeExtRefs), getOrCreateFile(Loc),
5525         getLineNumber(Loc));
5526   }
5527 }
5528 
5529 llvm::DIImportedEntity *
5530 CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
5531   if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
5532     return nullptr;
5533   auto &VH = NamespaceAliasCache[&NA];
5534   if (VH)
5535     return cast<llvm::DIImportedEntity>(VH);
5536   llvm::DIImportedEntity *R;
5537   auto Loc = NA.getLocation();
5538   if (const auto *Underlying =
5539           dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
5540     // This could cache & dedup here rather than relying on metadata deduping.
5541     R = DBuilder.createImportedDeclaration(
5542         getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
5543         EmitNamespaceAlias(*Underlying), getOrCreateFile(Loc),
5544         getLineNumber(Loc), NA.getName());
5545   else
5546     R = DBuilder.createImportedDeclaration(
5547         getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
5548         getOrCreateNamespace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
5549         getOrCreateFile(Loc), getLineNumber(Loc), NA.getName());
5550   VH.reset(R);
5551   return R;
5552 }
5553 
5554 llvm::DINamespace *
5555 CGDebugInfo::getOrCreateNamespace(const NamespaceDecl *NSDecl) {
5556   // Don't canonicalize the NamespaceDecl here: The DINamespace will be uniqued
5557   // if necessary, and this way multiple declarations of the same namespace in
5558   // different parent modules stay distinct.
5559   auto I = NamespaceCache.find(NSDecl);
5560   if (I != NamespaceCache.end())
5561     return cast<llvm::DINamespace>(I->second);
5562 
5563   llvm::DIScope *Context = getDeclContextDescriptor(NSDecl);
5564   // Don't trust the context if it is a DIModule (see comment above).
5565   llvm::DINamespace *NS =
5566       DBuilder.createNameSpace(Context, NSDecl->getName(), NSDecl->isInline());
5567   NamespaceCache[NSDecl].reset(NS);
5568   return NS;
5569 }
5570 
5571 void CGDebugInfo::setDwoId(uint64_t Signature) {
5572   assert(TheCU && "no main compile unit");
5573   TheCU->setDWOId(Signature);
5574 }
5575 
5576 void CGDebugInfo::finalize() {
5577   // Creating types might create further types - invalidating the current
5578   // element and the size(), so don't cache/reference them.
5579   for (size_t i = 0; i != ObjCInterfaceCache.size(); ++i) {
5580     ObjCInterfaceCacheEntry E = ObjCInterfaceCache[i];
5581     llvm::DIType *Ty = E.Type->getDecl()->getDefinition()
5582                            ? CreateTypeDefinition(E.Type, E.Unit)
5583                            : E.Decl;
5584     DBuilder.replaceTemporary(llvm::TempDIType(E.Decl), Ty);
5585   }
5586 
5587   // Add methods to interface.
5588   for (const auto &P : ObjCMethodCache) {
5589     if (P.second.empty())
5590       continue;
5591 
5592     QualType QTy(P.first->getTypeForDecl(), 0);
5593     auto It = TypeCache.find(QTy.getAsOpaquePtr());
5594     assert(It != TypeCache.end());
5595 
5596     llvm::DICompositeType *InterfaceDecl =
5597         cast<llvm::DICompositeType>(It->second);
5598 
5599     auto CurElts = InterfaceDecl->getElements();
5600     SmallVector<llvm::Metadata *, 16> EltTys(CurElts.begin(), CurElts.end());
5601 
5602     // For DWARF v4 or earlier, only add objc_direct methods.
5603     for (auto &SubprogramDirect : P.second)
5604       if (CGM.getCodeGenOpts().DwarfVersion >= 5 || SubprogramDirect.getInt())
5605         EltTys.push_back(SubprogramDirect.getPointer());
5606 
5607     llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
5608     DBuilder.replaceArrays(InterfaceDecl, Elements);
5609   }
5610 
5611   for (const auto &P : ReplaceMap) {
5612     assert(P.second);
5613     auto *Ty = cast<llvm::DIType>(P.second);
5614     assert(Ty->isForwardDecl());
5615 
5616     auto It = TypeCache.find(P.first);
5617     assert(It != TypeCache.end());
5618     assert(It->second);
5619 
5620     DBuilder.replaceTemporary(llvm::TempDIType(Ty),
5621                               cast<llvm::DIType>(It->second));
5622   }
5623 
5624   for (const auto &P : FwdDeclReplaceMap) {
5625     assert(P.second);
5626     llvm::TempMDNode FwdDecl(cast<llvm::MDNode>(P.second));
5627     llvm::Metadata *Repl;
5628 
5629     auto It = DeclCache.find(P.first);
5630     // If there has been no definition for the declaration, call RAUW
5631     // with ourselves, that will destroy the temporary MDNode and
5632     // replace it with a standard one, avoiding leaking memory.
5633     if (It == DeclCache.end())
5634       Repl = P.second;
5635     else
5636       Repl = It->second;
5637 
5638     if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(Repl))
5639       Repl = GVE->getVariable();
5640     DBuilder.replaceTemporary(std::move(FwdDecl), cast<llvm::MDNode>(Repl));
5641   }
5642 
5643   // We keep our own list of retained types, because we need to look
5644   // up the final type in the type cache.
5645   for (auto &RT : RetainedTypes)
5646     if (auto MD = TypeCache[RT])
5647       DBuilder.retainType(cast<llvm::DIType>(MD));
5648 
5649   DBuilder.finalize();
5650 }
5651 
5652 // Don't ignore in case of explicit cast where it is referenced indirectly.
5653 void CGDebugInfo::EmitExplicitCastType(QualType Ty) {
5654   if (CGM.getCodeGenOpts().hasReducedDebugInfo())
5655     if (auto *DieTy = getOrCreateType(Ty, TheCU->getFile()))
5656       DBuilder.retainType(DieTy);
5657 }
5658 
5659 void CGDebugInfo::EmitAndRetainType(QualType Ty) {
5660   if (CGM.getCodeGenOpts().hasMaybeUnusedDebugInfo())
5661     if (auto *DieTy = getOrCreateType(Ty, TheCU->getFile()))
5662       DBuilder.retainType(DieTy);
5663 }
5664 
5665 llvm::DebugLoc CGDebugInfo::SourceLocToDebugLoc(SourceLocation Loc) {
5666   if (LexicalBlockStack.empty())
5667     return llvm::DebugLoc();
5668 
5669   llvm::MDNode *Scope = LexicalBlockStack.back();
5670   return llvm::DILocation::get(CGM.getLLVMContext(), getLineNumber(Loc),
5671                                getColumnNumber(Loc), Scope);
5672 }
5673 
5674 llvm::DINode::DIFlags CGDebugInfo::getCallSiteRelatedAttrs() const {
5675   // Call site-related attributes are only useful in optimized programs, and
5676   // when there's a possibility of debugging backtraces.
5677   if (!CGM.getLangOpts().Optimize || DebugKind == codegenoptions::NoDebugInfo ||
5678       DebugKind == codegenoptions::LocTrackingOnly)
5679     return llvm::DINode::FlagZero;
5680 
5681   // Call site-related attributes are available in DWARF v5. Some debuggers,
5682   // while not fully DWARF v5-compliant, may accept these attributes as if they
5683   // were part of DWARF v4.
5684   bool SupportsDWARFv4Ext =
5685       CGM.getCodeGenOpts().DwarfVersion == 4 &&
5686       (CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB ||
5687        CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::GDB);
5688 
5689   if (!SupportsDWARFv4Ext && CGM.getCodeGenOpts().DwarfVersion < 5)
5690     return llvm::DINode::FlagZero;
5691 
5692   return llvm::DINode::FlagAllCallsDescribed;
5693 }
5694