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