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