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