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