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