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