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