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