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