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