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