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