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