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