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