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