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