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