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