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