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