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