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     return false;
2390 
2391   if (!LangOpts.CPlusPlus)
2392     return false;
2393 
2394   if (!RD->isCompleteDefinitionRequired())
2395     return true;
2396 
2397   const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
2398 
2399   if (!CXXDecl)
2400     return false;
2401 
2402   // Only emit complete debug info for a dynamic class when its vtable is
2403   // emitted.  However, Microsoft debuggers don't resolve type information
2404   // across DLL boundaries, so skip this optimization if the class or any of its
2405   // methods are marked dllimport. This isn't a complete solution, since objects
2406   // without any dllimport methods can be used in one DLL and constructed in
2407   // another, but it is the current behavior of LimitedDebugInfo.
2408   if (CXXDecl->hasDefinition() && CXXDecl->isDynamicClass() &&
2409       !isClassOrMethodDLLImport(CXXDecl))
2410     return true;
2411 
2412   TemplateSpecializationKind Spec = TSK_Undeclared;
2413   if (const auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD))
2414     Spec = SD->getSpecializationKind();
2415 
2416   if (Spec == TSK_ExplicitInstantiationDeclaration &&
2417       hasExplicitMemberDefinition(CXXDecl->method_begin(),
2418                                   CXXDecl->method_end()))
2419     return true;
2420 
2421   // In constructor homing mode, only emit complete debug info for a class
2422   // when its constructor is emitted.
2423   if ((DebugKind == codegenoptions::DebugInfoConstructor) &&
2424       canUseCtorHoming(CXXDecl))
2425     return true;
2426 
2427   return false;
2428 }
2429 
2430 void CGDebugInfo::completeRequiredType(const RecordDecl *RD) {
2431   if (shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD, CGM.getLangOpts()))
2432     return;
2433 
2434   QualType Ty = CGM.getContext().getRecordType(RD);
2435   llvm::DIType *T = getTypeOrNull(Ty);
2436   if (T && T->isForwardDecl())
2437     completeClassData(RD);
2438 }
2439 
2440 llvm::DIType *CGDebugInfo::CreateType(const RecordType *Ty) {
2441   RecordDecl *RD = Ty->getDecl();
2442   llvm::DIType *T = cast_or_null<llvm::DIType>(getTypeOrNull(QualType(Ty, 0)));
2443   if (T || shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD,
2444                                 CGM.getLangOpts())) {
2445     if (!T)
2446       T = getOrCreateRecordFwdDecl(Ty, getDeclContextDescriptor(RD));
2447     return T;
2448   }
2449 
2450   return CreateTypeDefinition(Ty);
2451 }
2452 
2453 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {
2454   RecordDecl *RD = Ty->getDecl();
2455 
2456   // Get overall information about the record type for the debug info.
2457   llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
2458 
2459   // Records and classes and unions can all be recursive.  To handle them, we
2460   // first generate a debug descriptor for the struct as a forward declaration.
2461   // Then (if it is a definition) we go through and get debug info for all of
2462   // its members.  Finally, we create a descriptor for the complete type (which
2463   // may refer to the forward decl if the struct is recursive) and replace all
2464   // uses of the forward declaration with the final definition.
2465   llvm::DICompositeType *FwdDecl = getOrCreateLimitedType(Ty);
2466 
2467   const RecordDecl *D = RD->getDefinition();
2468   if (!D || !D->isCompleteDefinition())
2469     return FwdDecl;
2470 
2471   if (const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
2472     CollectContainingType(CXXDecl, FwdDecl);
2473 
2474   // Push the struct on region stack.
2475   LexicalBlockStack.emplace_back(&*FwdDecl);
2476   RegionMap[Ty->getDecl()].reset(FwdDecl);
2477 
2478   // Convert all the elements.
2479   SmallVector<llvm::Metadata *, 16> EltTys;
2480   // what about nested types?
2481 
2482   // Note: The split of CXXDecl information here is intentional, the
2483   // gdb tests will depend on a certain ordering at printout. The debug
2484   // information offsets are still correct if we merge them all together
2485   // though.
2486   const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
2487   if (CXXDecl) {
2488     CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
2489     CollectVTableInfo(CXXDecl, DefUnit, EltTys);
2490   }
2491 
2492   // Collect data fields (including static variables and any initializers).
2493   CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
2494   if (CXXDecl)
2495     CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
2496 
2497   LexicalBlockStack.pop_back();
2498   RegionMap.erase(Ty->getDecl());
2499 
2500   llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
2501   DBuilder.replaceArrays(FwdDecl, Elements);
2502 
2503   if (FwdDecl->isTemporary())
2504     FwdDecl =
2505         llvm::MDNode::replaceWithPermanent(llvm::TempDICompositeType(FwdDecl));
2506 
2507   RegionMap[Ty->getDecl()].reset(FwdDecl);
2508   return FwdDecl;
2509 }
2510 
2511 llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectType *Ty,
2512                                       llvm::DIFile *Unit) {
2513   // Ignore protocols.
2514   return getOrCreateType(Ty->getBaseType(), Unit);
2515 }
2516 
2517 llvm::DIType *CGDebugInfo::CreateType(const ObjCTypeParamType *Ty,
2518                                       llvm::DIFile *Unit) {
2519   // Ignore protocols.
2520   SourceLocation Loc = Ty->getDecl()->getLocation();
2521 
2522   // Use Typedefs to represent ObjCTypeParamType.
2523   return DBuilder.createTypedef(
2524       getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit),
2525       Ty->getDecl()->getName(), getOrCreateFile(Loc), getLineNumber(Loc),
2526       getDeclContextDescriptor(Ty->getDecl()));
2527 }
2528 
2529 /// \return true if Getter has the default name for the property PD.
2530 static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
2531                                  const ObjCMethodDecl *Getter) {
2532   assert(PD);
2533   if (!Getter)
2534     return true;
2535 
2536   assert(Getter->getDeclName().isObjCZeroArgSelector());
2537   return PD->getName() ==
2538          Getter->getDeclName().getObjCSelector().getNameForSlot(0);
2539 }
2540 
2541 /// \return true if Setter has the default name for the property PD.
2542 static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
2543                                  const ObjCMethodDecl *Setter) {
2544   assert(PD);
2545   if (!Setter)
2546     return true;
2547 
2548   assert(Setter->getDeclName().isObjCOneArgSelector());
2549   return SelectorTable::constructSetterName(PD->getName()) ==
2550          Setter->getDeclName().getObjCSelector().getNameForSlot(0);
2551 }
2552 
2553 llvm::DIType *CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
2554                                       llvm::DIFile *Unit) {
2555   ObjCInterfaceDecl *ID = Ty->getDecl();
2556   if (!ID)
2557     return nullptr;
2558 
2559   // Return a forward declaration if this type was imported from a clang module,
2560   // and this is not the compile unit with the implementation of the type (which
2561   // may contain hidden ivars).
2562   if (DebugTypeExtRefs && ID->isFromASTFile() && ID->getDefinition() &&
2563       !ID->getImplementation())
2564     return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
2565                                       ID->getName(),
2566                                       getDeclContextDescriptor(ID), Unit, 0);
2567 
2568   // Get overall information about the record type for the debug info.
2569   llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
2570   unsigned Line = getLineNumber(ID->getLocation());
2571   auto RuntimeLang =
2572       static_cast<llvm::dwarf::SourceLanguage>(TheCU->getSourceLanguage());
2573 
2574   // If this is just a forward declaration return a special forward-declaration
2575   // debug type since we won't be able to lay out the entire type.
2576   ObjCInterfaceDecl *Def = ID->getDefinition();
2577   if (!Def || !Def->getImplementation()) {
2578     llvm::DIScope *Mod = getParentModuleOrNull(ID);
2579     llvm::DIType *FwdDecl = DBuilder.createReplaceableCompositeType(
2580         llvm::dwarf::DW_TAG_structure_type, ID->getName(), Mod ? Mod : TheCU,
2581         DefUnit, Line, RuntimeLang);
2582     ObjCInterfaceCache.push_back(ObjCInterfaceCacheEntry(Ty, FwdDecl, Unit));
2583     return FwdDecl;
2584   }
2585 
2586   return CreateTypeDefinition(Ty, Unit);
2587 }
2588 
2589 llvm::DIModule *CGDebugInfo::getOrCreateModuleRef(ASTSourceDescriptor Mod,
2590                                                   bool CreateSkeletonCU) {
2591   // Use the Module pointer as the key into the cache. This is a
2592   // nullptr if the "Module" is a PCH, which is safe because we don't
2593   // support chained PCH debug info, so there can only be a single PCH.
2594   const Module *M = Mod.getModuleOrNull();
2595   auto ModRef = ModuleCache.find(M);
2596   if (ModRef != ModuleCache.end())
2597     return cast<llvm::DIModule>(ModRef->second);
2598 
2599   // Macro definitions that were defined with "-D" on the command line.
2600   SmallString<128> ConfigMacros;
2601   {
2602     llvm::raw_svector_ostream OS(ConfigMacros);
2603     const auto &PPOpts = CGM.getPreprocessorOpts();
2604     unsigned I = 0;
2605     // Translate the macro definitions back into a command line.
2606     for (auto &M : PPOpts.Macros) {
2607       if (++I > 1)
2608         OS << " ";
2609       const std::string &Macro = M.first;
2610       bool Undef = M.second;
2611       OS << "\"-" << (Undef ? 'U' : 'D');
2612       for (char c : Macro)
2613         switch (c) {
2614         case '\\':
2615           OS << "\\\\";
2616           break;
2617         case '"':
2618           OS << "\\\"";
2619           break;
2620         default:
2621           OS << c;
2622         }
2623       OS << '\"';
2624     }
2625   }
2626 
2627   bool IsRootModule = M ? !M->Parent : true;
2628   // When a module name is specified as -fmodule-name, that module gets a
2629   // clang::Module object, but it won't actually be built or imported; it will
2630   // be textual.
2631   if (CreateSkeletonCU && IsRootModule && Mod.getASTFile().empty() && M)
2632     assert(StringRef(M->Name).startswith(CGM.getLangOpts().ModuleName) &&
2633            "clang module without ASTFile must be specified by -fmodule-name");
2634 
2635   // Return a StringRef to the remapped Path.
2636   auto RemapPath = [this](StringRef Path) -> std::string {
2637     std::string Remapped = remapDIPath(Path);
2638     StringRef Relative(Remapped);
2639     StringRef CompDir = TheCU->getDirectory();
2640     if (Relative.consume_front(CompDir))
2641       Relative.consume_front(llvm::sys::path::get_separator());
2642 
2643     return Relative.str();
2644   };
2645 
2646   if (CreateSkeletonCU && IsRootModule && !Mod.getASTFile().empty()) {
2647     // PCH files don't have a signature field in the control block,
2648     // but LLVM detects skeleton CUs by looking for a non-zero DWO id.
2649     // We use the lower 64 bits for debug info.
2650 
2651     uint64_t Signature = 0;
2652     if (const auto &ModSig = Mod.getSignature())
2653       Signature = ModSig.truncatedValue();
2654     else
2655       Signature = ~1ULL;
2656 
2657     llvm::DIBuilder DIB(CGM.getModule());
2658     SmallString<0> PCM;
2659     if (!llvm::sys::path::is_absolute(Mod.getASTFile()))
2660       PCM = Mod.getPath();
2661     llvm::sys::path::append(PCM, Mod.getASTFile());
2662     DIB.createCompileUnit(
2663         TheCU->getSourceLanguage(),
2664         // TODO: Support "Source" from external AST providers?
2665         DIB.createFile(Mod.getModuleName(), TheCU->getDirectory()),
2666         TheCU->getProducer(), false, StringRef(), 0, RemapPath(PCM),
2667         llvm::DICompileUnit::FullDebug, Signature);
2668     DIB.finalize();
2669   }
2670 
2671   llvm::DIModule *Parent =
2672       IsRootModule ? nullptr
2673                    : getOrCreateModuleRef(ASTSourceDescriptor(*M->Parent),
2674                                           CreateSkeletonCU);
2675   std::string IncludePath = Mod.getPath().str();
2676   llvm::DIModule *DIMod =
2677       DBuilder.createModule(Parent, Mod.getModuleName(), ConfigMacros,
2678                             RemapPath(IncludePath));
2679   ModuleCache[M].reset(DIMod);
2680   return DIMod;
2681 }
2682 
2683 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const ObjCInterfaceType *Ty,
2684                                                 llvm::DIFile *Unit) {
2685   ObjCInterfaceDecl *ID = Ty->getDecl();
2686   llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
2687   unsigned Line = getLineNumber(ID->getLocation());
2688   unsigned RuntimeLang = TheCU->getSourceLanguage();
2689 
2690   // Bit size, align and offset of the type.
2691   uint64_t Size = CGM.getContext().getTypeSize(Ty);
2692   auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
2693 
2694   llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
2695   if (ID->getImplementation())
2696     Flags |= llvm::DINode::FlagObjcClassComplete;
2697 
2698   llvm::DIScope *Mod = getParentModuleOrNull(ID);
2699   llvm::DICompositeType *RealDecl = DBuilder.createStructType(
2700       Mod ? Mod : Unit, ID->getName(), DefUnit, Line, Size, Align, Flags,
2701       nullptr, llvm::DINodeArray(), RuntimeLang);
2702 
2703   QualType QTy(Ty, 0);
2704   TypeCache[QTy.getAsOpaquePtr()].reset(RealDecl);
2705 
2706   // Push the struct on region stack.
2707   LexicalBlockStack.emplace_back(RealDecl);
2708   RegionMap[Ty->getDecl()].reset(RealDecl);
2709 
2710   // Convert all the elements.
2711   SmallVector<llvm::Metadata *, 16> EltTys;
2712 
2713   ObjCInterfaceDecl *SClass = ID->getSuperClass();
2714   if (SClass) {
2715     llvm::DIType *SClassTy =
2716         getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
2717     if (!SClassTy)
2718       return nullptr;
2719 
2720     llvm::DIType *InhTag = DBuilder.createInheritance(RealDecl, SClassTy, 0, 0,
2721                                                       llvm::DINode::FlagZero);
2722     EltTys.push_back(InhTag);
2723   }
2724 
2725   // Create entries for all of the properties.
2726   auto AddProperty = [&](const ObjCPropertyDecl *PD) {
2727     SourceLocation Loc = PD->getLocation();
2728     llvm::DIFile *PUnit = getOrCreateFile(Loc);
2729     unsigned PLine = getLineNumber(Loc);
2730     ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
2731     ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
2732     llvm::MDNode *PropertyNode = DBuilder.createObjCProperty(
2733         PD->getName(), PUnit, PLine,
2734         hasDefaultGetterName(PD, Getter) ? ""
2735                                          : getSelectorName(PD->getGetterName()),
2736         hasDefaultSetterName(PD, Setter) ? ""
2737                                          : getSelectorName(PD->getSetterName()),
2738         PD->getPropertyAttributes(), getOrCreateType(PD->getType(), PUnit));
2739     EltTys.push_back(PropertyNode);
2740   };
2741   {
2742     llvm::SmallPtrSet<const IdentifierInfo *, 16> PropertySet;
2743     for (const ObjCCategoryDecl *ClassExt : ID->known_extensions())
2744       for (auto *PD : ClassExt->properties()) {
2745         PropertySet.insert(PD->getIdentifier());
2746         AddProperty(PD);
2747       }
2748     for (const auto *PD : ID->properties()) {
2749       // Don't emit duplicate metadata for properties that were already in a
2750       // class extension.
2751       if (!PropertySet.insert(PD->getIdentifier()).second)
2752         continue;
2753       AddProperty(PD);
2754     }
2755   }
2756 
2757   const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
2758   unsigned FieldNo = 0;
2759   for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
2760        Field = Field->getNextIvar(), ++FieldNo) {
2761     llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
2762     if (!FieldTy)
2763       return nullptr;
2764 
2765     StringRef FieldName = Field->getName();
2766 
2767     // Ignore unnamed fields.
2768     if (FieldName.empty())
2769       continue;
2770 
2771     // Get the location for the field.
2772     llvm::DIFile *FieldDefUnit = getOrCreateFile(Field->getLocation());
2773     unsigned FieldLine = getLineNumber(Field->getLocation());
2774     QualType FType = Field->getType();
2775     uint64_t FieldSize = 0;
2776     uint32_t FieldAlign = 0;
2777 
2778     if (!FType->isIncompleteArrayType()) {
2779 
2780       // Bit size, align and offset of the type.
2781       FieldSize = Field->isBitField()
2782                       ? Field->getBitWidthValue(CGM.getContext())
2783                       : CGM.getContext().getTypeSize(FType);
2784       FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext());
2785     }
2786 
2787     uint64_t FieldOffset;
2788     if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
2789       // We don't know the runtime offset of an ivar if we're using the
2790       // non-fragile ABI.  For bitfields, use the bit offset into the first
2791       // byte of storage of the bitfield.  For other fields, use zero.
2792       if (Field->isBitField()) {
2793         FieldOffset =
2794             CGM.getObjCRuntime().ComputeBitfieldBitOffset(CGM, ID, Field);
2795         FieldOffset %= CGM.getContext().getCharWidth();
2796       } else {
2797         FieldOffset = 0;
2798       }
2799     } else {
2800       FieldOffset = RL.getFieldOffset(FieldNo);
2801     }
2802 
2803     llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
2804     if (Field->getAccessControl() == ObjCIvarDecl::Protected)
2805       Flags = llvm::DINode::FlagProtected;
2806     else if (Field->getAccessControl() == ObjCIvarDecl::Private)
2807       Flags = llvm::DINode::FlagPrivate;
2808     else if (Field->getAccessControl() == ObjCIvarDecl::Public)
2809       Flags = llvm::DINode::FlagPublic;
2810 
2811     llvm::MDNode *PropertyNode = nullptr;
2812     if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
2813       if (ObjCPropertyImplDecl *PImpD =
2814               ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
2815         if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
2816           SourceLocation Loc = PD->getLocation();
2817           llvm::DIFile *PUnit = getOrCreateFile(Loc);
2818           unsigned PLine = getLineNumber(Loc);
2819           ObjCMethodDecl *Getter = PImpD->getGetterMethodDecl();
2820           ObjCMethodDecl *Setter = PImpD->getSetterMethodDecl();
2821           PropertyNode = DBuilder.createObjCProperty(
2822               PD->getName(), PUnit, PLine,
2823               hasDefaultGetterName(PD, Getter)
2824                   ? ""
2825                   : getSelectorName(PD->getGetterName()),
2826               hasDefaultSetterName(PD, Setter)
2827                   ? ""
2828                   : getSelectorName(PD->getSetterName()),
2829               PD->getPropertyAttributes(),
2830               getOrCreateType(PD->getType(), PUnit));
2831         }
2832       }
2833     }
2834     FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit, FieldLine,
2835                                       FieldSize, FieldAlign, FieldOffset, Flags,
2836                                       FieldTy, PropertyNode);
2837     EltTys.push_back(FieldTy);
2838   }
2839 
2840   llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
2841   DBuilder.replaceArrays(RealDecl, Elements);
2842 
2843   LexicalBlockStack.pop_back();
2844   return RealDecl;
2845 }
2846 
2847 llvm::DIType *CGDebugInfo::CreateType(const VectorType *Ty,
2848                                       llvm::DIFile *Unit) {
2849   llvm::DIType *ElementTy = getOrCreateType(Ty->getElementType(), Unit);
2850   int64_t Count = Ty->getNumElements();
2851 
2852   llvm::Metadata *Subscript;
2853   QualType QTy(Ty, 0);
2854   auto SizeExpr = SizeExprCache.find(QTy);
2855   if (SizeExpr != SizeExprCache.end())
2856     Subscript = DBuilder.getOrCreateSubrange(
2857         SizeExpr->getSecond() /*count*/, nullptr /*lowerBound*/,
2858         nullptr /*upperBound*/, nullptr /*stride*/);
2859   else {
2860     auto *CountNode =
2861         llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
2862             llvm::Type::getInt64Ty(CGM.getLLVMContext()), Count ? Count : -1));
2863     Subscript = DBuilder.getOrCreateSubrange(
2864         CountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
2865         nullptr /*stride*/);
2866   }
2867   llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
2868 
2869   uint64_t Size = CGM.getContext().getTypeSize(Ty);
2870   auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
2871 
2872   return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
2873 }
2874 
2875 llvm::DIType *CGDebugInfo::CreateType(const ConstantMatrixType *Ty,
2876                                       llvm::DIFile *Unit) {
2877   // FIXME: Create another debug type for matrices
2878   // For the time being, it treats it like a nested ArrayType.
2879 
2880   llvm::DIType *ElementTy = getOrCreateType(Ty->getElementType(), Unit);
2881   uint64_t Size = CGM.getContext().getTypeSize(Ty);
2882   uint32_t Align = getTypeAlignIfRequired(Ty, CGM.getContext());
2883 
2884   // Create ranges for both dimensions.
2885   llvm::SmallVector<llvm::Metadata *, 2> Subscripts;
2886   auto *ColumnCountNode =
2887       llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
2888           llvm::Type::getInt64Ty(CGM.getLLVMContext()), Ty->getNumColumns()));
2889   auto *RowCountNode =
2890       llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
2891           llvm::Type::getInt64Ty(CGM.getLLVMContext()), Ty->getNumRows()));
2892   Subscripts.push_back(DBuilder.getOrCreateSubrange(
2893       ColumnCountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
2894       nullptr /*stride*/));
2895   Subscripts.push_back(DBuilder.getOrCreateSubrange(
2896       RowCountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
2897       nullptr /*stride*/));
2898   llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
2899   return DBuilder.createArrayType(Size, Align, ElementTy, SubscriptArray);
2900 }
2901 
2902 llvm::DIType *CGDebugInfo::CreateType(const ArrayType *Ty, llvm::DIFile *Unit) {
2903   uint64_t Size;
2904   uint32_t Align;
2905 
2906   // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
2907   if (const auto *VAT = dyn_cast<VariableArrayType>(Ty)) {
2908     Size = 0;
2909     Align = getTypeAlignIfRequired(CGM.getContext().getBaseElementType(VAT),
2910                                    CGM.getContext());
2911   } else if (Ty->isIncompleteArrayType()) {
2912     Size = 0;
2913     if (Ty->getElementType()->isIncompleteType())
2914       Align = 0;
2915     else
2916       Align = getTypeAlignIfRequired(Ty->getElementType(), CGM.getContext());
2917   } else if (Ty->isIncompleteType()) {
2918     Size = 0;
2919     Align = 0;
2920   } else {
2921     // Size and align of the whole array, not the element type.
2922     Size = CGM.getContext().getTypeSize(Ty);
2923     Align = getTypeAlignIfRequired(Ty, CGM.getContext());
2924   }
2925 
2926   // Add the dimensions of the array.  FIXME: This loses CV qualifiers from
2927   // interior arrays, do we care?  Why aren't nested arrays represented the
2928   // obvious/recursive way?
2929   SmallVector<llvm::Metadata *, 8> Subscripts;
2930   QualType EltTy(Ty, 0);
2931   while ((Ty = dyn_cast<ArrayType>(EltTy))) {
2932     // If the number of elements is known, then count is that number. Otherwise,
2933     // it's -1. This allows us to represent a subrange with an array of 0
2934     // elements, like this:
2935     //
2936     //   struct foo {
2937     //     int x[0];
2938     //   };
2939     int64_t Count = -1; // Count == -1 is an unbounded array.
2940     if (const auto *CAT = dyn_cast<ConstantArrayType>(Ty))
2941       Count = CAT->getSize().getZExtValue();
2942     else if (const auto *VAT = dyn_cast<VariableArrayType>(Ty)) {
2943       if (Expr *Size = VAT->getSizeExpr()) {
2944         Expr::EvalResult Result;
2945         if (Size->EvaluateAsInt(Result, CGM.getContext()))
2946           Count = Result.Val.getInt().getExtValue();
2947       }
2948     }
2949 
2950     auto SizeNode = SizeExprCache.find(EltTy);
2951     if (SizeNode != SizeExprCache.end())
2952       Subscripts.push_back(DBuilder.getOrCreateSubrange(
2953           SizeNode->getSecond() /*count*/, nullptr /*lowerBound*/,
2954           nullptr /*upperBound*/, nullptr /*stride*/));
2955     else {
2956       auto *CountNode =
2957           llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
2958               llvm::Type::getInt64Ty(CGM.getLLVMContext()), Count));
2959       Subscripts.push_back(DBuilder.getOrCreateSubrange(
2960           CountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
2961           nullptr /*stride*/));
2962     }
2963     EltTy = Ty->getElementType();
2964   }
2965 
2966   llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
2967 
2968   return DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
2969                                   SubscriptArray);
2970 }
2971 
2972 llvm::DIType *CGDebugInfo::CreateType(const LValueReferenceType *Ty,
2973                                       llvm::DIFile *Unit) {
2974   return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type, Ty,
2975                                Ty->getPointeeType(), Unit);
2976 }
2977 
2978 llvm::DIType *CGDebugInfo::CreateType(const RValueReferenceType *Ty,
2979                                       llvm::DIFile *Unit) {
2980   return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type, Ty,
2981                                Ty->getPointeeType(), Unit);
2982 }
2983 
2984 llvm::DIType *CGDebugInfo::CreateType(const MemberPointerType *Ty,
2985                                       llvm::DIFile *U) {
2986   llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
2987   uint64_t Size = 0;
2988 
2989   if (!Ty->isIncompleteType()) {
2990     Size = CGM.getContext().getTypeSize(Ty);
2991 
2992     // Set the MS inheritance model. There is no flag for the unspecified model.
2993     if (CGM.getTarget().getCXXABI().isMicrosoft()) {
2994       switch (Ty->getMostRecentCXXRecordDecl()->getMSInheritanceModel()) {
2995       case MSInheritanceModel::Single:
2996         Flags |= llvm::DINode::FlagSingleInheritance;
2997         break;
2998       case MSInheritanceModel::Multiple:
2999         Flags |= llvm::DINode::FlagMultipleInheritance;
3000         break;
3001       case MSInheritanceModel::Virtual:
3002         Flags |= llvm::DINode::FlagVirtualInheritance;
3003         break;
3004       case MSInheritanceModel::Unspecified:
3005         break;
3006       }
3007     }
3008   }
3009 
3010   llvm::DIType *ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
3011   if (Ty->isMemberDataPointerType())
3012     return DBuilder.createMemberPointerType(
3013         getOrCreateType(Ty->getPointeeType(), U), ClassType, Size, /*Align=*/0,
3014         Flags);
3015 
3016   const FunctionProtoType *FPT =
3017       Ty->getPointeeType()->getAs<FunctionProtoType>();
3018   return DBuilder.createMemberPointerType(
3019       getOrCreateInstanceMethodType(
3020           CXXMethodDecl::getThisType(FPT, Ty->getMostRecentCXXRecordDecl()),
3021           FPT, U, false),
3022       ClassType, Size, /*Align=*/0, Flags);
3023 }
3024 
3025 llvm::DIType *CGDebugInfo::CreateType(const AtomicType *Ty, llvm::DIFile *U) {
3026   auto *FromTy = getOrCreateType(Ty->getValueType(), U);
3027   return DBuilder.createQualifiedType(llvm::dwarf::DW_TAG_atomic_type, FromTy);
3028 }
3029 
3030 llvm::DIType *CGDebugInfo::CreateType(const PipeType *Ty, llvm::DIFile *U) {
3031   return getOrCreateType(Ty->getElementType(), U);
3032 }
3033 
3034 llvm::DIType *CGDebugInfo::CreateEnumType(const EnumType *Ty) {
3035   const EnumDecl *ED = Ty->getDecl();
3036 
3037   uint64_t Size = 0;
3038   uint32_t Align = 0;
3039   if (!ED->getTypeForDecl()->isIncompleteType()) {
3040     Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
3041     Align = getDeclAlignIfRequired(ED, CGM.getContext());
3042   }
3043 
3044   SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
3045 
3046   bool isImportedFromModule =
3047       DebugTypeExtRefs && ED->isFromASTFile() && ED->getDefinition();
3048 
3049   // If this is just a forward declaration, construct an appropriately
3050   // marked node and just return it.
3051   if (isImportedFromModule || !ED->getDefinition()) {
3052     // Note that it is possible for enums to be created as part of
3053     // their own declcontext. In this case a FwdDecl will be created
3054     // twice. This doesn't cause a problem because both FwdDecls are
3055     // entered into the ReplaceMap: finalize() will replace the first
3056     // FwdDecl with the second and then replace the second with
3057     // complete type.
3058     llvm::DIScope *EDContext = getDeclContextDescriptor(ED);
3059     llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
3060     llvm::TempDIScope TmpContext(DBuilder.createReplaceableCompositeType(
3061         llvm::dwarf::DW_TAG_enumeration_type, "", TheCU, DefUnit, 0));
3062 
3063     unsigned Line = getLineNumber(ED->getLocation());
3064     StringRef EDName = ED->getName();
3065     llvm::DIType *RetTy = DBuilder.createReplaceableCompositeType(
3066         llvm::dwarf::DW_TAG_enumeration_type, EDName, EDContext, DefUnit, Line,
3067         0, Size, Align, llvm::DINode::FlagFwdDecl, Identifier);
3068 
3069     ReplaceMap.emplace_back(
3070         std::piecewise_construct, std::make_tuple(Ty),
3071         std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
3072     return RetTy;
3073   }
3074 
3075   return CreateTypeDefinition(Ty);
3076 }
3077 
3078 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const EnumType *Ty) {
3079   const EnumDecl *ED = Ty->getDecl();
3080   uint64_t Size = 0;
3081   uint32_t Align = 0;
3082   if (!ED->getTypeForDecl()->isIncompleteType()) {
3083     Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
3084     Align = getDeclAlignIfRequired(ED, CGM.getContext());
3085   }
3086 
3087   SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
3088 
3089   // Create elements for each enumerator.
3090   SmallVector<llvm::Metadata *, 16> Enumerators;
3091   ED = ED->getDefinition();
3092   bool IsSigned = ED->getIntegerType()->isSignedIntegerType();
3093   for (const auto *Enum : ED->enumerators()) {
3094     const auto &InitVal = Enum->getInitVal();
3095     auto Value = IsSigned ? InitVal.getSExtValue() : InitVal.getZExtValue();
3096     Enumerators.push_back(
3097         DBuilder.createEnumerator(Enum->getName(), Value, !IsSigned));
3098   }
3099 
3100   // Return a CompositeType for the enum itself.
3101   llvm::DINodeArray EltArray = DBuilder.getOrCreateArray(Enumerators);
3102 
3103   llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
3104   unsigned Line = getLineNumber(ED->getLocation());
3105   llvm::DIScope *EnumContext = getDeclContextDescriptor(ED);
3106   llvm::DIType *ClassTy = getOrCreateType(ED->getIntegerType(), DefUnit);
3107   return DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit,
3108                                         Line, Size, Align, EltArray, ClassTy,
3109                                         Identifier, ED->isScoped());
3110 }
3111 
3112 llvm::DIMacro *CGDebugInfo::CreateMacro(llvm::DIMacroFile *Parent,
3113                                         unsigned MType, SourceLocation LineLoc,
3114                                         StringRef Name, StringRef Value) {
3115   unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(LineLoc);
3116   return DBuilder.createMacro(Parent, Line, MType, Name, Value);
3117 }
3118 
3119 llvm::DIMacroFile *CGDebugInfo::CreateTempMacroFile(llvm::DIMacroFile *Parent,
3120                                                     SourceLocation LineLoc,
3121                                                     SourceLocation FileLoc) {
3122   llvm::DIFile *FName = getOrCreateFile(FileLoc);
3123   unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(LineLoc);
3124   return DBuilder.createTempMacroFile(Parent, Line, FName);
3125 }
3126 
3127 static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
3128   Qualifiers Quals;
3129   do {
3130     Qualifiers InnerQuals = T.getLocalQualifiers();
3131     // Qualifiers::operator+() doesn't like it if you add a Qualifier
3132     // that is already there.
3133     Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals);
3134     Quals += InnerQuals;
3135     QualType LastT = T;
3136     switch (T->getTypeClass()) {
3137     default:
3138       return C.getQualifiedType(T.getTypePtr(), Quals);
3139     case Type::TemplateSpecialization: {
3140       const auto *Spec = cast<TemplateSpecializationType>(T);
3141       if (Spec->isTypeAlias())
3142         return C.getQualifiedType(T.getTypePtr(), Quals);
3143       T = Spec->desugar();
3144       break;
3145     }
3146     case Type::TypeOfExpr:
3147       T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
3148       break;
3149     case Type::TypeOf:
3150       T = cast<TypeOfType>(T)->getUnderlyingType();
3151       break;
3152     case Type::Decltype:
3153       T = cast<DecltypeType>(T)->getUnderlyingType();
3154       break;
3155     case Type::UnaryTransform:
3156       T = cast<UnaryTransformType>(T)->getUnderlyingType();
3157       break;
3158     case Type::Attributed:
3159       T = cast<AttributedType>(T)->getEquivalentType();
3160       break;
3161     case Type::Elaborated:
3162       T = cast<ElaboratedType>(T)->getNamedType();
3163       break;
3164     case Type::Paren:
3165       T = cast<ParenType>(T)->getInnerType();
3166       break;
3167     case Type::MacroQualified:
3168       T = cast<MacroQualifiedType>(T)->getUnderlyingType();
3169       break;
3170     case Type::SubstTemplateTypeParm:
3171       T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
3172       break;
3173     case Type::Auto:
3174     case Type::DeducedTemplateSpecialization: {
3175       QualType DT = cast<DeducedType>(T)->getDeducedType();
3176       assert(!DT.isNull() && "Undeduced types shouldn't reach here.");
3177       T = DT;
3178       break;
3179     }
3180     case Type::Adjusted:
3181     case Type::Decayed:
3182       // Decayed and adjusted types use the adjusted type in LLVM and DWARF.
3183       T = cast<AdjustedType>(T)->getAdjustedType();
3184       break;
3185     }
3186 
3187     assert(T != LastT && "Type unwrapping failed to unwrap!");
3188     (void)LastT;
3189   } while (true);
3190 }
3191 
3192 llvm::DIType *CGDebugInfo::getTypeOrNull(QualType Ty) {
3193   assert(Ty == UnwrapTypeForDebugInfo(Ty, CGM.getContext()));
3194   auto It = TypeCache.find(Ty.getAsOpaquePtr());
3195   if (It != TypeCache.end()) {
3196     // Verify that the debug info still exists.
3197     if (llvm::Metadata *V = It->second)
3198       return cast<llvm::DIType>(V);
3199   }
3200 
3201   return nullptr;
3202 }
3203 
3204 void CGDebugInfo::completeTemplateDefinition(
3205     const ClassTemplateSpecializationDecl &SD) {
3206   completeUnusedClass(SD);
3207 }
3208 
3209 void CGDebugInfo::completeUnusedClass(const CXXRecordDecl &D) {
3210   if (DebugKind <= codegenoptions::DebugLineTablesOnly)
3211     return;
3212 
3213   completeClassData(&D);
3214   // In case this type has no member function definitions being emitted, ensure
3215   // it is retained
3216   RetainedTypes.push_back(CGM.getContext().getRecordType(&D).getAsOpaquePtr());
3217 }
3218 
3219 llvm::DIType *CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile *Unit) {
3220   if (Ty.isNull())
3221     return nullptr;
3222 
3223   llvm::TimeTraceScope TimeScope("DebugType", [&]() {
3224     std::string Name;
3225     llvm::raw_string_ostream OS(Name);
3226     Ty.print(OS, getPrintingPolicy());
3227     return Name;
3228   });
3229 
3230   // Unwrap the type as needed for debug information.
3231   Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
3232 
3233   if (auto *T = getTypeOrNull(Ty))
3234     return T;
3235 
3236   llvm::DIType *Res = CreateTypeNode(Ty, Unit);
3237   void *TyPtr = Ty.getAsOpaquePtr();
3238 
3239   // And update the type cache.
3240   TypeCache[TyPtr].reset(Res);
3241 
3242   return Res;
3243 }
3244 
3245 llvm::DIModule *CGDebugInfo::getParentModuleOrNull(const Decl *D) {
3246   // A forward declaration inside a module header does not belong to the module.
3247   if (isa<RecordDecl>(D) && !cast<RecordDecl>(D)->getDefinition())
3248     return nullptr;
3249   if (DebugTypeExtRefs && D->isFromASTFile()) {
3250     // Record a reference to an imported clang module or precompiled header.
3251     auto *Reader = CGM.getContext().getExternalSource();
3252     auto Idx = D->getOwningModuleID();
3253     auto Info = Reader->getSourceDescriptor(Idx);
3254     if (Info)
3255       return getOrCreateModuleRef(*Info, /*SkeletonCU=*/true);
3256   } else if (ClangModuleMap) {
3257     // We are building a clang module or a precompiled header.
3258     //
3259     // TODO: When D is a CXXRecordDecl or a C++ Enum, the ODR applies
3260     // and it wouldn't be necessary to specify the parent scope
3261     // because the type is already unique by definition (it would look
3262     // like the output of -fno-standalone-debug). On the other hand,
3263     // the parent scope helps a consumer to quickly locate the object
3264     // file where the type's definition is located, so it might be
3265     // best to make this behavior a command line or debugger tuning
3266     // option.
3267     if (Module *M = D->getOwningModule()) {
3268       // This is a (sub-)module.
3269       auto Info = ASTSourceDescriptor(*M);
3270       return getOrCreateModuleRef(Info, /*SkeletonCU=*/false);
3271     } else {
3272       // This the precompiled header being built.
3273       return getOrCreateModuleRef(PCHDescriptor, /*SkeletonCU=*/false);
3274     }
3275   }
3276 
3277   return nullptr;
3278 }
3279 
3280 llvm::DIType *CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile *Unit) {
3281   // Handle qualifiers, which recursively handles what they refer to.
3282   if (Ty.hasLocalQualifiers())
3283     return CreateQualifiedType(Ty, Unit);
3284 
3285   // Work out details of type.
3286   switch (Ty->getTypeClass()) {
3287 #define TYPE(Class, Base)
3288 #define ABSTRACT_TYPE(Class, Base)
3289 #define NON_CANONICAL_TYPE(Class, Base)
3290 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3291 #include "clang/AST/TypeNodes.inc"
3292     llvm_unreachable("Dependent types cannot show up in debug information");
3293 
3294   case Type::ExtVector:
3295   case Type::Vector:
3296     return CreateType(cast<VectorType>(Ty), Unit);
3297   case Type::ConstantMatrix:
3298     return CreateType(cast<ConstantMatrixType>(Ty), Unit);
3299   case Type::ObjCObjectPointer:
3300     return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
3301   case Type::ObjCObject:
3302     return CreateType(cast<ObjCObjectType>(Ty), Unit);
3303   case Type::ObjCTypeParam:
3304     return CreateType(cast<ObjCTypeParamType>(Ty), Unit);
3305   case Type::ObjCInterface:
3306     return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
3307   case Type::Builtin:
3308     return CreateType(cast<BuiltinType>(Ty));
3309   case Type::Complex:
3310     return CreateType(cast<ComplexType>(Ty));
3311   case Type::Pointer:
3312     return CreateType(cast<PointerType>(Ty), Unit);
3313   case Type::BlockPointer:
3314     return CreateType(cast<BlockPointerType>(Ty), Unit);
3315   case Type::Typedef:
3316     return CreateType(cast<TypedefType>(Ty), Unit);
3317   case Type::Record:
3318     return CreateType(cast<RecordType>(Ty));
3319   case Type::Enum:
3320     return CreateEnumType(cast<EnumType>(Ty));
3321   case Type::FunctionProto:
3322   case Type::FunctionNoProto:
3323     return CreateType(cast<FunctionType>(Ty), Unit);
3324   case Type::ConstantArray:
3325   case Type::VariableArray:
3326   case Type::IncompleteArray:
3327     return CreateType(cast<ArrayType>(Ty), Unit);
3328 
3329   case Type::LValueReference:
3330     return CreateType(cast<LValueReferenceType>(Ty), Unit);
3331   case Type::RValueReference:
3332     return CreateType(cast<RValueReferenceType>(Ty), Unit);
3333 
3334   case Type::MemberPointer:
3335     return CreateType(cast<MemberPointerType>(Ty), Unit);
3336 
3337   case Type::Atomic:
3338     return CreateType(cast<AtomicType>(Ty), Unit);
3339 
3340   case Type::ExtInt:
3341     return CreateType(cast<ExtIntType>(Ty));
3342   case Type::Pipe:
3343     return CreateType(cast<PipeType>(Ty), Unit);
3344 
3345   case Type::TemplateSpecialization:
3346     return CreateType(cast<TemplateSpecializationType>(Ty), Unit);
3347 
3348   case Type::Auto:
3349   case Type::Attributed:
3350   case Type::Adjusted:
3351   case Type::Decayed:
3352   case Type::DeducedTemplateSpecialization:
3353   case Type::Elaborated:
3354   case Type::Paren:
3355   case Type::MacroQualified:
3356   case Type::SubstTemplateTypeParm:
3357   case Type::TypeOfExpr:
3358   case Type::TypeOf:
3359   case Type::Decltype:
3360   case Type::UnaryTransform:
3361     break;
3362   }
3363 
3364   llvm_unreachable("type should have been unwrapped!");
3365 }
3366 
3367 llvm::DICompositeType *
3368 CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty) {
3369   QualType QTy(Ty, 0);
3370 
3371   auto *T = cast_or_null<llvm::DICompositeType>(getTypeOrNull(QTy));
3372 
3373   // We may have cached a forward decl when we could have created
3374   // a non-forward decl. Go ahead and create a non-forward decl
3375   // now.
3376   if (T && !T->isForwardDecl())
3377     return T;
3378 
3379   // Otherwise create the type.
3380   llvm::DICompositeType *Res = CreateLimitedType(Ty);
3381 
3382   // Propagate members from the declaration to the definition
3383   // CreateType(const RecordType*) will overwrite this with the members in the
3384   // correct order if the full type is needed.
3385   DBuilder.replaceArrays(Res, T ? T->getElements() : llvm::DINodeArray());
3386 
3387   // And update the type cache.
3388   TypeCache[QTy.getAsOpaquePtr()].reset(Res);
3389   return Res;
3390 }
3391 
3392 // TODO: Currently used for context chains when limiting debug info.
3393 llvm::DICompositeType *CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
3394   RecordDecl *RD = Ty->getDecl();
3395 
3396   // Get overall information about the record type for the debug info.
3397   StringRef RDName = getClassName(RD);
3398   const SourceLocation Loc = RD->getLocation();
3399   llvm::DIFile *DefUnit = nullptr;
3400   unsigned Line = 0;
3401   if (Loc.isValid()) {
3402     DefUnit = getOrCreateFile(Loc);
3403     Line = getLineNumber(Loc);
3404   }
3405 
3406   llvm::DIScope *RDContext = getDeclContextDescriptor(RD);
3407 
3408   // If we ended up creating the type during the context chain construction,
3409   // just return that.
3410   auto *T = cast_or_null<llvm::DICompositeType>(
3411       getTypeOrNull(CGM.getContext().getRecordType(RD)));
3412   if (T && (!T->isForwardDecl() || !RD->getDefinition()))
3413     return T;
3414 
3415   // If this is just a forward or incomplete declaration, construct an
3416   // appropriately marked node and just return it.
3417   const RecordDecl *D = RD->getDefinition();
3418   if (!D || !D->isCompleteDefinition())
3419     return getOrCreateRecordFwdDecl(Ty, RDContext);
3420 
3421   uint64_t Size = CGM.getContext().getTypeSize(Ty);
3422   auto Align = getDeclAlignIfRequired(D, CGM.getContext());
3423 
3424   SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
3425 
3426   // Explicitly record the calling convention and export symbols for C++
3427   // records.
3428   auto Flags = llvm::DINode::FlagZero;
3429   if (auto CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3430     if (CGM.getCXXABI().getRecordArgABI(CXXRD) == CGCXXABI::RAA_Indirect)
3431       Flags |= llvm::DINode::FlagTypePassByReference;
3432     else
3433       Flags |= llvm::DINode::FlagTypePassByValue;
3434 
3435     // Record if a C++ record is non-trivial type.
3436     if (!CXXRD->isTrivial())
3437       Flags |= llvm::DINode::FlagNonTrivial;
3438 
3439     // Record exports it symbols to the containing structure.
3440     if (CXXRD->isAnonymousStructOrUnion())
3441         Flags |= llvm::DINode::FlagExportSymbols;
3442   }
3443 
3444   llvm::DICompositeType *RealDecl = DBuilder.createReplaceableCompositeType(
3445       getTagForRecord(RD), RDName, RDContext, DefUnit, Line, 0, Size, Align,
3446       Flags, Identifier);
3447 
3448   // Elements of composite types usually have back to the type, creating
3449   // uniquing cycles.  Distinct nodes are more efficient.
3450   switch (RealDecl->getTag()) {
3451   default:
3452     llvm_unreachable("invalid composite type tag");
3453 
3454   case llvm::dwarf::DW_TAG_array_type:
3455   case llvm::dwarf::DW_TAG_enumeration_type:
3456     // Array elements and most enumeration elements don't have back references,
3457     // so they don't tend to be involved in uniquing cycles and there is some
3458     // chance of merging them when linking together two modules.  Only make
3459     // them distinct if they are ODR-uniqued.
3460     if (Identifier.empty())
3461       break;
3462     LLVM_FALLTHROUGH;
3463 
3464   case llvm::dwarf::DW_TAG_structure_type:
3465   case llvm::dwarf::DW_TAG_union_type:
3466   case llvm::dwarf::DW_TAG_class_type:
3467     // Immediately resolve to a distinct node.
3468     RealDecl =
3469         llvm::MDNode::replaceWithDistinct(llvm::TempDICompositeType(RealDecl));
3470     break;
3471   }
3472 
3473   RegionMap[Ty->getDecl()].reset(RealDecl);
3474   TypeCache[QualType(Ty, 0).getAsOpaquePtr()].reset(RealDecl);
3475 
3476   if (const auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD))
3477     DBuilder.replaceArrays(RealDecl, llvm::DINodeArray(),
3478                            CollectCXXTemplateParams(TSpecial, DefUnit));
3479   return RealDecl;
3480 }
3481 
3482 void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,
3483                                         llvm::DICompositeType *RealDecl) {
3484   // A class's primary base or the class itself contains the vtable.
3485   llvm::DICompositeType *ContainingType = nullptr;
3486   const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
3487   if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
3488     // Seek non-virtual primary base root.
3489     while (1) {
3490       const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
3491       const CXXRecordDecl *PBT = BRL.getPrimaryBase();
3492       if (PBT && !BRL.isPrimaryBaseVirtual())
3493         PBase = PBT;
3494       else
3495         break;
3496     }
3497     ContainingType = cast<llvm::DICompositeType>(
3498         getOrCreateType(QualType(PBase->getTypeForDecl(), 0),
3499                         getOrCreateFile(RD->getLocation())));
3500   } else if (RD->isDynamicClass())
3501     ContainingType = RealDecl;
3502 
3503   DBuilder.replaceVTableHolder(RealDecl, ContainingType);
3504 }
3505 
3506 llvm::DIType *CGDebugInfo::CreateMemberType(llvm::DIFile *Unit, QualType FType,
3507                                             StringRef Name, uint64_t *Offset) {
3508   llvm::DIType *FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
3509   uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
3510   auto FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext());
3511   llvm::DIType *Ty =
3512       DBuilder.createMemberType(Unit, Name, Unit, 0, FieldSize, FieldAlign,
3513                                 *Offset, llvm::DINode::FlagZero, FieldTy);
3514   *Offset += FieldSize;
3515   return Ty;
3516 }
3517 
3518 void CGDebugInfo::collectFunctionDeclProps(GlobalDecl GD, llvm::DIFile *Unit,
3519                                            StringRef &Name,
3520                                            StringRef &LinkageName,
3521                                            llvm::DIScope *&FDContext,
3522                                            llvm::DINodeArray &TParamsArray,
3523                                            llvm::DINode::DIFlags &Flags) {
3524   const auto *FD = cast<FunctionDecl>(GD.getDecl());
3525   Name = getFunctionName(FD);
3526   // Use mangled name as linkage name for C/C++ functions.
3527   if (FD->hasPrototype()) {
3528     LinkageName = CGM.getMangledName(GD);
3529     Flags |= llvm::DINode::FlagPrototyped;
3530   }
3531   // No need to replicate the linkage name if it isn't different from the
3532   // subprogram name, no need to have it at all unless coverage is enabled or
3533   // debug is set to more than just line tables or extra debug info is needed.
3534   if (LinkageName == Name || (!CGM.getCodeGenOpts().EmitGcovArcs &&
3535                               !CGM.getCodeGenOpts().EmitGcovNotes &&
3536                               !CGM.getCodeGenOpts().DebugInfoForProfiling &&
3537                               DebugKind <= codegenoptions::DebugLineTablesOnly))
3538     LinkageName = StringRef();
3539 
3540   // Emit the function scope in line tables only mode (if CodeView) to
3541   // differentiate between function names.
3542   if (CGM.getCodeGenOpts().hasReducedDebugInfo() ||
3543       (DebugKind == codegenoptions::DebugLineTablesOnly &&
3544        CGM.getCodeGenOpts().EmitCodeView)) {
3545     if (const NamespaceDecl *NSDecl =
3546             dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
3547       FDContext = getOrCreateNamespace(NSDecl);
3548     else if (const RecordDecl *RDecl =
3549                  dyn_cast_or_null<RecordDecl>(FD->getDeclContext())) {
3550       llvm::DIScope *Mod = getParentModuleOrNull(RDecl);
3551       FDContext = getContextDescriptor(RDecl, Mod ? Mod : TheCU);
3552     }
3553   }
3554   if (CGM.getCodeGenOpts().hasReducedDebugInfo()) {
3555     // Check if it is a noreturn-marked function
3556     if (FD->isNoReturn())
3557       Flags |= llvm::DINode::FlagNoReturn;
3558     // Collect template parameters.
3559     TParamsArray = CollectFunctionTemplateParams(FD, Unit);
3560   }
3561 }
3562 
3563 void CGDebugInfo::collectVarDeclProps(const VarDecl *VD, llvm::DIFile *&Unit,
3564                                       unsigned &LineNo, QualType &T,
3565                                       StringRef &Name, StringRef &LinkageName,
3566                                       llvm::MDTuple *&TemplateParameters,
3567                                       llvm::DIScope *&VDContext) {
3568   Unit = getOrCreateFile(VD->getLocation());
3569   LineNo = getLineNumber(VD->getLocation());
3570 
3571   setLocation(VD->getLocation());
3572 
3573   T = VD->getType();
3574   if (T->isIncompleteArrayType()) {
3575     // CodeGen turns int[] into int[1] so we'll do the same here.
3576     llvm::APInt ConstVal(32, 1);
3577     QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3578 
3579     T = CGM.getContext().getConstantArrayType(ET, ConstVal, nullptr,
3580                                               ArrayType::Normal, 0);
3581   }
3582 
3583   Name = VD->getName();
3584   if (VD->getDeclContext() && !isa<FunctionDecl>(VD->getDeclContext()) &&
3585       !isa<ObjCMethodDecl>(VD->getDeclContext()))
3586     LinkageName = CGM.getMangledName(VD);
3587   if (LinkageName == Name)
3588     LinkageName = StringRef();
3589 
3590   if (isa<VarTemplateSpecializationDecl>(VD)) {
3591     llvm::DINodeArray parameterNodes = CollectVarTemplateParams(VD, &*Unit);
3592     TemplateParameters = parameterNodes.get();
3593   } else {
3594     TemplateParameters = nullptr;
3595   }
3596 
3597   // Since we emit declarations (DW_AT_members) for static members, place the
3598   // definition of those static members in the namespace they were declared in
3599   // in the source code (the lexical decl context).
3600   // FIXME: Generalize this for even non-member global variables where the
3601   // declaration and definition may have different lexical decl contexts, once
3602   // we have support for emitting declarations of (non-member) global variables.
3603   const DeclContext *DC = VD->isStaticDataMember() ? VD->getLexicalDeclContext()
3604                                                    : VD->getDeclContext();
3605   // When a record type contains an in-line initialization of a static data
3606   // member, and the record type is marked as __declspec(dllexport), an implicit
3607   // definition of the member will be created in the record context.  DWARF
3608   // doesn't seem to have a nice way to describe this in a form that consumers
3609   // are likely to understand, so fake the "normal" situation of a definition
3610   // outside the class by putting it in the global scope.
3611   if (DC->isRecord())
3612     DC = CGM.getContext().getTranslationUnitDecl();
3613 
3614   llvm::DIScope *Mod = getParentModuleOrNull(VD);
3615   VDContext = getContextDescriptor(cast<Decl>(DC), Mod ? Mod : TheCU);
3616 }
3617 
3618 llvm::DISubprogram *CGDebugInfo::getFunctionFwdDeclOrStub(GlobalDecl GD,
3619                                                           bool Stub) {
3620   llvm::DINodeArray TParamsArray;
3621   StringRef Name, LinkageName;
3622   llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3623   llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
3624   SourceLocation Loc = GD.getDecl()->getLocation();
3625   llvm::DIFile *Unit = getOrCreateFile(Loc);
3626   llvm::DIScope *DContext = Unit;
3627   unsigned Line = getLineNumber(Loc);
3628   collectFunctionDeclProps(GD, Unit, Name, LinkageName, DContext, TParamsArray,
3629                            Flags);
3630   auto *FD = cast<FunctionDecl>(GD.getDecl());
3631 
3632   // Build function type.
3633   SmallVector<QualType, 16> ArgTypes;
3634   for (const ParmVarDecl *Parm : FD->parameters())
3635     ArgTypes.push_back(Parm->getType());
3636 
3637   CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
3638   QualType FnType = CGM.getContext().getFunctionType(
3639       FD->getReturnType(), ArgTypes, FunctionProtoType::ExtProtoInfo(CC));
3640   if (!FD->isExternallyVisible())
3641     SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;
3642   if (CGM.getLangOpts().Optimize)
3643     SPFlags |= llvm::DISubprogram::SPFlagOptimized;
3644 
3645   if (Stub) {
3646     Flags |= getCallSiteRelatedAttrs();
3647     SPFlags |= llvm::DISubprogram::SPFlagDefinition;
3648     return DBuilder.createFunction(
3649         DContext, Name, LinkageName, Unit, Line,
3650         getOrCreateFunctionType(GD.getDecl(), FnType, Unit), 0, Flags, SPFlags,
3651         TParamsArray.get(), getFunctionDeclaration(FD));
3652   }
3653 
3654   llvm::DISubprogram *SP = DBuilder.createTempFunctionFwdDecl(
3655       DContext, Name, LinkageName, Unit, Line,
3656       getOrCreateFunctionType(GD.getDecl(), FnType, Unit), 0, Flags, SPFlags,
3657       TParamsArray.get(), getFunctionDeclaration(FD));
3658   const FunctionDecl *CanonDecl = FD->getCanonicalDecl();
3659   FwdDeclReplaceMap.emplace_back(std::piecewise_construct,
3660                                  std::make_tuple(CanonDecl),
3661                                  std::make_tuple(SP));
3662   return SP;
3663 }
3664 
3665 llvm::DISubprogram *CGDebugInfo::getFunctionForwardDeclaration(GlobalDecl GD) {
3666   return getFunctionFwdDeclOrStub(GD, /* Stub = */ false);
3667 }
3668 
3669 llvm::DISubprogram *CGDebugInfo::getFunctionStub(GlobalDecl GD) {
3670   return getFunctionFwdDeclOrStub(GD, /* Stub = */ true);
3671 }
3672 
3673 llvm::DIGlobalVariable *
3674 CGDebugInfo::getGlobalVariableForwardDeclaration(const VarDecl *VD) {
3675   QualType T;
3676   StringRef Name, LinkageName;
3677   SourceLocation Loc = VD->getLocation();
3678   llvm::DIFile *Unit = getOrCreateFile(Loc);
3679   llvm::DIScope *DContext = Unit;
3680   unsigned Line = getLineNumber(Loc);
3681   llvm::MDTuple *TemplateParameters = nullptr;
3682 
3683   collectVarDeclProps(VD, Unit, Line, T, Name, LinkageName, TemplateParameters,
3684                       DContext);
3685   auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
3686   auto *GV = DBuilder.createTempGlobalVariableFwdDecl(
3687       DContext, Name, LinkageName, Unit, Line, getOrCreateType(T, Unit),
3688       !VD->isExternallyVisible(), nullptr, TemplateParameters, Align);
3689   FwdDeclReplaceMap.emplace_back(
3690       std::piecewise_construct,
3691       std::make_tuple(cast<VarDecl>(VD->getCanonicalDecl())),
3692       std::make_tuple(static_cast<llvm::Metadata *>(GV)));
3693   return GV;
3694 }
3695 
3696 llvm::DINode *CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
3697   // We only need a declaration (not a definition) of the type - so use whatever
3698   // we would otherwise do to get a type for a pointee. (forward declarations in
3699   // limited debug info, full definitions (if the type definition is available)
3700   // in unlimited debug info)
3701   if (const auto *TD = dyn_cast<TypeDecl>(D))
3702     return getOrCreateType(CGM.getContext().getTypeDeclType(TD),
3703                            getOrCreateFile(TD->getLocation()));
3704   auto I = DeclCache.find(D->getCanonicalDecl());
3705 
3706   if (I != DeclCache.end()) {
3707     auto N = I->second;
3708     if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(N))
3709       return GVE->getVariable();
3710     return dyn_cast_or_null<llvm::DINode>(N);
3711   }
3712 
3713   // No definition for now. Emit a forward definition that might be
3714   // merged with a potential upcoming definition.
3715   if (const auto *FD = dyn_cast<FunctionDecl>(D))
3716     return getFunctionForwardDeclaration(FD);
3717   else if (const auto *VD = dyn_cast<VarDecl>(D))
3718     return getGlobalVariableForwardDeclaration(VD);
3719 
3720   return nullptr;
3721 }
3722 
3723 llvm::DISubprogram *CGDebugInfo::getFunctionDeclaration(const Decl *D) {
3724   if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly)
3725     return nullptr;
3726 
3727   const auto *FD = dyn_cast<FunctionDecl>(D);
3728   if (!FD)
3729     return nullptr;
3730 
3731   // Setup context.
3732   auto *S = getDeclContextDescriptor(D);
3733 
3734   auto MI = SPCache.find(FD->getCanonicalDecl());
3735   if (MI == SPCache.end()) {
3736     if (const auto *MD = dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
3737       return CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()),
3738                                      cast<llvm::DICompositeType>(S));
3739     }
3740   }
3741   if (MI != SPCache.end()) {
3742     auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
3743     if (SP && !SP->isDefinition())
3744       return SP;
3745   }
3746 
3747   for (auto NextFD : FD->redecls()) {
3748     auto MI = SPCache.find(NextFD->getCanonicalDecl());
3749     if (MI != SPCache.end()) {
3750       auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
3751       if (SP && !SP->isDefinition())
3752         return SP;
3753     }
3754   }
3755   return nullptr;
3756 }
3757 
3758 llvm::DISubprogram *CGDebugInfo::getObjCMethodDeclaration(
3759     const Decl *D, llvm::DISubroutineType *FnType, unsigned LineNo,
3760     llvm::DINode::DIFlags Flags, llvm::DISubprogram::DISPFlags SPFlags) {
3761   if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly)
3762     return nullptr;
3763 
3764   const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
3765   if (!OMD)
3766     return nullptr;
3767 
3768   if (CGM.getCodeGenOpts().DwarfVersion < 5 && !OMD->isDirectMethod())
3769     return nullptr;
3770 
3771   if (OMD->isDirectMethod())
3772     SPFlags |= llvm::DISubprogram::SPFlagObjCDirect;
3773 
3774   // Starting with DWARF V5 method declarations are emitted as children of
3775   // the interface type.
3776   auto *ID = dyn_cast_or_null<ObjCInterfaceDecl>(D->getDeclContext());
3777   if (!ID)
3778     ID = OMD->getClassInterface();
3779   if (!ID)
3780     return nullptr;
3781   QualType QTy(ID->getTypeForDecl(), 0);
3782   auto It = TypeCache.find(QTy.getAsOpaquePtr());
3783   if (It == TypeCache.end())
3784     return nullptr;
3785   auto *InterfaceType = cast<llvm::DICompositeType>(It->second);
3786   llvm::DISubprogram *FD = DBuilder.createFunction(
3787       InterfaceType, getObjCMethodName(OMD), StringRef(),
3788       InterfaceType->getFile(), LineNo, FnType, LineNo, Flags, SPFlags);
3789   DBuilder.finalizeSubprogram(FD);
3790   ObjCMethodCache[ID].push_back({FD, OMD->isDirectMethod()});
3791   return FD;
3792 }
3793 
3794 // getOrCreateFunctionType - Construct type. If it is a c++ method, include
3795 // implicit parameter "this".
3796 llvm::DISubroutineType *CGDebugInfo::getOrCreateFunctionType(const Decl *D,
3797                                                              QualType FnType,
3798                                                              llvm::DIFile *F) {
3799   // In CodeView, we emit the function types in line tables only because the
3800   // only way to distinguish between functions is by display name and type.
3801   if (!D || (DebugKind <= codegenoptions::DebugLineTablesOnly &&
3802              !CGM.getCodeGenOpts().EmitCodeView))
3803     // Create fake but valid subroutine type. Otherwise -verify would fail, and
3804     // subprogram DIE will miss DW_AT_decl_file and DW_AT_decl_line fields.
3805     return DBuilder.createSubroutineType(DBuilder.getOrCreateTypeArray(None));
3806 
3807   if (const auto *Method = dyn_cast<CXXMethodDecl>(D))
3808     return getOrCreateMethodType(Method, F, false);
3809 
3810   const auto *FTy = FnType->getAs<FunctionType>();
3811   CallingConv CC = FTy ? FTy->getCallConv() : CallingConv::CC_C;
3812 
3813   if (const auto *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
3814     // Add "self" and "_cmd"
3815     SmallVector<llvm::Metadata *, 16> Elts;
3816 
3817     // First element is always return type. For 'void' functions it is NULL.
3818     QualType ResultTy = OMethod->getReturnType();
3819 
3820     // Replace the instancetype keyword with the actual type.
3821     if (ResultTy == CGM.getContext().getObjCInstanceType())
3822       ResultTy = CGM.getContext().getPointerType(
3823           QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
3824 
3825     Elts.push_back(getOrCreateType(ResultTy, F));
3826     // "self" pointer is always first argument.
3827     QualType SelfDeclTy;
3828     if (auto *SelfDecl = OMethod->getSelfDecl())
3829       SelfDeclTy = SelfDecl->getType();
3830     else if (auto *FPT = dyn_cast<FunctionProtoType>(FnType))
3831       if (FPT->getNumParams() > 1)
3832         SelfDeclTy = FPT->getParamType(0);
3833     if (!SelfDeclTy.isNull())
3834       Elts.push_back(
3835           CreateSelfType(SelfDeclTy, getOrCreateType(SelfDeclTy, F)));
3836     // "_cmd" pointer is always second argument.
3837     Elts.push_back(DBuilder.createArtificialType(
3838         getOrCreateType(CGM.getContext().getObjCSelType(), F)));
3839     // Get rest of the arguments.
3840     for (const auto *PI : OMethod->parameters())
3841       Elts.push_back(getOrCreateType(PI->getType(), F));
3842     // Variadic methods need a special marker at the end of the type list.
3843     if (OMethod->isVariadic())
3844       Elts.push_back(DBuilder.createUnspecifiedParameter());
3845 
3846     llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
3847     return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
3848                                          getDwarfCC(CC));
3849   }
3850 
3851   // Handle variadic function types; they need an additional
3852   // unspecified parameter.
3853   if (const auto *FD = dyn_cast<FunctionDecl>(D))
3854     if (FD->isVariadic()) {
3855       SmallVector<llvm::Metadata *, 16> EltTys;
3856       EltTys.push_back(getOrCreateType(FD->getReturnType(), F));
3857       if (const auto *FPT = dyn_cast<FunctionProtoType>(FnType))
3858         for (QualType ParamType : FPT->param_types())
3859           EltTys.push_back(getOrCreateType(ParamType, F));
3860       EltTys.push_back(DBuilder.createUnspecifiedParameter());
3861       llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
3862       return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
3863                                            getDwarfCC(CC));
3864     }
3865 
3866   return cast<llvm::DISubroutineType>(getOrCreateType(FnType, F));
3867 }
3868 
3869 void CGDebugInfo::emitFunctionStart(GlobalDecl GD, SourceLocation Loc,
3870                                     SourceLocation ScopeLoc, QualType FnType,
3871                                     llvm::Function *Fn, bool CurFuncIsThunk) {
3872   StringRef Name;
3873   StringRef LinkageName;
3874 
3875   FnBeginRegionCount.push_back(LexicalBlockStack.size());
3876 
3877   const Decl *D = GD.getDecl();
3878   bool HasDecl = (D != nullptr);
3879 
3880   llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3881   llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
3882   llvm::DIFile *Unit = getOrCreateFile(Loc);
3883   llvm::DIScope *FDContext = Unit;
3884   llvm::DINodeArray TParamsArray;
3885   if (!HasDecl) {
3886     // Use llvm function name.
3887     LinkageName = Fn->getName();
3888   } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
3889     // If there is a subprogram for this function available then use it.
3890     auto FI = SPCache.find(FD->getCanonicalDecl());
3891     if (FI != SPCache.end()) {
3892       auto *SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
3893       if (SP && SP->isDefinition()) {
3894         LexicalBlockStack.emplace_back(SP);
3895         RegionMap[D].reset(SP);
3896         return;
3897       }
3898     }
3899     collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
3900                              TParamsArray, Flags);
3901   } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) {
3902     Name = getObjCMethodName(OMD);
3903     Flags |= llvm::DINode::FlagPrototyped;
3904   } else if (isa<VarDecl>(D) &&
3905              GD.getDynamicInitKind() != DynamicInitKind::NoStub) {
3906     // This is a global initializer or atexit destructor for a global variable.
3907     Name = getDynamicInitializerName(cast<VarDecl>(D), GD.getDynamicInitKind(),
3908                                      Fn);
3909   } else {
3910     Name = Fn->getName();
3911 
3912     if (isa<BlockDecl>(D))
3913       LinkageName = Name;
3914 
3915     Flags |= llvm::DINode::FlagPrototyped;
3916   }
3917   if (Name.startswith("\01"))
3918     Name = Name.substr(1);
3919 
3920   if (!HasDecl || D->isImplicit() || D->hasAttr<ArtificialAttr>() ||
3921       (isa<VarDecl>(D) && GD.getDynamicInitKind() != DynamicInitKind::NoStub)) {
3922     Flags |= llvm::DINode::FlagArtificial;
3923     // Artificial functions should not silently reuse CurLoc.
3924     CurLoc = SourceLocation();
3925   }
3926 
3927   if (CurFuncIsThunk)
3928     Flags |= llvm::DINode::FlagThunk;
3929 
3930   if (Fn->hasLocalLinkage())
3931     SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;
3932   if (CGM.getLangOpts().Optimize)
3933     SPFlags |= llvm::DISubprogram::SPFlagOptimized;
3934 
3935   llvm::DINode::DIFlags FlagsForDef = Flags | getCallSiteRelatedAttrs();
3936   llvm::DISubprogram::DISPFlags SPFlagsForDef =
3937       SPFlags | llvm::DISubprogram::SPFlagDefinition;
3938 
3939   const unsigned LineNo = getLineNumber(Loc.isValid() ? Loc : CurLoc);
3940   unsigned ScopeLine = getLineNumber(ScopeLoc);
3941   llvm::DISubroutineType *DIFnType = getOrCreateFunctionType(D, FnType, Unit);
3942   llvm::DISubprogram *Decl = nullptr;
3943   if (D)
3944     Decl = isa<ObjCMethodDecl>(D)
3945                ? getObjCMethodDeclaration(D, DIFnType, LineNo, Flags, SPFlags)
3946                : getFunctionDeclaration(D);
3947 
3948   // FIXME: The function declaration we're constructing here is mostly reusing
3949   // declarations from CXXMethodDecl and not constructing new ones for arbitrary
3950   // FunctionDecls. When/if we fix this we can have FDContext be TheCU/null for
3951   // all subprograms instead of the actual context since subprogram definitions
3952   // are emitted as CU level entities by the backend.
3953   llvm::DISubprogram *SP = DBuilder.createFunction(
3954       FDContext, Name, LinkageName, Unit, LineNo, DIFnType, ScopeLine,
3955       FlagsForDef, SPFlagsForDef, TParamsArray.get(), Decl);
3956   Fn->setSubprogram(SP);
3957   // We might get here with a VarDecl in the case we're generating
3958   // code for the initialization of globals. Do not record these decls
3959   // as they will overwrite the actual VarDecl Decl in the cache.
3960   if (HasDecl && isa<FunctionDecl>(D))
3961     DeclCache[D->getCanonicalDecl()].reset(SP);
3962 
3963   // Push the function onto the lexical block stack.
3964   LexicalBlockStack.emplace_back(SP);
3965 
3966   if (HasDecl)
3967     RegionMap[D].reset(SP);
3968 }
3969 
3970 void CGDebugInfo::EmitFunctionDecl(GlobalDecl GD, SourceLocation Loc,
3971                                    QualType FnType, llvm::Function *Fn) {
3972   StringRef Name;
3973   StringRef LinkageName;
3974 
3975   const Decl *D = GD.getDecl();
3976   if (!D)
3977     return;
3978 
3979   llvm::TimeTraceScope TimeScope("DebugFunction", [&]() {
3980     std::string Name;
3981     llvm::raw_string_ostream OS(Name);
3982     if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
3983       ND->getNameForDiagnostic(OS, getPrintingPolicy(),
3984                                /*Qualified=*/true);
3985     return Name;
3986   });
3987 
3988   llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3989   llvm::DIFile *Unit = getOrCreateFile(Loc);
3990   bool IsDeclForCallSite = Fn ? true : false;
3991   llvm::DIScope *FDContext =
3992       IsDeclForCallSite ? Unit : getDeclContextDescriptor(D);
3993   llvm::DINodeArray TParamsArray;
3994   if (isa<FunctionDecl>(D)) {
3995     // If there is a DISubprogram for this function available then use it.
3996     collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
3997                              TParamsArray, Flags);
3998   } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) {
3999     Name = getObjCMethodName(OMD);
4000     Flags |= llvm::DINode::FlagPrototyped;
4001   } else {
4002     llvm_unreachable("not a function or ObjC method");
4003   }
4004   if (!Name.empty() && Name[0] == '\01')
4005     Name = Name.substr(1);
4006 
4007   if (D->isImplicit()) {
4008     Flags |= llvm::DINode::FlagArtificial;
4009     // Artificial functions without a location should not silently reuse CurLoc.
4010     if (Loc.isInvalid())
4011       CurLoc = SourceLocation();
4012   }
4013   unsigned LineNo = getLineNumber(Loc);
4014   unsigned ScopeLine = 0;
4015   llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
4016   if (CGM.getLangOpts().Optimize)
4017     SPFlags |= llvm::DISubprogram::SPFlagOptimized;
4018 
4019   llvm::DISubprogram *SP = DBuilder.createFunction(
4020       FDContext, Name, LinkageName, Unit, LineNo,
4021       getOrCreateFunctionType(D, FnType, Unit), ScopeLine, Flags, SPFlags,
4022       TParamsArray.get(), getFunctionDeclaration(D));
4023 
4024   if (IsDeclForCallSite)
4025     Fn->setSubprogram(SP);
4026 
4027   DBuilder.finalizeSubprogram(SP);
4028 }
4029 
4030 void CGDebugInfo::EmitFuncDeclForCallSite(llvm::CallBase *CallOrInvoke,
4031                                           QualType CalleeType,
4032                                           const FunctionDecl *CalleeDecl) {
4033   if (!CallOrInvoke)
4034     return;
4035   auto *Func = CallOrInvoke->getCalledFunction();
4036   if (!Func)
4037     return;
4038   if (Func->getSubprogram())
4039     return;
4040 
4041   // Do not emit a declaration subprogram for a builtin, a function with nodebug
4042   // attribute, or if call site info isn't required. Also, elide declarations
4043   // for functions with reserved names, as call site-related features aren't
4044   // interesting in this case (& also, the compiler may emit calls to these
4045   // functions without debug locations, which makes the verifier complain).
4046   if (CalleeDecl->getBuiltinID() != 0 || CalleeDecl->hasAttr<NoDebugAttr>() ||
4047       getCallSiteRelatedAttrs() == llvm::DINode::FlagZero)
4048     return;
4049   if (const auto *Id = CalleeDecl->getIdentifier())
4050     if (Id->isReservedName())
4051       return;
4052 
4053   // If there is no DISubprogram attached to the function being called,
4054   // create the one describing the function in order to have complete
4055   // call site debug info.
4056   if (!CalleeDecl->isStatic() && !CalleeDecl->isInlined())
4057     EmitFunctionDecl(CalleeDecl, CalleeDecl->getLocation(), CalleeType, Func);
4058 }
4059 
4060 void CGDebugInfo::EmitInlineFunctionStart(CGBuilderTy &Builder, GlobalDecl GD) {
4061   const auto *FD = cast<FunctionDecl>(GD.getDecl());
4062   // If there is a subprogram for this function available then use it.
4063   auto FI = SPCache.find(FD->getCanonicalDecl());
4064   llvm::DISubprogram *SP = nullptr;
4065   if (FI != SPCache.end())
4066     SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
4067   if (!SP || !SP->isDefinition())
4068     SP = getFunctionStub(GD);
4069   FnBeginRegionCount.push_back(LexicalBlockStack.size());
4070   LexicalBlockStack.emplace_back(SP);
4071   setInlinedAt(Builder.getCurrentDebugLocation());
4072   EmitLocation(Builder, FD->getLocation());
4073 }
4074 
4075 void CGDebugInfo::EmitInlineFunctionEnd(CGBuilderTy &Builder) {
4076   assert(CurInlinedAt && "unbalanced inline scope stack");
4077   EmitFunctionEnd(Builder, nullptr);
4078   setInlinedAt(llvm::DebugLoc(CurInlinedAt).getInlinedAt());
4079 }
4080 
4081 void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc) {
4082   // Update our current location
4083   setLocation(Loc);
4084 
4085   if (CurLoc.isInvalid() || CurLoc.isMacroID() || LexicalBlockStack.empty())
4086     return;
4087 
4088   llvm::MDNode *Scope = LexicalBlockStack.back();
4089   Builder.SetCurrentDebugLocation(
4090       llvm::DILocation::get(CGM.getLLVMContext(), getLineNumber(CurLoc),
4091                             getColumnNumber(CurLoc), Scope, CurInlinedAt));
4092 }
4093 
4094 void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
4095   llvm::MDNode *Back = nullptr;
4096   if (!LexicalBlockStack.empty())
4097     Back = LexicalBlockStack.back().get();
4098   LexicalBlockStack.emplace_back(DBuilder.createLexicalBlock(
4099       cast<llvm::DIScope>(Back), getOrCreateFile(CurLoc), getLineNumber(CurLoc),
4100       getColumnNumber(CurLoc)));
4101 }
4102 
4103 void CGDebugInfo::AppendAddressSpaceXDeref(
4104     unsigned AddressSpace, SmallVectorImpl<int64_t> &Expr) const {
4105   Optional<unsigned> DWARFAddressSpace =
4106       CGM.getTarget().getDWARFAddressSpace(AddressSpace);
4107   if (!DWARFAddressSpace)
4108     return;
4109 
4110   Expr.push_back(llvm::dwarf::DW_OP_constu);
4111   Expr.push_back(DWARFAddressSpace.getValue());
4112   Expr.push_back(llvm::dwarf::DW_OP_swap);
4113   Expr.push_back(llvm::dwarf::DW_OP_xderef);
4114 }
4115 
4116 void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
4117                                         SourceLocation Loc) {
4118   // Set our current location.
4119   setLocation(Loc);
4120 
4121   // Emit a line table change for the current location inside the new scope.
4122   Builder.SetCurrentDebugLocation(llvm::DILocation::get(
4123       CGM.getLLVMContext(), getLineNumber(Loc), getColumnNumber(Loc),
4124       LexicalBlockStack.back(), CurInlinedAt));
4125 
4126   if (DebugKind <= codegenoptions::DebugLineTablesOnly)
4127     return;
4128 
4129   // Create a new lexical block and push it on the stack.
4130   CreateLexicalBlock(Loc);
4131 }
4132 
4133 void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
4134                                       SourceLocation Loc) {
4135   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4136 
4137   // Provide an entry in the line table for the end of the block.
4138   EmitLocation(Builder, Loc);
4139 
4140   if (DebugKind <= codegenoptions::DebugLineTablesOnly)
4141     return;
4142 
4143   LexicalBlockStack.pop_back();
4144 }
4145 
4146 void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder, llvm::Function *Fn) {
4147   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4148   unsigned RCount = FnBeginRegionCount.back();
4149   assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
4150 
4151   // Pop all regions for this function.
4152   while (LexicalBlockStack.size() != RCount) {
4153     // Provide an entry in the line table for the end of the block.
4154     EmitLocation(Builder, CurLoc);
4155     LexicalBlockStack.pop_back();
4156   }
4157   FnBeginRegionCount.pop_back();
4158 
4159   if (Fn && Fn->getSubprogram())
4160     DBuilder.finalizeSubprogram(Fn->getSubprogram());
4161 }
4162 
4163 CGDebugInfo::BlockByRefType
4164 CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
4165                                           uint64_t *XOffset) {
4166   SmallVector<llvm::Metadata *, 5> EltTys;
4167   QualType FType;
4168   uint64_t FieldSize, FieldOffset;
4169   uint32_t FieldAlign;
4170 
4171   llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
4172   QualType Type = VD->getType();
4173 
4174   FieldOffset = 0;
4175   FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
4176   EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
4177   EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
4178   FType = CGM.getContext().IntTy;
4179   EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
4180   EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
4181 
4182   bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
4183   if (HasCopyAndDispose) {
4184     FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
4185     EltTys.push_back(
4186         CreateMemberType(Unit, FType, "__copy_helper", &FieldOffset));
4187     EltTys.push_back(
4188         CreateMemberType(Unit, FType, "__destroy_helper", &FieldOffset));
4189   }
4190   bool HasByrefExtendedLayout;
4191   Qualifiers::ObjCLifetime Lifetime;
4192   if (CGM.getContext().getByrefLifetime(Type, Lifetime,
4193                                         HasByrefExtendedLayout) &&
4194       HasByrefExtendedLayout) {
4195     FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
4196     EltTys.push_back(
4197         CreateMemberType(Unit, FType, "__byref_variable_layout", &FieldOffset));
4198   }
4199 
4200   CharUnits Align = CGM.getContext().getDeclAlign(VD);
4201   if (Align > CGM.getContext().toCharUnitsFromBits(
4202                   CGM.getTarget().getPointerAlign(0))) {
4203     CharUnits FieldOffsetInBytes =
4204         CGM.getContext().toCharUnitsFromBits(FieldOffset);
4205     CharUnits AlignedOffsetInBytes = FieldOffsetInBytes.alignTo(Align);
4206     CharUnits NumPaddingBytes = AlignedOffsetInBytes - FieldOffsetInBytes;
4207 
4208     if (NumPaddingBytes.isPositive()) {
4209       llvm::APInt pad(32, NumPaddingBytes.getQuantity());
4210       FType = CGM.getContext().getConstantArrayType(
4211           CGM.getContext().CharTy, pad, nullptr, ArrayType::Normal, 0);
4212       EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
4213     }
4214   }
4215 
4216   FType = Type;
4217   llvm::DIType *WrappedTy = getOrCreateType(FType, Unit);
4218   FieldSize = CGM.getContext().getTypeSize(FType);
4219   FieldAlign = CGM.getContext().toBits(Align);
4220 
4221   *XOffset = FieldOffset;
4222   llvm::DIType *FieldTy = DBuilder.createMemberType(
4223       Unit, VD->getName(), Unit, 0, FieldSize, FieldAlign, FieldOffset,
4224       llvm::DINode::FlagZero, WrappedTy);
4225   EltTys.push_back(FieldTy);
4226   FieldOffset += FieldSize;
4227 
4228   llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
4229   return {DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0,
4230                                     llvm::DINode::FlagZero, nullptr, Elements),
4231           WrappedTy};
4232 }
4233 
4234 llvm::DILocalVariable *CGDebugInfo::EmitDeclare(const VarDecl *VD,
4235                                                 llvm::Value *Storage,
4236                                                 llvm::Optional<unsigned> ArgNo,
4237                                                 CGBuilderTy &Builder,
4238                                                 const bool UsePointerValue) {
4239   assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4240   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4241   if (VD->hasAttr<NoDebugAttr>())
4242     return nullptr;
4243 
4244   bool Unwritten =
4245       VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) &&
4246                            cast<Decl>(VD->getDeclContext())->isImplicit());
4247   llvm::DIFile *Unit = nullptr;
4248   if (!Unwritten)
4249     Unit = getOrCreateFile(VD->getLocation());
4250   llvm::DIType *Ty;
4251   uint64_t XOffset = 0;
4252   if (VD->hasAttr<BlocksAttr>())
4253     Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset).WrappedType;
4254   else
4255     Ty = getOrCreateType(VD->getType(), Unit);
4256 
4257   // If there is no debug info for this type then do not emit debug info
4258   // for this variable.
4259   if (!Ty)
4260     return nullptr;
4261 
4262   // Get location information.
4263   unsigned Line = 0;
4264   unsigned Column = 0;
4265   if (!Unwritten) {
4266     Line = getLineNumber(VD->getLocation());
4267     Column = getColumnNumber(VD->getLocation());
4268   }
4269   SmallVector<int64_t, 13> Expr;
4270   llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
4271   if (VD->isImplicit())
4272     Flags |= llvm::DINode::FlagArtificial;
4273 
4274   auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
4275 
4276   unsigned AddressSpace = CGM.getContext().getTargetAddressSpace(VD->getType());
4277   AppendAddressSpaceXDeref(AddressSpace, Expr);
4278 
4279   // If this is implicit parameter of CXXThis or ObjCSelf kind, then give it an
4280   // object pointer flag.
4281   if (const auto *IPD = dyn_cast<ImplicitParamDecl>(VD)) {
4282     if (IPD->getParameterKind() == ImplicitParamDecl::CXXThis ||
4283         IPD->getParameterKind() == ImplicitParamDecl::ObjCSelf)
4284       Flags |= llvm::DINode::FlagObjectPointer;
4285   }
4286 
4287   // Note: Older versions of clang used to emit byval references with an extra
4288   // DW_OP_deref, because they referenced the IR arg directly instead of
4289   // referencing an alloca. Newer versions of LLVM don't treat allocas
4290   // differently from other function arguments when used in a dbg.declare.
4291   auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
4292   StringRef Name = VD->getName();
4293   if (!Name.empty()) {
4294     if (VD->hasAttr<BlocksAttr>()) {
4295       // Here, we need an offset *into* the alloca.
4296       CharUnits offset = CharUnits::fromQuantity(32);
4297       Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4298       // offset of __forwarding field
4299       offset = CGM.getContext().toCharUnitsFromBits(
4300           CGM.getTarget().getPointerWidth(0));
4301       Expr.push_back(offset.getQuantity());
4302       Expr.push_back(llvm::dwarf::DW_OP_deref);
4303       Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4304       // offset of x field
4305       offset = CGM.getContext().toCharUnitsFromBits(XOffset);
4306       Expr.push_back(offset.getQuantity());
4307     }
4308   } else if (const auto *RT = dyn_cast<RecordType>(VD->getType())) {
4309     // If VD is an anonymous union then Storage represents value for
4310     // all union fields.
4311     const RecordDecl *RD = RT->getDecl();
4312     if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
4313       // GDB has trouble finding local variables in anonymous unions, so we emit
4314       // artificial local variables for each of the members.
4315       //
4316       // FIXME: Remove this code as soon as GDB supports this.
4317       // The debug info verifier in LLVM operates based on the assumption that a
4318       // variable has the same size as its storage and we had to disable the
4319       // check for artificial variables.
4320       for (const auto *Field : RD->fields()) {
4321         llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
4322         StringRef FieldName = Field->getName();
4323 
4324         // Ignore unnamed fields. Do not ignore unnamed records.
4325         if (FieldName.empty() && !isa<RecordType>(Field->getType()))
4326           continue;
4327 
4328         // Use VarDecl's Tag, Scope and Line number.
4329         auto FieldAlign = getDeclAlignIfRequired(Field, CGM.getContext());
4330         auto *D = DBuilder.createAutoVariable(
4331             Scope, FieldName, Unit, Line, FieldTy, CGM.getLangOpts().Optimize,
4332             Flags | llvm::DINode::FlagArtificial, FieldAlign);
4333 
4334         // Insert an llvm.dbg.declare into the current block.
4335         DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
4336                                llvm::DILocation::get(CGM.getLLVMContext(), Line,
4337                                                      Column, Scope,
4338                                                      CurInlinedAt),
4339                                Builder.GetInsertBlock());
4340       }
4341     }
4342   }
4343 
4344   // Clang stores the sret pointer provided by the caller in a static alloca.
4345   // Use DW_OP_deref to tell the debugger to load the pointer and treat it as
4346   // the address of the variable.
4347   if (UsePointerValue) {
4348     assert(std::find(Expr.begin(), Expr.end(), llvm::dwarf::DW_OP_deref) ==
4349                Expr.end() &&
4350            "Debug info already contains DW_OP_deref.");
4351     Expr.push_back(llvm::dwarf::DW_OP_deref);
4352   }
4353 
4354   // Create the descriptor for the variable.
4355   auto *D = ArgNo ? DBuilder.createParameterVariable(
4356                         Scope, Name, *ArgNo, Unit, Line, Ty,
4357                         CGM.getLangOpts().Optimize, Flags)
4358                   : DBuilder.createAutoVariable(Scope, Name, Unit, Line, Ty,
4359                                                 CGM.getLangOpts().Optimize,
4360                                                 Flags, Align);
4361 
4362   // Insert an llvm.dbg.declare into the current block.
4363   DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
4364                          llvm::DILocation::get(CGM.getLLVMContext(), Line,
4365                                                Column, Scope, CurInlinedAt),
4366                          Builder.GetInsertBlock());
4367 
4368   return D;
4369 }
4370 
4371 llvm::DILocalVariable *
4372 CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD, llvm::Value *Storage,
4373                                        CGBuilderTy &Builder,
4374                                        const bool UsePointerValue) {
4375   assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4376   return EmitDeclare(VD, Storage, llvm::None, Builder, UsePointerValue);
4377 }
4378 
4379 void CGDebugInfo::EmitLabel(const LabelDecl *D, CGBuilderTy &Builder) {
4380   assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4381   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4382 
4383   if (D->hasAttr<NoDebugAttr>())
4384     return;
4385 
4386   auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
4387   llvm::DIFile *Unit = getOrCreateFile(D->getLocation());
4388 
4389   // Get location information.
4390   unsigned Line = getLineNumber(D->getLocation());
4391   unsigned Column = getColumnNumber(D->getLocation());
4392 
4393   StringRef Name = D->getName();
4394 
4395   // Create the descriptor for the label.
4396   auto *L =
4397       DBuilder.createLabel(Scope, Name, Unit, Line, CGM.getLangOpts().Optimize);
4398 
4399   // Insert an llvm.dbg.label into the current block.
4400   DBuilder.insertLabel(L,
4401                        llvm::DILocation::get(CGM.getLLVMContext(), Line, Column,
4402                                              Scope, CurInlinedAt),
4403                        Builder.GetInsertBlock());
4404 }
4405 
4406 llvm::DIType *CGDebugInfo::CreateSelfType(const QualType &QualTy,
4407                                           llvm::DIType *Ty) {
4408   llvm::DIType *CachedTy = getTypeOrNull(QualTy);
4409   if (CachedTy)
4410     Ty = CachedTy;
4411   return DBuilder.createObjectPointerType(Ty);
4412 }
4413 
4414 void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(
4415     const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder,
4416     const CGBlockInfo &blockInfo, llvm::Instruction *InsertPoint) {
4417   assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4418   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4419 
4420   if (Builder.GetInsertBlock() == nullptr)
4421     return;
4422   if (VD->hasAttr<NoDebugAttr>())
4423     return;
4424 
4425   bool isByRef = VD->hasAttr<BlocksAttr>();
4426 
4427   uint64_t XOffset = 0;
4428   llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
4429   llvm::DIType *Ty;
4430   if (isByRef)
4431     Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset).WrappedType;
4432   else
4433     Ty = getOrCreateType(VD->getType(), Unit);
4434 
4435   // Self is passed along as an implicit non-arg variable in a
4436   // block. Mark it as the object pointer.
4437   if (const auto *IPD = dyn_cast<ImplicitParamDecl>(VD))
4438     if (IPD->getParameterKind() == ImplicitParamDecl::ObjCSelf)
4439       Ty = CreateSelfType(VD->getType(), Ty);
4440 
4441   // Get location information.
4442   const unsigned Line =
4443       getLineNumber(VD->getLocation().isValid() ? VD->getLocation() : CurLoc);
4444   unsigned Column = getColumnNumber(VD->getLocation());
4445 
4446   const llvm::DataLayout &target = CGM.getDataLayout();
4447 
4448   CharUnits offset = CharUnits::fromQuantity(
4449       target.getStructLayout(blockInfo.StructureType)
4450           ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
4451 
4452   SmallVector<int64_t, 9> addr;
4453   addr.push_back(llvm::dwarf::DW_OP_deref);
4454   addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4455   addr.push_back(offset.getQuantity());
4456   if (isByRef) {
4457     addr.push_back(llvm::dwarf::DW_OP_deref);
4458     addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4459     // offset of __forwarding field
4460     offset =
4461         CGM.getContext().toCharUnitsFromBits(target.getPointerSizeInBits(0));
4462     addr.push_back(offset.getQuantity());
4463     addr.push_back(llvm::dwarf::DW_OP_deref);
4464     addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4465     // offset of x field
4466     offset = CGM.getContext().toCharUnitsFromBits(XOffset);
4467     addr.push_back(offset.getQuantity());
4468   }
4469 
4470   // Create the descriptor for the variable.
4471   auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
4472   auto *D = DBuilder.createAutoVariable(
4473       cast<llvm::DILocalScope>(LexicalBlockStack.back()), VD->getName(), Unit,
4474       Line, Ty, false, llvm::DINode::FlagZero, Align);
4475 
4476   // Insert an llvm.dbg.declare into the current block.
4477   auto DL = llvm::DILocation::get(CGM.getLLVMContext(), Line, Column,
4478                                   LexicalBlockStack.back(), CurInlinedAt);
4479   auto *Expr = DBuilder.createExpression(addr);
4480   if (InsertPoint)
4481     DBuilder.insertDeclare(Storage, D, Expr, DL, InsertPoint);
4482   else
4483     DBuilder.insertDeclare(Storage, D, Expr, DL, Builder.GetInsertBlock());
4484 }
4485 
4486 void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
4487                                            unsigned ArgNo,
4488                                            CGBuilderTy &Builder) {
4489   assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4490   EmitDeclare(VD, AI, ArgNo, Builder);
4491 }
4492 
4493 namespace {
4494 struct BlockLayoutChunk {
4495   uint64_t OffsetInBits;
4496   const BlockDecl::Capture *Capture;
4497 };
4498 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
4499   return l.OffsetInBits < r.OffsetInBits;
4500 }
4501 } // namespace
4502 
4503 void CGDebugInfo::collectDefaultFieldsForBlockLiteralDeclare(
4504     const CGBlockInfo &Block, const ASTContext &Context, SourceLocation Loc,
4505     const llvm::StructLayout &BlockLayout, llvm::DIFile *Unit,
4506     SmallVectorImpl<llvm::Metadata *> &Fields) {
4507   // Blocks in OpenCL have unique constraints which make the standard fields
4508   // redundant while requiring size and align fields for enqueue_kernel. See
4509   // initializeForBlockHeader in CGBlocks.cpp
4510   if (CGM.getLangOpts().OpenCL) {
4511     Fields.push_back(createFieldType("__size", Context.IntTy, Loc, AS_public,
4512                                      BlockLayout.getElementOffsetInBits(0),
4513                                      Unit, Unit));
4514     Fields.push_back(createFieldType("__align", Context.IntTy, Loc, AS_public,
4515                                      BlockLayout.getElementOffsetInBits(1),
4516                                      Unit, Unit));
4517   } else {
4518     Fields.push_back(createFieldType("__isa", Context.VoidPtrTy, Loc, AS_public,
4519                                      BlockLayout.getElementOffsetInBits(0),
4520                                      Unit, Unit));
4521     Fields.push_back(createFieldType("__flags", Context.IntTy, Loc, AS_public,
4522                                      BlockLayout.getElementOffsetInBits(1),
4523                                      Unit, Unit));
4524     Fields.push_back(
4525         createFieldType("__reserved", Context.IntTy, Loc, AS_public,
4526                         BlockLayout.getElementOffsetInBits(2), Unit, Unit));
4527     auto *FnTy = Block.getBlockExpr()->getFunctionType();
4528     auto FnPtrType = CGM.getContext().getPointerType(FnTy->desugar());
4529     Fields.push_back(createFieldType("__FuncPtr", FnPtrType, Loc, AS_public,
4530                                      BlockLayout.getElementOffsetInBits(3),
4531                                      Unit, Unit));
4532     Fields.push_back(createFieldType(
4533         "__descriptor",
4534         Context.getPointerType(Block.NeedsCopyDispose
4535                                    ? Context.getBlockDescriptorExtendedType()
4536                                    : Context.getBlockDescriptorType()),
4537         Loc, AS_public, BlockLayout.getElementOffsetInBits(4), Unit, Unit));
4538   }
4539 }
4540 
4541 void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
4542                                                        StringRef Name,
4543                                                        unsigned ArgNo,
4544                                                        llvm::AllocaInst *Alloca,
4545                                                        CGBuilderTy &Builder) {
4546   assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4547   ASTContext &C = CGM.getContext();
4548   const BlockDecl *blockDecl = block.getBlockDecl();
4549 
4550   // Collect some general information about the block's location.
4551   SourceLocation loc = blockDecl->getCaretLocation();
4552   llvm::DIFile *tunit = getOrCreateFile(loc);
4553   unsigned line = getLineNumber(loc);
4554   unsigned column = getColumnNumber(loc);
4555 
4556   // Build the debug-info type for the block literal.
4557   getDeclContextDescriptor(blockDecl);
4558 
4559   const llvm::StructLayout *blockLayout =
4560       CGM.getDataLayout().getStructLayout(block.StructureType);
4561 
4562   SmallVector<llvm::Metadata *, 16> fields;
4563   collectDefaultFieldsForBlockLiteralDeclare(block, C, loc, *blockLayout, tunit,
4564                                              fields);
4565 
4566   // We want to sort the captures by offset, not because DWARF
4567   // requires this, but because we're paranoid about debuggers.
4568   SmallVector<BlockLayoutChunk, 8> chunks;
4569 
4570   // 'this' capture.
4571   if (blockDecl->capturesCXXThis()) {
4572     BlockLayoutChunk chunk;
4573     chunk.OffsetInBits =
4574         blockLayout->getElementOffsetInBits(block.CXXThisIndex);
4575     chunk.Capture = nullptr;
4576     chunks.push_back(chunk);
4577   }
4578 
4579   // Variable captures.
4580   for (const auto &capture : blockDecl->captures()) {
4581     const VarDecl *variable = capture.getVariable();
4582     const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
4583 
4584     // Ignore constant captures.
4585     if (captureInfo.isConstant())
4586       continue;
4587 
4588     BlockLayoutChunk chunk;
4589     chunk.OffsetInBits =
4590         blockLayout->getElementOffsetInBits(captureInfo.getIndex());
4591     chunk.Capture = &capture;
4592     chunks.push_back(chunk);
4593   }
4594 
4595   // Sort by offset.
4596   llvm::array_pod_sort(chunks.begin(), chunks.end());
4597 
4598   for (const BlockLayoutChunk &Chunk : chunks) {
4599     uint64_t offsetInBits = Chunk.OffsetInBits;
4600     const BlockDecl::Capture *capture = Chunk.Capture;
4601 
4602     // If we have a null capture, this must be the C++ 'this' capture.
4603     if (!capture) {
4604       QualType type;
4605       if (auto *Method =
4606               cast_or_null<CXXMethodDecl>(blockDecl->getNonClosureContext()))
4607         type = Method->getThisType();
4608       else if (auto *RDecl = dyn_cast<CXXRecordDecl>(blockDecl->getParent()))
4609         type = QualType(RDecl->getTypeForDecl(), 0);
4610       else
4611         llvm_unreachable("unexpected block declcontext");
4612 
4613       fields.push_back(createFieldType("this", type, loc, AS_public,
4614                                        offsetInBits, tunit, tunit));
4615       continue;
4616     }
4617 
4618     const VarDecl *variable = capture->getVariable();
4619     StringRef name = variable->getName();
4620 
4621     llvm::DIType *fieldType;
4622     if (capture->isByRef()) {
4623       TypeInfo PtrInfo = C.getTypeInfo(C.VoidPtrTy);
4624       auto Align = PtrInfo.AlignIsRequired ? PtrInfo.Align : 0;
4625       // FIXME: This recomputes the layout of the BlockByRefWrapper.
4626       uint64_t xoffset;
4627       fieldType =
4628           EmitTypeForVarWithBlocksAttr(variable, &xoffset).BlockByRefWrapper;
4629       fieldType = DBuilder.createPointerType(fieldType, PtrInfo.Width);
4630       fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
4631                                             PtrInfo.Width, Align, offsetInBits,
4632                                             llvm::DINode::FlagZero, fieldType);
4633     } else {
4634       auto Align = getDeclAlignIfRequired(variable, CGM.getContext());
4635       fieldType = createFieldType(name, variable->getType(), loc, AS_public,
4636                                   offsetInBits, Align, tunit, tunit);
4637     }
4638     fields.push_back(fieldType);
4639   }
4640 
4641   SmallString<36> typeName;
4642   llvm::raw_svector_ostream(typeName)
4643       << "__block_literal_" << CGM.getUniqueBlockCount();
4644 
4645   llvm::DINodeArray fieldsArray = DBuilder.getOrCreateArray(fields);
4646 
4647   llvm::DIType *type =
4648       DBuilder.createStructType(tunit, typeName.str(), tunit, line,
4649                                 CGM.getContext().toBits(block.BlockSize), 0,
4650                                 llvm::DINode::FlagZero, nullptr, fieldsArray);
4651   type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
4652 
4653   // Get overall information about the block.
4654   llvm::DINode::DIFlags flags = llvm::DINode::FlagArtificial;
4655   auto *scope = cast<llvm::DILocalScope>(LexicalBlockStack.back());
4656 
4657   // Create the descriptor for the parameter.
4658   auto *debugVar = DBuilder.createParameterVariable(
4659       scope, Name, ArgNo, tunit, line, type, CGM.getLangOpts().Optimize, flags);
4660 
4661   // Insert an llvm.dbg.declare into the current block.
4662   DBuilder.insertDeclare(Alloca, debugVar, DBuilder.createExpression(),
4663                          llvm::DILocation::get(CGM.getLLVMContext(), line,
4664                                                column, scope, CurInlinedAt),
4665                          Builder.GetInsertBlock());
4666 }
4667 
4668 llvm::DIDerivedType *
4669 CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {
4670   if (!D || !D->isStaticDataMember())
4671     return nullptr;
4672 
4673   auto MI = StaticDataMemberCache.find(D->getCanonicalDecl());
4674   if (MI != StaticDataMemberCache.end()) {
4675     assert(MI->second && "Static data member declaration should still exist");
4676     return MI->second;
4677   }
4678 
4679   // If the member wasn't found in the cache, lazily construct and add it to the
4680   // type (used when a limited form of the type is emitted).
4681   auto DC = D->getDeclContext();
4682   auto *Ctxt = cast<llvm::DICompositeType>(getDeclContextDescriptor(D));
4683   return CreateRecordStaticField(D, Ctxt, cast<RecordDecl>(DC));
4684 }
4685 
4686 llvm::DIGlobalVariableExpression *CGDebugInfo::CollectAnonRecordDecls(
4687     const RecordDecl *RD, llvm::DIFile *Unit, unsigned LineNo,
4688     StringRef LinkageName, llvm::GlobalVariable *Var, llvm::DIScope *DContext) {
4689   llvm::DIGlobalVariableExpression *GVE = nullptr;
4690 
4691   for (const auto *Field : RD->fields()) {
4692     llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
4693     StringRef FieldName = Field->getName();
4694 
4695     // Ignore unnamed fields, but recurse into anonymous records.
4696     if (FieldName.empty()) {
4697       if (const auto *RT = dyn_cast<RecordType>(Field->getType()))
4698         GVE = CollectAnonRecordDecls(RT->getDecl(), Unit, LineNo, LinkageName,
4699                                      Var, DContext);
4700       continue;
4701     }
4702     // Use VarDecl's Tag, Scope and Line number.
4703     GVE = DBuilder.createGlobalVariableExpression(
4704         DContext, FieldName, LinkageName, Unit, LineNo, FieldTy,
4705         Var->hasLocalLinkage());
4706     Var->addDebugInfo(GVE);
4707   }
4708   return GVE;
4709 }
4710 
4711 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
4712                                      const VarDecl *D) {
4713   assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4714   if (D->hasAttr<NoDebugAttr>())
4715     return;
4716 
4717   llvm::TimeTraceScope TimeScope("DebugGlobalVariable", [&]() {
4718     std::string Name;
4719     llvm::raw_string_ostream OS(Name);
4720     D->getNameForDiagnostic(OS, getPrintingPolicy(),
4721                             /*Qualified=*/true);
4722     return Name;
4723   });
4724 
4725   // If we already created a DIGlobalVariable for this declaration, just attach
4726   // it to the llvm::GlobalVariable.
4727   auto Cached = DeclCache.find(D->getCanonicalDecl());
4728   if (Cached != DeclCache.end())
4729     return Var->addDebugInfo(
4730         cast<llvm::DIGlobalVariableExpression>(Cached->second));
4731 
4732   // Create global variable debug descriptor.
4733   llvm::DIFile *Unit = nullptr;
4734   llvm::DIScope *DContext = nullptr;
4735   unsigned LineNo;
4736   StringRef DeclName, LinkageName;
4737   QualType T;
4738   llvm::MDTuple *TemplateParameters = nullptr;
4739   collectVarDeclProps(D, Unit, LineNo, T, DeclName, LinkageName,
4740                       TemplateParameters, DContext);
4741 
4742   // Attempt to store one global variable for the declaration - even if we
4743   // emit a lot of fields.
4744   llvm::DIGlobalVariableExpression *GVE = nullptr;
4745 
4746   // If this is an anonymous union then we'll want to emit a global
4747   // variable for each member of the anonymous union so that it's possible
4748   // to find the name of any field in the union.
4749   if (T->isUnionType() && DeclName.empty()) {
4750     const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
4751     assert(RD->isAnonymousStructOrUnion() &&
4752            "unnamed non-anonymous struct or union?");
4753     GVE = CollectAnonRecordDecls(RD, Unit, LineNo, LinkageName, Var, DContext);
4754   } else {
4755     auto Align = getDeclAlignIfRequired(D, CGM.getContext());
4756 
4757     SmallVector<int64_t, 4> Expr;
4758     unsigned AddressSpace =
4759         CGM.getContext().getTargetAddressSpace(D->getType());
4760     if (CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) {
4761       if (D->hasAttr<CUDASharedAttr>())
4762         AddressSpace =
4763             CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared);
4764       else if (D->hasAttr<CUDAConstantAttr>())
4765         AddressSpace =
4766             CGM.getContext().getTargetAddressSpace(LangAS::cuda_constant);
4767     }
4768     AppendAddressSpaceXDeref(AddressSpace, Expr);
4769 
4770     GVE = DBuilder.createGlobalVariableExpression(
4771         DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
4772         Var->hasLocalLinkage(), true,
4773         Expr.empty() ? nullptr : DBuilder.createExpression(Expr),
4774         getOrCreateStaticDataMemberDeclarationOrNull(D), TemplateParameters,
4775         Align);
4776     Var->addDebugInfo(GVE);
4777   }
4778   DeclCache[D->getCanonicalDecl()].reset(GVE);
4779 }
4780 
4781 void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD, const APValue &Init) {
4782   assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4783   if (VD->hasAttr<NoDebugAttr>())
4784     return;
4785   llvm::TimeTraceScope TimeScope("DebugConstGlobalVariable", [&]() {
4786     std::string Name;
4787     llvm::raw_string_ostream OS(Name);
4788     VD->getNameForDiagnostic(OS, getPrintingPolicy(),
4789                              /*Qualified=*/true);
4790     return Name;
4791   });
4792 
4793   auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
4794   // Create the descriptor for the variable.
4795   llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
4796   StringRef Name = VD->getName();
4797   llvm::DIType *Ty = getOrCreateType(VD->getType(), Unit);
4798 
4799   if (const auto *ECD = dyn_cast<EnumConstantDecl>(VD)) {
4800     const auto *ED = cast<EnumDecl>(ECD->getDeclContext());
4801     assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
4802 
4803     if (CGM.getCodeGenOpts().EmitCodeView) {
4804       // If CodeView, emit enums as global variables, unless they are defined
4805       // inside a class. We do this because MSVC doesn't emit S_CONSTANTs for
4806       // enums in classes, and because it is difficult to attach this scope
4807       // information to the global variable.
4808       if (isa<RecordDecl>(ED->getDeclContext()))
4809         return;
4810     } else {
4811       // If not CodeView, emit DW_TAG_enumeration_type if necessary. For
4812       // example: for "enum { ZERO };", a DW_TAG_enumeration_type is created the
4813       // first time `ZERO` is referenced in a function.
4814       llvm::DIType *EDTy =
4815           getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
4816       assert (EDTy->getTag() == llvm::dwarf::DW_TAG_enumeration_type);
4817       (void)EDTy;
4818       return;
4819     }
4820   }
4821 
4822   // Do not emit separate definitions for function local consts.
4823   if (isa<FunctionDecl>(VD->getDeclContext()))
4824     return;
4825 
4826   VD = cast<ValueDecl>(VD->getCanonicalDecl());
4827   auto *VarD = dyn_cast<VarDecl>(VD);
4828   if (VarD && VarD->isStaticDataMember()) {
4829     auto *RD = cast<RecordDecl>(VarD->getDeclContext());
4830     getDeclContextDescriptor(VarD);
4831     // Ensure that the type is retained even though it's otherwise unreferenced.
4832     //
4833     // FIXME: This is probably unnecessary, since Ty should reference RD
4834     // through its scope.
4835     RetainedTypes.push_back(
4836         CGM.getContext().getRecordType(RD).getAsOpaquePtr());
4837 
4838     return;
4839   }
4840   llvm::DIScope *DContext = getDeclContextDescriptor(VD);
4841 
4842   auto &GV = DeclCache[VD];
4843   if (GV)
4844     return;
4845   llvm::DIExpression *InitExpr = nullptr;
4846   if (CGM.getContext().getTypeSize(VD->getType()) <= 64) {
4847     // FIXME: Add a representation for integer constants wider than 64 bits.
4848     if (Init.isInt())
4849       InitExpr =
4850           DBuilder.createConstantValueExpression(Init.getInt().getExtValue());
4851     else if (Init.isFloat())
4852       InitExpr = DBuilder.createConstantValueExpression(
4853           Init.getFloat().bitcastToAPInt().getZExtValue());
4854   }
4855 
4856   llvm::MDTuple *TemplateParameters = nullptr;
4857 
4858   if (isa<VarTemplateSpecializationDecl>(VD))
4859     if (VarD) {
4860       llvm::DINodeArray parameterNodes = CollectVarTemplateParams(VarD, &*Unit);
4861       TemplateParameters = parameterNodes.get();
4862     }
4863 
4864   GV.reset(DBuilder.createGlobalVariableExpression(
4865       DContext, Name, StringRef(), Unit, getLineNumber(VD->getLocation()), Ty,
4866       true, true, InitExpr, getOrCreateStaticDataMemberDeclarationOrNull(VarD),
4867       TemplateParameters, Align));
4868 }
4869 
4870 void CGDebugInfo::EmitExternalVariable(llvm::GlobalVariable *Var,
4871                                        const VarDecl *D) {
4872   assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4873   if (D->hasAttr<NoDebugAttr>())
4874     return;
4875 
4876   auto Align = getDeclAlignIfRequired(D, CGM.getContext());
4877   llvm::DIFile *Unit = getOrCreateFile(D->getLocation());
4878   StringRef Name = D->getName();
4879   llvm::DIType *Ty = getOrCreateType(D->getType(), Unit);
4880 
4881   llvm::DIScope *DContext = getDeclContextDescriptor(D);
4882   llvm::DIGlobalVariableExpression *GVE =
4883       DBuilder.createGlobalVariableExpression(
4884           DContext, Name, StringRef(), Unit, getLineNumber(D->getLocation()),
4885           Ty, false, false, nullptr, nullptr, nullptr, Align);
4886   Var->addDebugInfo(GVE);
4887 }
4888 
4889 llvm::DIScope *CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
4890   if (!LexicalBlockStack.empty())
4891     return LexicalBlockStack.back();
4892   llvm::DIScope *Mod = getParentModuleOrNull(D);
4893   return getContextDescriptor(D, Mod ? Mod : TheCU);
4894 }
4895 
4896 void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
4897   if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
4898     return;
4899   const NamespaceDecl *NSDecl = UD.getNominatedNamespace();
4900   if (!NSDecl->isAnonymousNamespace() ||
4901       CGM.getCodeGenOpts().DebugExplicitImport) {
4902     auto Loc = UD.getLocation();
4903     if (!Loc.isValid())
4904       Loc = CurLoc;
4905     DBuilder.createImportedModule(
4906         getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
4907         getOrCreateNamespace(NSDecl), getOrCreateFile(Loc), getLineNumber(Loc));
4908   }
4909 }
4910 
4911 void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
4912   if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
4913     return;
4914   assert(UD.shadow_size() &&
4915          "We shouldn't be codegening an invalid UsingDecl containing no decls");
4916   // Emitting one decl is sufficient - debuggers can detect that this is an
4917   // overloaded name & provide lookup for all the overloads.
4918   const UsingShadowDecl &USD = **UD.shadow_begin();
4919 
4920   // FIXME: Skip functions with undeduced auto return type for now since we
4921   // don't currently have the plumbing for separate declarations & definitions
4922   // of free functions and mismatched types (auto in the declaration, concrete
4923   // return type in the definition)
4924   if (const auto *FD = dyn_cast<FunctionDecl>(USD.getUnderlyingDecl()))
4925     if (const auto *AT =
4926             FD->getType()->castAs<FunctionProtoType>()->getContainedAutoType())
4927       if (AT->getDeducedType().isNull())
4928         return;
4929   if (llvm::DINode *Target =
4930           getDeclarationOrDefinition(USD.getUnderlyingDecl())) {
4931     auto Loc = USD.getLocation();
4932     DBuilder.createImportedDeclaration(
4933         getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
4934         getOrCreateFile(Loc), getLineNumber(Loc));
4935   }
4936 }
4937 
4938 void CGDebugInfo::EmitImportDecl(const ImportDecl &ID) {
4939   if (CGM.getCodeGenOpts().getDebuggerTuning() != llvm::DebuggerKind::LLDB)
4940     return;
4941   if (Module *M = ID.getImportedModule()) {
4942     auto Info = ASTSourceDescriptor(*M);
4943     auto Loc = ID.getLocation();
4944     DBuilder.createImportedDeclaration(
4945         getCurrentContextDescriptor(cast<Decl>(ID.getDeclContext())),
4946         getOrCreateModuleRef(Info, DebugTypeExtRefs), getOrCreateFile(Loc),
4947         getLineNumber(Loc));
4948   }
4949 }
4950 
4951 llvm::DIImportedEntity *
4952 CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
4953   if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
4954     return nullptr;
4955   auto &VH = NamespaceAliasCache[&NA];
4956   if (VH)
4957     return cast<llvm::DIImportedEntity>(VH);
4958   llvm::DIImportedEntity *R;
4959   auto Loc = NA.getLocation();
4960   if (const auto *Underlying =
4961           dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
4962     // This could cache & dedup here rather than relying on metadata deduping.
4963     R = DBuilder.createImportedDeclaration(
4964         getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
4965         EmitNamespaceAlias(*Underlying), getOrCreateFile(Loc),
4966         getLineNumber(Loc), NA.getName());
4967   else
4968     R = DBuilder.createImportedDeclaration(
4969         getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
4970         getOrCreateNamespace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
4971         getOrCreateFile(Loc), getLineNumber(Loc), NA.getName());
4972   VH.reset(R);
4973   return R;
4974 }
4975 
4976 llvm::DINamespace *
4977 CGDebugInfo::getOrCreateNamespace(const NamespaceDecl *NSDecl) {
4978   // Don't canonicalize the NamespaceDecl here: The DINamespace will be uniqued
4979   // if necessary, and this way multiple declarations of the same namespace in
4980   // different parent modules stay distinct.
4981   auto I = NamespaceCache.find(NSDecl);
4982   if (I != NamespaceCache.end())
4983     return cast<llvm::DINamespace>(I->second);
4984 
4985   llvm::DIScope *Context = getDeclContextDescriptor(NSDecl);
4986   // Don't trust the context if it is a DIModule (see comment above).
4987   llvm::DINamespace *NS =
4988       DBuilder.createNameSpace(Context, NSDecl->getName(), NSDecl->isInline());
4989   NamespaceCache[NSDecl].reset(NS);
4990   return NS;
4991 }
4992 
4993 void CGDebugInfo::setDwoId(uint64_t Signature) {
4994   assert(TheCU && "no main compile unit");
4995   TheCU->setDWOId(Signature);
4996 }
4997 
4998 void CGDebugInfo::finalize() {
4999   // Creating types might create further types - invalidating the current
5000   // element and the size(), so don't cache/reference them.
5001   for (size_t i = 0; i != ObjCInterfaceCache.size(); ++i) {
5002     ObjCInterfaceCacheEntry E = ObjCInterfaceCache[i];
5003     llvm::DIType *Ty = E.Type->getDecl()->getDefinition()
5004                            ? CreateTypeDefinition(E.Type, E.Unit)
5005                            : E.Decl;
5006     DBuilder.replaceTemporary(llvm::TempDIType(E.Decl), Ty);
5007   }
5008 
5009   // Add methods to interface.
5010   for (const auto &P : ObjCMethodCache) {
5011     if (P.second.empty())
5012       continue;
5013 
5014     QualType QTy(P.first->getTypeForDecl(), 0);
5015     auto It = TypeCache.find(QTy.getAsOpaquePtr());
5016     assert(It != TypeCache.end());
5017 
5018     llvm::DICompositeType *InterfaceDecl =
5019         cast<llvm::DICompositeType>(It->second);
5020 
5021     auto CurElts = InterfaceDecl->getElements();
5022     SmallVector<llvm::Metadata *, 16> EltTys(CurElts.begin(), CurElts.end());
5023 
5024     // For DWARF v4 or earlier, only add objc_direct methods.
5025     for (auto &SubprogramDirect : P.second)
5026       if (CGM.getCodeGenOpts().DwarfVersion >= 5 || SubprogramDirect.getInt())
5027         EltTys.push_back(SubprogramDirect.getPointer());
5028 
5029     llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
5030     DBuilder.replaceArrays(InterfaceDecl, Elements);
5031   }
5032 
5033   for (const auto &P : ReplaceMap) {
5034     assert(P.second);
5035     auto *Ty = cast<llvm::DIType>(P.second);
5036     assert(Ty->isForwardDecl());
5037 
5038     auto It = TypeCache.find(P.first);
5039     assert(It != TypeCache.end());
5040     assert(It->second);
5041 
5042     DBuilder.replaceTemporary(llvm::TempDIType(Ty),
5043                               cast<llvm::DIType>(It->second));
5044   }
5045 
5046   for (const auto &P : FwdDeclReplaceMap) {
5047     assert(P.second);
5048     llvm::TempMDNode FwdDecl(cast<llvm::MDNode>(P.second));
5049     llvm::Metadata *Repl;
5050 
5051     auto It = DeclCache.find(P.first);
5052     // If there has been no definition for the declaration, call RAUW
5053     // with ourselves, that will destroy the temporary MDNode and
5054     // replace it with a standard one, avoiding leaking memory.
5055     if (It == DeclCache.end())
5056       Repl = P.second;
5057     else
5058       Repl = It->second;
5059 
5060     if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(Repl))
5061       Repl = GVE->getVariable();
5062     DBuilder.replaceTemporary(std::move(FwdDecl), cast<llvm::MDNode>(Repl));
5063   }
5064 
5065   // We keep our own list of retained types, because we need to look
5066   // up the final type in the type cache.
5067   for (auto &RT : RetainedTypes)
5068     if (auto MD = TypeCache[RT])
5069       DBuilder.retainType(cast<llvm::DIType>(MD));
5070 
5071   DBuilder.finalize();
5072 }
5073 
5074 // Don't ignore in case of explicit cast where it is referenced indirectly.
5075 void CGDebugInfo::EmitExplicitCastType(QualType Ty) {
5076   if (CGM.getCodeGenOpts().hasReducedDebugInfo())
5077     if (auto *DieTy = getOrCreateType(Ty, TheCU->getFile()))
5078       DBuilder.retainType(DieTy);
5079 }
5080 
5081 void CGDebugInfo::EmitAndRetainType(QualType Ty) {
5082   if (CGM.getCodeGenOpts().hasMaybeUnusedDebugInfo())
5083     if (auto *DieTy = getOrCreateType(Ty, TheCU->getFile()))
5084       DBuilder.retainType(DieTy);
5085 }
5086 
5087 llvm::DebugLoc CGDebugInfo::SourceLocToDebugLoc(SourceLocation Loc) {
5088   if (LexicalBlockStack.empty())
5089     return llvm::DebugLoc();
5090 
5091   llvm::MDNode *Scope = LexicalBlockStack.back();
5092   return llvm::DILocation::get(CGM.getLLVMContext(), getLineNumber(Loc),
5093                                getColumnNumber(Loc), Scope);
5094 }
5095 
5096 llvm::DINode::DIFlags CGDebugInfo::getCallSiteRelatedAttrs() const {
5097   // Call site-related attributes are only useful in optimized programs, and
5098   // when there's a possibility of debugging backtraces.
5099   if (!CGM.getLangOpts().Optimize || DebugKind == codegenoptions::NoDebugInfo ||
5100       DebugKind == codegenoptions::LocTrackingOnly)
5101     return llvm::DINode::FlagZero;
5102 
5103   // Call site-related attributes are available in DWARF v5. Some debuggers,
5104   // while not fully DWARF v5-compliant, may accept these attributes as if they
5105   // were part of DWARF v4.
5106   bool SupportsDWARFv4Ext =
5107       CGM.getCodeGenOpts().DwarfVersion == 4 &&
5108       (CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB ||
5109        CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::GDB);
5110 
5111   if (!SupportsDWARFv4Ext && CGM.getCodeGenOpts().DwarfVersion < 5)
5112     return llvm::DINode::FlagZero;
5113 
5114   return llvm::DINode::FlagAllCallsDescribed;
5115 }
5116