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