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