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