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