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