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         }
1872         assert(V && "Failed to find template parameter pointer");
1873         V = V->stripPointerCasts();
1874       }
1875       TemplateParams.push_back(DBuilder.createTemplateValueParameter(
1876           TheCU, Name, TTy, defaultParameter, cast_or_null<llvm::Constant>(V)));
1877     } break;
1878     case TemplateArgument::NullPtr: {
1879       QualType T = TA.getNullPtrType();
1880       llvm::DIType *TTy = getOrCreateType(T, Unit);
1881       llvm::Constant *V = nullptr;
1882       // Special case member data pointer null values since they're actually -1
1883       // instead of zero.
1884       if (const auto *MPT = dyn_cast<MemberPointerType>(T.getTypePtr()))
1885         // But treat member function pointers as simple zero integers because
1886         // it's easier than having a special case in LLVM's CodeGen. If LLVM
1887         // CodeGen grows handling for values of non-null member function
1888         // pointers then perhaps we could remove this special case and rely on
1889         // EmitNullMemberPointer for member function pointers.
1890         if (MPT->isMemberDataPointer())
1891           V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1892       if (!V)
1893         V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
1894       TemplateParams.push_back(DBuilder.createTemplateValueParameter(
1895           TheCU, Name, TTy, defaultParameter, V));
1896     } break;
1897     case TemplateArgument::Template:
1898       TemplateParams.push_back(DBuilder.createTemplateTemplateParameter(
1899           TheCU, Name, nullptr,
1900           TA.getAsTemplate().getAsTemplateDecl()->getQualifiedNameAsString()));
1901       break;
1902     case TemplateArgument::Pack:
1903       TemplateParams.push_back(DBuilder.createTemplateParameterPack(
1904           TheCU, Name, nullptr,
1905           CollectTemplateParams(nullptr, TA.getPackAsArray(), Unit)));
1906       break;
1907     case TemplateArgument::Expression: {
1908       const Expr *E = TA.getAsExpr();
1909       QualType T = E->getType();
1910       if (E->isGLValue())
1911         T = CGM.getContext().getLValueReferenceType(T);
1912       llvm::Constant *V = ConstantEmitter(CGM).emitAbstract(E, T);
1913       assert(V && "Expression in template argument isn't constant");
1914       llvm::DIType *TTy = getOrCreateType(T, Unit);
1915       TemplateParams.push_back(DBuilder.createTemplateValueParameter(
1916           TheCU, Name, TTy, defaultParameter, V->stripPointerCasts()));
1917     } break;
1918     // And the following should never occur:
1919     case TemplateArgument::TemplateExpansion:
1920     case TemplateArgument::Null:
1921       llvm_unreachable(
1922           "These argument types shouldn't exist in concrete types");
1923     }
1924   }
1925   return DBuilder.getOrCreateArray(TemplateParams);
1926 }
1927 
1928 llvm::DINodeArray
1929 CGDebugInfo::CollectFunctionTemplateParams(const FunctionDecl *FD,
1930                                            llvm::DIFile *Unit) {
1931   if (FD->getTemplatedKind() ==
1932       FunctionDecl::TK_FunctionTemplateSpecialization) {
1933     const TemplateParameterList *TList = FD->getTemplateSpecializationInfo()
1934                                              ->getTemplate()
1935                                              ->getTemplateParameters();
1936     return CollectTemplateParams(
1937         TList, FD->getTemplateSpecializationArgs()->asArray(), Unit);
1938   }
1939   return llvm::DINodeArray();
1940 }
1941 
1942 llvm::DINodeArray CGDebugInfo::CollectVarTemplateParams(const VarDecl *VL,
1943                                                         llvm::DIFile *Unit) {
1944   // Always get the full list of parameters, not just the ones from the
1945   // specialization. A partial specialization may have fewer parameters than
1946   // there are arguments.
1947   auto *TS = dyn_cast<VarTemplateSpecializationDecl>(VL);
1948   if (!TS)
1949     return llvm::DINodeArray();
1950   VarTemplateDecl *T = TS->getSpecializedTemplate();
1951   const TemplateParameterList *TList = T->getTemplateParameters();
1952   auto TA = TS->getTemplateArgs().asArray();
1953   return CollectTemplateParams(TList, TA, Unit);
1954 }
1955 
1956 llvm::DINodeArray CGDebugInfo::CollectCXXTemplateParams(
1957     const ClassTemplateSpecializationDecl *TSpecial, llvm::DIFile *Unit) {
1958   // Always get the full list of parameters, not just the ones from the
1959   // specialization. A partial specialization may have fewer parameters than
1960   // there are arguments.
1961   TemplateParameterList *TPList =
1962       TSpecial->getSpecializedTemplate()->getTemplateParameters();
1963   const TemplateArgumentList &TAList = TSpecial->getTemplateArgs();
1964   return CollectTemplateParams(TPList, TAList.asArray(), Unit);
1965 }
1966 
1967 llvm::DIType *CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile *Unit) {
1968   if (VTablePtrType)
1969     return VTablePtrType;
1970 
1971   ASTContext &Context = CGM.getContext();
1972 
1973   /* Function type */
1974   llvm::Metadata *STy = getOrCreateType(Context.IntTy, Unit);
1975   llvm::DITypeRefArray SElements = DBuilder.getOrCreateTypeArray(STy);
1976   llvm::DIType *SubTy = DBuilder.createSubroutineType(SElements);
1977   unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1978   unsigned VtblPtrAddressSpace = CGM.getTarget().getVtblPtrAddressSpace();
1979   Optional<unsigned> DWARFAddressSpace =
1980       CGM.getTarget().getDWARFAddressSpace(VtblPtrAddressSpace);
1981 
1982   llvm::DIType *vtbl_ptr_type = DBuilder.createPointerType(
1983       SubTy, Size, 0, DWARFAddressSpace, "__vtbl_ptr_type");
1984   VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1985   return VTablePtrType;
1986 }
1987 
1988 StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
1989   // Copy the gdb compatible name on the side and use its reference.
1990   return internString("_vptr$", RD->getNameAsString());
1991 }
1992 
1993 StringRef CGDebugInfo::getDynamicInitializerName(const VarDecl *VD,
1994                                                  DynamicInitKind StubKind,
1995                                                  llvm::Function *InitFn) {
1996   // If we're not emitting codeview, use the mangled name. For Itanium, this is
1997   // arbitrary.
1998   if (!CGM.getCodeGenOpts().EmitCodeView)
1999     return InitFn->getName();
2000 
2001   // Print the normal qualified name for the variable, then break off the last
2002   // NNS, and add the appropriate other text. Clang always prints the global
2003   // variable name without template arguments, so we can use rsplit("::") and
2004   // then recombine the pieces.
2005   SmallString<128> QualifiedGV;
2006   StringRef Quals;
2007   StringRef GVName;
2008   {
2009     llvm::raw_svector_ostream OS(QualifiedGV);
2010     VD->printQualifiedName(OS, getPrintingPolicy());
2011     std::tie(Quals, GVName) = OS.str().rsplit("::");
2012     if (GVName.empty())
2013       std::swap(Quals, GVName);
2014   }
2015 
2016   SmallString<128> InitName;
2017   llvm::raw_svector_ostream OS(InitName);
2018   if (!Quals.empty())
2019     OS << Quals << "::";
2020 
2021   switch (StubKind) {
2022   case DynamicInitKind::NoStub:
2023     llvm_unreachable("not an initializer");
2024   case DynamicInitKind::Initializer:
2025     OS << "`dynamic initializer for '";
2026     break;
2027   case DynamicInitKind::AtExit:
2028     OS << "`dynamic atexit destructor for '";
2029     break;
2030   }
2031 
2032   OS << GVName;
2033 
2034   // Add any template specialization args.
2035   if (const auto *VTpl = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
2036     printTemplateArgumentList(OS, VTpl->getTemplateArgs().asArray(),
2037                               getPrintingPolicy());
2038   }
2039 
2040   OS << '\'';
2041 
2042   return internString(OS.str());
2043 }
2044 
2045 void CGDebugInfo::CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile *Unit,
2046                                     SmallVectorImpl<llvm::Metadata *> &EltTys,
2047                                     llvm::DICompositeType *RecordTy) {
2048   // If this class is not dynamic then there is not any vtable info to collect.
2049   if (!RD->isDynamicClass())
2050     return;
2051 
2052   // Don't emit any vtable shape or vptr info if this class doesn't have an
2053   // extendable vfptr. This can happen if the class doesn't have virtual
2054   // methods, or in the MS ABI if those virtual methods only come from virtually
2055   // inherited bases.
2056   const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2057   if (!RL.hasExtendableVFPtr())
2058     return;
2059 
2060   // CodeView needs to know how large the vtable of every dynamic class is, so
2061   // emit a special named pointer type into the element list. The vptr type
2062   // points to this type as well.
2063   llvm::DIType *VPtrTy = nullptr;
2064   bool NeedVTableShape = CGM.getCodeGenOpts().EmitCodeView &&
2065                          CGM.getTarget().getCXXABI().isMicrosoft();
2066   if (NeedVTableShape) {
2067     uint64_t PtrWidth =
2068         CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
2069     const VTableLayout &VFTLayout =
2070         CGM.getMicrosoftVTableContext().getVFTableLayout(RD, CharUnits::Zero());
2071     unsigned VSlotCount =
2072         VFTLayout.vtable_components().size() - CGM.getLangOpts().RTTIData;
2073     unsigned VTableWidth = PtrWidth * VSlotCount;
2074     unsigned VtblPtrAddressSpace = CGM.getTarget().getVtblPtrAddressSpace();
2075     Optional<unsigned> DWARFAddressSpace =
2076         CGM.getTarget().getDWARFAddressSpace(VtblPtrAddressSpace);
2077 
2078     // Create a very wide void* type and insert it directly in the element list.
2079     llvm::DIType *VTableType = DBuilder.createPointerType(
2080         nullptr, VTableWidth, 0, DWARFAddressSpace, "__vtbl_ptr_type");
2081     EltTys.push_back(VTableType);
2082 
2083     // The vptr is a pointer to this special vtable type.
2084     VPtrTy = DBuilder.createPointerType(VTableType, PtrWidth);
2085   }
2086 
2087   // If there is a primary base then the artificial vptr member lives there.
2088   if (RL.getPrimaryBase())
2089     return;
2090 
2091   if (!VPtrTy)
2092     VPtrTy = getOrCreateVTablePtrType(Unit);
2093 
2094   unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
2095   llvm::DIType *VPtrMember =
2096       DBuilder.createMemberType(Unit, getVTableName(RD), Unit, 0, Size, 0, 0,
2097                                 llvm::DINode::FlagArtificial, VPtrTy);
2098   EltTys.push_back(VPtrMember);
2099 }
2100 
2101 llvm::DIType *CGDebugInfo::getOrCreateRecordType(QualType RTy,
2102                                                  SourceLocation Loc) {
2103   assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
2104   llvm::DIType *T = getOrCreateType(RTy, getOrCreateFile(Loc));
2105   return T;
2106 }
2107 
2108 llvm::DIType *CGDebugInfo::getOrCreateInterfaceType(QualType D,
2109                                                     SourceLocation Loc) {
2110   return getOrCreateStandaloneType(D, Loc);
2111 }
2112 
2113 llvm::DIType *CGDebugInfo::getOrCreateStandaloneType(QualType D,
2114                                                      SourceLocation Loc) {
2115   assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
2116   assert(!D.isNull() && "null type");
2117   llvm::DIType *T = getOrCreateType(D, getOrCreateFile(Loc));
2118   assert(T && "could not create debug info for type");
2119 
2120   RetainedTypes.push_back(D.getAsOpaquePtr());
2121   return T;
2122 }
2123 
2124 void CGDebugInfo::addHeapAllocSiteMetadata(llvm::Instruction *CI,
2125                                            QualType D,
2126                                            SourceLocation Loc) {
2127   llvm::MDNode *node;
2128   if (D.getTypePtr()->isVoidPointerType()) {
2129     node = llvm::MDNode::get(CGM.getLLVMContext(), None);
2130   } else {
2131     QualType PointeeTy = D.getTypePtr()->getPointeeType();
2132     node = getOrCreateType(PointeeTy, getOrCreateFile(Loc));
2133   }
2134 
2135   CI->setMetadata("heapallocsite", node);
2136 }
2137 
2138 void CGDebugInfo::completeType(const EnumDecl *ED) {
2139   if (DebugKind <= codegenoptions::DebugLineTablesOnly)
2140     return;
2141   QualType Ty = CGM.getContext().getEnumType(ED);
2142   void *TyPtr = Ty.getAsOpaquePtr();
2143   auto I = TypeCache.find(TyPtr);
2144   if (I == TypeCache.end() || !cast<llvm::DIType>(I->second)->isForwardDecl())
2145     return;
2146   llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<EnumType>());
2147   assert(!Res->isForwardDecl());
2148   TypeCache[TyPtr].reset(Res);
2149 }
2150 
2151 void CGDebugInfo::completeType(const RecordDecl *RD) {
2152   if (DebugKind > codegenoptions::LimitedDebugInfo ||
2153       !CGM.getLangOpts().CPlusPlus)
2154     completeRequiredType(RD);
2155 }
2156 
2157 /// Return true if the class or any of its methods are marked dllimport.
2158 static bool isClassOrMethodDLLImport(const CXXRecordDecl *RD) {
2159   if (RD->hasAttr<DLLImportAttr>())
2160     return true;
2161   for (const CXXMethodDecl *MD : RD->methods())
2162     if (MD->hasAttr<DLLImportAttr>())
2163       return true;
2164   return false;
2165 }
2166 
2167 /// Does a type definition exist in an imported clang module?
2168 static bool isDefinedInClangModule(const RecordDecl *RD) {
2169   // Only definitions that where imported from an AST file come from a module.
2170   if (!RD || !RD->isFromASTFile())
2171     return false;
2172   // Anonymous entities cannot be addressed. Treat them as not from module.
2173   if (!RD->isExternallyVisible() && RD->getName().empty())
2174     return false;
2175   if (auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD)) {
2176     if (!CXXDecl->isCompleteDefinition())
2177       return false;
2178     // Check wether RD is a template.
2179     auto TemplateKind = CXXDecl->getTemplateSpecializationKind();
2180     if (TemplateKind != TSK_Undeclared) {
2181       // Unfortunately getOwningModule() isn't accurate enough to find the
2182       // owning module of a ClassTemplateSpecializationDecl that is inside a
2183       // namespace spanning multiple modules.
2184       bool Explicit = false;
2185       if (auto *TD = dyn_cast<ClassTemplateSpecializationDecl>(CXXDecl))
2186         Explicit = TD->isExplicitInstantiationOrSpecialization();
2187       if (!Explicit && CXXDecl->getEnclosingNamespaceContext())
2188         return false;
2189       // This is a template, check the origin of the first member.
2190       if (CXXDecl->field_begin() == CXXDecl->field_end())
2191         return TemplateKind == TSK_ExplicitInstantiationDeclaration;
2192       if (!CXXDecl->field_begin()->isFromASTFile())
2193         return false;
2194     }
2195   }
2196   return true;
2197 }
2198 
2199 void CGDebugInfo::completeClassData(const RecordDecl *RD) {
2200   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
2201     if (CXXRD->isDynamicClass() &&
2202         CGM.getVTableLinkage(CXXRD) ==
2203             llvm::GlobalValue::AvailableExternallyLinkage &&
2204         !isClassOrMethodDLLImport(CXXRD))
2205       return;
2206 
2207   if (DebugTypeExtRefs && isDefinedInClangModule(RD->getDefinition()))
2208     return;
2209 
2210   completeClass(RD);
2211 }
2212 
2213 void CGDebugInfo::completeClass(const RecordDecl *RD) {
2214   if (DebugKind <= codegenoptions::DebugLineTablesOnly)
2215     return;
2216   QualType Ty = CGM.getContext().getRecordType(RD);
2217   void *TyPtr = Ty.getAsOpaquePtr();
2218   auto I = TypeCache.find(TyPtr);
2219   if (I != TypeCache.end() && !cast<llvm::DIType>(I->second)->isForwardDecl())
2220     return;
2221   llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<RecordType>());
2222   assert(!Res->isForwardDecl());
2223   TypeCache[TyPtr].reset(Res);
2224 }
2225 
2226 static bool hasExplicitMemberDefinition(CXXRecordDecl::method_iterator I,
2227                                         CXXRecordDecl::method_iterator End) {
2228   for (CXXMethodDecl *MD : llvm::make_range(I, End))
2229     if (FunctionDecl *Tmpl = MD->getInstantiatedFromMemberFunction())
2230       if (!Tmpl->isImplicit() && Tmpl->isThisDeclarationADefinition() &&
2231           !MD->getMemberSpecializationInfo()->isExplicitSpecialization())
2232         return true;
2233   return false;
2234 }
2235 
2236 static bool shouldOmitDefinition(codegenoptions::DebugInfoKind DebugKind,
2237                                  bool DebugTypeExtRefs, const RecordDecl *RD,
2238                                  const LangOptions &LangOpts) {
2239   if (DebugTypeExtRefs && isDefinedInClangModule(RD->getDefinition()))
2240     return true;
2241 
2242   if (auto *ES = RD->getASTContext().getExternalSource())
2243     if (ES->hasExternalDefinitions(RD) == ExternalASTSource::EK_Always)
2244       return true;
2245 
2246   if (DebugKind > codegenoptions::LimitedDebugInfo)
2247     return false;
2248 
2249   if (!LangOpts.CPlusPlus)
2250     return false;
2251 
2252   if (!RD->isCompleteDefinitionRequired())
2253     return true;
2254 
2255   const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
2256 
2257   if (!CXXDecl)
2258     return false;
2259 
2260   // Only emit complete debug info for a dynamic class when its vtable is
2261   // emitted.  However, Microsoft debuggers don't resolve type information
2262   // across DLL boundaries, so skip this optimization if the class or any of its
2263   // methods are marked dllimport. This isn't a complete solution, since objects
2264   // without any dllimport methods can be used in one DLL and constructed in
2265   // another, but it is the current behavior of LimitedDebugInfo.
2266   if (CXXDecl->hasDefinition() && CXXDecl->isDynamicClass() &&
2267       !isClassOrMethodDLLImport(CXXDecl))
2268     return true;
2269 
2270   // In constructor debug mode, only emit debug info for a class when its
2271   // constructor is emitted. Skip this optimization if the class or any of
2272   // its methods are marked dllimport.
2273   if (DebugKind == codegenoptions::DebugInfoConstructor &&
2274       !CXXDecl->isLambda() && !CXXDecl->hasConstexprNonCopyMoveConstructor() &&
2275       !isClassOrMethodDLLImport(CXXDecl))
2276     for (const auto *Ctor : CXXDecl->ctors())
2277       if (Ctor->isUserProvided())
2278         return true;
2279 
2280   TemplateSpecializationKind Spec = TSK_Undeclared;
2281   if (const auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD))
2282     Spec = SD->getSpecializationKind();
2283 
2284   if (Spec == TSK_ExplicitInstantiationDeclaration &&
2285       hasExplicitMemberDefinition(CXXDecl->method_begin(),
2286                                   CXXDecl->method_end()))
2287     return true;
2288 
2289   return false;
2290 }
2291 
2292 void CGDebugInfo::completeRequiredType(const RecordDecl *RD) {
2293   if (shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD, CGM.getLangOpts()))
2294     return;
2295 
2296   QualType Ty = CGM.getContext().getRecordType(RD);
2297   llvm::DIType *T = getTypeOrNull(Ty);
2298   if (T && T->isForwardDecl())
2299     completeClassData(RD);
2300 }
2301 
2302 llvm::DIType *CGDebugInfo::CreateType(const RecordType *Ty) {
2303   RecordDecl *RD = Ty->getDecl();
2304   llvm::DIType *T = cast_or_null<llvm::DIType>(getTypeOrNull(QualType(Ty, 0)));
2305   if (T || shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD,
2306                                 CGM.getLangOpts())) {
2307     if (!T)
2308       T = getOrCreateRecordFwdDecl(Ty, getDeclContextDescriptor(RD));
2309     return T;
2310   }
2311 
2312   return CreateTypeDefinition(Ty);
2313 }
2314 
2315 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {
2316   RecordDecl *RD = Ty->getDecl();
2317 
2318   // Get overall information about the record type for the debug info.
2319   llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
2320 
2321   // Records and classes and unions can all be recursive.  To handle them, we
2322   // first generate a debug descriptor for the struct as a forward declaration.
2323   // Then (if it is a definition) we go through and get debug info for all of
2324   // its members.  Finally, we create a descriptor for the complete type (which
2325   // may refer to the forward decl if the struct is recursive) and replace all
2326   // uses of the forward declaration with the final definition.
2327   llvm::DICompositeType *FwdDecl = getOrCreateLimitedType(Ty, DefUnit);
2328 
2329   const RecordDecl *D = RD->getDefinition();
2330   if (!D || !D->isCompleteDefinition())
2331     return FwdDecl;
2332 
2333   if (const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
2334     CollectContainingType(CXXDecl, FwdDecl);
2335 
2336   // Push the struct on region stack.
2337   LexicalBlockStack.emplace_back(&*FwdDecl);
2338   RegionMap[Ty->getDecl()].reset(FwdDecl);
2339 
2340   // Convert all the elements.
2341   SmallVector<llvm::Metadata *, 16> EltTys;
2342   // what about nested types?
2343 
2344   // Note: The split of CXXDecl information here is intentional, the
2345   // gdb tests will depend on a certain ordering at printout. The debug
2346   // information offsets are still correct if we merge them all together
2347   // though.
2348   const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
2349   if (CXXDecl) {
2350     CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
2351     CollectVTableInfo(CXXDecl, DefUnit, EltTys, FwdDecl);
2352   }
2353 
2354   // Collect data fields (including static variables and any initializers).
2355   CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
2356   if (CXXDecl)
2357     CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
2358 
2359   LexicalBlockStack.pop_back();
2360   RegionMap.erase(Ty->getDecl());
2361 
2362   llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
2363   DBuilder.replaceArrays(FwdDecl, Elements);
2364 
2365   if (FwdDecl->isTemporary())
2366     FwdDecl =
2367         llvm::MDNode::replaceWithPermanent(llvm::TempDICompositeType(FwdDecl));
2368 
2369   RegionMap[Ty->getDecl()].reset(FwdDecl);
2370   return FwdDecl;
2371 }
2372 
2373 llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectType *Ty,
2374                                       llvm::DIFile *Unit) {
2375   // Ignore protocols.
2376   return getOrCreateType(Ty->getBaseType(), Unit);
2377 }
2378 
2379 llvm::DIType *CGDebugInfo::CreateType(const ObjCTypeParamType *Ty,
2380                                       llvm::DIFile *Unit) {
2381   // Ignore protocols.
2382   SourceLocation Loc = Ty->getDecl()->getLocation();
2383 
2384   // Use Typedefs to represent ObjCTypeParamType.
2385   return DBuilder.createTypedef(
2386       getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit),
2387       Ty->getDecl()->getName(), getOrCreateFile(Loc), getLineNumber(Loc),
2388       getDeclContextDescriptor(Ty->getDecl()));
2389 }
2390 
2391 /// \return true if Getter has the default name for the property PD.
2392 static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
2393                                  const ObjCMethodDecl *Getter) {
2394   assert(PD);
2395   if (!Getter)
2396     return true;
2397 
2398   assert(Getter->getDeclName().isObjCZeroArgSelector());
2399   return PD->getName() ==
2400          Getter->getDeclName().getObjCSelector().getNameForSlot(0);
2401 }
2402 
2403 /// \return true if Setter has the default name for the property PD.
2404 static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
2405                                  const ObjCMethodDecl *Setter) {
2406   assert(PD);
2407   if (!Setter)
2408     return true;
2409 
2410   assert(Setter->getDeclName().isObjCOneArgSelector());
2411   return SelectorTable::constructSetterName(PD->getName()) ==
2412          Setter->getDeclName().getObjCSelector().getNameForSlot(0);
2413 }
2414 
2415 llvm::DIType *CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
2416                                       llvm::DIFile *Unit) {
2417   ObjCInterfaceDecl *ID = Ty->getDecl();
2418   if (!ID)
2419     return nullptr;
2420 
2421   // Return a forward declaration if this type was imported from a clang module,
2422   // and this is not the compile unit with the implementation of the type (which
2423   // may contain hidden ivars).
2424   if (DebugTypeExtRefs && ID->isFromASTFile() && ID->getDefinition() &&
2425       !ID->getImplementation())
2426     return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
2427                                       ID->getName(),
2428                                       getDeclContextDescriptor(ID), Unit, 0);
2429 
2430   // Get overall information about the record type for the debug info.
2431   llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
2432   unsigned Line = getLineNumber(ID->getLocation());
2433   auto RuntimeLang =
2434       static_cast<llvm::dwarf::SourceLanguage>(TheCU->getSourceLanguage());
2435 
2436   // If this is just a forward declaration return a special forward-declaration
2437   // debug type since we won't be able to lay out the entire type.
2438   ObjCInterfaceDecl *Def = ID->getDefinition();
2439   if (!Def || !Def->getImplementation()) {
2440     llvm::DIScope *Mod = getParentModuleOrNull(ID);
2441     llvm::DIType *FwdDecl = DBuilder.createReplaceableCompositeType(
2442         llvm::dwarf::DW_TAG_structure_type, ID->getName(), Mod ? Mod : TheCU,
2443         DefUnit, Line, RuntimeLang);
2444     ObjCInterfaceCache.push_back(ObjCInterfaceCacheEntry(Ty, FwdDecl, Unit));
2445     return FwdDecl;
2446   }
2447 
2448   return CreateTypeDefinition(Ty, Unit);
2449 }
2450 
2451 llvm::DIModule *CGDebugInfo::getOrCreateModuleRef(ASTSourceDescriptor Mod,
2452                                                   bool CreateSkeletonCU) {
2453   // Use the Module pointer as the key into the cache. This is a
2454   // nullptr if the "Module" is a PCH, which is safe because we don't
2455   // support chained PCH debug info, so there can only be a single PCH.
2456   const Module *M = Mod.getModuleOrNull();
2457   auto ModRef = ModuleCache.find(M);
2458   if (ModRef != ModuleCache.end())
2459     return cast<llvm::DIModule>(ModRef->second);
2460 
2461   // Macro definitions that were defined with "-D" on the command line.
2462   SmallString<128> ConfigMacros;
2463   {
2464     llvm::raw_svector_ostream OS(ConfigMacros);
2465     const auto &PPOpts = CGM.getPreprocessorOpts();
2466     unsigned I = 0;
2467     // Translate the macro definitions back into a command line.
2468     for (auto &M : PPOpts.Macros) {
2469       if (++I > 1)
2470         OS << " ";
2471       const std::string &Macro = M.first;
2472       bool Undef = M.second;
2473       OS << "\"-" << (Undef ? 'U' : 'D');
2474       for (char c : Macro)
2475         switch (c) {
2476         case '\\':
2477           OS << "\\\\";
2478           break;
2479         case '"':
2480           OS << "\\\"";
2481           break;
2482         default:
2483           OS << c;
2484         }
2485       OS << '\"';
2486     }
2487   }
2488 
2489   bool IsRootModule = M ? !M->Parent : true;
2490   // When a module name is specified as -fmodule-name, that module gets a
2491   // clang::Module object, but it won't actually be built or imported; it will
2492   // be textual.
2493   if (CreateSkeletonCU && IsRootModule && Mod.getASTFile().empty() && M)
2494     assert(StringRef(M->Name).startswith(CGM.getLangOpts().ModuleName) &&
2495            "clang module without ASTFile must be specified by -fmodule-name");
2496 
2497   // Return a StringRef to the remapped Path.
2498   auto RemapPath = [this](StringRef Path) -> std::string {
2499     std::string Remapped = remapDIPath(Path);
2500     StringRef Relative(Remapped);
2501     StringRef CompDir = TheCU->getDirectory();
2502     if (Relative.consume_front(CompDir))
2503       Relative.consume_front(llvm::sys::path::get_separator());
2504 
2505     return Relative.str();
2506   };
2507 
2508   if (CreateSkeletonCU && IsRootModule && !Mod.getASTFile().empty()) {
2509     // PCH files don't have a signature field in the control block,
2510     // but LLVM detects skeleton CUs by looking for a non-zero DWO id.
2511     // We use the lower 64 bits for debug info.
2512     uint64_t Signature =
2513         Mod.getSignature()
2514             ? (uint64_t)Mod.getSignature()[1] << 32 | Mod.getSignature()[0]
2515             : ~1ULL;
2516     llvm::DIBuilder DIB(CGM.getModule());
2517     SmallString<0> PCM;
2518     if (!llvm::sys::path::is_absolute(Mod.getASTFile()))
2519       PCM = Mod.getPath();
2520     llvm::sys::path::append(PCM, Mod.getASTFile());
2521     DIB.createCompileUnit(
2522         TheCU->getSourceLanguage(),
2523         // TODO: Support "Source" from external AST providers?
2524         DIB.createFile(Mod.getModuleName(), TheCU->getDirectory()),
2525         TheCU->getProducer(), false, StringRef(), 0, RemapPath(PCM),
2526         llvm::DICompileUnit::FullDebug, Signature);
2527     DIB.finalize();
2528   }
2529 
2530   llvm::DIModule *Parent =
2531       IsRootModule ? nullptr
2532                    : getOrCreateModuleRef(ASTSourceDescriptor(*M->Parent),
2533                                           CreateSkeletonCU);
2534   std::string IncludePath = Mod.getPath().str();
2535   llvm::DIModule *DIMod =
2536       DBuilder.createModule(Parent, Mod.getModuleName(), ConfigMacros,
2537                             RemapPath(IncludePath));
2538   ModuleCache[M].reset(DIMod);
2539   return DIMod;
2540 }
2541 
2542 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const ObjCInterfaceType *Ty,
2543                                                 llvm::DIFile *Unit) {
2544   ObjCInterfaceDecl *ID = Ty->getDecl();
2545   llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
2546   unsigned Line = getLineNumber(ID->getLocation());
2547   unsigned RuntimeLang = TheCU->getSourceLanguage();
2548 
2549   // Bit size, align and offset of the type.
2550   uint64_t Size = CGM.getContext().getTypeSize(Ty);
2551   auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
2552 
2553   llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
2554   if (ID->getImplementation())
2555     Flags |= llvm::DINode::FlagObjcClassComplete;
2556 
2557   llvm::DIScope *Mod = getParentModuleOrNull(ID);
2558   llvm::DICompositeType *RealDecl = DBuilder.createStructType(
2559       Mod ? Mod : Unit, ID->getName(), DefUnit, Line, Size, Align, Flags,
2560       nullptr, llvm::DINodeArray(), RuntimeLang);
2561 
2562   QualType QTy(Ty, 0);
2563   TypeCache[QTy.getAsOpaquePtr()].reset(RealDecl);
2564 
2565   // Push the struct on region stack.
2566   LexicalBlockStack.emplace_back(RealDecl);
2567   RegionMap[Ty->getDecl()].reset(RealDecl);
2568 
2569   // Convert all the elements.
2570   SmallVector<llvm::Metadata *, 16> EltTys;
2571 
2572   ObjCInterfaceDecl *SClass = ID->getSuperClass();
2573   if (SClass) {
2574     llvm::DIType *SClassTy =
2575         getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
2576     if (!SClassTy)
2577       return nullptr;
2578 
2579     llvm::DIType *InhTag = DBuilder.createInheritance(RealDecl, SClassTy, 0, 0,
2580                                                       llvm::DINode::FlagZero);
2581     EltTys.push_back(InhTag);
2582   }
2583 
2584   // Create entries for all of the properties.
2585   auto AddProperty = [&](const ObjCPropertyDecl *PD) {
2586     SourceLocation Loc = PD->getLocation();
2587     llvm::DIFile *PUnit = getOrCreateFile(Loc);
2588     unsigned PLine = getLineNumber(Loc);
2589     ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
2590     ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
2591     llvm::MDNode *PropertyNode = DBuilder.createObjCProperty(
2592         PD->getName(), PUnit, PLine,
2593         hasDefaultGetterName(PD, Getter) ? ""
2594                                          : getSelectorName(PD->getGetterName()),
2595         hasDefaultSetterName(PD, Setter) ? ""
2596                                          : getSelectorName(PD->getSetterName()),
2597         PD->getPropertyAttributes(), getOrCreateType(PD->getType(), PUnit));
2598     EltTys.push_back(PropertyNode);
2599   };
2600   {
2601     llvm::SmallPtrSet<const IdentifierInfo *, 16> PropertySet;
2602     for (const ObjCCategoryDecl *ClassExt : ID->known_extensions())
2603       for (auto *PD : ClassExt->properties()) {
2604         PropertySet.insert(PD->getIdentifier());
2605         AddProperty(PD);
2606       }
2607     for (const auto *PD : ID->properties()) {
2608       // Don't emit duplicate metadata for properties that were already in a
2609       // class extension.
2610       if (!PropertySet.insert(PD->getIdentifier()).second)
2611         continue;
2612       AddProperty(PD);
2613     }
2614   }
2615 
2616   const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
2617   unsigned FieldNo = 0;
2618   for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
2619        Field = Field->getNextIvar(), ++FieldNo) {
2620     llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
2621     if (!FieldTy)
2622       return nullptr;
2623 
2624     StringRef FieldName = Field->getName();
2625 
2626     // Ignore unnamed fields.
2627     if (FieldName.empty())
2628       continue;
2629 
2630     // Get the location for the field.
2631     llvm::DIFile *FieldDefUnit = getOrCreateFile(Field->getLocation());
2632     unsigned FieldLine = getLineNumber(Field->getLocation());
2633     QualType FType = Field->getType();
2634     uint64_t FieldSize = 0;
2635     uint32_t FieldAlign = 0;
2636 
2637     if (!FType->isIncompleteArrayType()) {
2638 
2639       // Bit size, align and offset of the type.
2640       FieldSize = Field->isBitField()
2641                       ? Field->getBitWidthValue(CGM.getContext())
2642                       : CGM.getContext().getTypeSize(FType);
2643       FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext());
2644     }
2645 
2646     uint64_t FieldOffset;
2647     if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
2648       // We don't know the runtime offset of an ivar if we're using the
2649       // non-fragile ABI.  For bitfields, use the bit offset into the first
2650       // byte of storage of the bitfield.  For other fields, use zero.
2651       if (Field->isBitField()) {
2652         FieldOffset =
2653             CGM.getObjCRuntime().ComputeBitfieldBitOffset(CGM, ID, Field);
2654         FieldOffset %= CGM.getContext().getCharWidth();
2655       } else {
2656         FieldOffset = 0;
2657       }
2658     } else {
2659       FieldOffset = RL.getFieldOffset(FieldNo);
2660     }
2661 
2662     llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
2663     if (Field->getAccessControl() == ObjCIvarDecl::Protected)
2664       Flags = llvm::DINode::FlagProtected;
2665     else if (Field->getAccessControl() == ObjCIvarDecl::Private)
2666       Flags = llvm::DINode::FlagPrivate;
2667     else if (Field->getAccessControl() == ObjCIvarDecl::Public)
2668       Flags = llvm::DINode::FlagPublic;
2669 
2670     llvm::MDNode *PropertyNode = nullptr;
2671     if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
2672       if (ObjCPropertyImplDecl *PImpD =
2673               ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
2674         if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
2675           SourceLocation Loc = PD->getLocation();
2676           llvm::DIFile *PUnit = getOrCreateFile(Loc);
2677           unsigned PLine = getLineNumber(Loc);
2678           ObjCMethodDecl *Getter = PImpD->getGetterMethodDecl();
2679           ObjCMethodDecl *Setter = PImpD->getSetterMethodDecl();
2680           PropertyNode = DBuilder.createObjCProperty(
2681               PD->getName(), PUnit, PLine,
2682               hasDefaultGetterName(PD, Getter)
2683                   ? ""
2684                   : getSelectorName(PD->getGetterName()),
2685               hasDefaultSetterName(PD, Setter)
2686                   ? ""
2687                   : getSelectorName(PD->getSetterName()),
2688               PD->getPropertyAttributes(),
2689               getOrCreateType(PD->getType(), PUnit));
2690         }
2691       }
2692     }
2693     FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit, FieldLine,
2694                                       FieldSize, FieldAlign, FieldOffset, Flags,
2695                                       FieldTy, PropertyNode);
2696     EltTys.push_back(FieldTy);
2697   }
2698 
2699   llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
2700   DBuilder.replaceArrays(RealDecl, Elements);
2701 
2702   LexicalBlockStack.pop_back();
2703   return RealDecl;
2704 }
2705 
2706 llvm::DIType *CGDebugInfo::CreateType(const VectorType *Ty,
2707                                       llvm::DIFile *Unit) {
2708   llvm::DIType *ElementTy = getOrCreateType(Ty->getElementType(), Unit);
2709   int64_t Count = Ty->getNumElements();
2710 
2711   llvm::Metadata *Subscript;
2712   QualType QTy(Ty, 0);
2713   auto SizeExpr = SizeExprCache.find(QTy);
2714   if (SizeExpr != SizeExprCache.end())
2715     Subscript = DBuilder.getOrCreateSubrange(0, SizeExpr->getSecond());
2716   else
2717     Subscript = DBuilder.getOrCreateSubrange(0, Count ? Count : -1);
2718   llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
2719 
2720   uint64_t Size = CGM.getContext().getTypeSize(Ty);
2721   auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
2722 
2723   return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
2724 }
2725 
2726 llvm::DIType *CGDebugInfo::CreateType(const ArrayType *Ty, llvm::DIFile *Unit) {
2727   uint64_t Size;
2728   uint32_t Align;
2729 
2730   // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
2731   if (const auto *VAT = dyn_cast<VariableArrayType>(Ty)) {
2732     Size = 0;
2733     Align = getTypeAlignIfRequired(CGM.getContext().getBaseElementType(VAT),
2734                                    CGM.getContext());
2735   } else if (Ty->isIncompleteArrayType()) {
2736     Size = 0;
2737     if (Ty->getElementType()->isIncompleteType())
2738       Align = 0;
2739     else
2740       Align = getTypeAlignIfRequired(Ty->getElementType(), CGM.getContext());
2741   } else if (Ty->isIncompleteType()) {
2742     Size = 0;
2743     Align = 0;
2744   } else {
2745     // Size and align of the whole array, not the element type.
2746     Size = CGM.getContext().getTypeSize(Ty);
2747     Align = getTypeAlignIfRequired(Ty, CGM.getContext());
2748   }
2749 
2750   // Add the dimensions of the array.  FIXME: This loses CV qualifiers from
2751   // interior arrays, do we care?  Why aren't nested arrays represented the
2752   // obvious/recursive way?
2753   SmallVector<llvm::Metadata *, 8> Subscripts;
2754   QualType EltTy(Ty, 0);
2755   while ((Ty = dyn_cast<ArrayType>(EltTy))) {
2756     // If the number of elements is known, then count is that number. Otherwise,
2757     // it's -1. This allows us to represent a subrange with an array of 0
2758     // elements, like this:
2759     //
2760     //   struct foo {
2761     //     int x[0];
2762     //   };
2763     int64_t Count = -1; // Count == -1 is an unbounded array.
2764     if (const auto *CAT = dyn_cast<ConstantArrayType>(Ty))
2765       Count = CAT->getSize().getZExtValue();
2766     else if (const auto *VAT = dyn_cast<VariableArrayType>(Ty)) {
2767       if (Expr *Size = VAT->getSizeExpr()) {
2768         Expr::EvalResult Result;
2769         if (Size->EvaluateAsInt(Result, CGM.getContext()))
2770           Count = Result.Val.getInt().getExtValue();
2771       }
2772     }
2773 
2774     auto SizeNode = SizeExprCache.find(EltTy);
2775     if (SizeNode != SizeExprCache.end())
2776       Subscripts.push_back(
2777           DBuilder.getOrCreateSubrange(0, SizeNode->getSecond()));
2778     else
2779       Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
2780     EltTy = Ty->getElementType();
2781   }
2782 
2783   llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
2784 
2785   return DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
2786                                   SubscriptArray);
2787 }
2788 
2789 llvm::DIType *CGDebugInfo::CreateType(const LValueReferenceType *Ty,
2790                                       llvm::DIFile *Unit) {
2791   return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type, Ty,
2792                                Ty->getPointeeType(), Unit);
2793 }
2794 
2795 llvm::DIType *CGDebugInfo::CreateType(const RValueReferenceType *Ty,
2796                                       llvm::DIFile *Unit) {
2797   return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type, Ty,
2798                                Ty->getPointeeType(), Unit);
2799 }
2800 
2801 llvm::DIType *CGDebugInfo::CreateType(const MemberPointerType *Ty,
2802                                       llvm::DIFile *U) {
2803   llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
2804   uint64_t Size = 0;
2805 
2806   if (!Ty->isIncompleteType()) {
2807     Size = CGM.getContext().getTypeSize(Ty);
2808 
2809     // Set the MS inheritance model. There is no flag for the unspecified model.
2810     if (CGM.getTarget().getCXXABI().isMicrosoft()) {
2811       switch (Ty->getMostRecentCXXRecordDecl()->getMSInheritanceModel()) {
2812       case MSInheritanceModel::Single:
2813         Flags |= llvm::DINode::FlagSingleInheritance;
2814         break;
2815       case MSInheritanceModel::Multiple:
2816         Flags |= llvm::DINode::FlagMultipleInheritance;
2817         break;
2818       case MSInheritanceModel::Virtual:
2819         Flags |= llvm::DINode::FlagVirtualInheritance;
2820         break;
2821       case MSInheritanceModel::Unspecified:
2822         break;
2823       }
2824     }
2825   }
2826 
2827   llvm::DIType *ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
2828   if (Ty->isMemberDataPointerType())
2829     return DBuilder.createMemberPointerType(
2830         getOrCreateType(Ty->getPointeeType(), U), ClassType, Size, /*Align=*/0,
2831         Flags);
2832 
2833   const FunctionProtoType *FPT =
2834       Ty->getPointeeType()->getAs<FunctionProtoType>();
2835   return DBuilder.createMemberPointerType(
2836       getOrCreateInstanceMethodType(
2837           CXXMethodDecl::getThisType(FPT, Ty->getMostRecentCXXRecordDecl()),
2838           FPT, U, false),
2839       ClassType, Size, /*Align=*/0, Flags);
2840 }
2841 
2842 llvm::DIType *CGDebugInfo::CreateType(const AtomicType *Ty, llvm::DIFile *U) {
2843   auto *FromTy = getOrCreateType(Ty->getValueType(), U);
2844   return DBuilder.createQualifiedType(llvm::dwarf::DW_TAG_atomic_type, FromTy);
2845 }
2846 
2847 llvm::DIType *CGDebugInfo::CreateType(const PipeType *Ty, llvm::DIFile *U) {
2848   return getOrCreateType(Ty->getElementType(), U);
2849 }
2850 
2851 llvm::DIType *CGDebugInfo::CreateEnumType(const EnumType *Ty) {
2852   const EnumDecl *ED = Ty->getDecl();
2853 
2854   uint64_t Size = 0;
2855   uint32_t Align = 0;
2856   if (!ED->getTypeForDecl()->isIncompleteType()) {
2857     Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
2858     Align = getDeclAlignIfRequired(ED, CGM.getContext());
2859   }
2860 
2861   SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
2862 
2863   bool isImportedFromModule =
2864       DebugTypeExtRefs && ED->isFromASTFile() && ED->getDefinition();
2865 
2866   // If this is just a forward declaration, construct an appropriately
2867   // marked node and just return it.
2868   if (isImportedFromModule || !ED->getDefinition()) {
2869     // Note that it is possible for enums to be created as part of
2870     // their own declcontext. In this case a FwdDecl will be created
2871     // twice. This doesn't cause a problem because both FwdDecls are
2872     // entered into the ReplaceMap: finalize() will replace the first
2873     // FwdDecl with the second and then replace the second with
2874     // complete type.
2875     llvm::DIScope *EDContext = getDeclContextDescriptor(ED);
2876     llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
2877     llvm::TempDIScope TmpContext(DBuilder.createReplaceableCompositeType(
2878         llvm::dwarf::DW_TAG_enumeration_type, "", TheCU, DefUnit, 0));
2879 
2880     unsigned Line = getLineNumber(ED->getLocation());
2881     StringRef EDName = ED->getName();
2882     llvm::DIType *RetTy = DBuilder.createReplaceableCompositeType(
2883         llvm::dwarf::DW_TAG_enumeration_type, EDName, EDContext, DefUnit, Line,
2884         0, Size, Align, llvm::DINode::FlagFwdDecl, Identifier);
2885 
2886     ReplaceMap.emplace_back(
2887         std::piecewise_construct, std::make_tuple(Ty),
2888         std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
2889     return RetTy;
2890   }
2891 
2892   return CreateTypeDefinition(Ty);
2893 }
2894 
2895 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const EnumType *Ty) {
2896   const EnumDecl *ED = Ty->getDecl();
2897   uint64_t Size = 0;
2898   uint32_t Align = 0;
2899   if (!ED->getTypeForDecl()->isIncompleteType()) {
2900     Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
2901     Align = getDeclAlignIfRequired(ED, CGM.getContext());
2902   }
2903 
2904   SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
2905 
2906   // Create elements for each enumerator.
2907   SmallVector<llvm::Metadata *, 16> Enumerators;
2908   ED = ED->getDefinition();
2909   bool IsSigned = ED->getIntegerType()->isSignedIntegerType();
2910   for (const auto *Enum : ED->enumerators()) {
2911     const auto &InitVal = Enum->getInitVal();
2912     auto Value = IsSigned ? InitVal.getSExtValue() : InitVal.getZExtValue();
2913     Enumerators.push_back(
2914         DBuilder.createEnumerator(Enum->getName(), Value, !IsSigned));
2915   }
2916 
2917   // Return a CompositeType for the enum itself.
2918   llvm::DINodeArray EltArray = DBuilder.getOrCreateArray(Enumerators);
2919 
2920   llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
2921   unsigned Line = getLineNumber(ED->getLocation());
2922   llvm::DIScope *EnumContext = getDeclContextDescriptor(ED);
2923   llvm::DIType *ClassTy = getOrCreateType(ED->getIntegerType(), DefUnit);
2924   return DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit,
2925                                         Line, Size, Align, EltArray, ClassTy,
2926                                         Identifier, ED->isScoped());
2927 }
2928 
2929 llvm::DIMacro *CGDebugInfo::CreateMacro(llvm::DIMacroFile *Parent,
2930                                         unsigned MType, SourceLocation LineLoc,
2931                                         StringRef Name, StringRef Value) {
2932   unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(LineLoc);
2933   return DBuilder.createMacro(Parent, Line, MType, Name, Value);
2934 }
2935 
2936 llvm::DIMacroFile *CGDebugInfo::CreateTempMacroFile(llvm::DIMacroFile *Parent,
2937                                                     SourceLocation LineLoc,
2938                                                     SourceLocation FileLoc) {
2939   llvm::DIFile *FName = getOrCreateFile(FileLoc);
2940   unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(LineLoc);
2941   return DBuilder.createTempMacroFile(Parent, Line, FName);
2942 }
2943 
2944 static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
2945   Qualifiers Quals;
2946   do {
2947     Qualifiers InnerQuals = T.getLocalQualifiers();
2948     // Qualifiers::operator+() doesn't like it if you add a Qualifier
2949     // that is already there.
2950     Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals);
2951     Quals += InnerQuals;
2952     QualType LastT = T;
2953     switch (T->getTypeClass()) {
2954     default:
2955       return C.getQualifiedType(T.getTypePtr(), Quals);
2956     case Type::TemplateSpecialization: {
2957       const auto *Spec = cast<TemplateSpecializationType>(T);
2958       if (Spec->isTypeAlias())
2959         return C.getQualifiedType(T.getTypePtr(), Quals);
2960       T = Spec->desugar();
2961       break;
2962     }
2963     case Type::TypeOfExpr:
2964       T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
2965       break;
2966     case Type::TypeOf:
2967       T = cast<TypeOfType>(T)->getUnderlyingType();
2968       break;
2969     case Type::Decltype:
2970       T = cast<DecltypeType>(T)->getUnderlyingType();
2971       break;
2972     case Type::UnaryTransform:
2973       T = cast<UnaryTransformType>(T)->getUnderlyingType();
2974       break;
2975     case Type::Attributed:
2976       T = cast<AttributedType>(T)->getEquivalentType();
2977       break;
2978     case Type::Elaborated:
2979       T = cast<ElaboratedType>(T)->getNamedType();
2980       break;
2981     case Type::Paren:
2982       T = cast<ParenType>(T)->getInnerType();
2983       break;
2984     case Type::MacroQualified:
2985       T = cast<MacroQualifiedType>(T)->getUnderlyingType();
2986       break;
2987     case Type::SubstTemplateTypeParm:
2988       T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
2989       break;
2990     case Type::Auto:
2991     case Type::DeducedTemplateSpecialization: {
2992       QualType DT = cast<DeducedType>(T)->getDeducedType();
2993       assert(!DT.isNull() && "Undeduced types shouldn't reach here.");
2994       T = DT;
2995       break;
2996     }
2997     case Type::Adjusted:
2998     case Type::Decayed:
2999       // Decayed and adjusted types use the adjusted type in LLVM and DWARF.
3000       T = cast<AdjustedType>(T)->getAdjustedType();
3001       break;
3002     }
3003 
3004     assert(T != LastT && "Type unwrapping failed to unwrap!");
3005     (void)LastT;
3006   } while (true);
3007 }
3008 
3009 llvm::DIType *CGDebugInfo::getTypeOrNull(QualType Ty) {
3010 
3011   // Unwrap the type as needed for debug information.
3012   Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
3013 
3014   auto It = TypeCache.find(Ty.getAsOpaquePtr());
3015   if (It != TypeCache.end()) {
3016     // Verify that the debug info still exists.
3017     if (llvm::Metadata *V = It->second)
3018       return cast<llvm::DIType>(V);
3019   }
3020 
3021   return nullptr;
3022 }
3023 
3024 void CGDebugInfo::completeTemplateDefinition(
3025     const ClassTemplateSpecializationDecl &SD) {
3026   if (DebugKind <= codegenoptions::DebugLineTablesOnly)
3027     return;
3028   completeUnusedClass(SD);
3029 }
3030 
3031 void CGDebugInfo::completeUnusedClass(const CXXRecordDecl &D) {
3032   if (DebugKind <= codegenoptions::DebugLineTablesOnly)
3033     return;
3034 
3035   completeClassData(&D);
3036   // In case this type has no member function definitions being emitted, ensure
3037   // it is retained
3038   RetainedTypes.push_back(CGM.getContext().getRecordType(&D).getAsOpaquePtr());
3039 }
3040 
3041 llvm::DIType *CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile *Unit) {
3042   if (Ty.isNull())
3043     return nullptr;
3044 
3045   llvm::TimeTraceScope TimeScope("DebugType", [&]() {
3046     std::string Name;
3047     llvm::raw_string_ostream OS(Name);
3048     Ty.print(OS, getPrintingPolicy());
3049     return Name;
3050   });
3051 
3052   // Unwrap the type as needed for debug information.
3053   Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
3054 
3055   if (auto *T = getTypeOrNull(Ty))
3056     return T;
3057 
3058   llvm::DIType *Res = CreateTypeNode(Ty, Unit);
3059   void *TyPtr = Ty.getAsOpaquePtr();
3060 
3061   // And update the type cache.
3062   TypeCache[TyPtr].reset(Res);
3063 
3064   return Res;
3065 }
3066 
3067 llvm::DIModule *CGDebugInfo::getParentModuleOrNull(const Decl *D) {
3068   // A forward declaration inside a module header does not belong to the module.
3069   if (isa<RecordDecl>(D) && !cast<RecordDecl>(D)->getDefinition())
3070     return nullptr;
3071   if (DebugTypeExtRefs && D->isFromASTFile()) {
3072     // Record a reference to an imported clang module or precompiled header.
3073     auto *Reader = CGM.getContext().getExternalSource();
3074     auto Idx = D->getOwningModuleID();
3075     auto Info = Reader->getSourceDescriptor(Idx);
3076     if (Info)
3077       return getOrCreateModuleRef(*Info, /*SkeletonCU=*/true);
3078   } else if (ClangModuleMap) {
3079     // We are building a clang module or a precompiled header.
3080     //
3081     // TODO: When D is a CXXRecordDecl or a C++ Enum, the ODR applies
3082     // and it wouldn't be necessary to specify the parent scope
3083     // because the type is already unique by definition (it would look
3084     // like the output of -fno-standalone-debug). On the other hand,
3085     // the parent scope helps a consumer to quickly locate the object
3086     // file where the type's definition is located, so it might be
3087     // best to make this behavior a command line or debugger tuning
3088     // option.
3089     if (Module *M = D->getOwningModule()) {
3090       // This is a (sub-)module.
3091       auto Info = ASTSourceDescriptor(*M);
3092       return getOrCreateModuleRef(Info, /*SkeletonCU=*/false);
3093     } else {
3094       // This the precompiled header being built.
3095       return getOrCreateModuleRef(PCHDescriptor, /*SkeletonCU=*/false);
3096     }
3097   }
3098 
3099   return nullptr;
3100 }
3101 
3102 llvm::DIType *CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile *Unit) {
3103   // Handle qualifiers, which recursively handles what they refer to.
3104   if (Ty.hasLocalQualifiers())
3105     return CreateQualifiedType(Ty, Unit);
3106 
3107   // Work out details of type.
3108   switch (Ty->getTypeClass()) {
3109 #define TYPE(Class, Base)
3110 #define ABSTRACT_TYPE(Class, Base)
3111 #define NON_CANONICAL_TYPE(Class, Base)
3112 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3113 #include "clang/AST/TypeNodes.inc"
3114     llvm_unreachable("Dependent types cannot show up in debug information");
3115 
3116   case Type::ExtVector:
3117   case Type::Vector:
3118     return CreateType(cast<VectorType>(Ty), Unit);
3119   case Type::ObjCObjectPointer:
3120     return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
3121   case Type::ObjCObject:
3122     return CreateType(cast<ObjCObjectType>(Ty), Unit);
3123   case Type::ObjCTypeParam:
3124     return CreateType(cast<ObjCTypeParamType>(Ty), Unit);
3125   case Type::ObjCInterface:
3126     return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
3127   case Type::Builtin:
3128     return CreateType(cast<BuiltinType>(Ty));
3129   case Type::Complex:
3130     return CreateType(cast<ComplexType>(Ty));
3131   case Type::Pointer:
3132     return CreateType(cast<PointerType>(Ty), Unit);
3133   case Type::BlockPointer:
3134     return CreateType(cast<BlockPointerType>(Ty), Unit);
3135   case Type::Typedef:
3136     return CreateType(cast<TypedefType>(Ty), Unit);
3137   case Type::Record:
3138     return CreateType(cast<RecordType>(Ty));
3139   case Type::Enum:
3140     return CreateEnumType(cast<EnumType>(Ty));
3141   case Type::FunctionProto:
3142   case Type::FunctionNoProto:
3143     return CreateType(cast<FunctionType>(Ty), Unit);
3144   case Type::ConstantArray:
3145   case Type::VariableArray:
3146   case Type::IncompleteArray:
3147     return CreateType(cast<ArrayType>(Ty), Unit);
3148 
3149   case Type::LValueReference:
3150     return CreateType(cast<LValueReferenceType>(Ty), Unit);
3151   case Type::RValueReference:
3152     return CreateType(cast<RValueReferenceType>(Ty), Unit);
3153 
3154   case Type::MemberPointer:
3155     return CreateType(cast<MemberPointerType>(Ty), Unit);
3156 
3157   case Type::Atomic:
3158     return CreateType(cast<AtomicType>(Ty), Unit);
3159 
3160   case Type::Pipe:
3161     return CreateType(cast<PipeType>(Ty), Unit);
3162 
3163   case Type::TemplateSpecialization:
3164     return CreateType(cast<TemplateSpecializationType>(Ty), Unit);
3165 
3166   case Type::Auto:
3167   case Type::Attributed:
3168   case Type::Adjusted:
3169   case Type::Decayed:
3170   case Type::DeducedTemplateSpecialization:
3171   case Type::Elaborated:
3172   case Type::Paren:
3173   case Type::MacroQualified:
3174   case Type::SubstTemplateTypeParm:
3175   case Type::TypeOfExpr:
3176   case Type::TypeOf:
3177   case Type::Decltype:
3178   case Type::UnaryTransform:
3179   case Type::PackExpansion:
3180     break;
3181   }
3182 
3183   llvm_unreachable("type should have been unwrapped!");
3184 }
3185 
3186 llvm::DICompositeType *CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty,
3187                                                            llvm::DIFile *Unit) {
3188   QualType QTy(Ty, 0);
3189 
3190   auto *T = cast_or_null<llvm::DICompositeType>(getTypeOrNull(QTy));
3191 
3192   // We may have cached a forward decl when we could have created
3193   // a non-forward decl. Go ahead and create a non-forward decl
3194   // now.
3195   if (T && !T->isForwardDecl())
3196     return T;
3197 
3198   // Otherwise create the type.
3199   llvm::DICompositeType *Res = CreateLimitedType(Ty);
3200 
3201   // Propagate members from the declaration to the definition
3202   // CreateType(const RecordType*) will overwrite this with the members in the
3203   // correct order if the full type is needed.
3204   DBuilder.replaceArrays(Res, T ? T->getElements() : llvm::DINodeArray());
3205 
3206   // And update the type cache.
3207   TypeCache[QTy.getAsOpaquePtr()].reset(Res);
3208   return Res;
3209 }
3210 
3211 // TODO: Currently used for context chains when limiting debug info.
3212 llvm::DICompositeType *CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
3213   RecordDecl *RD = Ty->getDecl();
3214 
3215   // Get overall information about the record type for the debug info.
3216   llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
3217   unsigned Line = getLineNumber(RD->getLocation());
3218   StringRef RDName = getClassName(RD);
3219 
3220   llvm::DIScope *RDContext = getDeclContextDescriptor(RD);
3221 
3222   // If we ended up creating the type during the context chain construction,
3223   // just return that.
3224   auto *T = cast_or_null<llvm::DICompositeType>(
3225       getTypeOrNull(CGM.getContext().getRecordType(RD)));
3226   if (T && (!T->isForwardDecl() || !RD->getDefinition()))
3227     return T;
3228 
3229   // If this is just a forward or incomplete declaration, construct an
3230   // appropriately marked node and just return it.
3231   const RecordDecl *D = RD->getDefinition();
3232   if (!D || !D->isCompleteDefinition())
3233     return getOrCreateRecordFwdDecl(Ty, RDContext);
3234 
3235   uint64_t Size = CGM.getContext().getTypeSize(Ty);
3236   auto Align = getDeclAlignIfRequired(D, CGM.getContext());
3237 
3238   SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
3239 
3240   // Explicitly record the calling convention and export symbols for C++
3241   // records.
3242   auto Flags = llvm::DINode::FlagZero;
3243   if (auto CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3244     if (CGM.getCXXABI().getRecordArgABI(CXXRD) == CGCXXABI::RAA_Indirect)
3245       Flags |= llvm::DINode::FlagTypePassByReference;
3246     else
3247       Flags |= llvm::DINode::FlagTypePassByValue;
3248 
3249     // Record if a C++ record is non-trivial type.
3250     if (!CXXRD->isTrivial())
3251       Flags |= llvm::DINode::FlagNonTrivial;
3252 
3253     // Record exports it symbols to the containing structure.
3254     if (CXXRD->isAnonymousStructOrUnion())
3255         Flags |= llvm::DINode::FlagExportSymbols;
3256   }
3257 
3258   llvm::DICompositeType *RealDecl = DBuilder.createReplaceableCompositeType(
3259       getTagForRecord(RD), RDName, RDContext, DefUnit, Line, 0, Size, Align,
3260       Flags, Identifier);
3261 
3262   // Elements of composite types usually have back to the type, creating
3263   // uniquing cycles.  Distinct nodes are more efficient.
3264   switch (RealDecl->getTag()) {
3265   default:
3266     llvm_unreachable("invalid composite type tag");
3267 
3268   case llvm::dwarf::DW_TAG_array_type:
3269   case llvm::dwarf::DW_TAG_enumeration_type:
3270     // Array elements and most enumeration elements don't have back references,
3271     // so they don't tend to be involved in uniquing cycles and there is some
3272     // chance of merging them when linking together two modules.  Only make
3273     // them distinct if they are ODR-uniqued.
3274     if (Identifier.empty())
3275       break;
3276     LLVM_FALLTHROUGH;
3277 
3278   case llvm::dwarf::DW_TAG_structure_type:
3279   case llvm::dwarf::DW_TAG_union_type:
3280   case llvm::dwarf::DW_TAG_class_type:
3281     // Immediately resolve to a distinct node.
3282     RealDecl =
3283         llvm::MDNode::replaceWithDistinct(llvm::TempDICompositeType(RealDecl));
3284     break;
3285   }
3286 
3287   RegionMap[Ty->getDecl()].reset(RealDecl);
3288   TypeCache[QualType(Ty, 0).getAsOpaquePtr()].reset(RealDecl);
3289 
3290   if (const auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD))
3291     DBuilder.replaceArrays(RealDecl, llvm::DINodeArray(),
3292                            CollectCXXTemplateParams(TSpecial, DefUnit));
3293   return RealDecl;
3294 }
3295 
3296 void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,
3297                                         llvm::DICompositeType *RealDecl) {
3298   // A class's primary base or the class itself contains the vtable.
3299   llvm::DICompositeType *ContainingType = nullptr;
3300   const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
3301   if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
3302     // Seek non-virtual primary base root.
3303     while (1) {
3304       const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
3305       const CXXRecordDecl *PBT = BRL.getPrimaryBase();
3306       if (PBT && !BRL.isPrimaryBaseVirtual())
3307         PBase = PBT;
3308       else
3309         break;
3310     }
3311     ContainingType = cast<llvm::DICompositeType>(
3312         getOrCreateType(QualType(PBase->getTypeForDecl(), 0),
3313                         getOrCreateFile(RD->getLocation())));
3314   } else if (RD->isDynamicClass())
3315     ContainingType = RealDecl;
3316 
3317   DBuilder.replaceVTableHolder(RealDecl, ContainingType);
3318 }
3319 
3320 llvm::DIType *CGDebugInfo::CreateMemberType(llvm::DIFile *Unit, QualType FType,
3321                                             StringRef Name, uint64_t *Offset) {
3322   llvm::DIType *FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
3323   uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
3324   auto FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext());
3325   llvm::DIType *Ty =
3326       DBuilder.createMemberType(Unit, Name, Unit, 0, FieldSize, FieldAlign,
3327                                 *Offset, llvm::DINode::FlagZero, FieldTy);
3328   *Offset += FieldSize;
3329   return Ty;
3330 }
3331 
3332 void CGDebugInfo::collectFunctionDeclProps(GlobalDecl GD, llvm::DIFile *Unit,
3333                                            StringRef &Name,
3334                                            StringRef &LinkageName,
3335                                            llvm::DIScope *&FDContext,
3336                                            llvm::DINodeArray &TParamsArray,
3337                                            llvm::DINode::DIFlags &Flags) {
3338   const auto *FD = cast<FunctionDecl>(GD.getDecl());
3339   Name = getFunctionName(FD);
3340   // Use mangled name as linkage name for C/C++ functions.
3341   if (FD->hasPrototype()) {
3342     LinkageName = CGM.getMangledName(GD);
3343     Flags |= llvm::DINode::FlagPrototyped;
3344   }
3345   // No need to replicate the linkage name if it isn't different from the
3346   // subprogram name, no need to have it at all unless coverage is enabled or
3347   // debug is set to more than just line tables or extra debug info is needed.
3348   if (LinkageName == Name || (!CGM.getCodeGenOpts().EmitGcovArcs &&
3349                               !CGM.getCodeGenOpts().EmitGcovNotes &&
3350                               !CGM.getCodeGenOpts().DebugInfoForProfiling &&
3351                               DebugKind <= codegenoptions::DebugLineTablesOnly))
3352     LinkageName = StringRef();
3353 
3354   if (CGM.getCodeGenOpts().hasReducedDebugInfo()) {
3355     if (const NamespaceDecl *NSDecl =
3356             dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
3357       FDContext = getOrCreateNamespace(NSDecl);
3358     else if (const RecordDecl *RDecl =
3359                  dyn_cast_or_null<RecordDecl>(FD->getDeclContext())) {
3360       llvm::DIScope *Mod = getParentModuleOrNull(RDecl);
3361       FDContext = getContextDescriptor(RDecl, Mod ? Mod : TheCU);
3362     }
3363     // Check if it is a noreturn-marked function
3364     if (FD->isNoReturn())
3365       Flags |= llvm::DINode::FlagNoReturn;
3366     // Collect template parameters.
3367     TParamsArray = CollectFunctionTemplateParams(FD, Unit);
3368   }
3369 }
3370 
3371 void CGDebugInfo::collectVarDeclProps(const VarDecl *VD, llvm::DIFile *&Unit,
3372                                       unsigned &LineNo, QualType &T,
3373                                       StringRef &Name, StringRef &LinkageName,
3374                                       llvm::MDTuple *&TemplateParameters,
3375                                       llvm::DIScope *&VDContext) {
3376   Unit = getOrCreateFile(VD->getLocation());
3377   LineNo = getLineNumber(VD->getLocation());
3378 
3379   setLocation(VD->getLocation());
3380 
3381   T = VD->getType();
3382   if (T->isIncompleteArrayType()) {
3383     // CodeGen turns int[] into int[1] so we'll do the same here.
3384     llvm::APInt ConstVal(32, 1);
3385     QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3386 
3387     T = CGM.getContext().getConstantArrayType(ET, ConstVal, nullptr,
3388                                               ArrayType::Normal, 0);
3389   }
3390 
3391   Name = VD->getName();
3392   if (VD->getDeclContext() && !isa<FunctionDecl>(VD->getDeclContext()) &&
3393       !isa<ObjCMethodDecl>(VD->getDeclContext()))
3394     LinkageName = CGM.getMangledName(VD);
3395   if (LinkageName == Name)
3396     LinkageName = StringRef();
3397 
3398   if (isa<VarTemplateSpecializationDecl>(VD)) {
3399     llvm::DINodeArray parameterNodes = CollectVarTemplateParams(VD, &*Unit);
3400     TemplateParameters = parameterNodes.get();
3401   } else {
3402     TemplateParameters = nullptr;
3403   }
3404 
3405   // Since we emit declarations (DW_AT_members) for static members, place the
3406   // definition of those static members in the namespace they were declared in
3407   // in the source code (the lexical decl context).
3408   // FIXME: Generalize this for even non-member global variables where the
3409   // declaration and definition may have different lexical decl contexts, once
3410   // we have support for emitting declarations of (non-member) global variables.
3411   const DeclContext *DC = VD->isStaticDataMember() ? VD->getLexicalDeclContext()
3412                                                    : VD->getDeclContext();
3413   // When a record type contains an in-line initialization of a static data
3414   // member, and the record type is marked as __declspec(dllexport), an implicit
3415   // definition of the member will be created in the record context.  DWARF
3416   // doesn't seem to have a nice way to describe this in a form that consumers
3417   // are likely to understand, so fake the "normal" situation of a definition
3418   // outside the class by putting it in the global scope.
3419   if (DC->isRecord())
3420     DC = CGM.getContext().getTranslationUnitDecl();
3421 
3422   llvm::DIScope *Mod = getParentModuleOrNull(VD);
3423   VDContext = getContextDescriptor(cast<Decl>(DC), Mod ? Mod : TheCU);
3424 }
3425 
3426 llvm::DISubprogram *CGDebugInfo::getFunctionFwdDeclOrStub(GlobalDecl GD,
3427                                                           bool Stub) {
3428   llvm::DINodeArray TParamsArray;
3429   StringRef Name, LinkageName;
3430   llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3431   llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
3432   SourceLocation Loc = GD.getDecl()->getLocation();
3433   llvm::DIFile *Unit = getOrCreateFile(Loc);
3434   llvm::DIScope *DContext = Unit;
3435   unsigned Line = getLineNumber(Loc);
3436   collectFunctionDeclProps(GD, Unit, Name, LinkageName, DContext, TParamsArray,
3437                            Flags);
3438   auto *FD = cast<FunctionDecl>(GD.getDecl());
3439 
3440   // Build function type.
3441   SmallVector<QualType, 16> ArgTypes;
3442   for (const ParmVarDecl *Parm : FD->parameters())
3443     ArgTypes.push_back(Parm->getType());
3444 
3445   CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
3446   QualType FnType = CGM.getContext().getFunctionType(
3447       FD->getReturnType(), ArgTypes, FunctionProtoType::ExtProtoInfo(CC));
3448   if (!FD->isExternallyVisible())
3449     SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;
3450   if (CGM.getLangOpts().Optimize)
3451     SPFlags |= llvm::DISubprogram::SPFlagOptimized;
3452 
3453   if (Stub) {
3454     Flags |= getCallSiteRelatedAttrs();
3455     SPFlags |= llvm::DISubprogram::SPFlagDefinition;
3456     return DBuilder.createFunction(
3457         DContext, Name, LinkageName, Unit, Line,
3458         getOrCreateFunctionType(GD.getDecl(), FnType, Unit), 0, Flags, SPFlags,
3459         TParamsArray.get(), getFunctionDeclaration(FD));
3460   }
3461 
3462   llvm::DISubprogram *SP = DBuilder.createTempFunctionFwdDecl(
3463       DContext, Name, LinkageName, Unit, Line,
3464       getOrCreateFunctionType(GD.getDecl(), FnType, Unit), 0, Flags, SPFlags,
3465       TParamsArray.get(), getFunctionDeclaration(FD));
3466   const FunctionDecl *CanonDecl = FD->getCanonicalDecl();
3467   FwdDeclReplaceMap.emplace_back(std::piecewise_construct,
3468                                  std::make_tuple(CanonDecl),
3469                                  std::make_tuple(SP));
3470   return SP;
3471 }
3472 
3473 llvm::DISubprogram *CGDebugInfo::getFunctionForwardDeclaration(GlobalDecl GD) {
3474   return getFunctionFwdDeclOrStub(GD, /* Stub = */ false);
3475 }
3476 
3477 llvm::DISubprogram *CGDebugInfo::getFunctionStub(GlobalDecl GD) {
3478   return getFunctionFwdDeclOrStub(GD, /* Stub = */ true);
3479 }
3480 
3481 llvm::DIGlobalVariable *
3482 CGDebugInfo::getGlobalVariableForwardDeclaration(const VarDecl *VD) {
3483   QualType T;
3484   StringRef Name, LinkageName;
3485   SourceLocation Loc = VD->getLocation();
3486   llvm::DIFile *Unit = getOrCreateFile(Loc);
3487   llvm::DIScope *DContext = Unit;
3488   unsigned Line = getLineNumber(Loc);
3489   llvm::MDTuple *TemplateParameters = nullptr;
3490 
3491   collectVarDeclProps(VD, Unit, Line, T, Name, LinkageName, TemplateParameters,
3492                       DContext);
3493   auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
3494   auto *GV = DBuilder.createTempGlobalVariableFwdDecl(
3495       DContext, Name, LinkageName, Unit, Line, getOrCreateType(T, Unit),
3496       !VD->isExternallyVisible(), nullptr, TemplateParameters, Align);
3497   FwdDeclReplaceMap.emplace_back(
3498       std::piecewise_construct,
3499       std::make_tuple(cast<VarDecl>(VD->getCanonicalDecl())),
3500       std::make_tuple(static_cast<llvm::Metadata *>(GV)));
3501   return GV;
3502 }
3503 
3504 llvm::DINode *CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
3505   // We only need a declaration (not a definition) of the type - so use whatever
3506   // we would otherwise do to get a type for a pointee. (forward declarations in
3507   // limited debug info, full definitions (if the type definition is available)
3508   // in unlimited debug info)
3509   if (const auto *TD = dyn_cast<TypeDecl>(D))
3510     return getOrCreateType(CGM.getContext().getTypeDeclType(TD),
3511                            getOrCreateFile(TD->getLocation()));
3512   auto I = DeclCache.find(D->getCanonicalDecl());
3513 
3514   if (I != DeclCache.end()) {
3515     auto N = I->second;
3516     if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(N))
3517       return GVE->getVariable();
3518     return dyn_cast_or_null<llvm::DINode>(N);
3519   }
3520 
3521   // No definition for now. Emit a forward definition that might be
3522   // merged with a potential upcoming definition.
3523   if (const auto *FD = dyn_cast<FunctionDecl>(D))
3524     return getFunctionForwardDeclaration(FD);
3525   else if (const auto *VD = dyn_cast<VarDecl>(D))
3526     return getGlobalVariableForwardDeclaration(VD);
3527 
3528   return nullptr;
3529 }
3530 
3531 llvm::DISubprogram *CGDebugInfo::getFunctionDeclaration(const Decl *D) {
3532   if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly)
3533     return nullptr;
3534 
3535   const auto *FD = dyn_cast<FunctionDecl>(D);
3536   if (!FD)
3537     return nullptr;
3538 
3539   // Setup context.
3540   auto *S = getDeclContextDescriptor(D);
3541 
3542   auto MI = SPCache.find(FD->getCanonicalDecl());
3543   if (MI == SPCache.end()) {
3544     if (const auto *MD = dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
3545       return CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()),
3546                                      cast<llvm::DICompositeType>(S));
3547     }
3548   }
3549   if (MI != SPCache.end()) {
3550     auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
3551     if (SP && !SP->isDefinition())
3552       return SP;
3553   }
3554 
3555   for (auto NextFD : FD->redecls()) {
3556     auto MI = SPCache.find(NextFD->getCanonicalDecl());
3557     if (MI != SPCache.end()) {
3558       auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
3559       if (SP && !SP->isDefinition())
3560         return SP;
3561     }
3562   }
3563   return nullptr;
3564 }
3565 
3566 llvm::DISubprogram *CGDebugInfo::getObjCMethodDeclaration(
3567     const Decl *D, llvm::DISubroutineType *FnType, unsigned LineNo,
3568     llvm::DINode::DIFlags Flags, llvm::DISubprogram::DISPFlags SPFlags) {
3569   if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly)
3570     return nullptr;
3571 
3572   const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
3573   if (!OMD)
3574     return nullptr;
3575 
3576   if (CGM.getCodeGenOpts().DwarfVersion < 5 && !OMD->isDirectMethod())
3577     return nullptr;
3578 
3579   if (OMD->isDirectMethod())
3580     SPFlags |= llvm::DISubprogram::SPFlagObjCDirect;
3581 
3582   // Starting with DWARF V5 method declarations are emitted as children of
3583   // the interface type.
3584   auto *ID = dyn_cast_or_null<ObjCInterfaceDecl>(D->getDeclContext());
3585   if (!ID)
3586     ID = OMD->getClassInterface();
3587   if (!ID)
3588     return nullptr;
3589   QualType QTy(ID->getTypeForDecl(), 0);
3590   auto It = TypeCache.find(QTy.getAsOpaquePtr());
3591   if (It == TypeCache.end())
3592     return nullptr;
3593   auto *InterfaceType = cast<llvm::DICompositeType>(It->second);
3594   llvm::DISubprogram *FD = DBuilder.createFunction(
3595       InterfaceType, getObjCMethodName(OMD), StringRef(),
3596       InterfaceType->getFile(), LineNo, FnType, LineNo, Flags, SPFlags);
3597   DBuilder.finalizeSubprogram(FD);
3598   ObjCMethodCache[ID].push_back({FD, OMD->isDirectMethod()});
3599   return FD;
3600 }
3601 
3602 // getOrCreateFunctionType - Construct type. If it is a c++ method, include
3603 // implicit parameter "this".
3604 llvm::DISubroutineType *CGDebugInfo::getOrCreateFunctionType(const Decl *D,
3605                                                              QualType FnType,
3606                                                              llvm::DIFile *F) {
3607   if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly)
3608     // Create fake but valid subroutine type. Otherwise -verify would fail, and
3609     // subprogram DIE will miss DW_AT_decl_file and DW_AT_decl_line fields.
3610     return DBuilder.createSubroutineType(DBuilder.getOrCreateTypeArray(None));
3611 
3612   if (const auto *Method = dyn_cast<CXXMethodDecl>(D))
3613     return getOrCreateMethodType(Method, F, false);
3614 
3615   const auto *FTy = FnType->getAs<FunctionType>();
3616   CallingConv CC = FTy ? FTy->getCallConv() : CallingConv::CC_C;
3617 
3618   if (const auto *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
3619     // Add "self" and "_cmd"
3620     SmallVector<llvm::Metadata *, 16> Elts;
3621 
3622     // First element is always return type. For 'void' functions it is NULL.
3623     QualType ResultTy = OMethod->getReturnType();
3624 
3625     // Replace the instancetype keyword with the actual type.
3626     if (ResultTy == CGM.getContext().getObjCInstanceType())
3627       ResultTy = CGM.getContext().getPointerType(
3628           QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
3629 
3630     Elts.push_back(getOrCreateType(ResultTy, F));
3631     // "self" pointer is always first argument.
3632     QualType SelfDeclTy;
3633     if (auto *SelfDecl = OMethod->getSelfDecl())
3634       SelfDeclTy = SelfDecl->getType();
3635     else if (auto *FPT = dyn_cast<FunctionProtoType>(FnType))
3636       if (FPT->getNumParams() > 1)
3637         SelfDeclTy = FPT->getParamType(0);
3638     if (!SelfDeclTy.isNull())
3639       Elts.push_back(
3640           CreateSelfType(SelfDeclTy, getOrCreateType(SelfDeclTy, F)));
3641     // "_cmd" pointer is always second argument.
3642     Elts.push_back(DBuilder.createArtificialType(
3643         getOrCreateType(CGM.getContext().getObjCSelType(), F)));
3644     // Get rest of the arguments.
3645     for (const auto *PI : OMethod->parameters())
3646       Elts.push_back(getOrCreateType(PI->getType(), F));
3647     // Variadic methods need a special marker at the end of the type list.
3648     if (OMethod->isVariadic())
3649       Elts.push_back(DBuilder.createUnspecifiedParameter());
3650 
3651     llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
3652     return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
3653                                          getDwarfCC(CC));
3654   }
3655 
3656   // Handle variadic function types; they need an additional
3657   // unspecified parameter.
3658   if (const auto *FD = dyn_cast<FunctionDecl>(D))
3659     if (FD->isVariadic()) {
3660       SmallVector<llvm::Metadata *, 16> EltTys;
3661       EltTys.push_back(getOrCreateType(FD->getReturnType(), F));
3662       if (const auto *FPT = dyn_cast<FunctionProtoType>(FnType))
3663         for (QualType ParamType : FPT->param_types())
3664           EltTys.push_back(getOrCreateType(ParamType, F));
3665       EltTys.push_back(DBuilder.createUnspecifiedParameter());
3666       llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
3667       return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
3668                                            getDwarfCC(CC));
3669     }
3670 
3671   return cast<llvm::DISubroutineType>(getOrCreateType(FnType, F));
3672 }
3673 
3674 void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, SourceLocation Loc,
3675                                     SourceLocation ScopeLoc, QualType FnType,
3676                                     llvm::Function *Fn, bool CurFuncIsThunk,
3677                                     CGBuilderTy &Builder) {
3678 
3679   StringRef Name;
3680   StringRef LinkageName;
3681 
3682   FnBeginRegionCount.push_back(LexicalBlockStack.size());
3683 
3684   const Decl *D = GD.getDecl();
3685   bool HasDecl = (D != nullptr);
3686 
3687   llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3688   llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
3689   llvm::DIFile *Unit = getOrCreateFile(Loc);
3690   llvm::DIScope *FDContext = Unit;
3691   llvm::DINodeArray TParamsArray;
3692   if (!HasDecl) {
3693     // Use llvm function name.
3694     LinkageName = Fn->getName();
3695   } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
3696     // If there is a subprogram for this function available then use it.
3697     auto FI = SPCache.find(FD->getCanonicalDecl());
3698     if (FI != SPCache.end()) {
3699       auto *SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
3700       if (SP && SP->isDefinition()) {
3701         LexicalBlockStack.emplace_back(SP);
3702         RegionMap[D].reset(SP);
3703         return;
3704       }
3705     }
3706     collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
3707                              TParamsArray, Flags);
3708   } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) {
3709     Name = getObjCMethodName(OMD);
3710     Flags |= llvm::DINode::FlagPrototyped;
3711   } else if (isa<VarDecl>(D) &&
3712              GD.getDynamicInitKind() != DynamicInitKind::NoStub) {
3713     // This is a global initializer or atexit destructor for a global variable.
3714     Name = getDynamicInitializerName(cast<VarDecl>(D), GD.getDynamicInitKind(),
3715                                      Fn);
3716   } else {
3717     Name = Fn->getName();
3718 
3719     if (isa<BlockDecl>(D))
3720       LinkageName = Name;
3721 
3722     Flags |= llvm::DINode::FlagPrototyped;
3723   }
3724   if (Name.startswith("\01"))
3725     Name = Name.substr(1);
3726 
3727   if (!HasDecl || D->isImplicit() || D->hasAttr<ArtificialAttr>()) {
3728     Flags |= llvm::DINode::FlagArtificial;
3729     // Artificial functions should not silently reuse CurLoc.
3730     CurLoc = SourceLocation();
3731   }
3732 
3733   if (CurFuncIsThunk)
3734     Flags |= llvm::DINode::FlagThunk;
3735 
3736   if (Fn->hasLocalLinkage())
3737     SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;
3738   if (CGM.getLangOpts().Optimize)
3739     SPFlags |= llvm::DISubprogram::SPFlagOptimized;
3740 
3741   llvm::DINode::DIFlags FlagsForDef = Flags | getCallSiteRelatedAttrs();
3742   llvm::DISubprogram::DISPFlags SPFlagsForDef =
3743       SPFlags | llvm::DISubprogram::SPFlagDefinition;
3744 
3745   unsigned LineNo = getLineNumber(Loc);
3746   unsigned ScopeLine = getLineNumber(ScopeLoc);
3747   llvm::DISubroutineType *DIFnType = getOrCreateFunctionType(D, FnType, Unit);
3748   llvm::DISubprogram *Decl = nullptr;
3749   if (D)
3750     Decl = isa<ObjCMethodDecl>(D)
3751                ? getObjCMethodDeclaration(D, DIFnType, LineNo, Flags, SPFlags)
3752                : getFunctionDeclaration(D);
3753 
3754   // FIXME: The function declaration we're constructing here is mostly reusing
3755   // declarations from CXXMethodDecl and not constructing new ones for arbitrary
3756   // FunctionDecls. When/if we fix this we can have FDContext be TheCU/null for
3757   // all subprograms instead of the actual context since subprogram definitions
3758   // are emitted as CU level entities by the backend.
3759   llvm::DISubprogram *SP = DBuilder.createFunction(
3760       FDContext, Name, LinkageName, Unit, LineNo, DIFnType, ScopeLine,
3761       FlagsForDef, SPFlagsForDef, TParamsArray.get(), Decl);
3762   Fn->setSubprogram(SP);
3763   // We might get here with a VarDecl in the case we're generating
3764   // code for the initialization of globals. Do not record these decls
3765   // as they will overwrite the actual VarDecl Decl in the cache.
3766   if (HasDecl && isa<FunctionDecl>(D))
3767     DeclCache[D->getCanonicalDecl()].reset(SP);
3768 
3769   // Push the function onto the lexical block stack.
3770   LexicalBlockStack.emplace_back(SP);
3771 
3772   if (HasDecl)
3773     RegionMap[D].reset(SP);
3774 }
3775 
3776 void CGDebugInfo::EmitFunctionDecl(GlobalDecl GD, SourceLocation Loc,
3777                                    QualType FnType, llvm::Function *Fn) {
3778   StringRef Name;
3779   StringRef LinkageName;
3780 
3781   const Decl *D = GD.getDecl();
3782   if (!D)
3783     return;
3784 
3785   llvm::TimeTraceScope TimeScope("DebugFunction", [&]() {
3786     std::string Name;
3787     llvm::raw_string_ostream OS(Name);
3788     if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
3789       ND->getNameForDiagnostic(OS, getPrintingPolicy(),
3790                                /*Qualified=*/true);
3791     return Name;
3792   });
3793 
3794   llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3795   llvm::DIFile *Unit = getOrCreateFile(Loc);
3796   bool IsDeclForCallSite = Fn ? true : false;
3797   llvm::DIScope *FDContext =
3798       IsDeclForCallSite ? Unit : getDeclContextDescriptor(D);
3799   llvm::DINodeArray TParamsArray;
3800   if (isa<FunctionDecl>(D)) {
3801     // If there is a DISubprogram for this function available then use it.
3802     collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
3803                              TParamsArray, Flags);
3804   } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) {
3805     Name = getObjCMethodName(OMD);
3806     Flags |= llvm::DINode::FlagPrototyped;
3807   } else {
3808     llvm_unreachable("not a function or ObjC method");
3809   }
3810   if (!Name.empty() && Name[0] == '\01')
3811     Name = Name.substr(1);
3812 
3813   if (D->isImplicit()) {
3814     Flags |= llvm::DINode::FlagArtificial;
3815     // Artificial functions without a location should not silently reuse CurLoc.
3816     if (Loc.isInvalid())
3817       CurLoc = SourceLocation();
3818   }
3819   unsigned LineNo = getLineNumber(Loc);
3820   unsigned ScopeLine = 0;
3821   llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
3822   if (CGM.getLangOpts().Optimize)
3823     SPFlags |= llvm::DISubprogram::SPFlagOptimized;
3824 
3825   llvm::DISubprogram *SP = DBuilder.createFunction(
3826       FDContext, Name, LinkageName, Unit, LineNo,
3827       getOrCreateFunctionType(D, FnType, Unit), ScopeLine, Flags, SPFlags,
3828       TParamsArray.get(), getFunctionDeclaration(D));
3829 
3830   if (IsDeclForCallSite)
3831     Fn->setSubprogram(SP);
3832 
3833   DBuilder.retainType(SP);
3834 }
3835 
3836 void CGDebugInfo::EmitFuncDeclForCallSite(llvm::CallBase *CallOrInvoke,
3837                                           QualType CalleeType,
3838                                           const FunctionDecl *CalleeDecl) {
3839   if (!CallOrInvoke)
3840     return;
3841   auto *Func = CallOrInvoke->getCalledFunction();
3842   if (!Func)
3843     return;
3844   if (Func->getSubprogram())
3845     return;
3846 
3847   // Do not emit a declaration subprogram for a builtin or if call site info
3848   // isn't required. Also, elide declarations for functions with reserved names,
3849   // as call site-related features aren't interesting in this case (& also, the
3850   // compiler may emit calls to these functions without debug locations, which
3851   // makes the verifier complain).
3852   if (CalleeDecl->getBuiltinID() != 0 ||
3853       getCallSiteRelatedAttrs() == llvm::DINode::FlagZero)
3854     return;
3855   if (const auto *Id = CalleeDecl->getIdentifier())
3856     if (Id->isReservedName())
3857       return;
3858 
3859   // If there is no DISubprogram attached to the function being called,
3860   // create the one describing the function in order to have complete
3861   // call site debug info.
3862   if (!CalleeDecl->isStatic() && !CalleeDecl->isInlined())
3863     EmitFunctionDecl(CalleeDecl, CalleeDecl->getLocation(), CalleeType, Func);
3864 }
3865 
3866 void CGDebugInfo::EmitInlineFunctionStart(CGBuilderTy &Builder, GlobalDecl GD) {
3867   const auto *FD = cast<FunctionDecl>(GD.getDecl());
3868   // If there is a subprogram for this function available then use it.
3869   auto FI = SPCache.find(FD->getCanonicalDecl());
3870   llvm::DISubprogram *SP = nullptr;
3871   if (FI != SPCache.end())
3872     SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
3873   if (!SP || !SP->isDefinition())
3874     SP = getFunctionStub(GD);
3875   FnBeginRegionCount.push_back(LexicalBlockStack.size());
3876   LexicalBlockStack.emplace_back(SP);
3877   setInlinedAt(Builder.getCurrentDebugLocation());
3878   EmitLocation(Builder, FD->getLocation());
3879 }
3880 
3881 void CGDebugInfo::EmitInlineFunctionEnd(CGBuilderTy &Builder) {
3882   assert(CurInlinedAt && "unbalanced inline scope stack");
3883   EmitFunctionEnd(Builder, nullptr);
3884   setInlinedAt(llvm::DebugLoc(CurInlinedAt).getInlinedAt());
3885 }
3886 
3887 void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc) {
3888   // Update our current location
3889   setLocation(Loc);
3890 
3891   if (CurLoc.isInvalid() || CurLoc.isMacroID() || LexicalBlockStack.empty())
3892     return;
3893 
3894   llvm::MDNode *Scope = LexicalBlockStack.back();
3895   Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(
3896       getLineNumber(CurLoc), getColumnNumber(CurLoc), Scope, CurInlinedAt));
3897 }
3898 
3899 void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
3900   llvm::MDNode *Back = nullptr;
3901   if (!LexicalBlockStack.empty())
3902     Back = LexicalBlockStack.back().get();
3903   LexicalBlockStack.emplace_back(DBuilder.createLexicalBlock(
3904       cast<llvm::DIScope>(Back), getOrCreateFile(CurLoc), getLineNumber(CurLoc),
3905       getColumnNumber(CurLoc)));
3906 }
3907 
3908 void CGDebugInfo::AppendAddressSpaceXDeref(
3909     unsigned AddressSpace, SmallVectorImpl<int64_t> &Expr) const {
3910   Optional<unsigned> DWARFAddressSpace =
3911       CGM.getTarget().getDWARFAddressSpace(AddressSpace);
3912   if (!DWARFAddressSpace)
3913     return;
3914 
3915   Expr.push_back(llvm::dwarf::DW_OP_constu);
3916   Expr.push_back(DWARFAddressSpace.getValue());
3917   Expr.push_back(llvm::dwarf::DW_OP_swap);
3918   Expr.push_back(llvm::dwarf::DW_OP_xderef);
3919 }
3920 
3921 void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
3922                                         SourceLocation Loc) {
3923   // Set our current location.
3924   setLocation(Loc);
3925 
3926   // Emit a line table change for the current location inside the new scope.
3927   Builder.SetCurrentDebugLocation(
3928       llvm::DebugLoc::get(getLineNumber(Loc), getColumnNumber(Loc),
3929                           LexicalBlockStack.back(), CurInlinedAt));
3930 
3931   if (DebugKind <= codegenoptions::DebugLineTablesOnly)
3932     return;
3933 
3934   // Create a new lexical block and push it on the stack.
3935   CreateLexicalBlock(Loc);
3936 }
3937 
3938 void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
3939                                       SourceLocation Loc) {
3940   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
3941 
3942   // Provide an entry in the line table for the end of the block.
3943   EmitLocation(Builder, Loc);
3944 
3945   if (DebugKind <= codegenoptions::DebugLineTablesOnly)
3946     return;
3947 
3948   LexicalBlockStack.pop_back();
3949 }
3950 
3951 void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder, llvm::Function *Fn) {
3952   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
3953   unsigned RCount = FnBeginRegionCount.back();
3954   assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
3955 
3956   // Pop all regions for this function.
3957   while (LexicalBlockStack.size() != RCount) {
3958     // Provide an entry in the line table for the end of the block.
3959     EmitLocation(Builder, CurLoc);
3960     LexicalBlockStack.pop_back();
3961   }
3962   FnBeginRegionCount.pop_back();
3963 
3964   if (Fn && Fn->getSubprogram())
3965     DBuilder.finalizeSubprogram(Fn->getSubprogram());
3966 }
3967 
3968 CGDebugInfo::BlockByRefType
3969 CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
3970                                           uint64_t *XOffset) {
3971   SmallVector<llvm::Metadata *, 5> EltTys;
3972   QualType FType;
3973   uint64_t FieldSize, FieldOffset;
3974   uint32_t FieldAlign;
3975 
3976   llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
3977   QualType Type = VD->getType();
3978 
3979   FieldOffset = 0;
3980   FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
3981   EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
3982   EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
3983   FType = CGM.getContext().IntTy;
3984   EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
3985   EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
3986 
3987   bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
3988   if (HasCopyAndDispose) {
3989     FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
3990     EltTys.push_back(
3991         CreateMemberType(Unit, FType, "__copy_helper", &FieldOffset));
3992     EltTys.push_back(
3993         CreateMemberType(Unit, FType, "__destroy_helper", &FieldOffset));
3994   }
3995   bool HasByrefExtendedLayout;
3996   Qualifiers::ObjCLifetime Lifetime;
3997   if (CGM.getContext().getByrefLifetime(Type, Lifetime,
3998                                         HasByrefExtendedLayout) &&
3999       HasByrefExtendedLayout) {
4000     FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
4001     EltTys.push_back(
4002         CreateMemberType(Unit, FType, "__byref_variable_layout", &FieldOffset));
4003   }
4004 
4005   CharUnits Align = CGM.getContext().getDeclAlign(VD);
4006   if (Align > CGM.getContext().toCharUnitsFromBits(
4007                   CGM.getTarget().getPointerAlign(0))) {
4008     CharUnits FieldOffsetInBytes =
4009         CGM.getContext().toCharUnitsFromBits(FieldOffset);
4010     CharUnits AlignedOffsetInBytes = FieldOffsetInBytes.alignTo(Align);
4011     CharUnits NumPaddingBytes = AlignedOffsetInBytes - FieldOffsetInBytes;
4012 
4013     if (NumPaddingBytes.isPositive()) {
4014       llvm::APInt pad(32, NumPaddingBytes.getQuantity());
4015       FType = CGM.getContext().getConstantArrayType(
4016           CGM.getContext().CharTy, pad, nullptr, ArrayType::Normal, 0);
4017       EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
4018     }
4019   }
4020 
4021   FType = Type;
4022   llvm::DIType *WrappedTy = getOrCreateType(FType, Unit);
4023   FieldSize = CGM.getContext().getTypeSize(FType);
4024   FieldAlign = CGM.getContext().toBits(Align);
4025 
4026   *XOffset = FieldOffset;
4027   llvm::DIType *FieldTy = DBuilder.createMemberType(
4028       Unit, VD->getName(), Unit, 0, FieldSize, FieldAlign, FieldOffset,
4029       llvm::DINode::FlagZero, WrappedTy);
4030   EltTys.push_back(FieldTy);
4031   FieldOffset += FieldSize;
4032 
4033   llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
4034   return {DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0,
4035                                     llvm::DINode::FlagZero, nullptr, Elements),
4036           WrappedTy};
4037 }
4038 
4039 llvm::DILocalVariable *CGDebugInfo::EmitDeclare(const VarDecl *VD,
4040                                                 llvm::Value *Storage,
4041                                                 llvm::Optional<unsigned> ArgNo,
4042                                                 CGBuilderTy &Builder,
4043                                                 const bool UsePointerValue) {
4044   assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4045   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4046   if (VD->hasAttr<NoDebugAttr>())
4047     return nullptr;
4048 
4049   bool Unwritten =
4050       VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) &&
4051                            cast<Decl>(VD->getDeclContext())->isImplicit());
4052   llvm::DIFile *Unit = nullptr;
4053   if (!Unwritten)
4054     Unit = getOrCreateFile(VD->getLocation());
4055   llvm::DIType *Ty;
4056   uint64_t XOffset = 0;
4057   if (VD->hasAttr<BlocksAttr>())
4058     Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset).WrappedType;
4059   else
4060     Ty = getOrCreateType(VD->getType(), Unit);
4061 
4062   // If there is no debug info for this type then do not emit debug info
4063   // for this variable.
4064   if (!Ty)
4065     return nullptr;
4066 
4067   // Get location information.
4068   unsigned Line = 0;
4069   unsigned Column = 0;
4070   if (!Unwritten) {
4071     Line = getLineNumber(VD->getLocation());
4072     Column = getColumnNumber(VD->getLocation());
4073   }
4074   SmallVector<int64_t, 13> Expr;
4075   llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
4076   if (VD->isImplicit())
4077     Flags |= llvm::DINode::FlagArtificial;
4078 
4079   auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
4080 
4081   unsigned AddressSpace = CGM.getContext().getTargetAddressSpace(VD->getType());
4082   AppendAddressSpaceXDeref(AddressSpace, Expr);
4083 
4084   // If this is implicit parameter of CXXThis or ObjCSelf kind, then give it an
4085   // object pointer flag.
4086   if (const auto *IPD = dyn_cast<ImplicitParamDecl>(VD)) {
4087     if (IPD->getParameterKind() == ImplicitParamDecl::CXXThis ||
4088         IPD->getParameterKind() == ImplicitParamDecl::ObjCSelf)
4089       Flags |= llvm::DINode::FlagObjectPointer;
4090   }
4091 
4092   // Note: Older versions of clang used to emit byval references with an extra
4093   // DW_OP_deref, because they referenced the IR arg directly instead of
4094   // referencing an alloca. Newer versions of LLVM don't treat allocas
4095   // differently from other function arguments when used in a dbg.declare.
4096   auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
4097   StringRef Name = VD->getName();
4098   if (!Name.empty()) {
4099     if (VD->hasAttr<BlocksAttr>()) {
4100       // Here, we need an offset *into* the alloca.
4101       CharUnits offset = CharUnits::fromQuantity(32);
4102       Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4103       // offset of __forwarding field
4104       offset = CGM.getContext().toCharUnitsFromBits(
4105           CGM.getTarget().getPointerWidth(0));
4106       Expr.push_back(offset.getQuantity());
4107       Expr.push_back(llvm::dwarf::DW_OP_deref);
4108       Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4109       // offset of x field
4110       offset = CGM.getContext().toCharUnitsFromBits(XOffset);
4111       Expr.push_back(offset.getQuantity());
4112     }
4113   } else if (const auto *RT = dyn_cast<RecordType>(VD->getType())) {
4114     // If VD is an anonymous union then Storage represents value for
4115     // all union fields.
4116     const RecordDecl *RD = RT->getDecl();
4117     if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
4118       // GDB has trouble finding local variables in anonymous unions, so we emit
4119       // artificial local variables for each of the members.
4120       //
4121       // FIXME: Remove this code as soon as GDB supports this.
4122       // The debug info verifier in LLVM operates based on the assumption that a
4123       // variable has the same size as its storage and we had to disable the
4124       // check for artificial variables.
4125       for (const auto *Field : RD->fields()) {
4126         llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
4127         StringRef FieldName = Field->getName();
4128 
4129         // Ignore unnamed fields. Do not ignore unnamed records.
4130         if (FieldName.empty() && !isa<RecordType>(Field->getType()))
4131           continue;
4132 
4133         // Use VarDecl's Tag, Scope and Line number.
4134         auto FieldAlign = getDeclAlignIfRequired(Field, CGM.getContext());
4135         auto *D = DBuilder.createAutoVariable(
4136             Scope, FieldName, Unit, Line, FieldTy, CGM.getLangOpts().Optimize,
4137             Flags | llvm::DINode::FlagArtificial, FieldAlign);
4138 
4139         // Insert an llvm.dbg.declare into the current block.
4140         DBuilder.insertDeclare(
4141             Storage, D, DBuilder.createExpression(Expr),
4142             llvm::DebugLoc::get(Line, Column, Scope, CurInlinedAt),
4143             Builder.GetInsertBlock());
4144       }
4145     }
4146   }
4147 
4148   // Clang stores the sret pointer provided by the caller in a static alloca.
4149   // Use DW_OP_deref to tell the debugger to load the pointer and treat it as
4150   // the address of the variable.
4151   if (UsePointerValue) {
4152     assert(std::find(Expr.begin(), Expr.end(), llvm::dwarf::DW_OP_deref) ==
4153                Expr.end() &&
4154            "Debug info already contains DW_OP_deref.");
4155     Expr.push_back(llvm::dwarf::DW_OP_deref);
4156   }
4157 
4158   // Create the descriptor for the variable.
4159   auto *D = ArgNo ? DBuilder.createParameterVariable(
4160                         Scope, Name, *ArgNo, Unit, Line, Ty,
4161                         CGM.getLangOpts().Optimize, Flags)
4162                   : DBuilder.createAutoVariable(Scope, Name, Unit, Line, Ty,
4163                                                 CGM.getLangOpts().Optimize,
4164                                                 Flags, Align);
4165 
4166   // Insert an llvm.dbg.declare into the current block.
4167   DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
4168                          llvm::DebugLoc::get(Line, Column, Scope, CurInlinedAt),
4169                          Builder.GetInsertBlock());
4170 
4171   return D;
4172 }
4173 
4174 llvm::DILocalVariable *
4175 CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD, llvm::Value *Storage,
4176                                        CGBuilderTy &Builder,
4177                                        const bool UsePointerValue) {
4178   assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4179   return EmitDeclare(VD, Storage, llvm::None, Builder, UsePointerValue);
4180 }
4181 
4182 void CGDebugInfo::EmitLabel(const LabelDecl *D, CGBuilderTy &Builder) {
4183   assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4184   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4185 
4186   if (D->hasAttr<NoDebugAttr>())
4187     return;
4188 
4189   auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
4190   llvm::DIFile *Unit = getOrCreateFile(D->getLocation());
4191 
4192   // Get location information.
4193   unsigned Line = getLineNumber(D->getLocation());
4194   unsigned Column = getColumnNumber(D->getLocation());
4195 
4196   StringRef Name = D->getName();
4197 
4198   // Create the descriptor for the label.
4199   auto *L =
4200       DBuilder.createLabel(Scope, Name, Unit, Line, CGM.getLangOpts().Optimize);
4201 
4202   // Insert an llvm.dbg.label into the current block.
4203   DBuilder.insertLabel(L,
4204                        llvm::DebugLoc::get(Line, Column, Scope, CurInlinedAt),
4205                        Builder.GetInsertBlock());
4206 }
4207 
4208 llvm::DIType *CGDebugInfo::CreateSelfType(const QualType &QualTy,
4209                                           llvm::DIType *Ty) {
4210   llvm::DIType *CachedTy = getTypeOrNull(QualTy);
4211   if (CachedTy)
4212     Ty = CachedTy;
4213   return DBuilder.createObjectPointerType(Ty);
4214 }
4215 
4216 void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(
4217     const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder,
4218     const CGBlockInfo &blockInfo, llvm::Instruction *InsertPoint) {
4219   assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4220   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4221 
4222   if (Builder.GetInsertBlock() == nullptr)
4223     return;
4224   if (VD->hasAttr<NoDebugAttr>())
4225     return;
4226 
4227   bool isByRef = VD->hasAttr<BlocksAttr>();
4228 
4229   uint64_t XOffset = 0;
4230   llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
4231   llvm::DIType *Ty;
4232   if (isByRef)
4233     Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset).WrappedType;
4234   else
4235     Ty = getOrCreateType(VD->getType(), Unit);
4236 
4237   // Self is passed along as an implicit non-arg variable in a
4238   // block. Mark it as the object pointer.
4239   if (const auto *IPD = dyn_cast<ImplicitParamDecl>(VD))
4240     if (IPD->getParameterKind() == ImplicitParamDecl::ObjCSelf)
4241       Ty = CreateSelfType(VD->getType(), Ty);
4242 
4243   // Get location information.
4244   unsigned Line = getLineNumber(VD->getLocation());
4245   unsigned Column = getColumnNumber(VD->getLocation());
4246 
4247   const llvm::DataLayout &target = CGM.getDataLayout();
4248 
4249   CharUnits offset = CharUnits::fromQuantity(
4250       target.getStructLayout(blockInfo.StructureType)
4251           ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
4252 
4253   SmallVector<int64_t, 9> addr;
4254   addr.push_back(llvm::dwarf::DW_OP_deref);
4255   addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4256   addr.push_back(offset.getQuantity());
4257   if (isByRef) {
4258     addr.push_back(llvm::dwarf::DW_OP_deref);
4259     addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4260     // offset of __forwarding field
4261     offset =
4262         CGM.getContext().toCharUnitsFromBits(target.getPointerSizeInBits(0));
4263     addr.push_back(offset.getQuantity());
4264     addr.push_back(llvm::dwarf::DW_OP_deref);
4265     addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4266     // offset of x field
4267     offset = CGM.getContext().toCharUnitsFromBits(XOffset);
4268     addr.push_back(offset.getQuantity());
4269   }
4270 
4271   // Create the descriptor for the variable.
4272   auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
4273   auto *D = DBuilder.createAutoVariable(
4274       cast<llvm::DILocalScope>(LexicalBlockStack.back()), VD->getName(), Unit,
4275       Line, Ty, false, llvm::DINode::FlagZero, Align);
4276 
4277   // Insert an llvm.dbg.declare into the current block.
4278   auto DL =
4279       llvm::DebugLoc::get(Line, Column, LexicalBlockStack.back(), CurInlinedAt);
4280   auto *Expr = DBuilder.createExpression(addr);
4281   if (InsertPoint)
4282     DBuilder.insertDeclare(Storage, D, Expr, DL, InsertPoint);
4283   else
4284     DBuilder.insertDeclare(Storage, D, Expr, DL, Builder.GetInsertBlock());
4285 }
4286 
4287 void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
4288                                            unsigned ArgNo,
4289                                            CGBuilderTy &Builder) {
4290   assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4291   EmitDeclare(VD, AI, ArgNo, Builder);
4292 }
4293 
4294 namespace {
4295 struct BlockLayoutChunk {
4296   uint64_t OffsetInBits;
4297   const BlockDecl::Capture *Capture;
4298 };
4299 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
4300   return l.OffsetInBits < r.OffsetInBits;
4301 }
4302 } // namespace
4303 
4304 void CGDebugInfo::collectDefaultFieldsForBlockLiteralDeclare(
4305     const CGBlockInfo &Block, const ASTContext &Context, SourceLocation Loc,
4306     const llvm::StructLayout &BlockLayout, llvm::DIFile *Unit,
4307     SmallVectorImpl<llvm::Metadata *> &Fields) {
4308   // Blocks in OpenCL have unique constraints which make the standard fields
4309   // redundant while requiring size and align fields for enqueue_kernel. See
4310   // initializeForBlockHeader in CGBlocks.cpp
4311   if (CGM.getLangOpts().OpenCL) {
4312     Fields.push_back(createFieldType("__size", Context.IntTy, Loc, AS_public,
4313                                      BlockLayout.getElementOffsetInBits(0),
4314                                      Unit, Unit));
4315     Fields.push_back(createFieldType("__align", Context.IntTy, Loc, AS_public,
4316                                      BlockLayout.getElementOffsetInBits(1),
4317                                      Unit, Unit));
4318   } else {
4319     Fields.push_back(createFieldType("__isa", Context.VoidPtrTy, Loc, AS_public,
4320                                      BlockLayout.getElementOffsetInBits(0),
4321                                      Unit, Unit));
4322     Fields.push_back(createFieldType("__flags", Context.IntTy, Loc, AS_public,
4323                                      BlockLayout.getElementOffsetInBits(1),
4324                                      Unit, Unit));
4325     Fields.push_back(
4326         createFieldType("__reserved", Context.IntTy, Loc, AS_public,
4327                         BlockLayout.getElementOffsetInBits(2), Unit, Unit));
4328     auto *FnTy = Block.getBlockExpr()->getFunctionType();
4329     auto FnPtrType = CGM.getContext().getPointerType(FnTy->desugar());
4330     Fields.push_back(createFieldType("__FuncPtr", FnPtrType, Loc, AS_public,
4331                                      BlockLayout.getElementOffsetInBits(3),
4332                                      Unit, Unit));
4333     Fields.push_back(createFieldType(
4334         "__descriptor",
4335         Context.getPointerType(Block.NeedsCopyDispose
4336                                    ? Context.getBlockDescriptorExtendedType()
4337                                    : Context.getBlockDescriptorType()),
4338         Loc, AS_public, BlockLayout.getElementOffsetInBits(4), Unit, Unit));
4339   }
4340 }
4341 
4342 void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
4343                                                        StringRef Name,
4344                                                        unsigned ArgNo,
4345                                                        llvm::AllocaInst *Alloca,
4346                                                        CGBuilderTy &Builder) {
4347   assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4348   ASTContext &C = CGM.getContext();
4349   const BlockDecl *blockDecl = block.getBlockDecl();
4350 
4351   // Collect some general information about the block's location.
4352   SourceLocation loc = blockDecl->getCaretLocation();
4353   llvm::DIFile *tunit = getOrCreateFile(loc);
4354   unsigned line = getLineNumber(loc);
4355   unsigned column = getColumnNumber(loc);
4356 
4357   // Build the debug-info type for the block literal.
4358   getDeclContextDescriptor(blockDecl);
4359 
4360   const llvm::StructLayout *blockLayout =
4361       CGM.getDataLayout().getStructLayout(block.StructureType);
4362 
4363   SmallVector<llvm::Metadata *, 16> fields;
4364   collectDefaultFieldsForBlockLiteralDeclare(block, C, loc, *blockLayout, tunit,
4365                                              fields);
4366 
4367   // We want to sort the captures by offset, not because DWARF
4368   // requires this, but because we're paranoid about debuggers.
4369   SmallVector<BlockLayoutChunk, 8> chunks;
4370 
4371   // 'this' capture.
4372   if (blockDecl->capturesCXXThis()) {
4373     BlockLayoutChunk chunk;
4374     chunk.OffsetInBits =
4375         blockLayout->getElementOffsetInBits(block.CXXThisIndex);
4376     chunk.Capture = nullptr;
4377     chunks.push_back(chunk);
4378   }
4379 
4380   // Variable captures.
4381   for (const auto &capture : blockDecl->captures()) {
4382     const VarDecl *variable = capture.getVariable();
4383     const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
4384 
4385     // Ignore constant captures.
4386     if (captureInfo.isConstant())
4387       continue;
4388 
4389     BlockLayoutChunk chunk;
4390     chunk.OffsetInBits =
4391         blockLayout->getElementOffsetInBits(captureInfo.getIndex());
4392     chunk.Capture = &capture;
4393     chunks.push_back(chunk);
4394   }
4395 
4396   // Sort by offset.
4397   llvm::array_pod_sort(chunks.begin(), chunks.end());
4398 
4399   for (const BlockLayoutChunk &Chunk : chunks) {
4400     uint64_t offsetInBits = Chunk.OffsetInBits;
4401     const BlockDecl::Capture *capture = Chunk.Capture;
4402 
4403     // If we have a null capture, this must be the C++ 'this' capture.
4404     if (!capture) {
4405       QualType type;
4406       if (auto *Method =
4407               cast_or_null<CXXMethodDecl>(blockDecl->getNonClosureContext()))
4408         type = Method->getThisType();
4409       else if (auto *RDecl = dyn_cast<CXXRecordDecl>(blockDecl->getParent()))
4410         type = QualType(RDecl->getTypeForDecl(), 0);
4411       else
4412         llvm_unreachable("unexpected block declcontext");
4413 
4414       fields.push_back(createFieldType("this", type, loc, AS_public,
4415                                        offsetInBits, tunit, tunit));
4416       continue;
4417     }
4418 
4419     const VarDecl *variable = capture->getVariable();
4420     StringRef name = variable->getName();
4421 
4422     llvm::DIType *fieldType;
4423     if (capture->isByRef()) {
4424       TypeInfo PtrInfo = C.getTypeInfo(C.VoidPtrTy);
4425       auto Align = PtrInfo.AlignIsRequired ? PtrInfo.Align : 0;
4426       // FIXME: This recomputes the layout of the BlockByRefWrapper.
4427       uint64_t xoffset;
4428       fieldType =
4429           EmitTypeForVarWithBlocksAttr(variable, &xoffset).BlockByRefWrapper;
4430       fieldType = DBuilder.createPointerType(fieldType, PtrInfo.Width);
4431       fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
4432                                             PtrInfo.Width, Align, offsetInBits,
4433                                             llvm::DINode::FlagZero, fieldType);
4434     } else {
4435       auto Align = getDeclAlignIfRequired(variable, CGM.getContext());
4436       fieldType = createFieldType(name, variable->getType(), loc, AS_public,
4437                                   offsetInBits, Align, tunit, tunit);
4438     }
4439     fields.push_back(fieldType);
4440   }
4441 
4442   SmallString<36> typeName;
4443   llvm::raw_svector_ostream(typeName)
4444       << "__block_literal_" << CGM.getUniqueBlockCount();
4445 
4446   llvm::DINodeArray fieldsArray = DBuilder.getOrCreateArray(fields);
4447 
4448   llvm::DIType *type =
4449       DBuilder.createStructType(tunit, typeName.str(), tunit, line,
4450                                 CGM.getContext().toBits(block.BlockSize), 0,
4451                                 llvm::DINode::FlagZero, nullptr, fieldsArray);
4452   type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
4453 
4454   // Get overall information about the block.
4455   llvm::DINode::DIFlags flags = llvm::DINode::FlagArtificial;
4456   auto *scope = cast<llvm::DILocalScope>(LexicalBlockStack.back());
4457 
4458   // Create the descriptor for the parameter.
4459   auto *debugVar = DBuilder.createParameterVariable(
4460       scope, Name, ArgNo, tunit, line, type, CGM.getLangOpts().Optimize, flags);
4461 
4462   // Insert an llvm.dbg.declare into the current block.
4463   DBuilder.insertDeclare(Alloca, debugVar, DBuilder.createExpression(),
4464                          llvm::DebugLoc::get(line, column, scope, CurInlinedAt),
4465                          Builder.GetInsertBlock());
4466 }
4467 
4468 llvm::DIDerivedType *
4469 CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {
4470   if (!D || !D->isStaticDataMember())
4471     return nullptr;
4472 
4473   auto MI = StaticDataMemberCache.find(D->getCanonicalDecl());
4474   if (MI != StaticDataMemberCache.end()) {
4475     assert(MI->second && "Static data member declaration should still exist");
4476     return MI->second;
4477   }
4478 
4479   // If the member wasn't found in the cache, lazily construct and add it to the
4480   // type (used when a limited form of the type is emitted).
4481   auto DC = D->getDeclContext();
4482   auto *Ctxt = cast<llvm::DICompositeType>(getDeclContextDescriptor(D));
4483   return CreateRecordStaticField(D, Ctxt, cast<RecordDecl>(DC));
4484 }
4485 
4486 llvm::DIGlobalVariableExpression *CGDebugInfo::CollectAnonRecordDecls(
4487     const RecordDecl *RD, llvm::DIFile *Unit, unsigned LineNo,
4488     StringRef LinkageName, llvm::GlobalVariable *Var, llvm::DIScope *DContext) {
4489   llvm::DIGlobalVariableExpression *GVE = nullptr;
4490 
4491   for (const auto *Field : RD->fields()) {
4492     llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
4493     StringRef FieldName = Field->getName();
4494 
4495     // Ignore unnamed fields, but recurse into anonymous records.
4496     if (FieldName.empty()) {
4497       if (const auto *RT = dyn_cast<RecordType>(Field->getType()))
4498         GVE = CollectAnonRecordDecls(RT->getDecl(), Unit, LineNo, LinkageName,
4499                                      Var, DContext);
4500       continue;
4501     }
4502     // Use VarDecl's Tag, Scope and Line number.
4503     GVE = DBuilder.createGlobalVariableExpression(
4504         DContext, FieldName, LinkageName, Unit, LineNo, FieldTy,
4505         Var->hasLocalLinkage());
4506     Var->addDebugInfo(GVE);
4507   }
4508   return GVE;
4509 }
4510 
4511 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
4512                                      const VarDecl *D) {
4513   assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4514   if (D->hasAttr<NoDebugAttr>())
4515     return;
4516 
4517   llvm::TimeTraceScope TimeScope("DebugGlobalVariable", [&]() {
4518     std::string Name;
4519     llvm::raw_string_ostream OS(Name);
4520     D->getNameForDiagnostic(OS, getPrintingPolicy(),
4521                             /*Qualified=*/true);
4522     return Name;
4523   });
4524 
4525   // If we already created a DIGlobalVariable for this declaration, just attach
4526   // it to the llvm::GlobalVariable.
4527   auto Cached = DeclCache.find(D->getCanonicalDecl());
4528   if (Cached != DeclCache.end())
4529     return Var->addDebugInfo(
4530         cast<llvm::DIGlobalVariableExpression>(Cached->second));
4531 
4532   // Create global variable debug descriptor.
4533   llvm::DIFile *Unit = nullptr;
4534   llvm::DIScope *DContext = nullptr;
4535   unsigned LineNo;
4536   StringRef DeclName, LinkageName;
4537   QualType T;
4538   llvm::MDTuple *TemplateParameters = nullptr;
4539   collectVarDeclProps(D, Unit, LineNo, T, DeclName, LinkageName,
4540                       TemplateParameters, DContext);
4541 
4542   // Attempt to store one global variable for the declaration - even if we
4543   // emit a lot of fields.
4544   llvm::DIGlobalVariableExpression *GVE = nullptr;
4545 
4546   // If this is an anonymous union then we'll want to emit a global
4547   // variable for each member of the anonymous union so that it's possible
4548   // to find the name of any field in the union.
4549   if (T->isUnionType() && DeclName.empty()) {
4550     const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
4551     assert(RD->isAnonymousStructOrUnion() &&
4552            "unnamed non-anonymous struct or union?");
4553     GVE = CollectAnonRecordDecls(RD, Unit, LineNo, LinkageName, Var, DContext);
4554   } else {
4555     auto Align = getDeclAlignIfRequired(D, CGM.getContext());
4556 
4557     SmallVector<int64_t, 4> Expr;
4558     unsigned AddressSpace =
4559         CGM.getContext().getTargetAddressSpace(D->getType());
4560     if (CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) {
4561       if (D->hasAttr<CUDASharedAttr>())
4562         AddressSpace =
4563             CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared);
4564       else if (D->hasAttr<CUDAConstantAttr>())
4565         AddressSpace =
4566             CGM.getContext().getTargetAddressSpace(LangAS::cuda_constant);
4567     }
4568     AppendAddressSpaceXDeref(AddressSpace, Expr);
4569 
4570     GVE = DBuilder.createGlobalVariableExpression(
4571         DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
4572         Var->hasLocalLinkage(), true,
4573         Expr.empty() ? nullptr : DBuilder.createExpression(Expr),
4574         getOrCreateStaticDataMemberDeclarationOrNull(D), TemplateParameters,
4575         Align);
4576     Var->addDebugInfo(GVE);
4577   }
4578   DeclCache[D->getCanonicalDecl()].reset(GVE);
4579 }
4580 
4581 void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD, const APValue &Init) {
4582   assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4583   if (VD->hasAttr<NoDebugAttr>())
4584     return;
4585   llvm::TimeTraceScope TimeScope("DebugConstGlobalVariable", [&]() {
4586     std::string Name;
4587     llvm::raw_string_ostream OS(Name);
4588     VD->getNameForDiagnostic(OS, getPrintingPolicy(),
4589                              /*Qualified=*/true);
4590     return Name;
4591   });
4592 
4593   auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
4594   // Create the descriptor for the variable.
4595   llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
4596   StringRef Name = VD->getName();
4597   llvm::DIType *Ty = getOrCreateType(VD->getType(), Unit);
4598 
4599   if (const auto *ECD = dyn_cast<EnumConstantDecl>(VD)) {
4600     const auto *ED = cast<EnumDecl>(ECD->getDeclContext());
4601     assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
4602 
4603     if (CGM.getCodeGenOpts().EmitCodeView) {
4604       // If CodeView, emit enums as global variables, unless they are defined
4605       // inside a class. We do this because MSVC doesn't emit S_CONSTANTs for
4606       // enums in classes, and because it is difficult to attach this scope
4607       // information to the global variable.
4608       if (isa<RecordDecl>(ED->getDeclContext()))
4609         return;
4610     } else {
4611       // If not CodeView, emit DW_TAG_enumeration_type if necessary. For
4612       // example: for "enum { ZERO };", a DW_TAG_enumeration_type is created the
4613       // first time `ZERO` is referenced in a function.
4614       llvm::DIType *EDTy =
4615           getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
4616       assert (EDTy->getTag() == llvm::dwarf::DW_TAG_enumeration_type);
4617       (void)EDTy;
4618       return;
4619     }
4620   }
4621 
4622   llvm::DIScope *DContext = nullptr;
4623 
4624   // Do not emit separate definitions for function local consts.
4625   if (isa<FunctionDecl>(VD->getDeclContext()))
4626     return;
4627 
4628   // Emit definition for static members in CodeView.
4629   VD = cast<ValueDecl>(VD->getCanonicalDecl());
4630   auto *VarD = dyn_cast<VarDecl>(VD);
4631   if (VarD && VarD->isStaticDataMember()) {
4632     auto *RD = cast<RecordDecl>(VarD->getDeclContext());
4633     getDeclContextDescriptor(VarD);
4634     // Ensure that the type is retained even though it's otherwise unreferenced.
4635     //
4636     // FIXME: This is probably unnecessary, since Ty should reference RD
4637     // through its scope.
4638     RetainedTypes.push_back(
4639         CGM.getContext().getRecordType(RD).getAsOpaquePtr());
4640 
4641     if (!CGM.getCodeGenOpts().EmitCodeView)
4642       return;
4643 
4644     // Use the global scope for static members.
4645     DContext = getContextDescriptor(
4646         cast<Decl>(CGM.getContext().getTranslationUnitDecl()), TheCU);
4647   } else {
4648     DContext = getDeclContextDescriptor(VD);
4649   }
4650 
4651   auto &GV = DeclCache[VD];
4652   if (GV)
4653     return;
4654   llvm::DIExpression *InitExpr = nullptr;
4655   if (CGM.getContext().getTypeSize(VD->getType()) <= 64) {
4656     // FIXME: Add a representation for integer constants wider than 64 bits.
4657     if (Init.isInt())
4658       InitExpr =
4659           DBuilder.createConstantValueExpression(Init.getInt().getExtValue());
4660     else if (Init.isFloat())
4661       InitExpr = DBuilder.createConstantValueExpression(
4662           Init.getFloat().bitcastToAPInt().getZExtValue());
4663   }
4664 
4665   llvm::MDTuple *TemplateParameters = nullptr;
4666 
4667   if (isa<VarTemplateSpecializationDecl>(VD))
4668     if (VarD) {
4669       llvm::DINodeArray parameterNodes = CollectVarTemplateParams(VarD, &*Unit);
4670       TemplateParameters = parameterNodes.get();
4671     }
4672 
4673   GV.reset(DBuilder.createGlobalVariableExpression(
4674       DContext, Name, StringRef(), Unit, getLineNumber(VD->getLocation()), Ty,
4675       true, true, InitExpr, getOrCreateStaticDataMemberDeclarationOrNull(VarD),
4676       TemplateParameters, Align));
4677 }
4678 
4679 void CGDebugInfo::EmitExternalVariable(llvm::GlobalVariable *Var,
4680                                        const VarDecl *D) {
4681   assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4682   if (D->hasAttr<NoDebugAttr>())
4683     return;
4684 
4685   auto Align = getDeclAlignIfRequired(D, CGM.getContext());
4686   llvm::DIFile *Unit = getOrCreateFile(D->getLocation());
4687   StringRef Name = D->getName();
4688   llvm::DIType *Ty = getOrCreateType(D->getType(), Unit);
4689 
4690   llvm::DIScope *DContext = getDeclContextDescriptor(D);
4691   llvm::DIGlobalVariableExpression *GVE =
4692       DBuilder.createGlobalVariableExpression(
4693           DContext, Name, StringRef(), Unit, getLineNumber(D->getLocation()),
4694           Ty, false, false, nullptr, nullptr, nullptr, Align);
4695   Var->addDebugInfo(GVE);
4696 }
4697 
4698 llvm::DIScope *CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
4699   if (!LexicalBlockStack.empty())
4700     return LexicalBlockStack.back();
4701   llvm::DIScope *Mod = getParentModuleOrNull(D);
4702   return getContextDescriptor(D, Mod ? Mod : TheCU);
4703 }
4704 
4705 void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
4706   if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
4707     return;
4708   const NamespaceDecl *NSDecl = UD.getNominatedNamespace();
4709   if (!NSDecl->isAnonymousNamespace() ||
4710       CGM.getCodeGenOpts().DebugExplicitImport) {
4711     auto Loc = UD.getLocation();
4712     DBuilder.createImportedModule(
4713         getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
4714         getOrCreateNamespace(NSDecl), getOrCreateFile(Loc), getLineNumber(Loc));
4715   }
4716 }
4717 
4718 void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
4719   if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
4720     return;
4721   assert(UD.shadow_size() &&
4722          "We shouldn't be codegening an invalid UsingDecl containing no decls");
4723   // Emitting one decl is sufficient - debuggers can detect that this is an
4724   // overloaded name & provide lookup for all the overloads.
4725   const UsingShadowDecl &USD = **UD.shadow_begin();
4726 
4727   // FIXME: Skip functions with undeduced auto return type for now since we
4728   // don't currently have the plumbing for separate declarations & definitions
4729   // of free functions and mismatched types (auto in the declaration, concrete
4730   // return type in the definition)
4731   if (const auto *FD = dyn_cast<FunctionDecl>(USD.getUnderlyingDecl()))
4732     if (const auto *AT =
4733             FD->getType()->castAs<FunctionProtoType>()->getContainedAutoType())
4734       if (AT->getDeducedType().isNull())
4735         return;
4736   if (llvm::DINode *Target =
4737           getDeclarationOrDefinition(USD.getUnderlyingDecl())) {
4738     auto Loc = USD.getLocation();
4739     DBuilder.createImportedDeclaration(
4740         getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
4741         getOrCreateFile(Loc), getLineNumber(Loc));
4742   }
4743 }
4744 
4745 void CGDebugInfo::EmitImportDecl(const ImportDecl &ID) {
4746   if (CGM.getCodeGenOpts().getDebuggerTuning() != llvm::DebuggerKind::LLDB)
4747     return;
4748   if (Module *M = ID.getImportedModule()) {
4749     auto Info = ASTSourceDescriptor(*M);
4750     auto Loc = ID.getLocation();
4751     DBuilder.createImportedDeclaration(
4752         getCurrentContextDescriptor(cast<Decl>(ID.getDeclContext())),
4753         getOrCreateModuleRef(Info, DebugTypeExtRefs), getOrCreateFile(Loc),
4754         getLineNumber(Loc));
4755   }
4756 }
4757 
4758 llvm::DIImportedEntity *
4759 CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
4760   if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
4761     return nullptr;
4762   auto &VH = NamespaceAliasCache[&NA];
4763   if (VH)
4764     return cast<llvm::DIImportedEntity>(VH);
4765   llvm::DIImportedEntity *R;
4766   auto Loc = NA.getLocation();
4767   if (const auto *Underlying =
4768           dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
4769     // This could cache & dedup here rather than relying on metadata deduping.
4770     R = DBuilder.createImportedDeclaration(
4771         getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
4772         EmitNamespaceAlias(*Underlying), getOrCreateFile(Loc),
4773         getLineNumber(Loc), NA.getName());
4774   else
4775     R = DBuilder.createImportedDeclaration(
4776         getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
4777         getOrCreateNamespace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
4778         getOrCreateFile(Loc), getLineNumber(Loc), NA.getName());
4779   VH.reset(R);
4780   return R;
4781 }
4782 
4783 llvm::DINamespace *
4784 CGDebugInfo::getOrCreateNamespace(const NamespaceDecl *NSDecl) {
4785   // Don't canonicalize the NamespaceDecl here: The DINamespace will be uniqued
4786   // if necessary, and this way multiple declarations of the same namespace in
4787   // different parent modules stay distinct.
4788   auto I = NamespaceCache.find(NSDecl);
4789   if (I != NamespaceCache.end())
4790     return cast<llvm::DINamespace>(I->second);
4791 
4792   llvm::DIScope *Context = getDeclContextDescriptor(NSDecl);
4793   // Don't trust the context if it is a DIModule (see comment above).
4794   llvm::DINamespace *NS =
4795       DBuilder.createNameSpace(Context, NSDecl->getName(), NSDecl->isInline());
4796   NamespaceCache[NSDecl].reset(NS);
4797   return NS;
4798 }
4799 
4800 void CGDebugInfo::setDwoId(uint64_t Signature) {
4801   assert(TheCU && "no main compile unit");
4802   TheCU->setDWOId(Signature);
4803 }
4804 
4805 void CGDebugInfo::finalize() {
4806   // Creating types might create further types - invalidating the current
4807   // element and the size(), so don't cache/reference them.
4808   for (size_t i = 0; i != ObjCInterfaceCache.size(); ++i) {
4809     ObjCInterfaceCacheEntry E = ObjCInterfaceCache[i];
4810     llvm::DIType *Ty = E.Type->getDecl()->getDefinition()
4811                            ? CreateTypeDefinition(E.Type, E.Unit)
4812                            : E.Decl;
4813     DBuilder.replaceTemporary(llvm::TempDIType(E.Decl), Ty);
4814   }
4815 
4816   // Add methods to interface.
4817   for (const auto &P : ObjCMethodCache) {
4818     if (P.second.empty())
4819       continue;
4820 
4821     QualType QTy(P.first->getTypeForDecl(), 0);
4822     auto It = TypeCache.find(QTy.getAsOpaquePtr());
4823     assert(It != TypeCache.end());
4824 
4825     llvm::DICompositeType *InterfaceDecl =
4826         cast<llvm::DICompositeType>(It->second);
4827 
4828     auto CurElts = InterfaceDecl->getElements();
4829     SmallVector<llvm::Metadata *, 16> EltTys(CurElts.begin(), CurElts.end());
4830 
4831     // For DWARF v4 or earlier, only add objc_direct methods.
4832     for (auto &SubprogramDirect : P.second)
4833       if (CGM.getCodeGenOpts().DwarfVersion >= 5 || SubprogramDirect.getInt())
4834         EltTys.push_back(SubprogramDirect.getPointer());
4835 
4836     llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
4837     DBuilder.replaceArrays(InterfaceDecl, Elements);
4838   }
4839 
4840   for (const auto &P : ReplaceMap) {
4841     assert(P.second);
4842     auto *Ty = cast<llvm::DIType>(P.second);
4843     assert(Ty->isForwardDecl());
4844 
4845     auto It = TypeCache.find(P.first);
4846     assert(It != TypeCache.end());
4847     assert(It->second);
4848 
4849     DBuilder.replaceTemporary(llvm::TempDIType(Ty),
4850                               cast<llvm::DIType>(It->second));
4851   }
4852 
4853   for (const auto &P : FwdDeclReplaceMap) {
4854     assert(P.second);
4855     llvm::TempMDNode FwdDecl(cast<llvm::MDNode>(P.second));
4856     llvm::Metadata *Repl;
4857 
4858     auto It = DeclCache.find(P.first);
4859     // If there has been no definition for the declaration, call RAUW
4860     // with ourselves, that will destroy the temporary MDNode and
4861     // replace it with a standard one, avoiding leaking memory.
4862     if (It == DeclCache.end())
4863       Repl = P.second;
4864     else
4865       Repl = It->second;
4866 
4867     if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(Repl))
4868       Repl = GVE->getVariable();
4869     DBuilder.replaceTemporary(std::move(FwdDecl), cast<llvm::MDNode>(Repl));
4870   }
4871 
4872   // We keep our own list of retained types, because we need to look
4873   // up the final type in the type cache.
4874   for (auto &RT : RetainedTypes)
4875     if (auto MD = TypeCache[RT])
4876       DBuilder.retainType(cast<llvm::DIType>(MD));
4877 
4878   DBuilder.finalize();
4879 }
4880 
4881 void CGDebugInfo::EmitExplicitCastType(QualType Ty) {
4882   if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
4883     return;
4884 
4885   if (auto *DieTy = getOrCreateType(Ty, TheCU->getFile()))
4886     // Don't ignore in case of explicit cast where it is referenced indirectly.
4887     DBuilder.retainType(DieTy);
4888 }
4889 
4890 llvm::DebugLoc CGDebugInfo::SourceLocToDebugLoc(SourceLocation Loc) {
4891   if (LexicalBlockStack.empty())
4892     return llvm::DebugLoc();
4893 
4894   llvm::MDNode *Scope = LexicalBlockStack.back();
4895   return llvm::DebugLoc::get(getLineNumber(Loc), getColumnNumber(Loc), Scope);
4896 }
4897 
4898 llvm::DINode::DIFlags CGDebugInfo::getCallSiteRelatedAttrs() const {
4899   // Call site-related attributes are only useful in optimized programs, and
4900   // when there's a possibility of debugging backtraces.
4901   if (!CGM.getLangOpts().Optimize || DebugKind == codegenoptions::NoDebugInfo ||
4902       DebugKind == codegenoptions::LocTrackingOnly)
4903     return llvm::DINode::FlagZero;
4904 
4905   // Call site-related attributes are available in DWARF v5. Some debuggers,
4906   // while not fully DWARF v5-compliant, may accept these attributes as if they
4907   // were part of DWARF v4.
4908   bool SupportsDWARFv4Ext =
4909       CGM.getCodeGenOpts().DwarfVersion == 4 &&
4910       (CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB ||
4911        CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::GDB);
4912 
4913   if (!SupportsDWARFv4Ext && CGM.getCodeGenOpts().DwarfVersion < 5)
4914     return llvm::DINode::FlagZero;
4915 
4916   return llvm::DINode::FlagAllCallsDescribed;
4917 }
4918