1 //===-- ClangASTContext.cpp -------------------------------------*- C++ -*-===//
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 #include "lldb/Symbol/ClangASTContext.h"
11 
12 #include "llvm/Support/FormatAdapters.h"
13 #include "llvm/Support/FormatVariadic.h"
14 
15 // C Includes
16 // C++ Includes
17 #include <mutex>
18 #include <string>
19 #include <vector>
20 
21 // Other libraries and framework includes
22 
23 // Clang headers like to use NDEBUG inside of them to enable/disable debug
24 // related features using "#ifndef NDEBUG" preprocessor blocks to do one thing
25 // or another. This is bad because it means that if clang was built in release
26 // mode, it assumes that you are building in release mode which is not always
27 // the case. You can end up with functions that are defined as empty in header
28 // files when NDEBUG is not defined, and this can cause link errors with the
29 // clang .a files that you have since you might be missing functions in the .a
30 // file. So we have to define NDEBUG when including clang headers to avoid any
31 // mismatches. This is covered by rdar://problem/8691220
32 
33 #if !defined(NDEBUG) && !defined(LLVM_NDEBUG_OFF)
34 #define LLDB_DEFINED_NDEBUG_FOR_CLANG
35 #define NDEBUG
36 // Need to include assert.h so it is as clang would expect it to be (disabled)
37 #include <assert.h>
38 #endif
39 
40 #include "clang/AST/ASTContext.h"
41 #include "clang/AST/ASTImporter.h"
42 #include "clang/AST/Attr.h"
43 #include "clang/AST/CXXInheritance.h"
44 #include "clang/AST/DeclObjC.h"
45 #include "clang/AST/DeclTemplate.h"
46 #include "clang/AST/Mangle.h"
47 #include "clang/AST/RecordLayout.h"
48 #include "clang/AST/Type.h"
49 #include "clang/AST/VTableBuilder.h"
50 #include "clang/Basic/Builtins.h"
51 #include "clang/Basic/Diagnostic.h"
52 #include "clang/Basic/FileManager.h"
53 #include "clang/Basic/FileSystemOptions.h"
54 #include "clang/Basic/SourceManager.h"
55 #include "clang/Basic/TargetInfo.h"
56 #include "clang/Basic/TargetOptions.h"
57 #include "clang/Frontend/FrontendOptions.h"
58 #include "clang/Frontend/LangStandard.h"
59 
60 #ifdef LLDB_DEFINED_NDEBUG_FOR_CLANG
61 #undef NDEBUG
62 #undef LLDB_DEFINED_NDEBUG_FOR_CLANG
63 // Need to re-include assert.h so it is as _we_ would expect it to be (enabled)
64 #include <assert.h>
65 #endif
66 
67 #include "llvm/Support/Signals.h"
68 #include "llvm/Support/Threading.h"
69 
70 #include "Plugins/ExpressionParser/Clang/ClangFunctionCaller.h"
71 #include "Plugins/ExpressionParser/Clang/ClangUserExpression.h"
72 #include "Plugins/ExpressionParser/Clang/ClangUtilityFunction.h"
73 #include "lldb/Utility/ArchSpec.h"
74 #include "lldb/Utility/Flags.h"
75 
76 #include "lldb/Core/DumpDataExtractor.h"
77 #include "lldb/Core/Module.h"
78 #include "lldb/Core/PluginManager.h"
79 #include "lldb/Core/Scalar.h"
80 #include "lldb/Core/StreamFile.h"
81 #include "lldb/Core/ThreadSafeDenseMap.h"
82 #include "lldb/Core/UniqueCStringMap.h"
83 #include "lldb/Symbol/ClangASTContext.h"
84 #include "lldb/Symbol/ClangASTImporter.h"
85 #include "lldb/Symbol/ClangExternalASTSourceCallbacks.h"
86 #include "lldb/Symbol/ClangExternalASTSourceCommon.h"
87 #include "lldb/Symbol/ClangUtil.h"
88 #include "lldb/Symbol/ObjectFile.h"
89 #include "lldb/Symbol/SymbolFile.h"
90 #include "lldb/Symbol/VerifyDecl.h"
91 #include "lldb/Target/ExecutionContext.h"
92 #include "lldb/Target/Language.h"
93 #include "lldb/Target/ObjCLanguageRuntime.h"
94 #include "lldb/Target/Process.h"
95 #include "lldb/Target/Target.h"
96 #include "lldb/Utility/DataExtractor.h"
97 #include "lldb/Utility/LLDBAssert.h"
98 #include "lldb/Utility/Log.h"
99 #include "lldb/Utility/RegularExpression.h"
100 
101 #include "Plugins/SymbolFile/DWARF/DWARFASTParserClang.h"
102 //#include "Plugins/SymbolFile/PDB/PDBASTParser.h"
103 
104 #include <stdio.h>
105 
106 #include <mutex>
107 
108 using namespace lldb;
109 using namespace lldb_private;
110 using namespace llvm;
111 using namespace clang;
112 
113 namespace {
114 static inline bool
115 ClangASTContextSupportsLanguage(lldb::LanguageType language) {
116   return language == eLanguageTypeUnknown || // Clang is the default type system
117          Language::LanguageIsC(language) ||
118          Language::LanguageIsCPlusPlus(language) ||
119          Language::LanguageIsObjC(language) ||
120          Language::LanguageIsPascal(language) ||
121          // Use Clang for Rust until there is a proper language plugin for it
122          language == eLanguageTypeRust ||
123          language == eLanguageTypeExtRenderScript ||
124          // Use Clang for D until there is a proper language plugin for it
125          language == eLanguageTypeD;
126 }
127 }
128 
129 typedef lldb_private::ThreadSafeDenseMap<clang::ASTContext *, ClangASTContext *>
130     ClangASTMap;
131 
132 static ClangASTMap &GetASTMap() {
133   static ClangASTMap *g_map_ptr = nullptr;
134   static llvm::once_flag g_once_flag;
135   llvm::call_once(g_once_flag, []() {
136     g_map_ptr = new ClangASTMap(); // leaked on purpose to avoid spins
137   });
138   return *g_map_ptr;
139 }
140 
141 static bool IsOperator(const char *name,
142                        clang::OverloadedOperatorKind &op_kind) {
143   if (name == nullptr || name[0] == '\0')
144     return false;
145 
146 #define OPERATOR_PREFIX "operator"
147 #define OPERATOR_PREFIX_LENGTH (sizeof(OPERATOR_PREFIX) - 1)
148 
149   const char *post_op_name = nullptr;
150 
151   bool no_space = true;
152 
153   if (::strncmp(name, OPERATOR_PREFIX, OPERATOR_PREFIX_LENGTH))
154     return false;
155 
156   post_op_name = name + OPERATOR_PREFIX_LENGTH;
157 
158   if (post_op_name[0] == ' ') {
159     post_op_name++;
160     no_space = false;
161   }
162 
163 #undef OPERATOR_PREFIX
164 #undef OPERATOR_PREFIX_LENGTH
165 
166   // This is an operator, set the overloaded operator kind to invalid
167   // in case this is a conversion operator...
168   op_kind = clang::NUM_OVERLOADED_OPERATORS;
169 
170   switch (post_op_name[0]) {
171   default:
172     if (no_space)
173       return false;
174     break;
175   case 'n':
176     if (no_space)
177       return false;
178     if (strcmp(post_op_name, "new") == 0)
179       op_kind = clang::OO_New;
180     else if (strcmp(post_op_name, "new[]") == 0)
181       op_kind = clang::OO_Array_New;
182     break;
183 
184   case 'd':
185     if (no_space)
186       return false;
187     if (strcmp(post_op_name, "delete") == 0)
188       op_kind = clang::OO_Delete;
189     else if (strcmp(post_op_name, "delete[]") == 0)
190       op_kind = clang::OO_Array_Delete;
191     break;
192 
193   case '+':
194     if (post_op_name[1] == '\0')
195       op_kind = clang::OO_Plus;
196     else if (post_op_name[2] == '\0') {
197       if (post_op_name[1] == '=')
198         op_kind = clang::OO_PlusEqual;
199       else if (post_op_name[1] == '+')
200         op_kind = clang::OO_PlusPlus;
201     }
202     break;
203 
204   case '-':
205     if (post_op_name[1] == '\0')
206       op_kind = clang::OO_Minus;
207     else if (post_op_name[2] == '\0') {
208       switch (post_op_name[1]) {
209       case '=':
210         op_kind = clang::OO_MinusEqual;
211         break;
212       case '-':
213         op_kind = clang::OO_MinusMinus;
214         break;
215       case '>':
216         op_kind = clang::OO_Arrow;
217         break;
218       }
219     } else if (post_op_name[3] == '\0') {
220       if (post_op_name[2] == '*')
221         op_kind = clang::OO_ArrowStar;
222       break;
223     }
224     break;
225 
226   case '*':
227     if (post_op_name[1] == '\0')
228       op_kind = clang::OO_Star;
229     else if (post_op_name[1] == '=' && post_op_name[2] == '\0')
230       op_kind = clang::OO_StarEqual;
231     break;
232 
233   case '/':
234     if (post_op_name[1] == '\0')
235       op_kind = clang::OO_Slash;
236     else if (post_op_name[1] == '=' && post_op_name[2] == '\0')
237       op_kind = clang::OO_SlashEqual;
238     break;
239 
240   case '%':
241     if (post_op_name[1] == '\0')
242       op_kind = clang::OO_Percent;
243     else if (post_op_name[1] == '=' && post_op_name[2] == '\0')
244       op_kind = clang::OO_PercentEqual;
245     break;
246 
247   case '^':
248     if (post_op_name[1] == '\0')
249       op_kind = clang::OO_Caret;
250     else if (post_op_name[1] == '=' && post_op_name[2] == '\0')
251       op_kind = clang::OO_CaretEqual;
252     break;
253 
254   case '&':
255     if (post_op_name[1] == '\0')
256       op_kind = clang::OO_Amp;
257     else if (post_op_name[2] == '\0') {
258       switch (post_op_name[1]) {
259       case '=':
260         op_kind = clang::OO_AmpEqual;
261         break;
262       case '&':
263         op_kind = clang::OO_AmpAmp;
264         break;
265       }
266     }
267     break;
268 
269   case '|':
270     if (post_op_name[1] == '\0')
271       op_kind = clang::OO_Pipe;
272     else if (post_op_name[2] == '\0') {
273       switch (post_op_name[1]) {
274       case '=':
275         op_kind = clang::OO_PipeEqual;
276         break;
277       case '|':
278         op_kind = clang::OO_PipePipe;
279         break;
280       }
281     }
282     break;
283 
284   case '~':
285     if (post_op_name[1] == '\0')
286       op_kind = clang::OO_Tilde;
287     break;
288 
289   case '!':
290     if (post_op_name[1] == '\0')
291       op_kind = clang::OO_Exclaim;
292     else if (post_op_name[1] == '=' && post_op_name[2] == '\0')
293       op_kind = clang::OO_ExclaimEqual;
294     break;
295 
296   case '=':
297     if (post_op_name[1] == '\0')
298       op_kind = clang::OO_Equal;
299     else if (post_op_name[1] == '=' && post_op_name[2] == '\0')
300       op_kind = clang::OO_EqualEqual;
301     break;
302 
303   case '<':
304     if (post_op_name[1] == '\0')
305       op_kind = clang::OO_Less;
306     else if (post_op_name[2] == '\0') {
307       switch (post_op_name[1]) {
308       case '<':
309         op_kind = clang::OO_LessLess;
310         break;
311       case '=':
312         op_kind = clang::OO_LessEqual;
313         break;
314       }
315     } else if (post_op_name[3] == '\0') {
316       if (post_op_name[2] == '=')
317         op_kind = clang::OO_LessLessEqual;
318     }
319     break;
320 
321   case '>':
322     if (post_op_name[1] == '\0')
323       op_kind = clang::OO_Greater;
324     else if (post_op_name[2] == '\0') {
325       switch (post_op_name[1]) {
326       case '>':
327         op_kind = clang::OO_GreaterGreater;
328         break;
329       case '=':
330         op_kind = clang::OO_GreaterEqual;
331         break;
332       }
333     } else if (post_op_name[1] == '>' && post_op_name[2] == '=' &&
334                post_op_name[3] == '\0') {
335       op_kind = clang::OO_GreaterGreaterEqual;
336     }
337     break;
338 
339   case ',':
340     if (post_op_name[1] == '\0')
341       op_kind = clang::OO_Comma;
342     break;
343 
344   case '(':
345     if (post_op_name[1] == ')' && post_op_name[2] == '\0')
346       op_kind = clang::OO_Call;
347     break;
348 
349   case '[':
350     if (post_op_name[1] == ']' && post_op_name[2] == '\0')
351       op_kind = clang::OO_Subscript;
352     break;
353   }
354 
355   return true;
356 }
357 
358 clang::AccessSpecifier
359 ClangASTContext::ConvertAccessTypeToAccessSpecifier(AccessType access) {
360   switch (access) {
361   default:
362     break;
363   case eAccessNone:
364     return AS_none;
365   case eAccessPublic:
366     return AS_public;
367   case eAccessPrivate:
368     return AS_private;
369   case eAccessProtected:
370     return AS_protected;
371   }
372   return AS_none;
373 }
374 
375 static void ParseLangArgs(LangOptions &Opts, InputKind IK, const char *triple) {
376   // FIXME: Cleanup per-file based stuff.
377 
378   // Set some properties which depend solely on the input kind; it would be nice
379   // to move these to the language standard, and have the driver resolve the
380   // input kind + language standard.
381   if (IK.getLanguage() == InputKind::Asm) {
382     Opts.AsmPreprocessor = 1;
383   } else if (IK.isObjectiveC()) {
384     Opts.ObjC1 = Opts.ObjC2 = 1;
385   }
386 
387   LangStandard::Kind LangStd = LangStandard::lang_unspecified;
388 
389   if (LangStd == LangStandard::lang_unspecified) {
390     // Based on the base language, pick one.
391     switch (IK.getLanguage()) {
392     case InputKind::Unknown:
393     case InputKind::LLVM_IR:
394     case InputKind::RenderScript:
395       llvm_unreachable("Invalid input kind!");
396     case InputKind::OpenCL:
397       LangStd = LangStandard::lang_opencl10;
398       break;
399     case InputKind::CUDA:
400       LangStd = LangStandard::lang_cuda;
401       break;
402     case InputKind::Asm:
403     case InputKind::C:
404     case InputKind::ObjC:
405       LangStd = LangStandard::lang_gnu99;
406       break;
407     case InputKind::CXX:
408     case InputKind::ObjCXX:
409       LangStd = LangStandard::lang_gnucxx98;
410       break;
411     }
412   }
413 
414   const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd);
415   Opts.LineComment = Std.hasLineComments();
416   Opts.C99 = Std.isC99();
417   Opts.CPlusPlus = Std.isCPlusPlus();
418   Opts.CPlusPlus11 = Std.isCPlusPlus11();
419   Opts.Digraphs = Std.hasDigraphs();
420   Opts.GNUMode = Std.isGNUMode();
421   Opts.GNUInline = !Std.isC99();
422   Opts.HexFloats = Std.hasHexFloats();
423   Opts.ImplicitInt = Std.hasImplicitInt();
424 
425   Opts.WChar = true;
426 
427   // OpenCL has some additional defaults.
428   if (LangStd == LangStandard::lang_opencl10) {
429     Opts.OpenCL = 1;
430     Opts.AltiVec = 1;
431     Opts.CXXOperatorNames = 1;
432     Opts.LaxVectorConversions = 1;
433   }
434 
435   // OpenCL and C++ both have bool, true, false keywords.
436   Opts.Bool = Opts.OpenCL || Opts.CPlusPlus;
437 
438   Opts.setValueVisibilityMode(DefaultVisibility);
439 
440   // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs
441   // is specified, or -std is set to a conforming mode.
442   Opts.Trigraphs = !Opts.GNUMode;
443   Opts.CharIsSigned = ArchSpec(triple).CharIsSignedByDefault();
444   Opts.OptimizeSize = 0;
445 
446   // FIXME: Eliminate this dependency.
447   //    unsigned Opt =
448   //    Args.hasArg(OPT_Os) ? 2 : getLastArgIntValue(Args, OPT_O, 0, Diags);
449   //    Opts.Optimize = Opt != 0;
450   unsigned Opt = 0;
451 
452   // This is the __NO_INLINE__ define, which just depends on things like the
453   // optimization level and -fno-inline, not actually whether the backend has
454   // inlining enabled.
455   //
456   // FIXME: This is affected by other options (-fno-inline).
457   Opts.NoInlineDefine = !Opt;
458 }
459 
460 ClangASTContext::ClangASTContext(const char *target_triple)
461     : TypeSystem(TypeSystem::eKindClang), m_target_triple(), m_ast_ap(),
462       m_language_options_ap(), m_source_manager_ap(), m_diagnostics_engine_ap(),
463       m_target_options_rp(), m_target_info_ap(), m_identifier_table_ap(),
464       m_selector_table_ap(), m_builtins_ap(), m_callback_tag_decl(nullptr),
465       m_callback_objc_decl(nullptr), m_callback_baton(nullptr),
466       m_pointer_byte_size(0), m_ast_owned(false) {
467   if (target_triple && target_triple[0])
468     SetTargetTriple(target_triple);
469 }
470 
471 //----------------------------------------------------------------------
472 // Destructor
473 //----------------------------------------------------------------------
474 ClangASTContext::~ClangASTContext() { Finalize(); }
475 
476 ConstString ClangASTContext::GetPluginNameStatic() {
477   return ConstString("clang");
478 }
479 
480 ConstString ClangASTContext::GetPluginName() {
481   return ClangASTContext::GetPluginNameStatic();
482 }
483 
484 uint32_t ClangASTContext::GetPluginVersion() { return 1; }
485 
486 lldb::TypeSystemSP ClangASTContext::CreateInstance(lldb::LanguageType language,
487                                                    lldb_private::Module *module,
488                                                    Target *target) {
489   if (ClangASTContextSupportsLanguage(language)) {
490     ArchSpec arch;
491     if (module)
492       arch = module->GetArchitecture();
493     else if (target)
494       arch = target->GetArchitecture();
495 
496     if (arch.IsValid()) {
497       ArchSpec fixed_arch = arch;
498       // LLVM wants this to be set to iOS or MacOSX; if we're working on
499       // a bare-boards type image, change the triple for llvm's benefit.
500       if (fixed_arch.GetTriple().getVendor() == llvm::Triple::Apple &&
501           fixed_arch.GetTriple().getOS() == llvm::Triple::UnknownOS) {
502         if (fixed_arch.GetTriple().getArch() == llvm::Triple::arm ||
503             fixed_arch.GetTriple().getArch() == llvm::Triple::aarch64 ||
504             fixed_arch.GetTriple().getArch() == llvm::Triple::thumb) {
505           fixed_arch.GetTriple().setOS(llvm::Triple::IOS);
506         } else {
507           fixed_arch.GetTriple().setOS(llvm::Triple::MacOSX);
508         }
509       }
510 
511       if (module) {
512         std::shared_ptr<ClangASTContext> ast_sp(new ClangASTContext);
513         if (ast_sp) {
514           ast_sp->SetArchitecture(fixed_arch);
515         }
516         return ast_sp;
517       } else if (target && target->IsValid()) {
518         std::shared_ptr<ClangASTContextForExpressions> ast_sp(
519             new ClangASTContextForExpressions(*target));
520         if (ast_sp) {
521           ast_sp->SetArchitecture(fixed_arch);
522           ast_sp->m_scratch_ast_source_ap.reset(
523               new ClangASTSource(target->shared_from_this()));
524           lldbassert(ast_sp->getFileManager());
525           ast_sp->m_scratch_ast_source_ap->InstallASTContext(
526               *ast_sp->getASTContext(), *ast_sp->getFileManager(), true);
527           llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> proxy_ast_source(
528               ast_sp->m_scratch_ast_source_ap->CreateProxy());
529           ast_sp->SetExternalSource(proxy_ast_source);
530           return ast_sp;
531         }
532       }
533     }
534   }
535   return lldb::TypeSystemSP();
536 }
537 
538 void ClangASTContext::EnumerateSupportedLanguages(
539     std::set<lldb::LanguageType> &languages_for_types,
540     std::set<lldb::LanguageType> &languages_for_expressions) {
541   static std::vector<lldb::LanguageType> s_supported_languages_for_types(
542       {lldb::eLanguageTypeC89, lldb::eLanguageTypeC, lldb::eLanguageTypeC11,
543        lldb::eLanguageTypeC_plus_plus, lldb::eLanguageTypeC99,
544        lldb::eLanguageTypeObjC, lldb::eLanguageTypeObjC_plus_plus,
545        lldb::eLanguageTypeC_plus_plus_03, lldb::eLanguageTypeC_plus_plus_11,
546        lldb::eLanguageTypeC11, lldb::eLanguageTypeC_plus_plus_14});
547 
548   static std::vector<lldb::LanguageType> s_supported_languages_for_expressions(
549       {lldb::eLanguageTypeC_plus_plus, lldb::eLanguageTypeObjC_plus_plus,
550        lldb::eLanguageTypeC_plus_plus_03, lldb::eLanguageTypeC_plus_plus_11,
551        lldb::eLanguageTypeC_plus_plus_14});
552 
553   languages_for_types.insert(s_supported_languages_for_types.begin(),
554                              s_supported_languages_for_types.end());
555   languages_for_expressions.insert(
556       s_supported_languages_for_expressions.begin(),
557       s_supported_languages_for_expressions.end());
558 }
559 
560 void ClangASTContext::Initialize() {
561   PluginManager::RegisterPlugin(GetPluginNameStatic(),
562                                 "clang base AST context plug-in",
563                                 CreateInstance, EnumerateSupportedLanguages);
564 }
565 
566 void ClangASTContext::Terminate() {
567   PluginManager::UnregisterPlugin(CreateInstance);
568 }
569 
570 void ClangASTContext::Finalize() {
571   if (m_ast_ap.get()) {
572     GetASTMap().Erase(m_ast_ap.get());
573     if (!m_ast_owned)
574       m_ast_ap.release();
575   }
576 
577   m_builtins_ap.reset();
578   m_selector_table_ap.reset();
579   m_identifier_table_ap.reset();
580   m_target_info_ap.reset();
581   m_target_options_rp.reset();
582   m_diagnostics_engine_ap.reset();
583   m_source_manager_ap.reset();
584   m_language_options_ap.reset();
585   m_ast_ap.reset();
586   m_scratch_ast_source_ap.reset();
587 }
588 
589 void ClangASTContext::Clear() {
590   m_ast_ap.reset();
591   m_language_options_ap.reset();
592   m_source_manager_ap.reset();
593   m_diagnostics_engine_ap.reset();
594   m_target_options_rp.reset();
595   m_target_info_ap.reset();
596   m_identifier_table_ap.reset();
597   m_selector_table_ap.reset();
598   m_builtins_ap.reset();
599   m_pointer_byte_size = 0;
600 }
601 
602 const char *ClangASTContext::GetTargetTriple() {
603   return m_target_triple.c_str();
604 }
605 
606 void ClangASTContext::SetTargetTriple(const char *target_triple) {
607   Clear();
608   m_target_triple.assign(target_triple);
609 }
610 
611 void ClangASTContext::SetArchitecture(const ArchSpec &arch) {
612   SetTargetTriple(arch.GetTriple().str().c_str());
613 }
614 
615 bool ClangASTContext::HasExternalSource() {
616   ASTContext *ast = getASTContext();
617   if (ast)
618     return ast->getExternalSource() != nullptr;
619   return false;
620 }
621 
622 void ClangASTContext::SetExternalSource(
623     llvm::IntrusiveRefCntPtr<ExternalASTSource> &ast_source_ap) {
624   ASTContext *ast = getASTContext();
625   if (ast) {
626     ast->setExternalSource(ast_source_ap);
627     ast->getTranslationUnitDecl()->setHasExternalLexicalStorage(true);
628     // ast->getTranslationUnitDecl()->setHasExternalVisibleStorage(true);
629   }
630 }
631 
632 void ClangASTContext::RemoveExternalSource() {
633   ASTContext *ast = getASTContext();
634 
635   if (ast) {
636     llvm::IntrusiveRefCntPtr<ExternalASTSource> empty_ast_source_ap;
637     ast->setExternalSource(empty_ast_source_ap);
638     ast->getTranslationUnitDecl()->setHasExternalLexicalStorage(false);
639     // ast->getTranslationUnitDecl()->setHasExternalVisibleStorage(false);
640   }
641 }
642 
643 void ClangASTContext::setASTContext(clang::ASTContext *ast_ctx) {
644   if (!m_ast_owned) {
645     m_ast_ap.release();
646   }
647   m_ast_owned = false;
648   m_ast_ap.reset(ast_ctx);
649   GetASTMap().Insert(ast_ctx, this);
650 }
651 
652 ASTContext *ClangASTContext::getASTContext() {
653   if (m_ast_ap.get() == nullptr) {
654     m_ast_owned = true;
655     m_ast_ap.reset(new ASTContext(*getLanguageOptions(), *getSourceManager(),
656                                   *getIdentifierTable(), *getSelectorTable(),
657                                   *getBuiltinContext()));
658 
659     m_ast_ap->getDiagnostics().setClient(getDiagnosticConsumer(), false);
660 
661     // This can be NULL if we don't know anything about the architecture or if
662     // the
663     // target for an architecture isn't enabled in the llvm/clang that we built
664     TargetInfo *target_info = getTargetInfo();
665     if (target_info)
666       m_ast_ap->InitBuiltinTypes(*target_info);
667 
668     if ((m_callback_tag_decl || m_callback_objc_decl) && m_callback_baton) {
669       m_ast_ap->getTranslationUnitDecl()->setHasExternalLexicalStorage();
670       // m_ast_ap->getTranslationUnitDecl()->setHasExternalVisibleStorage();
671     }
672 
673     GetASTMap().Insert(m_ast_ap.get(), this);
674 
675     llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> ast_source_ap(
676         new ClangExternalASTSourceCallbacks(
677             ClangASTContext::CompleteTagDecl,
678             ClangASTContext::CompleteObjCInterfaceDecl, nullptr,
679             ClangASTContext::LayoutRecordType, this));
680     SetExternalSource(ast_source_ap);
681   }
682   return m_ast_ap.get();
683 }
684 
685 ClangASTContext *ClangASTContext::GetASTContext(clang::ASTContext *ast) {
686   ClangASTContext *clang_ast = GetASTMap().Lookup(ast);
687   return clang_ast;
688 }
689 
690 Builtin::Context *ClangASTContext::getBuiltinContext() {
691   if (m_builtins_ap.get() == nullptr)
692     m_builtins_ap.reset(new Builtin::Context());
693   return m_builtins_ap.get();
694 }
695 
696 IdentifierTable *ClangASTContext::getIdentifierTable() {
697   if (m_identifier_table_ap.get() == nullptr)
698     m_identifier_table_ap.reset(
699         new IdentifierTable(*ClangASTContext::getLanguageOptions(), nullptr));
700   return m_identifier_table_ap.get();
701 }
702 
703 LangOptions *ClangASTContext::getLanguageOptions() {
704   if (m_language_options_ap.get() == nullptr) {
705     m_language_options_ap.reset(new LangOptions());
706     ParseLangArgs(*m_language_options_ap, InputKind::ObjCXX, GetTargetTriple());
707     //        InitializeLangOptions(*m_language_options_ap, InputKind::ObjCXX);
708   }
709   return m_language_options_ap.get();
710 }
711 
712 SelectorTable *ClangASTContext::getSelectorTable() {
713   if (m_selector_table_ap.get() == nullptr)
714     m_selector_table_ap.reset(new SelectorTable());
715   return m_selector_table_ap.get();
716 }
717 
718 clang::FileManager *ClangASTContext::getFileManager() {
719   if (m_file_manager_ap.get() == nullptr) {
720     clang::FileSystemOptions file_system_options;
721     m_file_manager_ap.reset(new clang::FileManager(file_system_options));
722   }
723   return m_file_manager_ap.get();
724 }
725 
726 clang::SourceManager *ClangASTContext::getSourceManager() {
727   if (m_source_manager_ap.get() == nullptr)
728     m_source_manager_ap.reset(
729         new clang::SourceManager(*getDiagnosticsEngine(), *getFileManager()));
730   return m_source_manager_ap.get();
731 }
732 
733 clang::DiagnosticsEngine *ClangASTContext::getDiagnosticsEngine() {
734   if (m_diagnostics_engine_ap.get() == nullptr) {
735     llvm::IntrusiveRefCntPtr<DiagnosticIDs> diag_id_sp(new DiagnosticIDs());
736     m_diagnostics_engine_ap.reset(
737         new DiagnosticsEngine(diag_id_sp, new DiagnosticOptions()));
738   }
739   return m_diagnostics_engine_ap.get();
740 }
741 
742 clang::MangleContext *ClangASTContext::getMangleContext() {
743   if (m_mangle_ctx_ap.get() == nullptr)
744     m_mangle_ctx_ap.reset(getASTContext()->createMangleContext());
745   return m_mangle_ctx_ap.get();
746 }
747 
748 class NullDiagnosticConsumer : public DiagnosticConsumer {
749 public:
750   NullDiagnosticConsumer() {
751     m_log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS);
752   }
753 
754   void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
755                         const clang::Diagnostic &info) {
756     if (m_log) {
757       llvm::SmallVector<char, 32> diag_str(10);
758       info.FormatDiagnostic(diag_str);
759       diag_str.push_back('\0');
760       m_log->Printf("Compiler diagnostic: %s\n", diag_str.data());
761     }
762   }
763 
764   DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
765     return new NullDiagnosticConsumer();
766   }
767 
768 private:
769   Log *m_log;
770 };
771 
772 DiagnosticConsumer *ClangASTContext::getDiagnosticConsumer() {
773   if (m_diagnostic_consumer_ap.get() == nullptr)
774     m_diagnostic_consumer_ap.reset(new NullDiagnosticConsumer);
775 
776   return m_diagnostic_consumer_ap.get();
777 }
778 
779 std::shared_ptr<clang::TargetOptions> &ClangASTContext::getTargetOptions() {
780   if (m_target_options_rp.get() == nullptr && !m_target_triple.empty()) {
781     m_target_options_rp = std::make_shared<clang::TargetOptions>();
782     if (m_target_options_rp.get() != nullptr)
783       m_target_options_rp->Triple = m_target_triple;
784   }
785   return m_target_options_rp;
786 }
787 
788 TargetInfo *ClangASTContext::getTargetInfo() {
789   // target_triple should be something like "x86_64-apple-macosx"
790   if (m_target_info_ap.get() == nullptr && !m_target_triple.empty())
791     m_target_info_ap.reset(TargetInfo::CreateTargetInfo(*getDiagnosticsEngine(),
792                                                         getTargetOptions()));
793   return m_target_info_ap.get();
794 }
795 
796 #pragma mark Basic Types
797 
798 static inline bool QualTypeMatchesBitSize(const uint64_t bit_size,
799                                           ASTContext *ast, QualType qual_type) {
800   uint64_t qual_type_bit_size = ast->getTypeSize(qual_type);
801   if (qual_type_bit_size == bit_size)
802     return true;
803   return false;
804 }
805 
806 CompilerType
807 ClangASTContext::GetBuiltinTypeForEncodingAndBitSize(Encoding encoding,
808                                                      size_t bit_size) {
809   return ClangASTContext::GetBuiltinTypeForEncodingAndBitSize(
810       getASTContext(), encoding, bit_size);
811 }
812 
813 CompilerType ClangASTContext::GetBuiltinTypeForEncodingAndBitSize(
814     ASTContext *ast, Encoding encoding, uint32_t bit_size) {
815   if (!ast)
816     return CompilerType();
817   switch (encoding) {
818   case eEncodingInvalid:
819     if (QualTypeMatchesBitSize(bit_size, ast, ast->VoidPtrTy))
820       return CompilerType(ast, ast->VoidPtrTy);
821     break;
822 
823   case eEncodingUint:
824     if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedCharTy))
825       return CompilerType(ast, ast->UnsignedCharTy);
826     if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedShortTy))
827       return CompilerType(ast, ast->UnsignedShortTy);
828     if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedIntTy))
829       return CompilerType(ast, ast->UnsignedIntTy);
830     if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedLongTy))
831       return CompilerType(ast, ast->UnsignedLongTy);
832     if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedLongLongTy))
833       return CompilerType(ast, ast->UnsignedLongLongTy);
834     if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedInt128Ty))
835       return CompilerType(ast, ast->UnsignedInt128Ty);
836     break;
837 
838   case eEncodingSint:
839     if (QualTypeMatchesBitSize(bit_size, ast, ast->SignedCharTy))
840       return CompilerType(ast, ast->SignedCharTy);
841     if (QualTypeMatchesBitSize(bit_size, ast, ast->ShortTy))
842       return CompilerType(ast, ast->ShortTy);
843     if (QualTypeMatchesBitSize(bit_size, ast, ast->IntTy))
844       return CompilerType(ast, ast->IntTy);
845     if (QualTypeMatchesBitSize(bit_size, ast, ast->LongTy))
846       return CompilerType(ast, ast->LongTy);
847     if (QualTypeMatchesBitSize(bit_size, ast, ast->LongLongTy))
848       return CompilerType(ast, ast->LongLongTy);
849     if (QualTypeMatchesBitSize(bit_size, ast, ast->Int128Ty))
850       return CompilerType(ast, ast->Int128Ty);
851     break;
852 
853   case eEncodingIEEE754:
854     if (QualTypeMatchesBitSize(bit_size, ast, ast->FloatTy))
855       return CompilerType(ast, ast->FloatTy);
856     if (QualTypeMatchesBitSize(bit_size, ast, ast->DoubleTy))
857       return CompilerType(ast, ast->DoubleTy);
858     if (QualTypeMatchesBitSize(bit_size, ast, ast->LongDoubleTy))
859       return CompilerType(ast, ast->LongDoubleTy);
860     if (QualTypeMatchesBitSize(bit_size, ast, ast->HalfTy))
861       return CompilerType(ast, ast->HalfTy);
862     break;
863 
864   case eEncodingVector:
865     // Sanity check that bit_size is a multiple of 8's.
866     if (bit_size && !(bit_size & 0x7u))
867       return CompilerType(
868           ast, ast->getExtVectorType(ast->UnsignedCharTy, bit_size / 8));
869     break;
870   }
871 
872   return CompilerType();
873 }
874 
875 lldb::BasicType
876 ClangASTContext::GetBasicTypeEnumeration(const ConstString &name) {
877   if (name) {
878     typedef UniqueCStringMap<lldb::BasicType> TypeNameToBasicTypeMap;
879     static TypeNameToBasicTypeMap g_type_map;
880     static llvm::once_flag g_once_flag;
881     llvm::call_once(g_once_flag, []() {
882       // "void"
883       g_type_map.Append(ConstString("void"), eBasicTypeVoid);
884 
885       // "char"
886       g_type_map.Append(ConstString("char"), eBasicTypeChar);
887       g_type_map.Append(ConstString("signed char"), eBasicTypeSignedChar);
888       g_type_map.Append(ConstString("unsigned char"), eBasicTypeUnsignedChar);
889       g_type_map.Append(ConstString("wchar_t"), eBasicTypeWChar);
890       g_type_map.Append(ConstString("signed wchar_t"), eBasicTypeSignedWChar);
891       g_type_map.Append(ConstString("unsigned wchar_t"),
892                         eBasicTypeUnsignedWChar);
893       // "short"
894       g_type_map.Append(ConstString("short"), eBasicTypeShort);
895       g_type_map.Append(ConstString("short int"), eBasicTypeShort);
896       g_type_map.Append(ConstString("unsigned short"), eBasicTypeUnsignedShort);
897       g_type_map.Append(ConstString("unsigned short int"),
898                         eBasicTypeUnsignedShort);
899 
900       // "int"
901       g_type_map.Append(ConstString("int"), eBasicTypeInt);
902       g_type_map.Append(ConstString("signed int"), eBasicTypeInt);
903       g_type_map.Append(ConstString("unsigned int"), eBasicTypeUnsignedInt);
904       g_type_map.Append(ConstString("unsigned"), eBasicTypeUnsignedInt);
905 
906       // "long"
907       g_type_map.Append(ConstString("long"), eBasicTypeLong);
908       g_type_map.Append(ConstString("long int"), eBasicTypeLong);
909       g_type_map.Append(ConstString("unsigned long"), eBasicTypeUnsignedLong);
910       g_type_map.Append(ConstString("unsigned long int"),
911                         eBasicTypeUnsignedLong);
912 
913       // "long long"
914       g_type_map.Append(ConstString("long long"), eBasicTypeLongLong);
915       g_type_map.Append(ConstString("long long int"), eBasicTypeLongLong);
916       g_type_map.Append(ConstString("unsigned long long"),
917                         eBasicTypeUnsignedLongLong);
918       g_type_map.Append(ConstString("unsigned long long int"),
919                         eBasicTypeUnsignedLongLong);
920 
921       // "int128"
922       g_type_map.Append(ConstString("__int128_t"), eBasicTypeInt128);
923       g_type_map.Append(ConstString("__uint128_t"), eBasicTypeUnsignedInt128);
924 
925       // Miscellaneous
926       g_type_map.Append(ConstString("bool"), eBasicTypeBool);
927       g_type_map.Append(ConstString("float"), eBasicTypeFloat);
928       g_type_map.Append(ConstString("double"), eBasicTypeDouble);
929       g_type_map.Append(ConstString("long double"), eBasicTypeLongDouble);
930       g_type_map.Append(ConstString("id"), eBasicTypeObjCID);
931       g_type_map.Append(ConstString("SEL"), eBasicTypeObjCSel);
932       g_type_map.Append(ConstString("nullptr"), eBasicTypeNullPtr);
933       g_type_map.Sort();
934     });
935 
936     return g_type_map.Find(name, eBasicTypeInvalid);
937   }
938   return eBasicTypeInvalid;
939 }
940 
941 CompilerType ClangASTContext::GetBasicType(ASTContext *ast,
942                                            const ConstString &name) {
943   if (ast) {
944     lldb::BasicType basic_type = ClangASTContext::GetBasicTypeEnumeration(name);
945     return ClangASTContext::GetBasicType(ast, basic_type);
946   }
947   return CompilerType();
948 }
949 
950 uint32_t ClangASTContext::GetPointerByteSize() {
951   if (m_pointer_byte_size == 0)
952     m_pointer_byte_size = GetBasicType(lldb::eBasicTypeVoid)
953                               .GetPointerType()
954                               .GetByteSize(nullptr);
955   return m_pointer_byte_size;
956 }
957 
958 CompilerType ClangASTContext::GetBasicType(lldb::BasicType basic_type) {
959   return GetBasicType(getASTContext(), basic_type);
960 }
961 
962 CompilerType ClangASTContext::GetBasicType(ASTContext *ast,
963                                            lldb::BasicType basic_type) {
964   if (!ast)
965     return CompilerType();
966   lldb::opaque_compiler_type_t clang_type =
967       GetOpaqueCompilerType(ast, basic_type);
968 
969   if (clang_type)
970     return CompilerType(GetASTContext(ast), clang_type);
971   return CompilerType();
972 }
973 
974 CompilerType ClangASTContext::GetBuiltinTypeForDWARFEncodingAndBitSize(
975     const char *type_name, uint32_t dw_ate, uint32_t bit_size) {
976   ASTContext *ast = getASTContext();
977 
978 #define streq(a, b) strcmp(a, b) == 0
979   assert(ast != nullptr);
980   if (ast) {
981     switch (dw_ate) {
982     default:
983       break;
984 
985     case DW_ATE_address:
986       if (QualTypeMatchesBitSize(bit_size, ast, ast->VoidPtrTy))
987         return CompilerType(ast, ast->VoidPtrTy);
988       break;
989 
990     case DW_ATE_boolean:
991       if (QualTypeMatchesBitSize(bit_size, ast, ast->BoolTy))
992         return CompilerType(ast, ast->BoolTy);
993       if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedCharTy))
994         return CompilerType(ast, ast->UnsignedCharTy);
995       if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedShortTy))
996         return CompilerType(ast, ast->UnsignedShortTy);
997       if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedIntTy))
998         return CompilerType(ast, ast->UnsignedIntTy);
999       break;
1000 
1001     case DW_ATE_lo_user:
1002       // This has been seen to mean DW_AT_complex_integer
1003       if (type_name) {
1004         if (::strstr(type_name, "complex")) {
1005           CompilerType complex_int_clang_type =
1006               GetBuiltinTypeForDWARFEncodingAndBitSize("int", DW_ATE_signed,
1007                                                        bit_size / 2);
1008           return CompilerType(ast, ast->getComplexType(ClangUtil::GetQualType(
1009                                        complex_int_clang_type)));
1010         }
1011       }
1012       break;
1013 
1014     case DW_ATE_complex_float:
1015       if (QualTypeMatchesBitSize(bit_size, ast, ast->FloatComplexTy))
1016         return CompilerType(ast, ast->FloatComplexTy);
1017       else if (QualTypeMatchesBitSize(bit_size, ast, ast->DoubleComplexTy))
1018         return CompilerType(ast, ast->DoubleComplexTy);
1019       else if (QualTypeMatchesBitSize(bit_size, ast, ast->LongDoubleComplexTy))
1020         return CompilerType(ast, ast->LongDoubleComplexTy);
1021       else {
1022         CompilerType complex_float_clang_type =
1023             GetBuiltinTypeForDWARFEncodingAndBitSize("float", DW_ATE_float,
1024                                                      bit_size / 2);
1025         return CompilerType(ast, ast->getComplexType(ClangUtil::GetQualType(
1026                                      complex_float_clang_type)));
1027       }
1028       break;
1029 
1030     case DW_ATE_float:
1031       if (streq(type_name, "float") &&
1032           QualTypeMatchesBitSize(bit_size, ast, ast->FloatTy))
1033         return CompilerType(ast, ast->FloatTy);
1034       if (streq(type_name, "double") &&
1035           QualTypeMatchesBitSize(bit_size, ast, ast->DoubleTy))
1036         return CompilerType(ast, ast->DoubleTy);
1037       if (streq(type_name, "long double") &&
1038           QualTypeMatchesBitSize(bit_size, ast, ast->LongDoubleTy))
1039         return CompilerType(ast, ast->LongDoubleTy);
1040       // Fall back to not requiring a name match
1041       if (QualTypeMatchesBitSize(bit_size, ast, ast->FloatTy))
1042         return CompilerType(ast, ast->FloatTy);
1043       if (QualTypeMatchesBitSize(bit_size, ast, ast->DoubleTy))
1044         return CompilerType(ast, ast->DoubleTy);
1045       if (QualTypeMatchesBitSize(bit_size, ast, ast->LongDoubleTy))
1046         return CompilerType(ast, ast->LongDoubleTy);
1047       if (QualTypeMatchesBitSize(bit_size, ast, ast->HalfTy))
1048         return CompilerType(ast, ast->HalfTy);
1049       break;
1050 
1051     case DW_ATE_signed:
1052       if (type_name) {
1053         if (streq(type_name, "wchar_t") &&
1054             QualTypeMatchesBitSize(bit_size, ast, ast->WCharTy) &&
1055             (getTargetInfo() &&
1056              TargetInfo::isTypeSigned(getTargetInfo()->getWCharType())))
1057           return CompilerType(ast, ast->WCharTy);
1058         if (streq(type_name, "void") &&
1059             QualTypeMatchesBitSize(bit_size, ast, ast->VoidTy))
1060           return CompilerType(ast, ast->VoidTy);
1061         if (strstr(type_name, "long long") &&
1062             QualTypeMatchesBitSize(bit_size, ast, ast->LongLongTy))
1063           return CompilerType(ast, ast->LongLongTy);
1064         if (strstr(type_name, "long") &&
1065             QualTypeMatchesBitSize(bit_size, ast, ast->LongTy))
1066           return CompilerType(ast, ast->LongTy);
1067         if (strstr(type_name, "short") &&
1068             QualTypeMatchesBitSize(bit_size, ast, ast->ShortTy))
1069           return CompilerType(ast, ast->ShortTy);
1070         if (strstr(type_name, "char")) {
1071           if (QualTypeMatchesBitSize(bit_size, ast, ast->CharTy))
1072             return CompilerType(ast, ast->CharTy);
1073           if (QualTypeMatchesBitSize(bit_size, ast, ast->SignedCharTy))
1074             return CompilerType(ast, ast->SignedCharTy);
1075         }
1076         if (strstr(type_name, "int")) {
1077           if (QualTypeMatchesBitSize(bit_size, ast, ast->IntTy))
1078             return CompilerType(ast, ast->IntTy);
1079           if (QualTypeMatchesBitSize(bit_size, ast, ast->Int128Ty))
1080             return CompilerType(ast, ast->Int128Ty);
1081         }
1082       }
1083       // We weren't able to match up a type name, just search by size
1084       if (QualTypeMatchesBitSize(bit_size, ast, ast->CharTy))
1085         return CompilerType(ast, ast->CharTy);
1086       if (QualTypeMatchesBitSize(bit_size, ast, ast->ShortTy))
1087         return CompilerType(ast, ast->ShortTy);
1088       if (QualTypeMatchesBitSize(bit_size, ast, ast->IntTy))
1089         return CompilerType(ast, ast->IntTy);
1090       if (QualTypeMatchesBitSize(bit_size, ast, ast->LongTy))
1091         return CompilerType(ast, ast->LongTy);
1092       if (QualTypeMatchesBitSize(bit_size, ast, ast->LongLongTy))
1093         return CompilerType(ast, ast->LongLongTy);
1094       if (QualTypeMatchesBitSize(bit_size, ast, ast->Int128Ty))
1095         return CompilerType(ast, ast->Int128Ty);
1096       break;
1097 
1098     case DW_ATE_signed_char:
1099       if (ast->getLangOpts().CharIsSigned && type_name &&
1100           streq(type_name, "char")) {
1101         if (QualTypeMatchesBitSize(bit_size, ast, ast->CharTy))
1102           return CompilerType(ast, ast->CharTy);
1103       }
1104       if (QualTypeMatchesBitSize(bit_size, ast, ast->SignedCharTy))
1105         return CompilerType(ast, ast->SignedCharTy);
1106       break;
1107 
1108     case DW_ATE_unsigned:
1109       if (type_name) {
1110         if (streq(type_name, "wchar_t")) {
1111           if (QualTypeMatchesBitSize(bit_size, ast, ast->WCharTy)) {
1112             if (!(getTargetInfo() &&
1113                   TargetInfo::isTypeSigned(getTargetInfo()->getWCharType())))
1114               return CompilerType(ast, ast->WCharTy);
1115           }
1116         }
1117         if (strstr(type_name, "long long")) {
1118           if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedLongLongTy))
1119             return CompilerType(ast, ast->UnsignedLongLongTy);
1120         } else if (strstr(type_name, "long")) {
1121           if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedLongTy))
1122             return CompilerType(ast, ast->UnsignedLongTy);
1123         } else if (strstr(type_name, "short")) {
1124           if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedShortTy))
1125             return CompilerType(ast, ast->UnsignedShortTy);
1126         } else if (strstr(type_name, "char")) {
1127           if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedCharTy))
1128             return CompilerType(ast, ast->UnsignedCharTy);
1129         } else if (strstr(type_name, "int")) {
1130           if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedIntTy))
1131             return CompilerType(ast, ast->UnsignedIntTy);
1132           if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedInt128Ty))
1133             return CompilerType(ast, ast->UnsignedInt128Ty);
1134         }
1135       }
1136       // We weren't able to match up a type name, just search by size
1137       if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedCharTy))
1138         return CompilerType(ast, ast->UnsignedCharTy);
1139       if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedShortTy))
1140         return CompilerType(ast, ast->UnsignedShortTy);
1141       if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedIntTy))
1142         return CompilerType(ast, ast->UnsignedIntTy);
1143       if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedLongTy))
1144         return CompilerType(ast, ast->UnsignedLongTy);
1145       if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedLongLongTy))
1146         return CompilerType(ast, ast->UnsignedLongLongTy);
1147       if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedInt128Ty))
1148         return CompilerType(ast, ast->UnsignedInt128Ty);
1149       break;
1150 
1151     case DW_ATE_unsigned_char:
1152       if (!ast->getLangOpts().CharIsSigned && type_name &&
1153           streq(type_name, "char")) {
1154         if (QualTypeMatchesBitSize(bit_size, ast, ast->CharTy))
1155           return CompilerType(ast, ast->CharTy);
1156       }
1157       if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedCharTy))
1158         return CompilerType(ast, ast->UnsignedCharTy);
1159       if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedShortTy))
1160         return CompilerType(ast, ast->UnsignedShortTy);
1161       break;
1162 
1163     case DW_ATE_imaginary_float:
1164       break;
1165 
1166     case DW_ATE_UTF:
1167       if (type_name) {
1168         if (streq(type_name, "char16_t")) {
1169           return CompilerType(ast, ast->Char16Ty);
1170         } else if (streq(type_name, "char32_t")) {
1171           return CompilerType(ast, ast->Char32Ty);
1172         }
1173       }
1174       break;
1175     }
1176   }
1177   // This assert should fire for anything that we don't catch above so we know
1178   // to fix any issues we run into.
1179   if (type_name) {
1180     Host::SystemLog(Host::eSystemLogError, "error: need to add support for "
1181                                            "DW_TAG_base_type '%s' encoded with "
1182                                            "DW_ATE = 0x%x, bit_size = %u\n",
1183                     type_name, dw_ate, bit_size);
1184   } else {
1185     Host::SystemLog(Host::eSystemLogError, "error: need to add support for "
1186                                            "DW_TAG_base_type encoded with "
1187                                            "DW_ATE = 0x%x, bit_size = %u\n",
1188                     dw_ate, bit_size);
1189   }
1190   return CompilerType();
1191 }
1192 
1193 CompilerType ClangASTContext::GetUnknownAnyType(clang::ASTContext *ast) {
1194   if (ast)
1195     return CompilerType(ast, ast->UnknownAnyTy);
1196   return CompilerType();
1197 }
1198 
1199 CompilerType ClangASTContext::GetCStringType(bool is_const) {
1200   ASTContext *ast = getASTContext();
1201   QualType char_type(ast->CharTy);
1202 
1203   if (is_const)
1204     char_type.addConst();
1205 
1206   return CompilerType(ast, ast->getPointerType(char_type));
1207 }
1208 
1209 clang::DeclContext *
1210 ClangASTContext::GetTranslationUnitDecl(clang::ASTContext *ast) {
1211   return ast->getTranslationUnitDecl();
1212 }
1213 
1214 clang::Decl *ClangASTContext::CopyDecl(ASTContext *dst_ast, ASTContext *src_ast,
1215                                        clang::Decl *source_decl) {
1216   FileSystemOptions file_system_options;
1217   FileManager file_manager(file_system_options);
1218   ASTImporter importer(*dst_ast, file_manager, *src_ast, file_manager, false);
1219 
1220   return importer.Import(source_decl);
1221 }
1222 
1223 bool ClangASTContext::AreTypesSame(CompilerType type1, CompilerType type2,
1224                                    bool ignore_qualifiers) {
1225   ClangASTContext *ast =
1226       llvm::dyn_cast_or_null<ClangASTContext>(type1.GetTypeSystem());
1227   if (!ast || ast != type2.GetTypeSystem())
1228     return false;
1229 
1230   if (type1.GetOpaqueQualType() == type2.GetOpaqueQualType())
1231     return true;
1232 
1233   QualType type1_qual = ClangUtil::GetQualType(type1);
1234   QualType type2_qual = ClangUtil::GetQualType(type2);
1235 
1236   if (ignore_qualifiers) {
1237     type1_qual = type1_qual.getUnqualifiedType();
1238     type2_qual = type2_qual.getUnqualifiedType();
1239   }
1240 
1241   return ast->getASTContext()->hasSameType(type1_qual, type2_qual);
1242 }
1243 
1244 CompilerType ClangASTContext::GetTypeForDecl(clang::NamedDecl *decl) {
1245   if (clang::ObjCInterfaceDecl *interface_decl =
1246           llvm::dyn_cast<clang::ObjCInterfaceDecl>(decl))
1247     return GetTypeForDecl(interface_decl);
1248   if (clang::TagDecl *tag_decl = llvm::dyn_cast<clang::TagDecl>(decl))
1249     return GetTypeForDecl(tag_decl);
1250   return CompilerType();
1251 }
1252 
1253 CompilerType ClangASTContext::GetTypeForDecl(TagDecl *decl) {
1254   // No need to call the getASTContext() accessor (which can create the AST
1255   // if it isn't created yet, because we can't have created a decl in this
1256   // AST if our AST didn't already exist...
1257   ASTContext *ast = &decl->getASTContext();
1258   if (ast)
1259     return CompilerType(ast, ast->getTagDeclType(decl));
1260   return CompilerType();
1261 }
1262 
1263 CompilerType ClangASTContext::GetTypeForDecl(ObjCInterfaceDecl *decl) {
1264   // No need to call the getASTContext() accessor (which can create the AST
1265   // if it isn't created yet, because we can't have created a decl in this
1266   // AST if our AST didn't already exist...
1267   ASTContext *ast = &decl->getASTContext();
1268   if (ast)
1269     return CompilerType(ast, ast->getObjCInterfaceType(decl));
1270   return CompilerType();
1271 }
1272 
1273 #pragma mark Structure, Unions, Classes
1274 
1275 CompilerType ClangASTContext::CreateRecordType(DeclContext *decl_ctx,
1276                                                AccessType access_type,
1277                                                const char *name, int kind,
1278                                                LanguageType language,
1279                                                ClangASTMetadata *metadata) {
1280   ASTContext *ast = getASTContext();
1281   assert(ast != nullptr);
1282 
1283   if (decl_ctx == nullptr)
1284     decl_ctx = ast->getTranslationUnitDecl();
1285 
1286   if (language == eLanguageTypeObjC ||
1287       language == eLanguageTypeObjC_plus_plus) {
1288     bool isForwardDecl = true;
1289     bool isInternal = false;
1290     return CreateObjCClass(name, decl_ctx, isForwardDecl, isInternal, metadata);
1291   }
1292 
1293   // NOTE: Eventually CXXRecordDecl will be merged back into RecordDecl and
1294   // we will need to update this code. I was told to currently always use
1295   // the CXXRecordDecl class since we often don't know from debug information
1296   // if something is struct or a class, so we default to always use the more
1297   // complete definition just in case.
1298 
1299   bool is_anonymous = (!name) || (!name[0]);
1300 
1301   CXXRecordDecl *decl = CXXRecordDecl::Create(
1302       *ast, (TagDecl::TagKind)kind, decl_ctx, SourceLocation(),
1303       SourceLocation(), is_anonymous ? nullptr : &ast->Idents.get(name));
1304 
1305   if (is_anonymous)
1306     decl->setAnonymousStructOrUnion(true);
1307 
1308   if (decl) {
1309     if (metadata)
1310       SetMetadata(ast, decl, *metadata);
1311 
1312     if (access_type != eAccessNone)
1313       decl->setAccess(ConvertAccessTypeToAccessSpecifier(access_type));
1314 
1315     if (decl_ctx)
1316       decl_ctx->addDecl(decl);
1317 
1318     return CompilerType(ast, ast->getTagDeclType(decl));
1319   }
1320   return CompilerType();
1321 }
1322 
1323 namespace {
1324   bool IsValueParam(const clang::TemplateArgument &argument) {
1325     return argument.getKind() == TemplateArgument::Integral;
1326   }
1327 }
1328 
1329 static TemplateParameterList *CreateTemplateParameterList(
1330     ASTContext *ast,
1331     const ClangASTContext::TemplateParameterInfos &template_param_infos,
1332     llvm::SmallVector<NamedDecl *, 8> &template_param_decls) {
1333   const bool parameter_pack = false;
1334   const bool is_typename = false;
1335   const unsigned depth = 0;
1336   const size_t num_template_params = template_param_infos.args.size();
1337   DeclContext *const decl_context =
1338       ast->getTranslationUnitDecl(); // Is this the right decl context?,
1339   for (size_t i = 0; i < num_template_params; ++i) {
1340     const char *name = template_param_infos.names[i];
1341 
1342     IdentifierInfo *identifier_info = nullptr;
1343     if (name && name[0])
1344       identifier_info = &ast->Idents.get(name);
1345     if (IsValueParam(template_param_infos.args[i])) {
1346       template_param_decls.push_back(NonTypeTemplateParmDecl::Create(
1347           *ast, decl_context,
1348           SourceLocation(), SourceLocation(), depth, i, identifier_info,
1349           template_param_infos.args[i].getIntegralType(), parameter_pack,
1350           nullptr));
1351 
1352     } else {
1353       template_param_decls.push_back(TemplateTypeParmDecl::Create(
1354           *ast, decl_context,
1355           SourceLocation(), SourceLocation(), depth, i, identifier_info,
1356           is_typename, parameter_pack));
1357     }
1358   }
1359 
1360   if (template_param_infos.packed_args &&
1361       template_param_infos.packed_args->args.size()) {
1362     IdentifierInfo *identifier_info = nullptr;
1363     if (template_param_infos.pack_name && template_param_infos.pack_name[0])
1364       identifier_info = &ast->Idents.get(template_param_infos.pack_name);
1365     const bool parameter_pack_true = true;
1366     if (IsValueParam(template_param_infos.packed_args->args[0])) {
1367       template_param_decls.push_back(NonTypeTemplateParmDecl::Create(
1368           *ast, decl_context,
1369           SourceLocation(), SourceLocation(), depth, num_template_params,
1370           identifier_info,
1371           template_param_infos.packed_args->args[0].getIntegralType(),
1372           parameter_pack_true, nullptr));
1373     } else {
1374       template_param_decls.push_back(TemplateTypeParmDecl::Create(
1375           *ast, decl_context,
1376           SourceLocation(), SourceLocation(), depth, num_template_params,
1377           identifier_info,
1378           is_typename, parameter_pack_true));
1379     }
1380   }
1381   clang::Expr *const requires_clause = nullptr; // TODO: Concepts
1382   TemplateParameterList *template_param_list = TemplateParameterList::Create(
1383       *ast, SourceLocation(), SourceLocation(), template_param_decls,
1384       SourceLocation(), requires_clause);
1385   return template_param_list;
1386 }
1387 
1388 clang::FunctionTemplateDecl *ClangASTContext::CreateFunctionTemplateDecl(
1389     clang::DeclContext *decl_ctx, clang::FunctionDecl *func_decl,
1390     const char *name, const TemplateParameterInfos &template_param_infos) {
1391   //    /// \brief Create a function template node.
1392   ASTContext *ast = getASTContext();
1393 
1394   llvm::SmallVector<NamedDecl *, 8> template_param_decls;
1395 
1396   TemplateParameterList *template_param_list = CreateTemplateParameterList(
1397       ast, template_param_infos, template_param_decls);
1398   FunctionTemplateDecl *func_tmpl_decl = FunctionTemplateDecl::Create(
1399       *ast, decl_ctx, func_decl->getLocation(), func_decl->getDeclName(),
1400       template_param_list, func_decl);
1401 
1402   for (size_t i = 0, template_param_decl_count = template_param_decls.size();
1403        i < template_param_decl_count; ++i) {
1404     // TODO: verify which decl context we should put template_param_decls into..
1405     template_param_decls[i]->setDeclContext(func_decl);
1406   }
1407 
1408   return func_tmpl_decl;
1409 }
1410 
1411 void ClangASTContext::CreateFunctionTemplateSpecializationInfo(
1412     FunctionDecl *func_decl, clang::FunctionTemplateDecl *func_tmpl_decl,
1413     const TemplateParameterInfos &infos) {
1414   TemplateArgumentList template_args(TemplateArgumentList::OnStack, infos.args);
1415 
1416   func_decl->setFunctionTemplateSpecialization(func_tmpl_decl, &template_args,
1417                                                nullptr);
1418 }
1419 
1420 ClassTemplateDecl *ClangASTContext::CreateClassTemplateDecl(
1421     DeclContext *decl_ctx, lldb::AccessType access_type, const char *class_name,
1422     int kind, const TemplateParameterInfos &template_param_infos) {
1423   ASTContext *ast = getASTContext();
1424 
1425   ClassTemplateDecl *class_template_decl = nullptr;
1426   if (decl_ctx == nullptr)
1427     decl_ctx = ast->getTranslationUnitDecl();
1428 
1429   IdentifierInfo &identifier_info = ast->Idents.get(class_name);
1430   DeclarationName decl_name(&identifier_info);
1431 
1432   clang::DeclContext::lookup_result result = decl_ctx->lookup(decl_name);
1433 
1434   for (NamedDecl *decl : result) {
1435     class_template_decl = dyn_cast<clang::ClassTemplateDecl>(decl);
1436     if (class_template_decl)
1437       return class_template_decl;
1438   }
1439 
1440   llvm::SmallVector<NamedDecl *, 8> template_param_decls;
1441 
1442   TemplateParameterList *template_param_list = CreateTemplateParameterList(
1443       ast, template_param_infos, template_param_decls);
1444 
1445   CXXRecordDecl *template_cxx_decl = CXXRecordDecl::Create(
1446       *ast, (TagDecl::TagKind)kind,
1447       decl_ctx, // What decl context do we use here? TU? The actual decl
1448                 // context?
1449       SourceLocation(), SourceLocation(), &identifier_info);
1450 
1451   for (size_t i = 0, template_param_decl_count = template_param_decls.size();
1452        i < template_param_decl_count; ++i) {
1453     template_param_decls[i]->setDeclContext(template_cxx_decl);
1454   }
1455 
1456   // With templated classes, we say that a class is templated with
1457   // specializations, but that the bare class has no functions.
1458   // template_cxx_decl->startDefinition();
1459   // template_cxx_decl->completeDefinition();
1460 
1461   class_template_decl = ClassTemplateDecl::Create(
1462       *ast,
1463       decl_ctx, // What decl context do we use here? TU? The actual decl
1464                 // context?
1465       SourceLocation(), decl_name, template_param_list, template_cxx_decl);
1466 
1467   if (class_template_decl) {
1468     if (access_type != eAccessNone)
1469       class_template_decl->setAccess(
1470           ConvertAccessTypeToAccessSpecifier(access_type));
1471 
1472     // if (TagDecl *ctx_tag_decl = dyn_cast<TagDecl>(decl_ctx))
1473     //    CompleteTagDeclarationDefinition(GetTypeForDecl(ctx_tag_decl));
1474 
1475     decl_ctx->addDecl(class_template_decl);
1476 
1477 #ifdef LLDB_CONFIGURATION_DEBUG
1478     VerifyDecl(class_template_decl);
1479 #endif
1480   }
1481 
1482   return class_template_decl;
1483 }
1484 
1485 ClassTemplateSpecializationDecl *
1486 ClangASTContext::CreateClassTemplateSpecializationDecl(
1487     DeclContext *decl_ctx, ClassTemplateDecl *class_template_decl, int kind,
1488     const TemplateParameterInfos &template_param_infos) {
1489   ASTContext *ast = getASTContext();
1490   llvm::SmallVector<clang::TemplateArgument, 2> args(
1491       template_param_infos.args.size() +
1492       (template_param_infos.packed_args ? 1 : 0));
1493   std::copy(template_param_infos.args.begin(), template_param_infos.args.end(),
1494             args.begin());
1495   if (template_param_infos.packed_args) {
1496     args[args.size() - 1] = TemplateArgument::CreatePackCopy(
1497         *ast, template_param_infos.packed_args->args);
1498   }
1499   ClassTemplateSpecializationDecl *class_template_specialization_decl =
1500       ClassTemplateSpecializationDecl::Create(
1501           *ast, (TagDecl::TagKind)kind, decl_ctx, SourceLocation(),
1502           SourceLocation(), class_template_decl, args,
1503           nullptr);
1504 
1505   class_template_specialization_decl->setSpecializationKind(
1506       TSK_ExplicitSpecialization);
1507 
1508   return class_template_specialization_decl;
1509 }
1510 
1511 CompilerType ClangASTContext::CreateClassTemplateSpecializationType(
1512     ClassTemplateSpecializationDecl *class_template_specialization_decl) {
1513   if (class_template_specialization_decl) {
1514     ASTContext *ast = getASTContext();
1515     if (ast)
1516       return CompilerType(
1517           ast, ast->getTagDeclType(class_template_specialization_decl));
1518   }
1519   return CompilerType();
1520 }
1521 
1522 static inline bool check_op_param(bool is_method,
1523                                   clang::OverloadedOperatorKind op_kind,
1524                                   bool unary, bool binary,
1525                                   uint32_t num_params) {
1526   // Special-case call since it can take any number of operands
1527   if (op_kind == OO_Call)
1528     return true;
1529 
1530   // The parameter count doesn't include "this"
1531   if (is_method)
1532     ++num_params;
1533   if (num_params == 1)
1534     return unary;
1535   if (num_params == 2)
1536     return binary;
1537   else
1538     return false;
1539 }
1540 
1541 bool ClangASTContext::CheckOverloadedOperatorKindParameterCount(
1542     bool is_method, clang::OverloadedOperatorKind op_kind,
1543     uint32_t num_params) {
1544   switch (op_kind) {
1545   default:
1546     break;
1547   // C++ standard allows any number of arguments to new/delete
1548   case OO_New:
1549   case OO_Array_New:
1550   case OO_Delete:
1551   case OO_Array_Delete:
1552     return true;
1553   }
1554 
1555 #define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly)  \
1556   case OO_##Name:                                                              \
1557     return check_op_param(is_method, op_kind, Unary, Binary, num_params);
1558   switch (op_kind) {
1559 #include "clang/Basic/OperatorKinds.def"
1560   default:
1561     break;
1562   }
1563   return false;
1564 }
1565 
1566 clang::AccessSpecifier
1567 ClangASTContext::UnifyAccessSpecifiers(clang::AccessSpecifier lhs,
1568                                        clang::AccessSpecifier rhs) {
1569   // Make the access equal to the stricter of the field and the nested field's
1570   // access
1571   if (lhs == AS_none || rhs == AS_none)
1572     return AS_none;
1573   if (lhs == AS_private || rhs == AS_private)
1574     return AS_private;
1575   if (lhs == AS_protected || rhs == AS_protected)
1576     return AS_protected;
1577   return AS_public;
1578 }
1579 
1580 bool ClangASTContext::FieldIsBitfield(FieldDecl *field,
1581                                       uint32_t &bitfield_bit_size) {
1582   return FieldIsBitfield(getASTContext(), field, bitfield_bit_size);
1583 }
1584 
1585 bool ClangASTContext::FieldIsBitfield(ASTContext *ast, FieldDecl *field,
1586                                       uint32_t &bitfield_bit_size) {
1587   if (ast == nullptr || field == nullptr)
1588     return false;
1589 
1590   if (field->isBitField()) {
1591     Expr *bit_width_expr = field->getBitWidth();
1592     if (bit_width_expr) {
1593       llvm::APSInt bit_width_apsint;
1594       if (bit_width_expr->isIntegerConstantExpr(bit_width_apsint, *ast)) {
1595         bitfield_bit_size = bit_width_apsint.getLimitedValue(UINT32_MAX);
1596         return true;
1597       }
1598     }
1599   }
1600   return false;
1601 }
1602 
1603 bool ClangASTContext::RecordHasFields(const RecordDecl *record_decl) {
1604   if (record_decl == nullptr)
1605     return false;
1606 
1607   if (!record_decl->field_empty())
1608     return true;
1609 
1610   // No fields, lets check this is a CXX record and check the base classes
1611   const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
1612   if (cxx_record_decl) {
1613     CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
1614     for (base_class = cxx_record_decl->bases_begin(),
1615         base_class_end = cxx_record_decl->bases_end();
1616          base_class != base_class_end; ++base_class) {
1617       const CXXRecordDecl *base_class_decl = cast<CXXRecordDecl>(
1618           base_class->getType()->getAs<RecordType>()->getDecl());
1619       if (RecordHasFields(base_class_decl))
1620         return true;
1621     }
1622   }
1623   return false;
1624 }
1625 
1626 #pragma mark Objective C Classes
1627 
1628 CompilerType ClangASTContext::CreateObjCClass(const char *name,
1629                                               DeclContext *decl_ctx,
1630                                               bool isForwardDecl,
1631                                               bool isInternal,
1632                                               ClangASTMetadata *metadata) {
1633   ASTContext *ast = getASTContext();
1634   assert(ast != nullptr);
1635   assert(name && name[0]);
1636   if (decl_ctx == nullptr)
1637     decl_ctx = ast->getTranslationUnitDecl();
1638 
1639   ObjCInterfaceDecl *decl = ObjCInterfaceDecl::Create(
1640       *ast, decl_ctx, SourceLocation(), &ast->Idents.get(name), nullptr,
1641       nullptr, SourceLocation(),
1642       /*isForwardDecl,*/
1643       isInternal);
1644 
1645   if (decl && metadata)
1646     SetMetadata(ast, decl, *metadata);
1647 
1648   return CompilerType(ast, ast->getObjCInterfaceType(decl));
1649 }
1650 
1651 static inline bool BaseSpecifierIsEmpty(const CXXBaseSpecifier *b) {
1652   return ClangASTContext::RecordHasFields(b->getType()->getAsCXXRecordDecl()) ==
1653          false;
1654 }
1655 
1656 uint32_t
1657 ClangASTContext::GetNumBaseClasses(const CXXRecordDecl *cxx_record_decl,
1658                                    bool omit_empty_base_classes) {
1659   uint32_t num_bases = 0;
1660   if (cxx_record_decl) {
1661     if (omit_empty_base_classes) {
1662       CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
1663       for (base_class = cxx_record_decl->bases_begin(),
1664           base_class_end = cxx_record_decl->bases_end();
1665            base_class != base_class_end; ++base_class) {
1666         // Skip empty base classes
1667         if (omit_empty_base_classes) {
1668           if (BaseSpecifierIsEmpty(base_class))
1669             continue;
1670         }
1671         ++num_bases;
1672       }
1673     } else
1674       num_bases = cxx_record_decl->getNumBases();
1675   }
1676   return num_bases;
1677 }
1678 
1679 #pragma mark Namespace Declarations
1680 
1681 NamespaceDecl *
1682 ClangASTContext::GetUniqueNamespaceDeclaration(const char *name,
1683                                                DeclContext *decl_ctx) {
1684   NamespaceDecl *namespace_decl = nullptr;
1685   ASTContext *ast = getASTContext();
1686   TranslationUnitDecl *translation_unit_decl = ast->getTranslationUnitDecl();
1687   if (decl_ctx == nullptr)
1688     decl_ctx = translation_unit_decl;
1689 
1690   if (name) {
1691     IdentifierInfo &identifier_info = ast->Idents.get(name);
1692     DeclarationName decl_name(&identifier_info);
1693     clang::DeclContext::lookup_result result = decl_ctx->lookup(decl_name);
1694     for (NamedDecl *decl : result) {
1695       namespace_decl = dyn_cast<clang::NamespaceDecl>(decl);
1696       if (namespace_decl)
1697         return namespace_decl;
1698     }
1699 
1700     namespace_decl =
1701         NamespaceDecl::Create(*ast, decl_ctx, false, SourceLocation(),
1702                               SourceLocation(), &identifier_info, nullptr);
1703 
1704     decl_ctx->addDecl(namespace_decl);
1705   } else {
1706     if (decl_ctx == translation_unit_decl) {
1707       namespace_decl = translation_unit_decl->getAnonymousNamespace();
1708       if (namespace_decl)
1709         return namespace_decl;
1710 
1711       namespace_decl =
1712           NamespaceDecl::Create(*ast, decl_ctx, false, SourceLocation(),
1713                                 SourceLocation(), nullptr, nullptr);
1714       translation_unit_decl->setAnonymousNamespace(namespace_decl);
1715       translation_unit_decl->addDecl(namespace_decl);
1716       assert(namespace_decl == translation_unit_decl->getAnonymousNamespace());
1717     } else {
1718       NamespaceDecl *parent_namespace_decl = cast<NamespaceDecl>(decl_ctx);
1719       if (parent_namespace_decl) {
1720         namespace_decl = parent_namespace_decl->getAnonymousNamespace();
1721         if (namespace_decl)
1722           return namespace_decl;
1723         namespace_decl =
1724             NamespaceDecl::Create(*ast, decl_ctx, false, SourceLocation(),
1725                                   SourceLocation(), nullptr, nullptr);
1726         parent_namespace_decl->setAnonymousNamespace(namespace_decl);
1727         parent_namespace_decl->addDecl(namespace_decl);
1728         assert(namespace_decl ==
1729                parent_namespace_decl->getAnonymousNamespace());
1730       } else {
1731         // BAD!!!
1732       }
1733     }
1734   }
1735 #ifdef LLDB_CONFIGURATION_DEBUG
1736   VerifyDecl(namespace_decl);
1737 #endif
1738   return namespace_decl;
1739 }
1740 
1741 NamespaceDecl *ClangASTContext::GetUniqueNamespaceDeclaration(
1742     clang::ASTContext *ast, const char *name, clang::DeclContext *decl_ctx) {
1743   ClangASTContext *ast_ctx = ClangASTContext::GetASTContext(ast);
1744   if (ast_ctx == nullptr)
1745     return nullptr;
1746 
1747   return ast_ctx->GetUniqueNamespaceDeclaration(name, decl_ctx);
1748 }
1749 
1750 clang::BlockDecl *
1751 ClangASTContext::CreateBlockDeclaration(clang::DeclContext *ctx) {
1752   if (ctx != nullptr) {
1753     clang::BlockDecl *decl = clang::BlockDecl::Create(*getASTContext(), ctx,
1754                                                       clang::SourceLocation());
1755     ctx->addDecl(decl);
1756     return decl;
1757   }
1758   return nullptr;
1759 }
1760 
1761 clang::DeclContext *FindLCABetweenDecls(clang::DeclContext *left,
1762                                         clang::DeclContext *right,
1763                                         clang::DeclContext *root) {
1764   if (root == nullptr)
1765     return nullptr;
1766 
1767   std::set<clang::DeclContext *> path_left;
1768   for (clang::DeclContext *d = left; d != nullptr; d = d->getParent())
1769     path_left.insert(d);
1770 
1771   for (clang::DeclContext *d = right; d != nullptr; d = d->getParent())
1772     if (path_left.find(d) != path_left.end())
1773       return d;
1774 
1775   return nullptr;
1776 }
1777 
1778 clang::UsingDirectiveDecl *ClangASTContext::CreateUsingDirectiveDeclaration(
1779     clang::DeclContext *decl_ctx, clang::NamespaceDecl *ns_decl) {
1780   if (decl_ctx != nullptr && ns_decl != nullptr) {
1781     clang::TranslationUnitDecl *translation_unit =
1782         (clang::TranslationUnitDecl *)GetTranslationUnitDecl(getASTContext());
1783     clang::UsingDirectiveDecl *using_decl = clang::UsingDirectiveDecl::Create(
1784         *getASTContext(), decl_ctx, clang::SourceLocation(),
1785         clang::SourceLocation(), clang::NestedNameSpecifierLoc(),
1786         clang::SourceLocation(), ns_decl,
1787         FindLCABetweenDecls(decl_ctx, ns_decl, translation_unit));
1788     decl_ctx->addDecl(using_decl);
1789     return using_decl;
1790   }
1791   return nullptr;
1792 }
1793 
1794 clang::UsingDecl *
1795 ClangASTContext::CreateUsingDeclaration(clang::DeclContext *current_decl_ctx,
1796                                         clang::NamedDecl *target) {
1797   if (current_decl_ctx != nullptr && target != nullptr) {
1798     clang::UsingDecl *using_decl = clang::UsingDecl::Create(
1799         *getASTContext(), current_decl_ctx, clang::SourceLocation(),
1800         clang::NestedNameSpecifierLoc(), clang::DeclarationNameInfo(), false);
1801     clang::UsingShadowDecl *shadow_decl = clang::UsingShadowDecl::Create(
1802         *getASTContext(), current_decl_ctx, clang::SourceLocation(), using_decl,
1803         target);
1804     using_decl->addShadowDecl(shadow_decl);
1805     current_decl_ctx->addDecl(using_decl);
1806     return using_decl;
1807   }
1808   return nullptr;
1809 }
1810 
1811 clang::VarDecl *ClangASTContext::CreateVariableDeclaration(
1812     clang::DeclContext *decl_context, const char *name, clang::QualType type) {
1813   if (decl_context != nullptr) {
1814     clang::VarDecl *var_decl = clang::VarDecl::Create(
1815         *getASTContext(), decl_context, clang::SourceLocation(),
1816         clang::SourceLocation(),
1817         name && name[0] ? &getASTContext()->Idents.getOwn(name) : nullptr, type,
1818         nullptr, clang::SC_None);
1819     var_decl->setAccess(clang::AS_public);
1820     decl_context->addDecl(var_decl);
1821     return var_decl;
1822   }
1823   return nullptr;
1824 }
1825 
1826 lldb::opaque_compiler_type_t
1827 ClangASTContext::GetOpaqueCompilerType(clang::ASTContext *ast,
1828                                        lldb::BasicType basic_type) {
1829   switch (basic_type) {
1830   case eBasicTypeVoid:
1831     return ast->VoidTy.getAsOpaquePtr();
1832   case eBasicTypeChar:
1833     return ast->CharTy.getAsOpaquePtr();
1834   case eBasicTypeSignedChar:
1835     return ast->SignedCharTy.getAsOpaquePtr();
1836   case eBasicTypeUnsignedChar:
1837     return ast->UnsignedCharTy.getAsOpaquePtr();
1838   case eBasicTypeWChar:
1839     return ast->getWCharType().getAsOpaquePtr();
1840   case eBasicTypeSignedWChar:
1841     return ast->getSignedWCharType().getAsOpaquePtr();
1842   case eBasicTypeUnsignedWChar:
1843     return ast->getUnsignedWCharType().getAsOpaquePtr();
1844   case eBasicTypeChar16:
1845     return ast->Char16Ty.getAsOpaquePtr();
1846   case eBasicTypeChar32:
1847     return ast->Char32Ty.getAsOpaquePtr();
1848   case eBasicTypeShort:
1849     return ast->ShortTy.getAsOpaquePtr();
1850   case eBasicTypeUnsignedShort:
1851     return ast->UnsignedShortTy.getAsOpaquePtr();
1852   case eBasicTypeInt:
1853     return ast->IntTy.getAsOpaquePtr();
1854   case eBasicTypeUnsignedInt:
1855     return ast->UnsignedIntTy.getAsOpaquePtr();
1856   case eBasicTypeLong:
1857     return ast->LongTy.getAsOpaquePtr();
1858   case eBasicTypeUnsignedLong:
1859     return ast->UnsignedLongTy.getAsOpaquePtr();
1860   case eBasicTypeLongLong:
1861     return ast->LongLongTy.getAsOpaquePtr();
1862   case eBasicTypeUnsignedLongLong:
1863     return ast->UnsignedLongLongTy.getAsOpaquePtr();
1864   case eBasicTypeInt128:
1865     return ast->Int128Ty.getAsOpaquePtr();
1866   case eBasicTypeUnsignedInt128:
1867     return ast->UnsignedInt128Ty.getAsOpaquePtr();
1868   case eBasicTypeBool:
1869     return ast->BoolTy.getAsOpaquePtr();
1870   case eBasicTypeHalf:
1871     return ast->HalfTy.getAsOpaquePtr();
1872   case eBasicTypeFloat:
1873     return ast->FloatTy.getAsOpaquePtr();
1874   case eBasicTypeDouble:
1875     return ast->DoubleTy.getAsOpaquePtr();
1876   case eBasicTypeLongDouble:
1877     return ast->LongDoubleTy.getAsOpaquePtr();
1878   case eBasicTypeFloatComplex:
1879     return ast->FloatComplexTy.getAsOpaquePtr();
1880   case eBasicTypeDoubleComplex:
1881     return ast->DoubleComplexTy.getAsOpaquePtr();
1882   case eBasicTypeLongDoubleComplex:
1883     return ast->LongDoubleComplexTy.getAsOpaquePtr();
1884   case eBasicTypeObjCID:
1885     return ast->getObjCIdType().getAsOpaquePtr();
1886   case eBasicTypeObjCClass:
1887     return ast->getObjCClassType().getAsOpaquePtr();
1888   case eBasicTypeObjCSel:
1889     return ast->getObjCSelType().getAsOpaquePtr();
1890   case eBasicTypeNullPtr:
1891     return ast->NullPtrTy.getAsOpaquePtr();
1892   default:
1893     return nullptr;
1894   }
1895 }
1896 
1897 #pragma mark Function Types
1898 
1899 clang::DeclarationName
1900 ClangASTContext::GetDeclarationName(const char *name,
1901                                     const CompilerType &function_clang_type) {
1902   if (!name || !name[0])
1903     return clang::DeclarationName();
1904 
1905   clang::OverloadedOperatorKind op_kind = clang::NUM_OVERLOADED_OPERATORS;
1906   if (!IsOperator(name, op_kind) || op_kind == clang::NUM_OVERLOADED_OPERATORS)
1907     return DeclarationName(&getASTContext()->Idents.get(
1908         name)); // Not operator, but a regular function.
1909 
1910   // Check the number of operator parameters. Sometimes we have
1911   // seen bad DWARF that doesn't correctly describe operators and
1912   // if we try to create a method and add it to the class, clang
1913   // will assert and crash, so we need to make sure things are
1914   // acceptable.
1915   clang::QualType method_qual_type(ClangUtil::GetQualType(function_clang_type));
1916   const clang::FunctionProtoType *function_type =
1917       llvm::dyn_cast<clang::FunctionProtoType>(method_qual_type.getTypePtr());
1918   if (function_type == nullptr)
1919     return clang::DeclarationName();
1920 
1921   const bool is_method = false;
1922   const unsigned int num_params = function_type->getNumParams();
1923   if (!ClangASTContext::CheckOverloadedOperatorKindParameterCount(
1924           is_method, op_kind, num_params))
1925     return clang::DeclarationName();
1926 
1927   return getASTContext()->DeclarationNames.getCXXOperatorName(op_kind);
1928 }
1929 
1930 FunctionDecl *ClangASTContext::CreateFunctionDeclaration(
1931     DeclContext *decl_ctx, const char *name,
1932     const CompilerType &function_clang_type, int storage, bool is_inline) {
1933   FunctionDecl *func_decl = nullptr;
1934   ASTContext *ast = getASTContext();
1935   if (decl_ctx == nullptr)
1936     decl_ctx = ast->getTranslationUnitDecl();
1937 
1938   const bool hasWrittenPrototype = true;
1939   const bool isConstexprSpecified = false;
1940 
1941   clang::DeclarationName declarationName =
1942       GetDeclarationName(name, function_clang_type);
1943   func_decl = FunctionDecl::Create(
1944       *ast, decl_ctx, SourceLocation(), SourceLocation(), declarationName,
1945       ClangUtil::GetQualType(function_clang_type), nullptr,
1946       (clang::StorageClass)storage, is_inline, hasWrittenPrototype,
1947       isConstexprSpecified);
1948   if (func_decl)
1949     decl_ctx->addDecl(func_decl);
1950 
1951 #ifdef LLDB_CONFIGURATION_DEBUG
1952   VerifyDecl(func_decl);
1953 #endif
1954 
1955   return func_decl;
1956 }
1957 
1958 CompilerType ClangASTContext::CreateFunctionType(
1959     ASTContext *ast, const CompilerType &result_type, const CompilerType *args,
1960     unsigned num_args, bool is_variadic, unsigned type_quals) {
1961   if (ast == nullptr)
1962     return CompilerType(); // invalid AST
1963 
1964   if (!result_type || !ClangUtil::IsClangType(result_type))
1965     return CompilerType(); // invalid return type
1966 
1967   std::vector<QualType> qual_type_args;
1968   if (num_args > 0 && args == nullptr)
1969     return CompilerType(); // invalid argument array passed in
1970 
1971   // Verify that all arguments are valid and the right type
1972   for (unsigned i = 0; i < num_args; ++i) {
1973     if (args[i]) {
1974       // Make sure we have a clang type in args[i] and not a type from another
1975       // language whose name might match
1976       const bool is_clang_type = ClangUtil::IsClangType(args[i]);
1977       lldbassert(is_clang_type);
1978       if (is_clang_type)
1979         qual_type_args.push_back(ClangUtil::GetQualType(args[i]));
1980       else
1981         return CompilerType(); //  invalid argument type (must be a clang type)
1982     } else
1983       return CompilerType(); // invalid argument type (empty)
1984   }
1985 
1986   // TODO: Detect calling convention in DWARF?
1987   FunctionProtoType::ExtProtoInfo proto_info;
1988   proto_info.Variadic = is_variadic;
1989   proto_info.ExceptionSpec = EST_None;
1990   proto_info.TypeQuals = type_quals;
1991   proto_info.RefQualifier = RQ_None;
1992 
1993   return CompilerType(ast,
1994                       ast->getFunctionType(ClangUtil::GetQualType(result_type),
1995                                            qual_type_args, proto_info));
1996 }
1997 
1998 ParmVarDecl *ClangASTContext::CreateParameterDeclaration(
1999     const char *name, const CompilerType &param_type, int storage) {
2000   ASTContext *ast = getASTContext();
2001   assert(ast != nullptr);
2002   return ParmVarDecl::Create(*ast, ast->getTranslationUnitDecl(),
2003                              SourceLocation(), SourceLocation(),
2004                              name && name[0] ? &ast->Idents.get(name) : nullptr,
2005                              ClangUtil::GetQualType(param_type), nullptr,
2006                              (clang::StorageClass)storage, nullptr);
2007 }
2008 
2009 void ClangASTContext::SetFunctionParameters(FunctionDecl *function_decl,
2010                                             ParmVarDecl **params,
2011                                             unsigned num_params) {
2012   if (function_decl)
2013     function_decl->setParams(ArrayRef<ParmVarDecl *>(params, num_params));
2014 }
2015 
2016 CompilerType
2017 ClangASTContext::CreateBlockPointerType(const CompilerType &function_type) {
2018   QualType block_type = m_ast_ap->getBlockPointerType(
2019       clang::QualType::getFromOpaquePtr(function_type.GetOpaqueQualType()));
2020 
2021   return CompilerType(this, block_type.getAsOpaquePtr());
2022 }
2023 
2024 #pragma mark Array Types
2025 
2026 CompilerType ClangASTContext::CreateArrayType(const CompilerType &element_type,
2027                                               size_t element_count,
2028                                               bool is_vector) {
2029   if (element_type.IsValid()) {
2030     ASTContext *ast = getASTContext();
2031     assert(ast != nullptr);
2032 
2033     if (is_vector) {
2034       return CompilerType(
2035           ast, ast->getExtVectorType(ClangUtil::GetQualType(element_type),
2036                                      element_count));
2037     } else {
2038 
2039       llvm::APInt ap_element_count(64, element_count);
2040       if (element_count == 0) {
2041         return CompilerType(ast, ast->getIncompleteArrayType(
2042                                      ClangUtil::GetQualType(element_type),
2043                                      clang::ArrayType::Normal, 0));
2044       } else {
2045         return CompilerType(
2046             ast, ast->getConstantArrayType(ClangUtil::GetQualType(element_type),
2047                                            ap_element_count,
2048                                            clang::ArrayType::Normal, 0));
2049       }
2050     }
2051   }
2052   return CompilerType();
2053 }
2054 
2055 CompilerType ClangASTContext::CreateStructForIdentifier(
2056     const ConstString &type_name,
2057     const std::initializer_list<std::pair<const char *, CompilerType>>
2058         &type_fields,
2059     bool packed) {
2060   CompilerType type;
2061   if (!type_name.IsEmpty() &&
2062       (type = GetTypeForIdentifier<clang::CXXRecordDecl>(type_name))
2063           .IsValid()) {
2064     lldbassert(0 && "Trying to create a type for an existing name");
2065     return type;
2066   }
2067 
2068   type = CreateRecordType(nullptr, lldb::eAccessPublic, type_name.GetCString(),
2069                           clang::TTK_Struct, lldb::eLanguageTypeC);
2070   StartTagDeclarationDefinition(type);
2071   for (const auto &field : type_fields)
2072     AddFieldToRecordType(type, field.first, field.second, lldb::eAccessPublic,
2073                          0);
2074   if (packed)
2075     SetIsPacked(type);
2076   CompleteTagDeclarationDefinition(type);
2077   return type;
2078 }
2079 
2080 CompilerType ClangASTContext::GetOrCreateStructForIdentifier(
2081     const ConstString &type_name,
2082     const std::initializer_list<std::pair<const char *, CompilerType>>
2083         &type_fields,
2084     bool packed) {
2085   CompilerType type;
2086   if ((type = GetTypeForIdentifier<clang::CXXRecordDecl>(type_name)).IsValid())
2087     return type;
2088 
2089   return CreateStructForIdentifier(type_name, type_fields, packed);
2090 }
2091 
2092 #pragma mark Enumeration Types
2093 
2094 CompilerType
2095 ClangASTContext::CreateEnumerationType(const char *name, DeclContext *decl_ctx,
2096                                        const Declaration &decl,
2097                                        const CompilerType &integer_clang_type,
2098                                        bool is_scoped) {
2099   // TODO: Do something intelligent with the Declaration object passed in
2100   // like maybe filling in the SourceLocation with it...
2101   ASTContext *ast = getASTContext();
2102 
2103   // TODO: ask about these...
2104   //    const bool IsFixed = false;
2105 
2106   EnumDecl *enum_decl = EnumDecl::Create(
2107       *ast, decl_ctx, SourceLocation(), SourceLocation(),
2108       name && name[0] ? &ast->Idents.get(name) : nullptr, nullptr,
2109       is_scoped, // IsScoped
2110       is_scoped, // IsScopedUsingClassTag
2111       false);    // IsFixed
2112 
2113   if (enum_decl) {
2114     // TODO: check if we should be setting the promotion type too?
2115     enum_decl->setIntegerType(ClangUtil::GetQualType(integer_clang_type));
2116 
2117     enum_decl->setAccess(AS_public); // TODO respect what's in the debug info
2118 
2119     return CompilerType(ast, ast->getTagDeclType(enum_decl));
2120   }
2121   return CompilerType();
2122 }
2123 
2124 // Disable this for now since I can't seem to get a nicely formatted float
2125 // out of the APFloat class without just getting the float, double or quad
2126 // and then using a formatted print on it which defeats the purpose. We ideally
2127 // would like to get perfect string values for any kind of float semantics
2128 // so we can support remote targets. The code below also requires a patch to
2129 // llvm::APInt.
2130 // bool
2131 // ClangASTContext::ConvertFloatValueToString (ASTContext *ast,
2132 // lldb::opaque_compiler_type_t clang_type, const uint8_t* bytes, size_t
2133 // byte_size, int apint_byte_order, std::string &float_str)
2134 //{
2135 //  uint32_t count = 0;
2136 //  bool is_complex = false;
2137 //  if (ClangASTContext::IsFloatingPointType (clang_type, count, is_complex))
2138 //  {
2139 //      unsigned num_bytes_per_float = byte_size / count;
2140 //      unsigned num_bits_per_float = num_bytes_per_float * 8;
2141 //
2142 //      float_str.clear();
2143 //      uint32_t i;
2144 //      for (i=0; i<count; i++)
2145 //      {
2146 //          APInt ap_int(num_bits_per_float, bytes + i * num_bytes_per_float,
2147 //          (APInt::ByteOrder)apint_byte_order);
2148 //          bool is_ieee = false;
2149 //          APFloat ap_float(ap_int, is_ieee);
2150 //          char s[1024];
2151 //          unsigned int hex_digits = 0;
2152 //          bool upper_case = false;
2153 //
2154 //          if (ap_float.convertToHexString(s, hex_digits, upper_case,
2155 //          APFloat::rmNearestTiesToEven) > 0)
2156 //          {
2157 //              if (i > 0)
2158 //                  float_str.append(", ");
2159 //              float_str.append(s);
2160 //              if (i == 1 && is_complex)
2161 //                  float_str.append(1, 'i');
2162 //          }
2163 //      }
2164 //      return !float_str.empty();
2165 //  }
2166 //  return false;
2167 //}
2168 
2169 CompilerType ClangASTContext::GetIntTypeFromBitSize(clang::ASTContext *ast,
2170                                                     size_t bit_size,
2171                                                     bool is_signed) {
2172   if (ast) {
2173     if (is_signed) {
2174       if (bit_size == ast->getTypeSize(ast->SignedCharTy))
2175         return CompilerType(ast, ast->SignedCharTy);
2176 
2177       if (bit_size == ast->getTypeSize(ast->ShortTy))
2178         return CompilerType(ast, ast->ShortTy);
2179 
2180       if (bit_size == ast->getTypeSize(ast->IntTy))
2181         return CompilerType(ast, ast->IntTy);
2182 
2183       if (bit_size == ast->getTypeSize(ast->LongTy))
2184         return CompilerType(ast, ast->LongTy);
2185 
2186       if (bit_size == ast->getTypeSize(ast->LongLongTy))
2187         return CompilerType(ast, ast->LongLongTy);
2188 
2189       if (bit_size == ast->getTypeSize(ast->Int128Ty))
2190         return CompilerType(ast, ast->Int128Ty);
2191     } else {
2192       if (bit_size == ast->getTypeSize(ast->UnsignedCharTy))
2193         return CompilerType(ast, ast->UnsignedCharTy);
2194 
2195       if (bit_size == ast->getTypeSize(ast->UnsignedShortTy))
2196         return CompilerType(ast, ast->UnsignedShortTy);
2197 
2198       if (bit_size == ast->getTypeSize(ast->UnsignedIntTy))
2199         return CompilerType(ast, ast->UnsignedIntTy);
2200 
2201       if (bit_size == ast->getTypeSize(ast->UnsignedLongTy))
2202         return CompilerType(ast, ast->UnsignedLongTy);
2203 
2204       if (bit_size == ast->getTypeSize(ast->UnsignedLongLongTy))
2205         return CompilerType(ast, ast->UnsignedLongLongTy);
2206 
2207       if (bit_size == ast->getTypeSize(ast->UnsignedInt128Ty))
2208         return CompilerType(ast, ast->UnsignedInt128Ty);
2209     }
2210   }
2211   return CompilerType();
2212 }
2213 
2214 CompilerType ClangASTContext::GetPointerSizedIntType(clang::ASTContext *ast,
2215                                                      bool is_signed) {
2216   if (ast)
2217     return GetIntTypeFromBitSize(ast, ast->getTypeSize(ast->VoidPtrTy),
2218                                  is_signed);
2219   return CompilerType();
2220 }
2221 
2222 void ClangASTContext::DumpDeclContextHiearchy(clang::DeclContext *decl_ctx) {
2223   if (decl_ctx) {
2224     DumpDeclContextHiearchy(decl_ctx->getParent());
2225 
2226     clang::NamedDecl *named_decl = llvm::dyn_cast<clang::NamedDecl>(decl_ctx);
2227     if (named_decl) {
2228       printf("%20s: %s\n", decl_ctx->getDeclKindName(),
2229              named_decl->getDeclName().getAsString().c_str());
2230     } else {
2231       printf("%20s\n", decl_ctx->getDeclKindName());
2232     }
2233   }
2234 }
2235 
2236 void ClangASTContext::DumpDeclHiearchy(clang::Decl *decl) {
2237   if (decl == nullptr)
2238     return;
2239   DumpDeclContextHiearchy(decl->getDeclContext());
2240 
2241   clang::RecordDecl *record_decl = llvm::dyn_cast<clang::RecordDecl>(decl);
2242   if (record_decl) {
2243     printf("%20s: %s%s\n", decl->getDeclKindName(),
2244            record_decl->getDeclName().getAsString().c_str(),
2245            record_decl->isInjectedClassName() ? " (injected class name)" : "");
2246 
2247   } else {
2248     clang::NamedDecl *named_decl = llvm::dyn_cast<clang::NamedDecl>(decl);
2249     if (named_decl) {
2250       printf("%20s: %s\n", decl->getDeclKindName(),
2251              named_decl->getDeclName().getAsString().c_str());
2252     } else {
2253       printf("%20s\n", decl->getDeclKindName());
2254     }
2255   }
2256 }
2257 
2258 bool ClangASTContext::DeclsAreEquivalent(clang::Decl *lhs_decl,
2259                                          clang::Decl *rhs_decl) {
2260   if (lhs_decl && rhs_decl) {
2261     //----------------------------------------------------------------------
2262     // Make sure the decl kinds match first
2263     //----------------------------------------------------------------------
2264     const clang::Decl::Kind lhs_decl_kind = lhs_decl->getKind();
2265     const clang::Decl::Kind rhs_decl_kind = rhs_decl->getKind();
2266 
2267     if (lhs_decl_kind == rhs_decl_kind) {
2268       //------------------------------------------------------------------
2269       // Now check that the decl contexts kinds are all equivalent
2270       // before we have to check any names of the decl contexts...
2271       //------------------------------------------------------------------
2272       clang::DeclContext *lhs_decl_ctx = lhs_decl->getDeclContext();
2273       clang::DeclContext *rhs_decl_ctx = rhs_decl->getDeclContext();
2274       if (lhs_decl_ctx && rhs_decl_ctx) {
2275         while (1) {
2276           if (lhs_decl_ctx && rhs_decl_ctx) {
2277             const clang::Decl::Kind lhs_decl_ctx_kind =
2278                 lhs_decl_ctx->getDeclKind();
2279             const clang::Decl::Kind rhs_decl_ctx_kind =
2280                 rhs_decl_ctx->getDeclKind();
2281             if (lhs_decl_ctx_kind == rhs_decl_ctx_kind) {
2282               lhs_decl_ctx = lhs_decl_ctx->getParent();
2283               rhs_decl_ctx = rhs_decl_ctx->getParent();
2284 
2285               if (lhs_decl_ctx == nullptr && rhs_decl_ctx == nullptr)
2286                 break;
2287             } else
2288               return false;
2289           } else
2290             return false;
2291         }
2292 
2293         //--------------------------------------------------------------
2294         // Now make sure the name of the decls match
2295         //--------------------------------------------------------------
2296         clang::NamedDecl *lhs_named_decl =
2297             llvm::dyn_cast<clang::NamedDecl>(lhs_decl);
2298         clang::NamedDecl *rhs_named_decl =
2299             llvm::dyn_cast<clang::NamedDecl>(rhs_decl);
2300         if (lhs_named_decl && rhs_named_decl) {
2301           clang::DeclarationName lhs_decl_name = lhs_named_decl->getDeclName();
2302           clang::DeclarationName rhs_decl_name = rhs_named_decl->getDeclName();
2303           if (lhs_decl_name.getNameKind() == rhs_decl_name.getNameKind()) {
2304             if (lhs_decl_name.getAsString() != rhs_decl_name.getAsString())
2305               return false;
2306           } else
2307             return false;
2308         } else
2309           return false;
2310 
2311         //--------------------------------------------------------------
2312         // We know that the decl context kinds all match, so now we need
2313         // to make sure the names match as well
2314         //--------------------------------------------------------------
2315         lhs_decl_ctx = lhs_decl->getDeclContext();
2316         rhs_decl_ctx = rhs_decl->getDeclContext();
2317         while (1) {
2318           switch (lhs_decl_ctx->getDeclKind()) {
2319           case clang::Decl::TranslationUnit:
2320             // We don't care about the translation unit names
2321             return true;
2322           default: {
2323             clang::NamedDecl *lhs_named_decl =
2324                 llvm::dyn_cast<clang::NamedDecl>(lhs_decl_ctx);
2325             clang::NamedDecl *rhs_named_decl =
2326                 llvm::dyn_cast<clang::NamedDecl>(rhs_decl_ctx);
2327             if (lhs_named_decl && rhs_named_decl) {
2328               clang::DeclarationName lhs_decl_name =
2329                   lhs_named_decl->getDeclName();
2330               clang::DeclarationName rhs_decl_name =
2331                   rhs_named_decl->getDeclName();
2332               if (lhs_decl_name.getNameKind() == rhs_decl_name.getNameKind()) {
2333                 if (lhs_decl_name.getAsString() != rhs_decl_name.getAsString())
2334                   return false;
2335               } else
2336                 return false;
2337             } else
2338               return false;
2339           } break;
2340           }
2341           lhs_decl_ctx = lhs_decl_ctx->getParent();
2342           rhs_decl_ctx = rhs_decl_ctx->getParent();
2343         }
2344       }
2345     }
2346   }
2347   return false;
2348 }
2349 bool ClangASTContext::GetCompleteDecl(clang::ASTContext *ast,
2350                                       clang::Decl *decl) {
2351   if (!decl)
2352     return false;
2353 
2354   ExternalASTSource *ast_source = ast->getExternalSource();
2355 
2356   if (!ast_source)
2357     return false;
2358 
2359   if (clang::TagDecl *tag_decl = llvm::dyn_cast<clang::TagDecl>(decl)) {
2360     if (tag_decl->isCompleteDefinition())
2361       return true;
2362 
2363     if (!tag_decl->hasExternalLexicalStorage())
2364       return false;
2365 
2366     ast_source->CompleteType(tag_decl);
2367 
2368     return !tag_decl->getTypeForDecl()->isIncompleteType();
2369   } else if (clang::ObjCInterfaceDecl *objc_interface_decl =
2370                  llvm::dyn_cast<clang::ObjCInterfaceDecl>(decl)) {
2371     if (objc_interface_decl->getDefinition())
2372       return true;
2373 
2374     if (!objc_interface_decl->hasExternalLexicalStorage())
2375       return false;
2376 
2377     ast_source->CompleteType(objc_interface_decl);
2378 
2379     return !objc_interface_decl->getTypeForDecl()->isIncompleteType();
2380   } else {
2381     return false;
2382   }
2383 }
2384 
2385 void ClangASTContext::SetMetadataAsUserID(const void *object,
2386                                           user_id_t user_id) {
2387   ClangASTMetadata meta_data;
2388   meta_data.SetUserID(user_id);
2389   SetMetadata(object, meta_data);
2390 }
2391 
2392 void ClangASTContext::SetMetadata(clang::ASTContext *ast, const void *object,
2393                                   ClangASTMetadata &metadata) {
2394   ClangExternalASTSourceCommon *external_source =
2395       ClangExternalASTSourceCommon::Lookup(ast->getExternalSource());
2396 
2397   if (external_source)
2398     external_source->SetMetadata(object, metadata);
2399 }
2400 
2401 ClangASTMetadata *ClangASTContext::GetMetadata(clang::ASTContext *ast,
2402                                                const void *object) {
2403   ClangExternalASTSourceCommon *external_source =
2404       ClangExternalASTSourceCommon::Lookup(ast->getExternalSource());
2405 
2406   if (external_source && external_source->HasMetadata(object))
2407     return external_source->GetMetadata(object);
2408   else
2409     return nullptr;
2410 }
2411 
2412 clang::DeclContext *
2413 ClangASTContext::GetAsDeclContext(clang::CXXMethodDecl *cxx_method_decl) {
2414   return llvm::dyn_cast<clang::DeclContext>(cxx_method_decl);
2415 }
2416 
2417 clang::DeclContext *
2418 ClangASTContext::GetAsDeclContext(clang::ObjCMethodDecl *objc_method_decl) {
2419   return llvm::dyn_cast<clang::DeclContext>(objc_method_decl);
2420 }
2421 
2422 bool ClangASTContext::SetTagTypeKind(clang::QualType tag_qual_type,
2423                                      int kind) const {
2424   const clang::Type *clang_type = tag_qual_type.getTypePtr();
2425   if (clang_type) {
2426     const clang::TagType *tag_type = llvm::dyn_cast<clang::TagType>(clang_type);
2427     if (tag_type) {
2428       clang::TagDecl *tag_decl =
2429           llvm::dyn_cast<clang::TagDecl>(tag_type->getDecl());
2430       if (tag_decl) {
2431         tag_decl->setTagKind((clang::TagDecl::TagKind)kind);
2432         return true;
2433       }
2434     }
2435   }
2436   return false;
2437 }
2438 
2439 bool ClangASTContext::SetDefaultAccessForRecordFields(
2440     clang::RecordDecl *record_decl, int default_accessibility,
2441     int *assigned_accessibilities, size_t num_assigned_accessibilities) {
2442   if (record_decl) {
2443     uint32_t field_idx;
2444     clang::RecordDecl::field_iterator field, field_end;
2445     for (field = record_decl->field_begin(),
2446         field_end = record_decl->field_end(), field_idx = 0;
2447          field != field_end; ++field, ++field_idx) {
2448       // If no accessibility was assigned, assign the correct one
2449       if (field_idx < num_assigned_accessibilities &&
2450           assigned_accessibilities[field_idx] == clang::AS_none)
2451         field->setAccess((clang::AccessSpecifier)default_accessibility);
2452     }
2453     return true;
2454   }
2455   return false;
2456 }
2457 
2458 clang::DeclContext *
2459 ClangASTContext::GetDeclContextForType(const CompilerType &type) {
2460   return GetDeclContextForType(ClangUtil::GetQualType(type));
2461 }
2462 
2463 clang::DeclContext *
2464 ClangASTContext::GetDeclContextForType(clang::QualType type) {
2465   if (type.isNull())
2466     return nullptr;
2467 
2468   clang::QualType qual_type = type.getCanonicalType();
2469   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2470   switch (type_class) {
2471   case clang::Type::ObjCInterface:
2472     return llvm::cast<clang::ObjCObjectType>(qual_type.getTypePtr())
2473         ->getInterface();
2474   case clang::Type::ObjCObjectPointer:
2475     return GetDeclContextForType(
2476         llvm::cast<clang::ObjCObjectPointerType>(qual_type.getTypePtr())
2477             ->getPointeeType());
2478   case clang::Type::Record:
2479     return llvm::cast<clang::RecordType>(qual_type)->getDecl();
2480   case clang::Type::Enum:
2481     return llvm::cast<clang::EnumType>(qual_type)->getDecl();
2482   case clang::Type::Typedef:
2483     return GetDeclContextForType(llvm::cast<clang::TypedefType>(qual_type)
2484                                      ->getDecl()
2485                                      ->getUnderlyingType());
2486   case clang::Type::Auto:
2487     return GetDeclContextForType(
2488         llvm::cast<clang::AutoType>(qual_type)->getDeducedType());
2489   case clang::Type::Elaborated:
2490     return GetDeclContextForType(
2491         llvm::cast<clang::ElaboratedType>(qual_type)->getNamedType());
2492   case clang::Type::Paren:
2493     return GetDeclContextForType(
2494         llvm::cast<clang::ParenType>(qual_type)->desugar());
2495   default:
2496     break;
2497   }
2498   // No DeclContext in this type...
2499   return nullptr;
2500 }
2501 
2502 static bool GetCompleteQualType(clang::ASTContext *ast,
2503                                 clang::QualType qual_type,
2504                                 bool allow_completion = true) {
2505   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2506   switch (type_class) {
2507   case clang::Type::ConstantArray:
2508   case clang::Type::IncompleteArray:
2509   case clang::Type::VariableArray: {
2510     const clang::ArrayType *array_type =
2511         llvm::dyn_cast<clang::ArrayType>(qual_type.getTypePtr());
2512 
2513     if (array_type)
2514       return GetCompleteQualType(ast, array_type->getElementType(),
2515                                  allow_completion);
2516   } break;
2517   case clang::Type::Record: {
2518     clang::CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
2519     if (cxx_record_decl) {
2520       if (cxx_record_decl->hasExternalLexicalStorage()) {
2521         const bool is_complete = cxx_record_decl->isCompleteDefinition();
2522         const bool fields_loaded =
2523             cxx_record_decl->hasLoadedFieldsFromExternalStorage();
2524         if (is_complete && fields_loaded)
2525           return true;
2526 
2527         if (!allow_completion)
2528           return false;
2529 
2530         // Call the field_begin() accessor to for it to use the external source
2531         // to load the fields...
2532         clang::ExternalASTSource *external_ast_source =
2533             ast->getExternalSource();
2534         if (external_ast_source) {
2535           external_ast_source->CompleteType(cxx_record_decl);
2536           if (cxx_record_decl->isCompleteDefinition()) {
2537             cxx_record_decl->field_begin();
2538             cxx_record_decl->setHasLoadedFieldsFromExternalStorage(true);
2539           }
2540         }
2541       }
2542     }
2543     const clang::TagType *tag_type =
2544         llvm::cast<clang::TagType>(qual_type.getTypePtr());
2545     return !tag_type->isIncompleteType();
2546   } break;
2547 
2548   case clang::Type::Enum: {
2549     const clang::TagType *tag_type =
2550         llvm::dyn_cast<clang::TagType>(qual_type.getTypePtr());
2551     if (tag_type) {
2552       clang::TagDecl *tag_decl = tag_type->getDecl();
2553       if (tag_decl) {
2554         if (tag_decl->getDefinition())
2555           return true;
2556 
2557         if (!allow_completion)
2558           return false;
2559 
2560         if (tag_decl->hasExternalLexicalStorage()) {
2561           if (ast) {
2562             clang::ExternalASTSource *external_ast_source =
2563                 ast->getExternalSource();
2564             if (external_ast_source) {
2565               external_ast_source->CompleteType(tag_decl);
2566               return !tag_type->isIncompleteType();
2567             }
2568           }
2569         }
2570         return false;
2571       }
2572     }
2573 
2574   } break;
2575   case clang::Type::ObjCObject:
2576   case clang::Type::ObjCInterface: {
2577     const clang::ObjCObjectType *objc_class_type =
2578         llvm::dyn_cast<clang::ObjCObjectType>(qual_type);
2579     if (objc_class_type) {
2580       clang::ObjCInterfaceDecl *class_interface_decl =
2581           objc_class_type->getInterface();
2582       // We currently can't complete objective C types through the newly added
2583       // ASTContext
2584       // because it only supports TagDecl objects right now...
2585       if (class_interface_decl) {
2586         if (class_interface_decl->getDefinition())
2587           return true;
2588 
2589         if (!allow_completion)
2590           return false;
2591 
2592         if (class_interface_decl->hasExternalLexicalStorage()) {
2593           if (ast) {
2594             clang::ExternalASTSource *external_ast_source =
2595                 ast->getExternalSource();
2596             if (external_ast_source) {
2597               external_ast_source->CompleteType(class_interface_decl);
2598               return !objc_class_type->isIncompleteType();
2599             }
2600           }
2601         }
2602         return false;
2603       }
2604     }
2605   } break;
2606 
2607   case clang::Type::Typedef:
2608     return GetCompleteQualType(ast, llvm::cast<clang::TypedefType>(qual_type)
2609                                         ->getDecl()
2610                                         ->getUnderlyingType(),
2611                                allow_completion);
2612 
2613   case clang::Type::Auto:
2614     return GetCompleteQualType(
2615         ast, llvm::cast<clang::AutoType>(qual_type)->getDeducedType(),
2616         allow_completion);
2617 
2618   case clang::Type::Elaborated:
2619     return GetCompleteQualType(
2620         ast, llvm::cast<clang::ElaboratedType>(qual_type)->getNamedType(),
2621         allow_completion);
2622 
2623   case clang::Type::Paren:
2624     return GetCompleteQualType(
2625         ast, llvm::cast<clang::ParenType>(qual_type)->desugar(),
2626         allow_completion);
2627 
2628   case clang::Type::Attributed:
2629     return GetCompleteQualType(
2630         ast, llvm::cast<clang::AttributedType>(qual_type)->getModifiedType(),
2631         allow_completion);
2632 
2633   default:
2634     break;
2635   }
2636 
2637   return true;
2638 }
2639 
2640 static clang::ObjCIvarDecl::AccessControl
2641 ConvertAccessTypeToObjCIvarAccessControl(AccessType access) {
2642   switch (access) {
2643   case eAccessNone:
2644     return clang::ObjCIvarDecl::None;
2645   case eAccessPublic:
2646     return clang::ObjCIvarDecl::Public;
2647   case eAccessPrivate:
2648     return clang::ObjCIvarDecl::Private;
2649   case eAccessProtected:
2650     return clang::ObjCIvarDecl::Protected;
2651   case eAccessPackage:
2652     return clang::ObjCIvarDecl::Package;
2653   }
2654   return clang::ObjCIvarDecl::None;
2655 }
2656 
2657 //----------------------------------------------------------------------
2658 // Tests
2659 //----------------------------------------------------------------------
2660 
2661 bool ClangASTContext::IsAggregateType(lldb::opaque_compiler_type_t type) {
2662   clang::QualType qual_type(GetCanonicalQualType(type));
2663 
2664   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2665   switch (type_class) {
2666   case clang::Type::IncompleteArray:
2667   case clang::Type::VariableArray:
2668   case clang::Type::ConstantArray:
2669   case clang::Type::ExtVector:
2670   case clang::Type::Vector:
2671   case clang::Type::Record:
2672   case clang::Type::ObjCObject:
2673   case clang::Type::ObjCInterface:
2674     return true;
2675   case clang::Type::Auto:
2676     return IsAggregateType(llvm::cast<clang::AutoType>(qual_type)
2677                                ->getDeducedType()
2678                                .getAsOpaquePtr());
2679   case clang::Type::Elaborated:
2680     return IsAggregateType(llvm::cast<clang::ElaboratedType>(qual_type)
2681                                ->getNamedType()
2682                                .getAsOpaquePtr());
2683   case clang::Type::Typedef:
2684     return IsAggregateType(llvm::cast<clang::TypedefType>(qual_type)
2685                                ->getDecl()
2686                                ->getUnderlyingType()
2687                                .getAsOpaquePtr());
2688   case clang::Type::Paren:
2689     return IsAggregateType(
2690         llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr());
2691   default:
2692     break;
2693   }
2694   // The clang type does have a value
2695   return false;
2696 }
2697 
2698 bool ClangASTContext::IsAnonymousType(lldb::opaque_compiler_type_t type) {
2699   clang::QualType qual_type(GetCanonicalQualType(type));
2700 
2701   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2702   switch (type_class) {
2703   case clang::Type::Record: {
2704     if (const clang::RecordType *record_type =
2705             llvm::dyn_cast_or_null<clang::RecordType>(
2706                 qual_type.getTypePtrOrNull())) {
2707       if (const clang::RecordDecl *record_decl = record_type->getDecl()) {
2708         return record_decl->isAnonymousStructOrUnion();
2709       }
2710     }
2711     break;
2712   }
2713   case clang::Type::Auto:
2714     return IsAnonymousType(llvm::cast<clang::AutoType>(qual_type)
2715                                ->getDeducedType()
2716                                .getAsOpaquePtr());
2717   case clang::Type::Elaborated:
2718     return IsAnonymousType(llvm::cast<clang::ElaboratedType>(qual_type)
2719                                ->getNamedType()
2720                                .getAsOpaquePtr());
2721   case clang::Type::Typedef:
2722     return IsAnonymousType(llvm::cast<clang::TypedefType>(qual_type)
2723                                ->getDecl()
2724                                ->getUnderlyingType()
2725                                .getAsOpaquePtr());
2726   case clang::Type::Paren:
2727     return IsAnonymousType(
2728         llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr());
2729   default:
2730     break;
2731   }
2732   // The clang type does have a value
2733   return false;
2734 }
2735 
2736 bool ClangASTContext::IsArrayType(lldb::opaque_compiler_type_t type,
2737                                   CompilerType *element_type_ptr,
2738                                   uint64_t *size, bool *is_incomplete) {
2739   clang::QualType qual_type(GetCanonicalQualType(type));
2740 
2741   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2742   switch (type_class) {
2743   default:
2744     break;
2745 
2746   case clang::Type::ConstantArray:
2747     if (element_type_ptr)
2748       element_type_ptr->SetCompilerType(
2749           getASTContext(),
2750           llvm::cast<clang::ConstantArrayType>(qual_type)->getElementType());
2751     if (size)
2752       *size = llvm::cast<clang::ConstantArrayType>(qual_type)
2753                   ->getSize()
2754                   .getLimitedValue(ULLONG_MAX);
2755     if (is_incomplete)
2756       *is_incomplete = false;
2757     return true;
2758 
2759   case clang::Type::IncompleteArray:
2760     if (element_type_ptr)
2761       element_type_ptr->SetCompilerType(
2762           getASTContext(),
2763           llvm::cast<clang::IncompleteArrayType>(qual_type)->getElementType());
2764     if (size)
2765       *size = 0;
2766     if (is_incomplete)
2767       *is_incomplete = true;
2768     return true;
2769 
2770   case clang::Type::VariableArray:
2771     if (element_type_ptr)
2772       element_type_ptr->SetCompilerType(
2773           getASTContext(),
2774           llvm::cast<clang::VariableArrayType>(qual_type)->getElementType());
2775     if (size)
2776       *size = 0;
2777     if (is_incomplete)
2778       *is_incomplete = false;
2779     return true;
2780 
2781   case clang::Type::DependentSizedArray:
2782     if (element_type_ptr)
2783       element_type_ptr->SetCompilerType(
2784           getASTContext(), llvm::cast<clang::DependentSizedArrayType>(qual_type)
2785                                ->getElementType());
2786     if (size)
2787       *size = 0;
2788     if (is_incomplete)
2789       *is_incomplete = false;
2790     return true;
2791 
2792   case clang::Type::Typedef:
2793     return IsArrayType(llvm::cast<clang::TypedefType>(qual_type)
2794                            ->getDecl()
2795                            ->getUnderlyingType()
2796                            .getAsOpaquePtr(),
2797                        element_type_ptr, size, is_incomplete);
2798   case clang::Type::Auto:
2799     return IsArrayType(llvm::cast<clang::AutoType>(qual_type)
2800                            ->getDeducedType()
2801                            .getAsOpaquePtr(),
2802                        element_type_ptr, size, is_incomplete);
2803   case clang::Type::Elaborated:
2804     return IsArrayType(llvm::cast<clang::ElaboratedType>(qual_type)
2805                            ->getNamedType()
2806                            .getAsOpaquePtr(),
2807                        element_type_ptr, size, is_incomplete);
2808   case clang::Type::Paren:
2809     return IsArrayType(
2810         llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr(),
2811         element_type_ptr, size, is_incomplete);
2812   }
2813   if (element_type_ptr)
2814     element_type_ptr->Clear();
2815   if (size)
2816     *size = 0;
2817   if (is_incomplete)
2818     *is_incomplete = false;
2819   return false;
2820 }
2821 
2822 bool ClangASTContext::IsVectorType(lldb::opaque_compiler_type_t type,
2823                                    CompilerType *element_type, uint64_t *size) {
2824   clang::QualType qual_type(GetCanonicalQualType(type));
2825 
2826   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2827   switch (type_class) {
2828   case clang::Type::Vector: {
2829     const clang::VectorType *vector_type =
2830         qual_type->getAs<clang::VectorType>();
2831     if (vector_type) {
2832       if (size)
2833         *size = vector_type->getNumElements();
2834       if (element_type)
2835         *element_type =
2836             CompilerType(getASTContext(), vector_type->getElementType());
2837     }
2838     return true;
2839   } break;
2840   case clang::Type::ExtVector: {
2841     const clang::ExtVectorType *ext_vector_type =
2842         qual_type->getAs<clang::ExtVectorType>();
2843     if (ext_vector_type) {
2844       if (size)
2845         *size = ext_vector_type->getNumElements();
2846       if (element_type)
2847         *element_type =
2848             CompilerType(getASTContext(), ext_vector_type->getElementType());
2849     }
2850     return true;
2851   }
2852   default:
2853     break;
2854   }
2855   return false;
2856 }
2857 
2858 bool ClangASTContext::IsRuntimeGeneratedType(
2859     lldb::opaque_compiler_type_t type) {
2860   clang::DeclContext *decl_ctx = ClangASTContext::GetASTContext(getASTContext())
2861                                      ->GetDeclContextForType(GetQualType(type));
2862   if (!decl_ctx)
2863     return false;
2864 
2865   if (!llvm::isa<clang::ObjCInterfaceDecl>(decl_ctx))
2866     return false;
2867 
2868   clang::ObjCInterfaceDecl *result_iface_decl =
2869       llvm::dyn_cast<clang::ObjCInterfaceDecl>(decl_ctx);
2870 
2871   ClangASTMetadata *ast_metadata =
2872       ClangASTContext::GetMetadata(getASTContext(), result_iface_decl);
2873   if (!ast_metadata)
2874     return false;
2875   return (ast_metadata->GetISAPtr() != 0);
2876 }
2877 
2878 bool ClangASTContext::IsCharType(lldb::opaque_compiler_type_t type) {
2879   return GetQualType(type).getUnqualifiedType()->isCharType();
2880 }
2881 
2882 bool ClangASTContext::IsCompleteType(lldb::opaque_compiler_type_t type) {
2883   const bool allow_completion = false;
2884   return GetCompleteQualType(getASTContext(), GetQualType(type),
2885                              allow_completion);
2886 }
2887 
2888 bool ClangASTContext::IsConst(lldb::opaque_compiler_type_t type) {
2889   return GetQualType(type).isConstQualified();
2890 }
2891 
2892 bool ClangASTContext::IsCStringType(lldb::opaque_compiler_type_t type,
2893                                     uint32_t &length) {
2894   CompilerType pointee_or_element_clang_type;
2895   length = 0;
2896   Flags type_flags(GetTypeInfo(type, &pointee_or_element_clang_type));
2897 
2898   if (!pointee_or_element_clang_type.IsValid())
2899     return false;
2900 
2901   if (type_flags.AnySet(eTypeIsArray | eTypeIsPointer)) {
2902     if (pointee_or_element_clang_type.IsCharType()) {
2903       if (type_flags.Test(eTypeIsArray)) {
2904         // We know the size of the array and it could be a C string
2905         // since it is an array of characters
2906         length = llvm::cast<clang::ConstantArrayType>(
2907                      GetCanonicalQualType(type).getTypePtr())
2908                      ->getSize()
2909                      .getLimitedValue();
2910       }
2911       return true;
2912     }
2913   }
2914   return false;
2915 }
2916 
2917 bool ClangASTContext::IsFunctionType(lldb::opaque_compiler_type_t type,
2918                                      bool *is_variadic_ptr) {
2919   if (type) {
2920     clang::QualType qual_type(GetCanonicalQualType(type));
2921 
2922     if (qual_type->isFunctionType()) {
2923       if (is_variadic_ptr) {
2924         const clang::FunctionProtoType *function_proto_type =
2925             llvm::dyn_cast<clang::FunctionProtoType>(qual_type.getTypePtr());
2926         if (function_proto_type)
2927           *is_variadic_ptr = function_proto_type->isVariadic();
2928         else
2929           *is_variadic_ptr = false;
2930       }
2931       return true;
2932     }
2933 
2934     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2935     switch (type_class) {
2936     default:
2937       break;
2938     case clang::Type::Typedef:
2939       return IsFunctionType(llvm::cast<clang::TypedefType>(qual_type)
2940                                 ->getDecl()
2941                                 ->getUnderlyingType()
2942                                 .getAsOpaquePtr(),
2943                             nullptr);
2944     case clang::Type::Auto:
2945       return IsFunctionType(llvm::cast<clang::AutoType>(qual_type)
2946                                 ->getDeducedType()
2947                                 .getAsOpaquePtr(),
2948                             nullptr);
2949     case clang::Type::Elaborated:
2950       return IsFunctionType(llvm::cast<clang::ElaboratedType>(qual_type)
2951                                 ->getNamedType()
2952                                 .getAsOpaquePtr(),
2953                             nullptr);
2954     case clang::Type::Paren:
2955       return IsFunctionType(
2956           llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr(),
2957           nullptr);
2958     case clang::Type::LValueReference:
2959     case clang::Type::RValueReference: {
2960       const clang::ReferenceType *reference_type =
2961           llvm::cast<clang::ReferenceType>(qual_type.getTypePtr());
2962       if (reference_type)
2963         return IsFunctionType(reference_type->getPointeeType().getAsOpaquePtr(),
2964                               nullptr);
2965     } break;
2966     }
2967   }
2968   return false;
2969 }
2970 
2971 // Used to detect "Homogeneous Floating-point Aggregates"
2972 uint32_t
2973 ClangASTContext::IsHomogeneousAggregate(lldb::opaque_compiler_type_t type,
2974                                         CompilerType *base_type_ptr) {
2975   if (!type)
2976     return 0;
2977 
2978   clang::QualType qual_type(GetCanonicalQualType(type));
2979   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2980   switch (type_class) {
2981   case clang::Type::Record:
2982     if (GetCompleteType(type)) {
2983       const clang::CXXRecordDecl *cxx_record_decl =
2984           qual_type->getAsCXXRecordDecl();
2985       if (cxx_record_decl) {
2986         if (cxx_record_decl->getNumBases() || cxx_record_decl->isDynamicClass())
2987           return 0;
2988       }
2989       const clang::RecordType *record_type =
2990           llvm::cast<clang::RecordType>(qual_type.getTypePtr());
2991       if (record_type) {
2992         const clang::RecordDecl *record_decl = record_type->getDecl();
2993         if (record_decl) {
2994           // We are looking for a structure that contains only floating point
2995           // types
2996           clang::RecordDecl::field_iterator field_pos,
2997               field_end = record_decl->field_end();
2998           uint32_t num_fields = 0;
2999           bool is_hva = false;
3000           bool is_hfa = false;
3001           clang::QualType base_qual_type;
3002           uint64_t base_bitwidth = 0;
3003           for (field_pos = record_decl->field_begin(); field_pos != field_end;
3004                ++field_pos) {
3005             clang::QualType field_qual_type = field_pos->getType();
3006             uint64_t field_bitwidth = getASTContext()->getTypeSize(qual_type);
3007             if (field_qual_type->isFloatingType()) {
3008               if (field_qual_type->isComplexType())
3009                 return 0;
3010               else {
3011                 if (num_fields == 0)
3012                   base_qual_type = field_qual_type;
3013                 else {
3014                   if (is_hva)
3015                     return 0;
3016                   is_hfa = true;
3017                   if (field_qual_type.getTypePtr() !=
3018                       base_qual_type.getTypePtr())
3019                     return 0;
3020                 }
3021               }
3022             } else if (field_qual_type->isVectorType() ||
3023                        field_qual_type->isExtVectorType()) {
3024               if (num_fields == 0) {
3025                 base_qual_type = field_qual_type;
3026                 base_bitwidth = field_bitwidth;
3027               } else {
3028                 if (is_hfa)
3029                   return 0;
3030                 is_hva = true;
3031                 if (base_bitwidth != field_bitwidth)
3032                   return 0;
3033                 if (field_qual_type.getTypePtr() != base_qual_type.getTypePtr())
3034                   return 0;
3035               }
3036             } else
3037               return 0;
3038             ++num_fields;
3039           }
3040           if (base_type_ptr)
3041             *base_type_ptr = CompilerType(getASTContext(), base_qual_type);
3042           return num_fields;
3043         }
3044       }
3045     }
3046     break;
3047 
3048   case clang::Type::Typedef:
3049     return IsHomogeneousAggregate(llvm::cast<clang::TypedefType>(qual_type)
3050                                       ->getDecl()
3051                                       ->getUnderlyingType()
3052                                       .getAsOpaquePtr(),
3053                                   base_type_ptr);
3054 
3055   case clang::Type::Auto:
3056     return IsHomogeneousAggregate(llvm::cast<clang::AutoType>(qual_type)
3057                                       ->getDeducedType()
3058                                       .getAsOpaquePtr(),
3059                                   base_type_ptr);
3060 
3061   case clang::Type::Elaborated:
3062     return IsHomogeneousAggregate(llvm::cast<clang::ElaboratedType>(qual_type)
3063                                       ->getNamedType()
3064                                       .getAsOpaquePtr(),
3065                                   base_type_ptr);
3066   default:
3067     break;
3068   }
3069   return 0;
3070 }
3071 
3072 size_t ClangASTContext::GetNumberOfFunctionArguments(
3073     lldb::opaque_compiler_type_t type) {
3074   if (type) {
3075     clang::QualType qual_type(GetCanonicalQualType(type));
3076     const clang::FunctionProtoType *func =
3077         llvm::dyn_cast<clang::FunctionProtoType>(qual_type.getTypePtr());
3078     if (func)
3079       return func->getNumParams();
3080   }
3081   return 0;
3082 }
3083 
3084 CompilerType
3085 ClangASTContext::GetFunctionArgumentAtIndex(lldb::opaque_compiler_type_t type,
3086                                             const size_t index) {
3087   if (type) {
3088     clang::QualType qual_type(GetQualType(type));
3089     const clang::FunctionProtoType *func =
3090         llvm::dyn_cast<clang::FunctionProtoType>(qual_type.getTypePtr());
3091     if (func) {
3092       if (index < func->getNumParams())
3093         return CompilerType(getASTContext(), func->getParamType(index));
3094     }
3095   }
3096   return CompilerType();
3097 }
3098 
3099 bool ClangASTContext::IsFunctionPointerType(lldb::opaque_compiler_type_t type) {
3100   if (type) {
3101     clang::QualType qual_type(GetCanonicalQualType(type));
3102 
3103     if (qual_type->isFunctionPointerType())
3104       return true;
3105 
3106     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3107     switch (type_class) {
3108     default:
3109       break;
3110     case clang::Type::Typedef:
3111       return IsFunctionPointerType(llvm::cast<clang::TypedefType>(qual_type)
3112                                        ->getDecl()
3113                                        ->getUnderlyingType()
3114                                        .getAsOpaquePtr());
3115     case clang::Type::Auto:
3116       return IsFunctionPointerType(llvm::cast<clang::AutoType>(qual_type)
3117                                        ->getDeducedType()
3118                                        .getAsOpaquePtr());
3119     case clang::Type::Elaborated:
3120       return IsFunctionPointerType(llvm::cast<clang::ElaboratedType>(qual_type)
3121                                        ->getNamedType()
3122                                        .getAsOpaquePtr());
3123     case clang::Type::Paren:
3124       return IsFunctionPointerType(
3125           llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr());
3126 
3127     case clang::Type::LValueReference:
3128     case clang::Type::RValueReference: {
3129       const clang::ReferenceType *reference_type =
3130           llvm::cast<clang::ReferenceType>(qual_type.getTypePtr());
3131       if (reference_type)
3132         return IsFunctionPointerType(
3133             reference_type->getPointeeType().getAsOpaquePtr());
3134     } break;
3135     }
3136   }
3137   return false;
3138 }
3139 
3140 bool ClangASTContext::IsBlockPointerType(
3141     lldb::opaque_compiler_type_t type,
3142     CompilerType *function_pointer_type_ptr) {
3143   if (type) {
3144     clang::QualType qual_type(GetCanonicalQualType(type));
3145 
3146     if (qual_type->isBlockPointerType()) {
3147       if (function_pointer_type_ptr) {
3148         const clang::BlockPointerType *block_pointer_type =
3149             qual_type->getAs<clang::BlockPointerType>();
3150         QualType pointee_type = block_pointer_type->getPointeeType();
3151         QualType function_pointer_type = m_ast_ap->getPointerType(pointee_type);
3152         *function_pointer_type_ptr =
3153             CompilerType(getASTContext(), function_pointer_type);
3154       }
3155       return true;
3156     }
3157 
3158     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3159     switch (type_class) {
3160     default:
3161       break;
3162     case clang::Type::Typedef:
3163       return IsBlockPointerType(llvm::cast<clang::TypedefType>(qual_type)
3164                                     ->getDecl()
3165                                     ->getUnderlyingType()
3166                                     .getAsOpaquePtr(),
3167                                 function_pointer_type_ptr);
3168     case clang::Type::Auto:
3169       return IsBlockPointerType(llvm::cast<clang::AutoType>(qual_type)
3170                                     ->getDeducedType()
3171                                     .getAsOpaquePtr(),
3172                                 function_pointer_type_ptr);
3173     case clang::Type::Elaborated:
3174       return IsBlockPointerType(llvm::cast<clang::ElaboratedType>(qual_type)
3175                                     ->getNamedType()
3176                                     .getAsOpaquePtr(),
3177                                 function_pointer_type_ptr);
3178     case clang::Type::Paren:
3179       return IsBlockPointerType(
3180           llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr(),
3181           function_pointer_type_ptr);
3182 
3183     case clang::Type::LValueReference:
3184     case clang::Type::RValueReference: {
3185       const clang::ReferenceType *reference_type =
3186           llvm::cast<clang::ReferenceType>(qual_type.getTypePtr());
3187       if (reference_type)
3188         return IsBlockPointerType(
3189             reference_type->getPointeeType().getAsOpaquePtr(),
3190             function_pointer_type_ptr);
3191     } break;
3192     }
3193   }
3194   return false;
3195 }
3196 
3197 bool ClangASTContext::IsIntegerType(lldb::opaque_compiler_type_t type,
3198                                     bool &is_signed) {
3199   if (!type)
3200     return false;
3201 
3202   clang::QualType qual_type(GetCanonicalQualType(type));
3203   const clang::BuiltinType *builtin_type =
3204       llvm::dyn_cast<clang::BuiltinType>(qual_type->getCanonicalTypeInternal());
3205 
3206   if (builtin_type) {
3207     if (builtin_type->isInteger()) {
3208       is_signed = builtin_type->isSignedInteger();
3209       return true;
3210     }
3211   }
3212 
3213   return false;
3214 }
3215 
3216 bool ClangASTContext::IsEnumerationType(lldb::opaque_compiler_type_t type,
3217                                         bool &is_signed) {
3218   if (type) {
3219     const clang::EnumType *enum_type = llvm::dyn_cast<clang::EnumType>(
3220         GetCanonicalQualType(type)->getCanonicalTypeInternal());
3221 
3222     if (enum_type) {
3223       IsIntegerType(enum_type->getDecl()->getIntegerType().getAsOpaquePtr(),
3224                     is_signed);
3225       return true;
3226     }
3227   }
3228 
3229   return false;
3230 }
3231 
3232 bool ClangASTContext::IsPointerType(lldb::opaque_compiler_type_t type,
3233                                     CompilerType *pointee_type) {
3234   if (type) {
3235     clang::QualType qual_type(GetCanonicalQualType(type));
3236     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3237     switch (type_class) {
3238     case clang::Type::Builtin:
3239       switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
3240       default:
3241         break;
3242       case clang::BuiltinType::ObjCId:
3243       case clang::BuiltinType::ObjCClass:
3244         return true;
3245       }
3246       return false;
3247     case clang::Type::ObjCObjectPointer:
3248       if (pointee_type)
3249         pointee_type->SetCompilerType(
3250             getASTContext(), llvm::cast<clang::ObjCObjectPointerType>(qual_type)
3251                                  ->getPointeeType());
3252       return true;
3253     case clang::Type::BlockPointer:
3254       if (pointee_type)
3255         pointee_type->SetCompilerType(
3256             getASTContext(),
3257             llvm::cast<clang::BlockPointerType>(qual_type)->getPointeeType());
3258       return true;
3259     case clang::Type::Pointer:
3260       if (pointee_type)
3261         pointee_type->SetCompilerType(
3262             getASTContext(),
3263             llvm::cast<clang::PointerType>(qual_type)->getPointeeType());
3264       return true;
3265     case clang::Type::MemberPointer:
3266       if (pointee_type)
3267         pointee_type->SetCompilerType(
3268             getASTContext(),
3269             llvm::cast<clang::MemberPointerType>(qual_type)->getPointeeType());
3270       return true;
3271     case clang::Type::Typedef:
3272       return IsPointerType(llvm::cast<clang::TypedefType>(qual_type)
3273                                ->getDecl()
3274                                ->getUnderlyingType()
3275                                .getAsOpaquePtr(),
3276                            pointee_type);
3277     case clang::Type::Auto:
3278       return IsPointerType(llvm::cast<clang::AutoType>(qual_type)
3279                                ->getDeducedType()
3280                                .getAsOpaquePtr(),
3281                            pointee_type);
3282     case clang::Type::Elaborated:
3283       return IsPointerType(llvm::cast<clang::ElaboratedType>(qual_type)
3284                                ->getNamedType()
3285                                .getAsOpaquePtr(),
3286                            pointee_type);
3287     case clang::Type::Paren:
3288       return IsPointerType(
3289           llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr(),
3290           pointee_type);
3291     default:
3292       break;
3293     }
3294   }
3295   if (pointee_type)
3296     pointee_type->Clear();
3297   return false;
3298 }
3299 
3300 bool ClangASTContext::IsPointerOrReferenceType(
3301     lldb::opaque_compiler_type_t type, CompilerType *pointee_type) {
3302   if (type) {
3303     clang::QualType qual_type(GetCanonicalQualType(type));
3304     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3305     switch (type_class) {
3306     case clang::Type::Builtin:
3307       switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
3308       default:
3309         break;
3310       case clang::BuiltinType::ObjCId:
3311       case clang::BuiltinType::ObjCClass:
3312         return true;
3313       }
3314       return false;
3315     case clang::Type::ObjCObjectPointer:
3316       if (pointee_type)
3317         pointee_type->SetCompilerType(
3318             getASTContext(), llvm::cast<clang::ObjCObjectPointerType>(qual_type)
3319                                  ->getPointeeType());
3320       return true;
3321     case clang::Type::BlockPointer:
3322       if (pointee_type)
3323         pointee_type->SetCompilerType(
3324             getASTContext(),
3325             llvm::cast<clang::BlockPointerType>(qual_type)->getPointeeType());
3326       return true;
3327     case clang::Type::Pointer:
3328       if (pointee_type)
3329         pointee_type->SetCompilerType(
3330             getASTContext(),
3331             llvm::cast<clang::PointerType>(qual_type)->getPointeeType());
3332       return true;
3333     case clang::Type::MemberPointer:
3334       if (pointee_type)
3335         pointee_type->SetCompilerType(
3336             getASTContext(),
3337             llvm::cast<clang::MemberPointerType>(qual_type)->getPointeeType());
3338       return true;
3339     case clang::Type::LValueReference:
3340       if (pointee_type)
3341         pointee_type->SetCompilerType(
3342             getASTContext(),
3343             llvm::cast<clang::LValueReferenceType>(qual_type)->desugar());
3344       return true;
3345     case clang::Type::RValueReference:
3346       if (pointee_type)
3347         pointee_type->SetCompilerType(
3348             getASTContext(),
3349             llvm::cast<clang::RValueReferenceType>(qual_type)->desugar());
3350       return true;
3351     case clang::Type::Typedef:
3352       return IsPointerOrReferenceType(llvm::cast<clang::TypedefType>(qual_type)
3353                                           ->getDecl()
3354                                           ->getUnderlyingType()
3355                                           .getAsOpaquePtr(),
3356                                       pointee_type);
3357     case clang::Type::Auto:
3358       return IsPointerOrReferenceType(llvm::cast<clang::AutoType>(qual_type)
3359                                           ->getDeducedType()
3360                                           .getAsOpaquePtr(),
3361                                       pointee_type);
3362     case clang::Type::Elaborated:
3363       return IsPointerOrReferenceType(
3364           llvm::cast<clang::ElaboratedType>(qual_type)
3365               ->getNamedType()
3366               .getAsOpaquePtr(),
3367           pointee_type);
3368     case clang::Type::Paren:
3369       return IsPointerOrReferenceType(
3370           llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr(),
3371           pointee_type);
3372     default:
3373       break;
3374     }
3375   }
3376   if (pointee_type)
3377     pointee_type->Clear();
3378   return false;
3379 }
3380 
3381 bool ClangASTContext::IsReferenceType(lldb::opaque_compiler_type_t type,
3382                                       CompilerType *pointee_type,
3383                                       bool *is_rvalue) {
3384   if (type) {
3385     clang::QualType qual_type(GetCanonicalQualType(type));
3386     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3387 
3388     switch (type_class) {
3389     case clang::Type::LValueReference:
3390       if (pointee_type)
3391         pointee_type->SetCompilerType(
3392             getASTContext(),
3393             llvm::cast<clang::LValueReferenceType>(qual_type)->desugar());
3394       if (is_rvalue)
3395         *is_rvalue = false;
3396       return true;
3397     case clang::Type::RValueReference:
3398       if (pointee_type)
3399         pointee_type->SetCompilerType(
3400             getASTContext(),
3401             llvm::cast<clang::RValueReferenceType>(qual_type)->desugar());
3402       if (is_rvalue)
3403         *is_rvalue = true;
3404       return true;
3405     case clang::Type::Typedef:
3406       return IsReferenceType(llvm::cast<clang::TypedefType>(qual_type)
3407                                  ->getDecl()
3408                                  ->getUnderlyingType()
3409                                  .getAsOpaquePtr(),
3410                              pointee_type, is_rvalue);
3411     case clang::Type::Auto:
3412       return IsReferenceType(llvm::cast<clang::AutoType>(qual_type)
3413                                  ->getDeducedType()
3414                                  .getAsOpaquePtr(),
3415                              pointee_type, is_rvalue);
3416     case clang::Type::Elaborated:
3417       return IsReferenceType(llvm::cast<clang::ElaboratedType>(qual_type)
3418                                  ->getNamedType()
3419                                  .getAsOpaquePtr(),
3420                              pointee_type, is_rvalue);
3421     case clang::Type::Paren:
3422       return IsReferenceType(
3423           llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr(),
3424           pointee_type, is_rvalue);
3425 
3426     default:
3427       break;
3428     }
3429   }
3430   if (pointee_type)
3431     pointee_type->Clear();
3432   return false;
3433 }
3434 
3435 bool ClangASTContext::IsFloatingPointType(lldb::opaque_compiler_type_t type,
3436                                           uint32_t &count, bool &is_complex) {
3437   if (type) {
3438     clang::QualType qual_type(GetCanonicalQualType(type));
3439 
3440     if (const clang::BuiltinType *BT = llvm::dyn_cast<clang::BuiltinType>(
3441             qual_type->getCanonicalTypeInternal())) {
3442       clang::BuiltinType::Kind kind = BT->getKind();
3443       if (kind >= clang::BuiltinType::Float &&
3444           kind <= clang::BuiltinType::LongDouble) {
3445         count = 1;
3446         is_complex = false;
3447         return true;
3448       }
3449     } else if (const clang::ComplexType *CT =
3450                    llvm::dyn_cast<clang::ComplexType>(
3451                        qual_type->getCanonicalTypeInternal())) {
3452       if (IsFloatingPointType(CT->getElementType().getAsOpaquePtr(), count,
3453                               is_complex)) {
3454         count = 2;
3455         is_complex = true;
3456         return true;
3457       }
3458     } else if (const clang::VectorType *VT = llvm::dyn_cast<clang::VectorType>(
3459                    qual_type->getCanonicalTypeInternal())) {
3460       if (IsFloatingPointType(VT->getElementType().getAsOpaquePtr(), count,
3461                               is_complex)) {
3462         count = VT->getNumElements();
3463         is_complex = false;
3464         return true;
3465       }
3466     }
3467   }
3468   count = 0;
3469   is_complex = false;
3470   return false;
3471 }
3472 
3473 bool ClangASTContext::IsDefined(lldb::opaque_compiler_type_t type) {
3474   if (!type)
3475     return false;
3476 
3477   clang::QualType qual_type(GetQualType(type));
3478   const clang::TagType *tag_type =
3479       llvm::dyn_cast<clang::TagType>(qual_type.getTypePtr());
3480   if (tag_type) {
3481     clang::TagDecl *tag_decl = tag_type->getDecl();
3482     if (tag_decl)
3483       return tag_decl->isCompleteDefinition();
3484     return false;
3485   } else {
3486     const clang::ObjCObjectType *objc_class_type =
3487         llvm::dyn_cast<clang::ObjCObjectType>(qual_type);
3488     if (objc_class_type) {
3489       clang::ObjCInterfaceDecl *class_interface_decl =
3490           objc_class_type->getInterface();
3491       if (class_interface_decl)
3492         return class_interface_decl->getDefinition() != nullptr;
3493       return false;
3494     }
3495   }
3496   return true;
3497 }
3498 
3499 bool ClangASTContext::IsObjCClassType(const CompilerType &type) {
3500   if (type) {
3501     clang::QualType qual_type(ClangUtil::GetCanonicalQualType(type));
3502 
3503     const clang::ObjCObjectPointerType *obj_pointer_type =
3504         llvm::dyn_cast<clang::ObjCObjectPointerType>(qual_type);
3505 
3506     if (obj_pointer_type)
3507       return obj_pointer_type->isObjCClassType();
3508   }
3509   return false;
3510 }
3511 
3512 bool ClangASTContext::IsObjCObjectOrInterfaceType(const CompilerType &type) {
3513   if (ClangUtil::IsClangType(type))
3514     return ClangUtil::GetCanonicalQualType(type)->isObjCObjectOrInterfaceType();
3515   return false;
3516 }
3517 
3518 bool ClangASTContext::IsClassType(lldb::opaque_compiler_type_t type) {
3519   if (!type)
3520     return false;
3521   clang::QualType qual_type(GetCanonicalQualType(type));
3522   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3523   return (type_class == clang::Type::Record);
3524 }
3525 
3526 bool ClangASTContext::IsEnumType(lldb::opaque_compiler_type_t type) {
3527   if (!type)
3528     return false;
3529   clang::QualType qual_type(GetCanonicalQualType(type));
3530   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3531   return (type_class == clang::Type::Enum);
3532 }
3533 
3534 bool ClangASTContext::IsPolymorphicClass(lldb::opaque_compiler_type_t type) {
3535   if (type) {
3536     clang::QualType qual_type(GetCanonicalQualType(type));
3537     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3538     switch (type_class) {
3539     case clang::Type::Record:
3540       if (GetCompleteType(type)) {
3541         const clang::RecordType *record_type =
3542             llvm::cast<clang::RecordType>(qual_type.getTypePtr());
3543         const clang::RecordDecl *record_decl = record_type->getDecl();
3544         if (record_decl) {
3545           const clang::CXXRecordDecl *cxx_record_decl =
3546               llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
3547           if (cxx_record_decl)
3548             return cxx_record_decl->isPolymorphic();
3549         }
3550       }
3551       break;
3552 
3553     default:
3554       break;
3555     }
3556   }
3557   return false;
3558 }
3559 
3560 bool ClangASTContext::IsPossibleDynamicType(lldb::opaque_compiler_type_t type,
3561                                             CompilerType *dynamic_pointee_type,
3562                                             bool check_cplusplus,
3563                                             bool check_objc) {
3564   clang::QualType pointee_qual_type;
3565   if (type) {
3566     clang::QualType qual_type(GetCanonicalQualType(type));
3567     bool success = false;
3568     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3569     switch (type_class) {
3570     case clang::Type::Builtin:
3571       if (check_objc &&
3572           llvm::cast<clang::BuiltinType>(qual_type)->getKind() ==
3573               clang::BuiltinType::ObjCId) {
3574         if (dynamic_pointee_type)
3575           dynamic_pointee_type->SetCompilerType(this, type);
3576         return true;
3577       }
3578       break;
3579 
3580     case clang::Type::ObjCObjectPointer:
3581       if (check_objc) {
3582         if (auto objc_pointee_type =
3583                 qual_type->getPointeeType().getTypePtrOrNull()) {
3584           if (auto objc_object_type =
3585                   llvm::dyn_cast_or_null<clang::ObjCObjectType>(
3586                       objc_pointee_type)) {
3587             if (objc_object_type->isObjCClass())
3588               return false;
3589           }
3590         }
3591         if (dynamic_pointee_type)
3592           dynamic_pointee_type->SetCompilerType(
3593               getASTContext(),
3594               llvm::cast<clang::ObjCObjectPointerType>(qual_type)
3595                   ->getPointeeType());
3596         return true;
3597       }
3598       break;
3599 
3600     case clang::Type::Pointer:
3601       pointee_qual_type =
3602           llvm::cast<clang::PointerType>(qual_type)->getPointeeType();
3603       success = true;
3604       break;
3605 
3606     case clang::Type::LValueReference:
3607     case clang::Type::RValueReference:
3608       pointee_qual_type =
3609           llvm::cast<clang::ReferenceType>(qual_type)->getPointeeType();
3610       success = true;
3611       break;
3612 
3613     case clang::Type::Typedef:
3614       return IsPossibleDynamicType(llvm::cast<clang::TypedefType>(qual_type)
3615                                        ->getDecl()
3616                                        ->getUnderlyingType()
3617                                        .getAsOpaquePtr(),
3618                                    dynamic_pointee_type, check_cplusplus,
3619                                    check_objc);
3620 
3621     case clang::Type::Auto:
3622       return IsPossibleDynamicType(llvm::cast<clang::AutoType>(qual_type)
3623                                        ->getDeducedType()
3624                                        .getAsOpaquePtr(),
3625                                    dynamic_pointee_type, check_cplusplus,
3626                                    check_objc);
3627 
3628     case clang::Type::Elaborated:
3629       return IsPossibleDynamicType(llvm::cast<clang::ElaboratedType>(qual_type)
3630                                        ->getNamedType()
3631                                        .getAsOpaquePtr(),
3632                                    dynamic_pointee_type, check_cplusplus,
3633                                    check_objc);
3634 
3635     case clang::Type::Paren:
3636       return IsPossibleDynamicType(
3637           llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr(),
3638           dynamic_pointee_type, check_cplusplus, check_objc);
3639     default:
3640       break;
3641     }
3642 
3643     if (success) {
3644       // Check to make sure what we are pointing too is a possible dynamic C++
3645       // type
3646       // We currently accept any "void *" (in case we have a class that has been
3647       // watered down to an opaque pointer) and virtual C++ classes.
3648       const clang::Type::TypeClass pointee_type_class =
3649           pointee_qual_type.getCanonicalType()->getTypeClass();
3650       switch (pointee_type_class) {
3651       case clang::Type::Builtin:
3652         switch (llvm::cast<clang::BuiltinType>(pointee_qual_type)->getKind()) {
3653         case clang::BuiltinType::UnknownAny:
3654         case clang::BuiltinType::Void:
3655           if (dynamic_pointee_type)
3656             dynamic_pointee_type->SetCompilerType(getASTContext(),
3657                                                   pointee_qual_type);
3658           return true;
3659         default:
3660           break;
3661         }
3662         break;
3663 
3664       case clang::Type::Record:
3665         if (check_cplusplus) {
3666           clang::CXXRecordDecl *cxx_record_decl =
3667               pointee_qual_type->getAsCXXRecordDecl();
3668           if (cxx_record_decl) {
3669             bool is_complete = cxx_record_decl->isCompleteDefinition();
3670 
3671             if (is_complete)
3672               success = cxx_record_decl->isDynamicClass();
3673             else {
3674               ClangASTMetadata *metadata = ClangASTContext::GetMetadata(
3675                   getASTContext(), cxx_record_decl);
3676               if (metadata)
3677                 success = metadata->GetIsDynamicCXXType();
3678               else {
3679                 is_complete = CompilerType(getASTContext(), pointee_qual_type)
3680                                   .GetCompleteType();
3681                 if (is_complete)
3682                   success = cxx_record_decl->isDynamicClass();
3683                 else
3684                   success = false;
3685               }
3686             }
3687 
3688             if (success) {
3689               if (dynamic_pointee_type)
3690                 dynamic_pointee_type->SetCompilerType(getASTContext(),
3691                                                       pointee_qual_type);
3692               return true;
3693             }
3694           }
3695         }
3696         break;
3697 
3698       case clang::Type::ObjCObject:
3699       case clang::Type::ObjCInterface:
3700         if (check_objc) {
3701           if (dynamic_pointee_type)
3702             dynamic_pointee_type->SetCompilerType(getASTContext(),
3703                                                   pointee_qual_type);
3704           return true;
3705         }
3706         break;
3707 
3708       default:
3709         break;
3710       }
3711     }
3712   }
3713   if (dynamic_pointee_type)
3714     dynamic_pointee_type->Clear();
3715   return false;
3716 }
3717 
3718 bool ClangASTContext::IsScalarType(lldb::opaque_compiler_type_t type) {
3719   if (!type)
3720     return false;
3721 
3722   return (GetTypeInfo(type, nullptr) & eTypeIsScalar) != 0;
3723 }
3724 
3725 bool ClangASTContext::IsTypedefType(lldb::opaque_compiler_type_t type) {
3726   if (!type)
3727     return false;
3728   return GetQualType(type)->getTypeClass() == clang::Type::Typedef;
3729 }
3730 
3731 bool ClangASTContext::IsVoidType(lldb::opaque_compiler_type_t type) {
3732   if (!type)
3733     return false;
3734   return GetCanonicalQualType(type)->isVoidType();
3735 }
3736 
3737 bool ClangASTContext::SupportsLanguage(lldb::LanguageType language) {
3738   return ClangASTContextSupportsLanguage(language);
3739 }
3740 
3741 bool ClangASTContext::GetCXXClassName(const CompilerType &type,
3742                                       std::string &class_name) {
3743   if (type) {
3744     clang::QualType qual_type(ClangUtil::GetCanonicalQualType(type));
3745     if (!qual_type.isNull()) {
3746       clang::CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
3747       if (cxx_record_decl) {
3748         class_name.assign(cxx_record_decl->getIdentifier()->getNameStart());
3749         return true;
3750       }
3751     }
3752   }
3753   class_name.clear();
3754   return false;
3755 }
3756 
3757 bool ClangASTContext::IsCXXClassType(const CompilerType &type) {
3758   if (!type)
3759     return false;
3760 
3761   clang::QualType qual_type(ClangUtil::GetCanonicalQualType(type));
3762   if (!qual_type.isNull() && qual_type->getAsCXXRecordDecl() != nullptr)
3763     return true;
3764   return false;
3765 }
3766 
3767 bool ClangASTContext::IsBeingDefined(lldb::opaque_compiler_type_t type) {
3768   if (!type)
3769     return false;
3770   clang::QualType qual_type(GetCanonicalQualType(type));
3771   const clang::TagType *tag_type = llvm::dyn_cast<clang::TagType>(qual_type);
3772   if (tag_type)
3773     return tag_type->isBeingDefined();
3774   return false;
3775 }
3776 
3777 bool ClangASTContext::IsObjCObjectPointerType(const CompilerType &type,
3778                                               CompilerType *class_type_ptr) {
3779   if (!type)
3780     return false;
3781 
3782   clang::QualType qual_type(ClangUtil::GetCanonicalQualType(type));
3783 
3784   if (!qual_type.isNull() && qual_type->isObjCObjectPointerType()) {
3785     if (class_type_ptr) {
3786       if (!qual_type->isObjCClassType() && !qual_type->isObjCIdType()) {
3787         const clang::ObjCObjectPointerType *obj_pointer_type =
3788             llvm::dyn_cast<clang::ObjCObjectPointerType>(qual_type);
3789         if (obj_pointer_type == nullptr)
3790           class_type_ptr->Clear();
3791         else
3792           class_type_ptr->SetCompilerType(
3793               type.GetTypeSystem(),
3794               clang::QualType(obj_pointer_type->getInterfaceType(), 0)
3795                   .getAsOpaquePtr());
3796       }
3797     }
3798     return true;
3799   }
3800   if (class_type_ptr)
3801     class_type_ptr->Clear();
3802   return false;
3803 }
3804 
3805 bool ClangASTContext::GetObjCClassName(const CompilerType &type,
3806                                        std::string &class_name) {
3807   if (!type)
3808     return false;
3809 
3810   clang::QualType qual_type(ClangUtil::GetCanonicalQualType(type));
3811 
3812   const clang::ObjCObjectType *object_type =
3813       llvm::dyn_cast<clang::ObjCObjectType>(qual_type);
3814   if (object_type) {
3815     const clang::ObjCInterfaceDecl *interface = object_type->getInterface();
3816     if (interface) {
3817       class_name = interface->getNameAsString();
3818       return true;
3819     }
3820   }
3821   return false;
3822 }
3823 
3824 //----------------------------------------------------------------------
3825 // Type Completion
3826 //----------------------------------------------------------------------
3827 
3828 bool ClangASTContext::GetCompleteType(lldb::opaque_compiler_type_t type) {
3829   if (!type)
3830     return false;
3831   const bool allow_completion = true;
3832   return GetCompleteQualType(getASTContext(), GetQualType(type),
3833                              allow_completion);
3834 }
3835 
3836 ConstString ClangASTContext::GetTypeName(lldb::opaque_compiler_type_t type) {
3837   std::string type_name;
3838   if (type) {
3839     clang::PrintingPolicy printing_policy(getASTContext()->getPrintingPolicy());
3840     clang::QualType qual_type(GetQualType(type));
3841     printing_policy.SuppressTagKeyword = true;
3842     const clang::TypedefType *typedef_type =
3843         qual_type->getAs<clang::TypedefType>();
3844     if (typedef_type) {
3845       const clang::TypedefNameDecl *typedef_decl = typedef_type->getDecl();
3846       type_name = typedef_decl->getQualifiedNameAsString();
3847     } else {
3848       type_name = qual_type.getAsString(printing_policy);
3849     }
3850   }
3851   return ConstString(type_name);
3852 }
3853 
3854 uint32_t
3855 ClangASTContext::GetTypeInfo(lldb::opaque_compiler_type_t type,
3856                              CompilerType *pointee_or_element_clang_type) {
3857   if (!type)
3858     return 0;
3859 
3860   if (pointee_or_element_clang_type)
3861     pointee_or_element_clang_type->Clear();
3862 
3863   clang::QualType qual_type(GetQualType(type));
3864 
3865   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3866   switch (type_class) {
3867   case clang::Type::Attributed:
3868     return GetTypeInfo(
3869         qual_type->getAs<clang::AttributedType>()
3870             ->getModifiedType().getAsOpaquePtr(),
3871         pointee_or_element_clang_type);
3872   case clang::Type::Builtin: {
3873     const clang::BuiltinType *builtin_type = llvm::dyn_cast<clang::BuiltinType>(
3874         qual_type->getCanonicalTypeInternal());
3875 
3876     uint32_t builtin_type_flags = eTypeIsBuiltIn | eTypeHasValue;
3877     switch (builtin_type->getKind()) {
3878     case clang::BuiltinType::ObjCId:
3879     case clang::BuiltinType::ObjCClass:
3880       if (pointee_or_element_clang_type)
3881         pointee_or_element_clang_type->SetCompilerType(
3882             getASTContext(), getASTContext()->ObjCBuiltinClassTy);
3883       builtin_type_flags |= eTypeIsPointer | eTypeIsObjC;
3884       break;
3885 
3886     case clang::BuiltinType::ObjCSel:
3887       if (pointee_or_element_clang_type)
3888         pointee_or_element_clang_type->SetCompilerType(getASTContext(),
3889                                                        getASTContext()->CharTy);
3890       builtin_type_flags |= eTypeIsPointer | eTypeIsObjC;
3891       break;
3892 
3893     case clang::BuiltinType::Bool:
3894     case clang::BuiltinType::Char_U:
3895     case clang::BuiltinType::UChar:
3896     case clang::BuiltinType::WChar_U:
3897     case clang::BuiltinType::Char16:
3898     case clang::BuiltinType::Char32:
3899     case clang::BuiltinType::UShort:
3900     case clang::BuiltinType::UInt:
3901     case clang::BuiltinType::ULong:
3902     case clang::BuiltinType::ULongLong:
3903     case clang::BuiltinType::UInt128:
3904     case clang::BuiltinType::Char_S:
3905     case clang::BuiltinType::SChar:
3906     case clang::BuiltinType::WChar_S:
3907     case clang::BuiltinType::Short:
3908     case clang::BuiltinType::Int:
3909     case clang::BuiltinType::Long:
3910     case clang::BuiltinType::LongLong:
3911     case clang::BuiltinType::Int128:
3912     case clang::BuiltinType::Float:
3913     case clang::BuiltinType::Double:
3914     case clang::BuiltinType::LongDouble:
3915       builtin_type_flags |= eTypeIsScalar;
3916       if (builtin_type->isInteger()) {
3917         builtin_type_flags |= eTypeIsInteger;
3918         if (builtin_type->isSignedInteger())
3919           builtin_type_flags |= eTypeIsSigned;
3920       } else if (builtin_type->isFloatingPoint())
3921         builtin_type_flags |= eTypeIsFloat;
3922       break;
3923     default:
3924       break;
3925     }
3926     return builtin_type_flags;
3927   }
3928 
3929   case clang::Type::BlockPointer:
3930     if (pointee_or_element_clang_type)
3931       pointee_or_element_clang_type->SetCompilerType(
3932           getASTContext(), qual_type->getPointeeType());
3933     return eTypeIsPointer | eTypeHasChildren | eTypeIsBlock;
3934 
3935   case clang::Type::Complex: {
3936     uint32_t complex_type_flags =
3937         eTypeIsBuiltIn | eTypeHasValue | eTypeIsComplex;
3938     const clang::ComplexType *complex_type = llvm::dyn_cast<clang::ComplexType>(
3939         qual_type->getCanonicalTypeInternal());
3940     if (complex_type) {
3941       clang::QualType complex_element_type(complex_type->getElementType());
3942       if (complex_element_type->isIntegerType())
3943         complex_type_flags |= eTypeIsFloat;
3944       else if (complex_element_type->isFloatingType())
3945         complex_type_flags |= eTypeIsInteger;
3946     }
3947     return complex_type_flags;
3948   } break;
3949 
3950   case clang::Type::ConstantArray:
3951   case clang::Type::DependentSizedArray:
3952   case clang::Type::IncompleteArray:
3953   case clang::Type::VariableArray:
3954     if (pointee_or_element_clang_type)
3955       pointee_or_element_clang_type->SetCompilerType(
3956           getASTContext(), llvm::cast<clang::ArrayType>(qual_type.getTypePtr())
3957                                ->getElementType());
3958     return eTypeHasChildren | eTypeIsArray;
3959 
3960   case clang::Type::DependentName:
3961     return 0;
3962   case clang::Type::DependentSizedExtVector:
3963     return eTypeHasChildren | eTypeIsVector;
3964   case clang::Type::DependentTemplateSpecialization:
3965     return eTypeIsTemplate;
3966   case clang::Type::Decltype:
3967     return 0;
3968 
3969   case clang::Type::Enum:
3970     if (pointee_or_element_clang_type)
3971       pointee_or_element_clang_type->SetCompilerType(
3972           getASTContext(),
3973           llvm::cast<clang::EnumType>(qual_type)->getDecl()->getIntegerType());
3974     return eTypeIsEnumeration | eTypeHasValue;
3975 
3976   case clang::Type::Auto:
3977     return CompilerType(
3978                getASTContext(),
3979                llvm::cast<clang::AutoType>(qual_type)->getDeducedType())
3980         .GetTypeInfo(pointee_or_element_clang_type);
3981   case clang::Type::Elaborated:
3982     return CompilerType(
3983                getASTContext(),
3984                llvm::cast<clang::ElaboratedType>(qual_type)->getNamedType())
3985         .GetTypeInfo(pointee_or_element_clang_type);
3986   case clang::Type::Paren:
3987     return CompilerType(getASTContext(),
3988                         llvm::cast<clang::ParenType>(qual_type)->desugar())
3989         .GetTypeInfo(pointee_or_element_clang_type);
3990 
3991   case clang::Type::FunctionProto:
3992     return eTypeIsFuncPrototype | eTypeHasValue;
3993   case clang::Type::FunctionNoProto:
3994     return eTypeIsFuncPrototype | eTypeHasValue;
3995   case clang::Type::InjectedClassName:
3996     return 0;
3997 
3998   case clang::Type::LValueReference:
3999   case clang::Type::RValueReference:
4000     if (pointee_or_element_clang_type)
4001       pointee_or_element_clang_type->SetCompilerType(
4002           getASTContext(),
4003           llvm::cast<clang::ReferenceType>(qual_type.getTypePtr())
4004               ->getPointeeType());
4005     return eTypeHasChildren | eTypeIsReference | eTypeHasValue;
4006 
4007   case clang::Type::MemberPointer:
4008     return eTypeIsPointer | eTypeIsMember | eTypeHasValue;
4009 
4010   case clang::Type::ObjCObjectPointer:
4011     if (pointee_or_element_clang_type)
4012       pointee_or_element_clang_type->SetCompilerType(
4013           getASTContext(), qual_type->getPointeeType());
4014     return eTypeHasChildren | eTypeIsObjC | eTypeIsClass | eTypeIsPointer |
4015            eTypeHasValue;
4016 
4017   case clang::Type::ObjCObject:
4018     return eTypeHasChildren | eTypeIsObjC | eTypeIsClass;
4019   case clang::Type::ObjCInterface:
4020     return eTypeHasChildren | eTypeIsObjC | eTypeIsClass;
4021 
4022   case clang::Type::Pointer:
4023     if (pointee_or_element_clang_type)
4024       pointee_or_element_clang_type->SetCompilerType(
4025           getASTContext(), qual_type->getPointeeType());
4026     return eTypeHasChildren | eTypeIsPointer | eTypeHasValue;
4027 
4028   case clang::Type::Record:
4029     if (qual_type->getAsCXXRecordDecl())
4030       return eTypeHasChildren | eTypeIsClass | eTypeIsCPlusPlus;
4031     else
4032       return eTypeHasChildren | eTypeIsStructUnion;
4033     break;
4034   case clang::Type::SubstTemplateTypeParm:
4035     return eTypeIsTemplate;
4036   case clang::Type::TemplateTypeParm:
4037     return eTypeIsTemplate;
4038   case clang::Type::TemplateSpecialization:
4039     return eTypeIsTemplate;
4040 
4041   case clang::Type::Typedef:
4042     return eTypeIsTypedef |
4043            CompilerType(getASTContext(),
4044                         llvm::cast<clang::TypedefType>(qual_type)
4045                             ->getDecl()
4046                             ->getUnderlyingType())
4047                .GetTypeInfo(pointee_or_element_clang_type);
4048   case clang::Type::TypeOfExpr:
4049     return 0;
4050   case clang::Type::TypeOf:
4051     return 0;
4052   case clang::Type::UnresolvedUsing:
4053     return 0;
4054 
4055   case clang::Type::ExtVector:
4056   case clang::Type::Vector: {
4057     uint32_t vector_type_flags = eTypeHasChildren | eTypeIsVector;
4058     const clang::VectorType *vector_type = llvm::dyn_cast<clang::VectorType>(
4059         qual_type->getCanonicalTypeInternal());
4060     if (vector_type) {
4061       if (vector_type->isIntegerType())
4062         vector_type_flags |= eTypeIsFloat;
4063       else if (vector_type->isFloatingType())
4064         vector_type_flags |= eTypeIsInteger;
4065     }
4066     return vector_type_flags;
4067   }
4068   default:
4069     return 0;
4070   }
4071   return 0;
4072 }
4073 
4074 lldb::LanguageType
4075 ClangASTContext::GetMinimumLanguage(lldb::opaque_compiler_type_t type) {
4076   if (!type)
4077     return lldb::eLanguageTypeC;
4078 
4079   // If the type is a reference, then resolve it to what it refers to first:
4080   clang::QualType qual_type(GetCanonicalQualType(type).getNonReferenceType());
4081   if (qual_type->isAnyPointerType()) {
4082     if (qual_type->isObjCObjectPointerType())
4083       return lldb::eLanguageTypeObjC;
4084 
4085     clang::QualType pointee_type(qual_type->getPointeeType());
4086     if (pointee_type->getPointeeCXXRecordDecl() != nullptr)
4087       return lldb::eLanguageTypeC_plus_plus;
4088     if (pointee_type->isObjCObjectOrInterfaceType())
4089       return lldb::eLanguageTypeObjC;
4090     if (pointee_type->isObjCClassType())
4091       return lldb::eLanguageTypeObjC;
4092     if (pointee_type.getTypePtr() ==
4093         getASTContext()->ObjCBuiltinIdTy.getTypePtr())
4094       return lldb::eLanguageTypeObjC;
4095   } else {
4096     if (qual_type->isObjCObjectOrInterfaceType())
4097       return lldb::eLanguageTypeObjC;
4098     if (qual_type->getAsCXXRecordDecl())
4099       return lldb::eLanguageTypeC_plus_plus;
4100     switch (qual_type->getTypeClass()) {
4101     default:
4102       break;
4103     case clang::Type::Builtin:
4104       switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
4105       default:
4106       case clang::BuiltinType::Void:
4107       case clang::BuiltinType::Bool:
4108       case clang::BuiltinType::Char_U:
4109       case clang::BuiltinType::UChar:
4110       case clang::BuiltinType::WChar_U:
4111       case clang::BuiltinType::Char16:
4112       case clang::BuiltinType::Char32:
4113       case clang::BuiltinType::UShort:
4114       case clang::BuiltinType::UInt:
4115       case clang::BuiltinType::ULong:
4116       case clang::BuiltinType::ULongLong:
4117       case clang::BuiltinType::UInt128:
4118       case clang::BuiltinType::Char_S:
4119       case clang::BuiltinType::SChar:
4120       case clang::BuiltinType::WChar_S:
4121       case clang::BuiltinType::Short:
4122       case clang::BuiltinType::Int:
4123       case clang::BuiltinType::Long:
4124       case clang::BuiltinType::LongLong:
4125       case clang::BuiltinType::Int128:
4126       case clang::BuiltinType::Float:
4127       case clang::BuiltinType::Double:
4128       case clang::BuiltinType::LongDouble:
4129         break;
4130 
4131       case clang::BuiltinType::NullPtr:
4132         return eLanguageTypeC_plus_plus;
4133 
4134       case clang::BuiltinType::ObjCId:
4135       case clang::BuiltinType::ObjCClass:
4136       case clang::BuiltinType::ObjCSel:
4137         return eLanguageTypeObjC;
4138 
4139       case clang::BuiltinType::Dependent:
4140       case clang::BuiltinType::Overload:
4141       case clang::BuiltinType::BoundMember:
4142       case clang::BuiltinType::UnknownAny:
4143         break;
4144       }
4145       break;
4146     case clang::Type::Typedef:
4147       return CompilerType(getASTContext(),
4148                           llvm::cast<clang::TypedefType>(qual_type)
4149                               ->getDecl()
4150                               ->getUnderlyingType())
4151           .GetMinimumLanguage();
4152     }
4153   }
4154   return lldb::eLanguageTypeC;
4155 }
4156 
4157 lldb::TypeClass
4158 ClangASTContext::GetTypeClass(lldb::opaque_compiler_type_t type) {
4159   if (!type)
4160     return lldb::eTypeClassInvalid;
4161 
4162   clang::QualType qual_type(GetQualType(type));
4163 
4164   switch (qual_type->getTypeClass()) {
4165   case clang::Type::UnaryTransform:
4166     break;
4167   case clang::Type::FunctionNoProto:
4168     return lldb::eTypeClassFunction;
4169   case clang::Type::FunctionProto:
4170     return lldb::eTypeClassFunction;
4171   case clang::Type::IncompleteArray:
4172     return lldb::eTypeClassArray;
4173   case clang::Type::VariableArray:
4174     return lldb::eTypeClassArray;
4175   case clang::Type::ConstantArray:
4176     return lldb::eTypeClassArray;
4177   case clang::Type::DependentSizedArray:
4178     return lldb::eTypeClassArray;
4179   case clang::Type::DependentSizedExtVector:
4180     return lldb::eTypeClassVector;
4181   case clang::Type::ExtVector:
4182     return lldb::eTypeClassVector;
4183   case clang::Type::Vector:
4184     return lldb::eTypeClassVector;
4185   case clang::Type::Builtin:
4186     return lldb::eTypeClassBuiltin;
4187   case clang::Type::ObjCObjectPointer:
4188     return lldb::eTypeClassObjCObjectPointer;
4189   case clang::Type::BlockPointer:
4190     return lldb::eTypeClassBlockPointer;
4191   case clang::Type::Pointer:
4192     return lldb::eTypeClassPointer;
4193   case clang::Type::LValueReference:
4194     return lldb::eTypeClassReference;
4195   case clang::Type::RValueReference:
4196     return lldb::eTypeClassReference;
4197   case clang::Type::MemberPointer:
4198     return lldb::eTypeClassMemberPointer;
4199   case clang::Type::Complex:
4200     if (qual_type->isComplexType())
4201       return lldb::eTypeClassComplexFloat;
4202     else
4203       return lldb::eTypeClassComplexInteger;
4204   case clang::Type::ObjCObject:
4205     return lldb::eTypeClassObjCObject;
4206   case clang::Type::ObjCInterface:
4207     return lldb::eTypeClassObjCInterface;
4208   case clang::Type::Record: {
4209     const clang::RecordType *record_type =
4210         llvm::cast<clang::RecordType>(qual_type.getTypePtr());
4211     const clang::RecordDecl *record_decl = record_type->getDecl();
4212     if (record_decl->isUnion())
4213       return lldb::eTypeClassUnion;
4214     else if (record_decl->isStruct())
4215       return lldb::eTypeClassStruct;
4216     else
4217       return lldb::eTypeClassClass;
4218   } break;
4219   case clang::Type::Enum:
4220     return lldb::eTypeClassEnumeration;
4221   case clang::Type::Typedef:
4222     return lldb::eTypeClassTypedef;
4223   case clang::Type::UnresolvedUsing:
4224     break;
4225   case clang::Type::Paren:
4226     return CompilerType(getASTContext(),
4227                         llvm::cast<clang::ParenType>(qual_type)->desugar())
4228         .GetTypeClass();
4229   case clang::Type::Auto:
4230     return CompilerType(
4231                getASTContext(),
4232                llvm::cast<clang::AutoType>(qual_type)->getDeducedType())
4233         .GetTypeClass();
4234   case clang::Type::Elaborated:
4235     return CompilerType(
4236                getASTContext(),
4237                llvm::cast<clang::ElaboratedType>(qual_type)->getNamedType())
4238         .GetTypeClass();
4239 
4240   case clang::Type::Attributed:
4241     break;
4242   case clang::Type::TemplateTypeParm:
4243     break;
4244   case clang::Type::SubstTemplateTypeParm:
4245     break;
4246   case clang::Type::SubstTemplateTypeParmPack:
4247     break;
4248   case clang::Type::InjectedClassName:
4249     break;
4250   case clang::Type::DependentName:
4251     break;
4252   case clang::Type::DependentTemplateSpecialization:
4253     break;
4254   case clang::Type::PackExpansion:
4255     break;
4256 
4257   case clang::Type::TypeOfExpr:
4258     break;
4259   case clang::Type::TypeOf:
4260     break;
4261   case clang::Type::Decltype:
4262     break;
4263   case clang::Type::TemplateSpecialization:
4264     break;
4265   case clang::Type::DeducedTemplateSpecialization:
4266     break;
4267   case clang::Type::Atomic:
4268     break;
4269   case clang::Type::Pipe:
4270     break;
4271 
4272   // pointer type decayed from an array or function type.
4273   case clang::Type::Decayed:
4274     break;
4275   case clang::Type::Adjusted:
4276     break;
4277   case clang::Type::ObjCTypeParam:
4278     break;
4279 
4280   case clang::Type::DependentAddressSpace:
4281     break;
4282   }
4283   // We don't know hot to display this type...
4284   return lldb::eTypeClassOther;
4285 }
4286 
4287 unsigned ClangASTContext::GetTypeQualifiers(lldb::opaque_compiler_type_t type) {
4288   if (type)
4289     return GetQualType(type).getQualifiers().getCVRQualifiers();
4290   return 0;
4291 }
4292 
4293 //----------------------------------------------------------------------
4294 // Creating related types
4295 //----------------------------------------------------------------------
4296 
4297 CompilerType
4298 ClangASTContext::GetArrayElementType(lldb::opaque_compiler_type_t type,
4299                                      uint64_t *stride) {
4300   if (type) {
4301     clang::QualType qual_type(GetCanonicalQualType(type));
4302 
4303     const clang::Type *array_eletype =
4304         qual_type.getTypePtr()->getArrayElementTypeNoTypeQual();
4305 
4306     if (!array_eletype)
4307       return CompilerType();
4308 
4309     CompilerType element_type(getASTContext(),
4310                               array_eletype->getCanonicalTypeUnqualified());
4311 
4312     // TODO: the real stride will be >= this value.. find the real one!
4313     if (stride)
4314       *stride = element_type.GetByteSize(nullptr);
4315 
4316     return element_type;
4317   }
4318   return CompilerType();
4319 }
4320 
4321 CompilerType ClangASTContext::GetArrayType(lldb::opaque_compiler_type_t type,
4322                                            uint64_t size) {
4323   if (type) {
4324     clang::QualType qual_type(GetCanonicalQualType(type));
4325     if (clang::ASTContext *ast_ctx = getASTContext()) {
4326       if (size != 0)
4327         return CompilerType(
4328             ast_ctx, ast_ctx->getConstantArrayType(
4329                          qual_type, llvm::APInt(64, size),
4330                          clang::ArrayType::ArraySizeModifier::Normal, 0));
4331       else
4332         return CompilerType(
4333             ast_ctx,
4334             ast_ctx->getIncompleteArrayType(
4335                 qual_type, clang::ArrayType::ArraySizeModifier::Normal, 0));
4336     }
4337   }
4338 
4339   return CompilerType();
4340 }
4341 
4342 CompilerType
4343 ClangASTContext::GetCanonicalType(lldb::opaque_compiler_type_t type) {
4344   if (type)
4345     return CompilerType(getASTContext(), GetCanonicalQualType(type));
4346   return CompilerType();
4347 }
4348 
4349 static clang::QualType GetFullyUnqualifiedType_Impl(clang::ASTContext *ast,
4350                                                     clang::QualType qual_type) {
4351   if (qual_type->isPointerType())
4352     qual_type = ast->getPointerType(
4353         GetFullyUnqualifiedType_Impl(ast, qual_type->getPointeeType()));
4354   else
4355     qual_type = qual_type.getUnqualifiedType();
4356   qual_type.removeLocalConst();
4357   qual_type.removeLocalRestrict();
4358   qual_type.removeLocalVolatile();
4359   return qual_type;
4360 }
4361 
4362 CompilerType
4363 ClangASTContext::GetFullyUnqualifiedType(lldb::opaque_compiler_type_t type) {
4364   if (type)
4365     return CompilerType(
4366         getASTContext(),
4367         GetFullyUnqualifiedType_Impl(getASTContext(), GetQualType(type)));
4368   return CompilerType();
4369 }
4370 
4371 int ClangASTContext::GetFunctionArgumentCount(
4372     lldb::opaque_compiler_type_t type) {
4373   if (type) {
4374     const clang::FunctionProtoType *func =
4375         llvm::dyn_cast<clang::FunctionProtoType>(GetCanonicalQualType(type));
4376     if (func)
4377       return func->getNumParams();
4378   }
4379   return -1;
4380 }
4381 
4382 CompilerType ClangASTContext::GetFunctionArgumentTypeAtIndex(
4383     lldb::opaque_compiler_type_t type, size_t idx) {
4384   if (type) {
4385     const clang::FunctionProtoType *func =
4386         llvm::dyn_cast<clang::FunctionProtoType>(GetQualType(type));
4387     if (func) {
4388       const uint32_t num_args = func->getNumParams();
4389       if (idx < num_args)
4390         return CompilerType(getASTContext(), func->getParamType(idx));
4391     }
4392   }
4393   return CompilerType();
4394 }
4395 
4396 CompilerType
4397 ClangASTContext::GetFunctionReturnType(lldb::opaque_compiler_type_t type) {
4398   if (type) {
4399     clang::QualType qual_type(GetQualType(type));
4400     const clang::FunctionProtoType *func =
4401         llvm::dyn_cast<clang::FunctionProtoType>(qual_type.getTypePtr());
4402     if (func)
4403       return CompilerType(getASTContext(), func->getReturnType());
4404   }
4405   return CompilerType();
4406 }
4407 
4408 size_t
4409 ClangASTContext::GetNumMemberFunctions(lldb::opaque_compiler_type_t type) {
4410   size_t num_functions = 0;
4411   if (type) {
4412     clang::QualType qual_type(GetCanonicalQualType(type));
4413     switch (qual_type->getTypeClass()) {
4414     case clang::Type::Record:
4415       if (GetCompleteQualType(getASTContext(), qual_type)) {
4416         const clang::RecordType *record_type =
4417             llvm::cast<clang::RecordType>(qual_type.getTypePtr());
4418         const clang::RecordDecl *record_decl = record_type->getDecl();
4419         assert(record_decl);
4420         const clang::CXXRecordDecl *cxx_record_decl =
4421             llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
4422         if (cxx_record_decl)
4423           num_functions = std::distance(cxx_record_decl->method_begin(),
4424                                         cxx_record_decl->method_end());
4425       }
4426       break;
4427 
4428     case clang::Type::ObjCObjectPointer: {
4429       const clang::ObjCObjectPointerType *objc_class_type =
4430           qual_type->getAs<clang::ObjCObjectPointerType>();
4431       const clang::ObjCInterfaceType *objc_interface_type =
4432           objc_class_type->getInterfaceType();
4433       if (objc_interface_type &&
4434           GetCompleteType(static_cast<lldb::opaque_compiler_type_t>(
4435               const_cast<clang::ObjCInterfaceType *>(objc_interface_type)))) {
4436         clang::ObjCInterfaceDecl *class_interface_decl =
4437             objc_interface_type->getDecl();
4438         if (class_interface_decl) {
4439           num_functions = std::distance(class_interface_decl->meth_begin(),
4440                                         class_interface_decl->meth_end());
4441         }
4442       }
4443       break;
4444     }
4445 
4446     case clang::Type::ObjCObject:
4447     case clang::Type::ObjCInterface:
4448       if (GetCompleteType(type)) {
4449         const clang::ObjCObjectType *objc_class_type =
4450             llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
4451         if (objc_class_type) {
4452           clang::ObjCInterfaceDecl *class_interface_decl =
4453               objc_class_type->getInterface();
4454           if (class_interface_decl)
4455             num_functions = std::distance(class_interface_decl->meth_begin(),
4456                                           class_interface_decl->meth_end());
4457         }
4458       }
4459       break;
4460 
4461     case clang::Type::Typedef:
4462       return CompilerType(getASTContext(),
4463                           llvm::cast<clang::TypedefType>(qual_type)
4464                               ->getDecl()
4465                               ->getUnderlyingType())
4466           .GetNumMemberFunctions();
4467 
4468     case clang::Type::Auto:
4469       return CompilerType(
4470                  getASTContext(),
4471                  llvm::cast<clang::AutoType>(qual_type)->getDeducedType())
4472           .GetNumMemberFunctions();
4473 
4474     case clang::Type::Elaborated:
4475       return CompilerType(
4476                  getASTContext(),
4477                  llvm::cast<clang::ElaboratedType>(qual_type)->getNamedType())
4478           .GetNumMemberFunctions();
4479 
4480     case clang::Type::Paren:
4481       return CompilerType(getASTContext(),
4482                           llvm::cast<clang::ParenType>(qual_type)->desugar())
4483           .GetNumMemberFunctions();
4484 
4485     default:
4486       break;
4487     }
4488   }
4489   return num_functions;
4490 }
4491 
4492 TypeMemberFunctionImpl
4493 ClangASTContext::GetMemberFunctionAtIndex(lldb::opaque_compiler_type_t type,
4494                                           size_t idx) {
4495   std::string name;
4496   MemberFunctionKind kind(MemberFunctionKind::eMemberFunctionKindUnknown);
4497   CompilerType clang_type;
4498   CompilerDecl clang_decl;
4499   if (type) {
4500     clang::QualType qual_type(GetCanonicalQualType(type));
4501     switch (qual_type->getTypeClass()) {
4502     case clang::Type::Record:
4503       if (GetCompleteQualType(getASTContext(), qual_type)) {
4504         const clang::RecordType *record_type =
4505             llvm::cast<clang::RecordType>(qual_type.getTypePtr());
4506         const clang::RecordDecl *record_decl = record_type->getDecl();
4507         assert(record_decl);
4508         const clang::CXXRecordDecl *cxx_record_decl =
4509             llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
4510         if (cxx_record_decl) {
4511           auto method_iter = cxx_record_decl->method_begin();
4512           auto method_end = cxx_record_decl->method_end();
4513           if (idx <
4514               static_cast<size_t>(std::distance(method_iter, method_end))) {
4515             std::advance(method_iter, idx);
4516             clang::CXXMethodDecl *cxx_method_decl =
4517                 method_iter->getCanonicalDecl();
4518             if (cxx_method_decl) {
4519               name = cxx_method_decl->getDeclName().getAsString();
4520               if (cxx_method_decl->isStatic())
4521                 kind = lldb::eMemberFunctionKindStaticMethod;
4522               else if (llvm::isa<clang::CXXConstructorDecl>(cxx_method_decl))
4523                 kind = lldb::eMemberFunctionKindConstructor;
4524               else if (llvm::isa<clang::CXXDestructorDecl>(cxx_method_decl))
4525                 kind = lldb::eMemberFunctionKindDestructor;
4526               else
4527                 kind = lldb::eMemberFunctionKindInstanceMethod;
4528               clang_type = CompilerType(
4529                   this, cxx_method_decl->getType().getAsOpaquePtr());
4530               clang_decl = CompilerDecl(this, cxx_method_decl);
4531             }
4532           }
4533         }
4534       }
4535       break;
4536 
4537     case clang::Type::ObjCObjectPointer: {
4538       const clang::ObjCObjectPointerType *objc_class_type =
4539           qual_type->getAs<clang::ObjCObjectPointerType>();
4540       const clang::ObjCInterfaceType *objc_interface_type =
4541           objc_class_type->getInterfaceType();
4542       if (objc_interface_type &&
4543           GetCompleteType(static_cast<lldb::opaque_compiler_type_t>(
4544               const_cast<clang::ObjCInterfaceType *>(objc_interface_type)))) {
4545         clang::ObjCInterfaceDecl *class_interface_decl =
4546             objc_interface_type->getDecl();
4547         if (class_interface_decl) {
4548           auto method_iter = class_interface_decl->meth_begin();
4549           auto method_end = class_interface_decl->meth_end();
4550           if (idx <
4551               static_cast<size_t>(std::distance(method_iter, method_end))) {
4552             std::advance(method_iter, idx);
4553             clang::ObjCMethodDecl *objc_method_decl =
4554                 method_iter->getCanonicalDecl();
4555             if (objc_method_decl) {
4556               clang_decl = CompilerDecl(this, objc_method_decl);
4557               name = objc_method_decl->getSelector().getAsString();
4558               if (objc_method_decl->isClassMethod())
4559                 kind = lldb::eMemberFunctionKindStaticMethod;
4560               else
4561                 kind = lldb::eMemberFunctionKindInstanceMethod;
4562             }
4563           }
4564         }
4565       }
4566       break;
4567     }
4568 
4569     case clang::Type::ObjCObject:
4570     case clang::Type::ObjCInterface:
4571       if (GetCompleteType(type)) {
4572         const clang::ObjCObjectType *objc_class_type =
4573             llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
4574         if (objc_class_type) {
4575           clang::ObjCInterfaceDecl *class_interface_decl =
4576               objc_class_type->getInterface();
4577           if (class_interface_decl) {
4578             auto method_iter = class_interface_decl->meth_begin();
4579             auto method_end = class_interface_decl->meth_end();
4580             if (idx <
4581                 static_cast<size_t>(std::distance(method_iter, method_end))) {
4582               std::advance(method_iter, idx);
4583               clang::ObjCMethodDecl *objc_method_decl =
4584                   method_iter->getCanonicalDecl();
4585               if (objc_method_decl) {
4586                 clang_decl = CompilerDecl(this, objc_method_decl);
4587                 name = objc_method_decl->getSelector().getAsString();
4588                 if (objc_method_decl->isClassMethod())
4589                   kind = lldb::eMemberFunctionKindStaticMethod;
4590                 else
4591                   kind = lldb::eMemberFunctionKindInstanceMethod;
4592               }
4593             }
4594           }
4595         }
4596       }
4597       break;
4598 
4599     case clang::Type::Typedef:
4600       return GetMemberFunctionAtIndex(llvm::cast<clang::TypedefType>(qual_type)
4601                                           ->getDecl()
4602                                           ->getUnderlyingType()
4603                                           .getAsOpaquePtr(),
4604                                       idx);
4605 
4606     case clang::Type::Auto:
4607       return GetMemberFunctionAtIndex(llvm::cast<clang::AutoType>(qual_type)
4608                                           ->getDeducedType()
4609                                           .getAsOpaquePtr(),
4610                                       idx);
4611 
4612     case clang::Type::Elaborated:
4613       return GetMemberFunctionAtIndex(
4614           llvm::cast<clang::ElaboratedType>(qual_type)
4615               ->getNamedType()
4616               .getAsOpaquePtr(),
4617           idx);
4618 
4619     case clang::Type::Paren:
4620       return GetMemberFunctionAtIndex(
4621           llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr(),
4622           idx);
4623 
4624     default:
4625       break;
4626     }
4627   }
4628 
4629   if (kind == eMemberFunctionKindUnknown)
4630     return TypeMemberFunctionImpl();
4631   else
4632     return TypeMemberFunctionImpl(clang_type, clang_decl, name, kind);
4633 }
4634 
4635 CompilerType
4636 ClangASTContext::GetNonReferenceType(lldb::opaque_compiler_type_t type) {
4637   if (type)
4638     return CompilerType(getASTContext(),
4639                         GetQualType(type).getNonReferenceType());
4640   return CompilerType();
4641 }
4642 
4643 CompilerType ClangASTContext::CreateTypedefType(
4644     const CompilerType &type, const char *typedef_name,
4645     const CompilerDeclContext &compiler_decl_ctx) {
4646   if (type && typedef_name && typedef_name[0]) {
4647     ClangASTContext *ast =
4648         llvm::dyn_cast<ClangASTContext>(type.GetTypeSystem());
4649     if (!ast)
4650       return CompilerType();
4651     clang::ASTContext *clang_ast = ast->getASTContext();
4652     clang::QualType qual_type(ClangUtil::GetQualType(type));
4653 
4654     clang::DeclContext *decl_ctx =
4655         ClangASTContext::DeclContextGetAsDeclContext(compiler_decl_ctx);
4656     if (decl_ctx == nullptr)
4657       decl_ctx = ast->getASTContext()->getTranslationUnitDecl();
4658 
4659     clang::TypedefDecl *decl = clang::TypedefDecl::Create(
4660         *clang_ast, decl_ctx, clang::SourceLocation(), clang::SourceLocation(),
4661         &clang_ast->Idents.get(typedef_name),
4662         clang_ast->getTrivialTypeSourceInfo(qual_type));
4663 
4664     decl->setAccess(clang::AS_public); // TODO respect proper access specifier
4665 
4666     // Get a uniqued clang::QualType for the typedef decl type
4667     return CompilerType(clang_ast, clang_ast->getTypedefType(decl));
4668   }
4669   return CompilerType();
4670 }
4671 
4672 CompilerType
4673 ClangASTContext::GetPointeeType(lldb::opaque_compiler_type_t type) {
4674   if (type) {
4675     clang::QualType qual_type(GetQualType(type));
4676     return CompilerType(getASTContext(),
4677                         qual_type.getTypePtr()->getPointeeType());
4678   }
4679   return CompilerType();
4680 }
4681 
4682 CompilerType
4683 ClangASTContext::GetPointerType(lldb::opaque_compiler_type_t type) {
4684   if (type) {
4685     clang::QualType qual_type(GetQualType(type));
4686 
4687     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
4688     switch (type_class) {
4689     case clang::Type::ObjCObject:
4690     case clang::Type::ObjCInterface:
4691       return CompilerType(getASTContext(),
4692                           getASTContext()->getObjCObjectPointerType(qual_type));
4693 
4694     default:
4695       return CompilerType(getASTContext(),
4696                           getASTContext()->getPointerType(qual_type));
4697     }
4698   }
4699   return CompilerType();
4700 }
4701 
4702 CompilerType
4703 ClangASTContext::GetLValueReferenceType(lldb::opaque_compiler_type_t type) {
4704   if (type)
4705     return CompilerType(this, getASTContext()
4706                                   ->getLValueReferenceType(GetQualType(type))
4707                                   .getAsOpaquePtr());
4708   else
4709     return CompilerType();
4710 }
4711 
4712 CompilerType
4713 ClangASTContext::GetRValueReferenceType(lldb::opaque_compiler_type_t type) {
4714   if (type)
4715     return CompilerType(this, getASTContext()
4716                                   ->getRValueReferenceType(GetQualType(type))
4717                                   .getAsOpaquePtr());
4718   else
4719     return CompilerType();
4720 }
4721 
4722 CompilerType
4723 ClangASTContext::AddConstModifier(lldb::opaque_compiler_type_t type) {
4724   if (type) {
4725     clang::QualType result(GetQualType(type));
4726     result.addConst();
4727     return CompilerType(this, result.getAsOpaquePtr());
4728   }
4729   return CompilerType();
4730 }
4731 
4732 CompilerType
4733 ClangASTContext::AddVolatileModifier(lldb::opaque_compiler_type_t type) {
4734   if (type) {
4735     clang::QualType result(GetQualType(type));
4736     result.addVolatile();
4737     return CompilerType(this, result.getAsOpaquePtr());
4738   }
4739   return CompilerType();
4740 }
4741 
4742 CompilerType
4743 ClangASTContext::AddRestrictModifier(lldb::opaque_compiler_type_t type) {
4744   if (type) {
4745     clang::QualType result(GetQualType(type));
4746     result.addRestrict();
4747     return CompilerType(this, result.getAsOpaquePtr());
4748   }
4749   return CompilerType();
4750 }
4751 
4752 CompilerType
4753 ClangASTContext::CreateTypedef(lldb::opaque_compiler_type_t type,
4754                                const char *typedef_name,
4755                                const CompilerDeclContext &compiler_decl_ctx) {
4756   if (type) {
4757     clang::ASTContext *clang_ast = getASTContext();
4758     clang::QualType qual_type(GetQualType(type));
4759 
4760     clang::DeclContext *decl_ctx =
4761         ClangASTContext::DeclContextGetAsDeclContext(compiler_decl_ctx);
4762     if (decl_ctx == nullptr)
4763       decl_ctx = getASTContext()->getTranslationUnitDecl();
4764 
4765     clang::TypedefDecl *decl = clang::TypedefDecl::Create(
4766         *clang_ast, decl_ctx, clang::SourceLocation(), clang::SourceLocation(),
4767         &clang_ast->Idents.get(typedef_name),
4768         clang_ast->getTrivialTypeSourceInfo(qual_type));
4769 
4770     clang::TagDecl *tdecl = nullptr;
4771     if (!qual_type.isNull()) {
4772       if (const clang::RecordType *rt = qual_type->getAs<clang::RecordType>())
4773         tdecl = rt->getDecl();
4774       if (const clang::EnumType *et = qual_type->getAs<clang::EnumType>())
4775         tdecl = et->getDecl();
4776     }
4777 
4778     // Check whether this declaration is an anonymous struct, union, or enum,
4779     // hidden behind a typedef. If so, we
4780     // try to check whether we have a typedef tag to attach to the original
4781     // record declaration
4782     if (tdecl && !tdecl->getIdentifier() && !tdecl->getTypedefNameForAnonDecl())
4783       tdecl->setTypedefNameForAnonDecl(decl);
4784 
4785     decl->setAccess(clang::AS_public); // TODO respect proper access specifier
4786 
4787     // Get a uniqued clang::QualType for the typedef decl type
4788     return CompilerType(this, clang_ast->getTypedefType(decl).getAsOpaquePtr());
4789   }
4790   return CompilerType();
4791 }
4792 
4793 CompilerType
4794 ClangASTContext::GetTypedefedType(lldb::opaque_compiler_type_t type) {
4795   if (type) {
4796     const clang::TypedefType *typedef_type =
4797         llvm::dyn_cast<clang::TypedefType>(GetQualType(type));
4798     if (typedef_type)
4799       return CompilerType(getASTContext(),
4800                           typedef_type->getDecl()->getUnderlyingType());
4801   }
4802   return CompilerType();
4803 }
4804 
4805 //----------------------------------------------------------------------
4806 // Create related types using the current type's AST
4807 //----------------------------------------------------------------------
4808 
4809 CompilerType ClangASTContext::GetBasicTypeFromAST(lldb::BasicType basic_type) {
4810   return ClangASTContext::GetBasicType(getASTContext(), basic_type);
4811 }
4812 //----------------------------------------------------------------------
4813 // Exploring the type
4814 //----------------------------------------------------------------------
4815 
4816 uint64_t ClangASTContext::GetBitSize(lldb::opaque_compiler_type_t type,
4817                                      ExecutionContextScope *exe_scope) {
4818   if (GetCompleteType(type)) {
4819     clang::QualType qual_type(GetCanonicalQualType(type));
4820     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
4821     switch (type_class) {
4822     case clang::Type::Record:
4823       if (GetCompleteType(type))
4824         return getASTContext()->getTypeSize(qual_type);
4825       else
4826         return 0;
4827       break;
4828 
4829     case clang::Type::ObjCInterface:
4830     case clang::Type::ObjCObject: {
4831       ExecutionContext exe_ctx(exe_scope);
4832       Process *process = exe_ctx.GetProcessPtr();
4833       if (process) {
4834         ObjCLanguageRuntime *objc_runtime = process->GetObjCLanguageRuntime();
4835         if (objc_runtime) {
4836           uint64_t bit_size = 0;
4837           if (objc_runtime->GetTypeBitSize(
4838                   CompilerType(getASTContext(), qual_type), bit_size))
4839             return bit_size;
4840         }
4841       } else {
4842         static bool g_printed = false;
4843         if (!g_printed) {
4844           StreamString s;
4845           DumpTypeDescription(type, &s);
4846 
4847           llvm::outs() << "warning: trying to determine the size of type ";
4848           llvm::outs() << s.GetString() << "\n";
4849           llvm::outs() << "without a valid ExecutionContext. this is not "
4850                           "reliable. please file a bug against LLDB.\n";
4851           llvm::outs() << "backtrace:\n";
4852           llvm::sys::PrintStackTrace(llvm::outs());
4853           llvm::outs() << "\n";
4854           g_printed = true;
4855         }
4856       }
4857     }
4858       LLVM_FALLTHROUGH;
4859     default:
4860       const uint32_t bit_size = getASTContext()->getTypeSize(qual_type);
4861       if (bit_size == 0) {
4862         if (qual_type->isIncompleteArrayType())
4863           return getASTContext()->getTypeSize(
4864               qual_type->getArrayElementTypeNoTypeQual()
4865                   ->getCanonicalTypeUnqualified());
4866       }
4867       if (qual_type->isObjCObjectOrInterfaceType())
4868         return bit_size +
4869                getASTContext()->getTypeSize(
4870                    getASTContext()->ObjCBuiltinClassTy);
4871       return bit_size;
4872     }
4873   }
4874   return 0;
4875 }
4876 
4877 size_t ClangASTContext::GetTypeBitAlign(lldb::opaque_compiler_type_t type) {
4878   if (GetCompleteType(type))
4879     return getASTContext()->getTypeAlign(GetQualType(type));
4880   return 0;
4881 }
4882 
4883 lldb::Encoding ClangASTContext::GetEncoding(lldb::opaque_compiler_type_t type,
4884                                             uint64_t &count) {
4885   if (!type)
4886     return lldb::eEncodingInvalid;
4887 
4888   count = 1;
4889   clang::QualType qual_type(GetCanonicalQualType(type));
4890 
4891   switch (qual_type->getTypeClass()) {
4892   case clang::Type::UnaryTransform:
4893     break;
4894 
4895   case clang::Type::FunctionNoProto:
4896   case clang::Type::FunctionProto:
4897     break;
4898 
4899   case clang::Type::IncompleteArray:
4900   case clang::Type::VariableArray:
4901     break;
4902 
4903   case clang::Type::ConstantArray:
4904     break;
4905 
4906   case clang::Type::ExtVector:
4907   case clang::Type::Vector:
4908     // TODO: Set this to more than one???
4909     break;
4910 
4911   case clang::Type::Builtin:
4912     switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
4913     case clang::BuiltinType::Void:
4914       break;
4915 
4916     case clang::BuiltinType::Bool:
4917     case clang::BuiltinType::Char_S:
4918     case clang::BuiltinType::SChar:
4919     case clang::BuiltinType::WChar_S:
4920     case clang::BuiltinType::Char16:
4921     case clang::BuiltinType::Char32:
4922     case clang::BuiltinType::Short:
4923     case clang::BuiltinType::Int:
4924     case clang::BuiltinType::Long:
4925     case clang::BuiltinType::LongLong:
4926     case clang::BuiltinType::Int128:
4927       return lldb::eEncodingSint;
4928 
4929     case clang::BuiltinType::Char_U:
4930     case clang::BuiltinType::UChar:
4931     case clang::BuiltinType::WChar_U:
4932     case clang::BuiltinType::UShort:
4933     case clang::BuiltinType::UInt:
4934     case clang::BuiltinType::ULong:
4935     case clang::BuiltinType::ULongLong:
4936     case clang::BuiltinType::UInt128:
4937       return lldb::eEncodingUint;
4938 
4939     case clang::BuiltinType::Half:
4940     case clang::BuiltinType::Float:
4941     case clang::BuiltinType::Float16:
4942     case clang::BuiltinType::Float128:
4943     case clang::BuiltinType::Double:
4944     case clang::BuiltinType::LongDouble:
4945       return lldb::eEncodingIEEE754;
4946 
4947     case clang::BuiltinType::ObjCClass:
4948     case clang::BuiltinType::ObjCId:
4949     case clang::BuiltinType::ObjCSel:
4950       return lldb::eEncodingUint;
4951 
4952     case clang::BuiltinType::NullPtr:
4953       return lldb::eEncodingUint;
4954 
4955     case clang::BuiltinType::Kind::ARCUnbridgedCast:
4956     case clang::BuiltinType::Kind::BoundMember:
4957     case clang::BuiltinType::Kind::BuiltinFn:
4958     case clang::BuiltinType::Kind::Dependent:
4959     case clang::BuiltinType::Kind::OCLClkEvent:
4960     case clang::BuiltinType::Kind::OCLEvent:
4961     case clang::BuiltinType::Kind::OCLImage1dRO:
4962     case clang::BuiltinType::Kind::OCLImage1dWO:
4963     case clang::BuiltinType::Kind::OCLImage1dRW:
4964     case clang::BuiltinType::Kind::OCLImage1dArrayRO:
4965     case clang::BuiltinType::Kind::OCLImage1dArrayWO:
4966     case clang::BuiltinType::Kind::OCLImage1dArrayRW:
4967     case clang::BuiltinType::Kind::OCLImage1dBufferRO:
4968     case clang::BuiltinType::Kind::OCLImage1dBufferWO:
4969     case clang::BuiltinType::Kind::OCLImage1dBufferRW:
4970     case clang::BuiltinType::Kind::OCLImage2dRO:
4971     case clang::BuiltinType::Kind::OCLImage2dWO:
4972     case clang::BuiltinType::Kind::OCLImage2dRW:
4973     case clang::BuiltinType::Kind::OCLImage2dArrayRO:
4974     case clang::BuiltinType::Kind::OCLImage2dArrayWO:
4975     case clang::BuiltinType::Kind::OCLImage2dArrayRW:
4976     case clang::BuiltinType::Kind::OCLImage2dArrayDepthRO:
4977     case clang::BuiltinType::Kind::OCLImage2dArrayDepthWO:
4978     case clang::BuiltinType::Kind::OCLImage2dArrayDepthRW:
4979     case clang::BuiltinType::Kind::OCLImage2dArrayMSAARO:
4980     case clang::BuiltinType::Kind::OCLImage2dArrayMSAAWO:
4981     case clang::BuiltinType::Kind::OCLImage2dArrayMSAARW:
4982     case clang::BuiltinType::Kind::OCLImage2dArrayMSAADepthRO:
4983     case clang::BuiltinType::Kind::OCLImage2dArrayMSAADepthWO:
4984     case clang::BuiltinType::Kind::OCLImage2dArrayMSAADepthRW:
4985     case clang::BuiltinType::Kind::OCLImage2dDepthRO:
4986     case clang::BuiltinType::Kind::OCLImage2dDepthWO:
4987     case clang::BuiltinType::Kind::OCLImage2dDepthRW:
4988     case clang::BuiltinType::Kind::OCLImage2dMSAARO:
4989     case clang::BuiltinType::Kind::OCLImage2dMSAAWO:
4990     case clang::BuiltinType::Kind::OCLImage2dMSAARW:
4991     case clang::BuiltinType::Kind::OCLImage2dMSAADepthRO:
4992     case clang::BuiltinType::Kind::OCLImage2dMSAADepthWO:
4993     case clang::BuiltinType::Kind::OCLImage2dMSAADepthRW:
4994     case clang::BuiltinType::Kind::OCLImage3dRO:
4995     case clang::BuiltinType::Kind::OCLImage3dWO:
4996     case clang::BuiltinType::Kind::OCLImage3dRW:
4997     case clang::BuiltinType::Kind::OCLQueue:
4998     case clang::BuiltinType::Kind::OCLReserveID:
4999     case clang::BuiltinType::Kind::OCLSampler:
5000     case clang::BuiltinType::Kind::OMPArraySection:
5001     case clang::BuiltinType::Kind::Overload:
5002     case clang::BuiltinType::Kind::PseudoObject:
5003     case clang::BuiltinType::Kind::UnknownAny:
5004       break;
5005     }
5006     break;
5007   // All pointer types are represented as unsigned integer encodings.
5008   // We may nee to add a eEncodingPointer if we ever need to know the
5009   // difference
5010   case clang::Type::ObjCObjectPointer:
5011   case clang::Type::BlockPointer:
5012   case clang::Type::Pointer:
5013   case clang::Type::LValueReference:
5014   case clang::Type::RValueReference:
5015   case clang::Type::MemberPointer:
5016     return lldb::eEncodingUint;
5017   case clang::Type::Complex: {
5018     lldb::Encoding encoding = lldb::eEncodingIEEE754;
5019     if (qual_type->isComplexType())
5020       encoding = lldb::eEncodingIEEE754;
5021     else {
5022       const clang::ComplexType *complex_type =
5023           qual_type->getAsComplexIntegerType();
5024       if (complex_type)
5025         encoding = CompilerType(getASTContext(), complex_type->getElementType())
5026                        .GetEncoding(count);
5027       else
5028         encoding = lldb::eEncodingSint;
5029     }
5030     count = 2;
5031     return encoding;
5032   }
5033 
5034   case clang::Type::ObjCInterface:
5035     break;
5036   case clang::Type::Record:
5037     break;
5038   case clang::Type::Enum:
5039     return lldb::eEncodingSint;
5040   case clang::Type::Typedef:
5041     return CompilerType(getASTContext(),
5042                         llvm::cast<clang::TypedefType>(qual_type)
5043                             ->getDecl()
5044                             ->getUnderlyingType())
5045         .GetEncoding(count);
5046 
5047   case clang::Type::Auto:
5048     return CompilerType(
5049                getASTContext(),
5050                llvm::cast<clang::AutoType>(qual_type)->getDeducedType())
5051         .GetEncoding(count);
5052 
5053   case clang::Type::Elaborated:
5054     return CompilerType(
5055                getASTContext(),
5056                llvm::cast<clang::ElaboratedType>(qual_type)->getNamedType())
5057         .GetEncoding(count);
5058 
5059   case clang::Type::Paren:
5060     return CompilerType(getASTContext(),
5061                         llvm::cast<clang::ParenType>(qual_type)->desugar())
5062         .GetEncoding(count);
5063 
5064   case clang::Type::DependentSizedArray:
5065   case clang::Type::DependentSizedExtVector:
5066   case clang::Type::UnresolvedUsing:
5067   case clang::Type::Attributed:
5068   case clang::Type::TemplateTypeParm:
5069   case clang::Type::SubstTemplateTypeParm:
5070   case clang::Type::SubstTemplateTypeParmPack:
5071   case clang::Type::InjectedClassName:
5072   case clang::Type::DependentName:
5073   case clang::Type::DependentTemplateSpecialization:
5074   case clang::Type::PackExpansion:
5075   case clang::Type::ObjCObject:
5076 
5077   case clang::Type::TypeOfExpr:
5078   case clang::Type::TypeOf:
5079   case clang::Type::Decltype:
5080   case clang::Type::TemplateSpecialization:
5081   case clang::Type::DeducedTemplateSpecialization:
5082   case clang::Type::Atomic:
5083   case clang::Type::Adjusted:
5084   case clang::Type::Pipe:
5085     break;
5086 
5087   // pointer type decayed from an array or function type.
5088   case clang::Type::Decayed:
5089     break;
5090   case clang::Type::ObjCTypeParam:
5091     break;
5092 
5093   case clang::Type::DependentAddressSpace:
5094     break;
5095   }
5096   count = 0;
5097   return lldb::eEncodingInvalid;
5098 }
5099 
5100 lldb::Format ClangASTContext::GetFormat(lldb::opaque_compiler_type_t type) {
5101   if (!type)
5102     return lldb::eFormatDefault;
5103 
5104   clang::QualType qual_type(GetCanonicalQualType(type));
5105 
5106   switch (qual_type->getTypeClass()) {
5107   case clang::Type::UnaryTransform:
5108     break;
5109 
5110   case clang::Type::FunctionNoProto:
5111   case clang::Type::FunctionProto:
5112     break;
5113 
5114   case clang::Type::IncompleteArray:
5115   case clang::Type::VariableArray:
5116     break;
5117 
5118   case clang::Type::ConstantArray:
5119     return lldb::eFormatVoid; // no value
5120 
5121   case clang::Type::ExtVector:
5122   case clang::Type::Vector:
5123     break;
5124 
5125   case clang::Type::Builtin:
5126     switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
5127     // default: assert(0 && "Unknown builtin type!");
5128     case clang::BuiltinType::UnknownAny:
5129     case clang::BuiltinType::Void:
5130     case clang::BuiltinType::BoundMember:
5131       break;
5132 
5133     case clang::BuiltinType::Bool:
5134       return lldb::eFormatBoolean;
5135     case clang::BuiltinType::Char_S:
5136     case clang::BuiltinType::SChar:
5137     case clang::BuiltinType::WChar_S:
5138     case clang::BuiltinType::Char_U:
5139     case clang::BuiltinType::UChar:
5140     case clang::BuiltinType::WChar_U:
5141       return lldb::eFormatChar;
5142     case clang::BuiltinType::Char16:
5143       return lldb::eFormatUnicode16;
5144     case clang::BuiltinType::Char32:
5145       return lldb::eFormatUnicode32;
5146     case clang::BuiltinType::UShort:
5147       return lldb::eFormatUnsigned;
5148     case clang::BuiltinType::Short:
5149       return lldb::eFormatDecimal;
5150     case clang::BuiltinType::UInt:
5151       return lldb::eFormatUnsigned;
5152     case clang::BuiltinType::Int:
5153       return lldb::eFormatDecimal;
5154     case clang::BuiltinType::ULong:
5155       return lldb::eFormatUnsigned;
5156     case clang::BuiltinType::Long:
5157       return lldb::eFormatDecimal;
5158     case clang::BuiltinType::ULongLong:
5159       return lldb::eFormatUnsigned;
5160     case clang::BuiltinType::LongLong:
5161       return lldb::eFormatDecimal;
5162     case clang::BuiltinType::UInt128:
5163       return lldb::eFormatUnsigned;
5164     case clang::BuiltinType::Int128:
5165       return lldb::eFormatDecimal;
5166     case clang::BuiltinType::Half:
5167     case clang::BuiltinType::Float:
5168     case clang::BuiltinType::Double:
5169     case clang::BuiltinType::LongDouble:
5170       return lldb::eFormatFloat;
5171     default:
5172       return lldb::eFormatHex;
5173     }
5174     break;
5175   case clang::Type::ObjCObjectPointer:
5176     return lldb::eFormatHex;
5177   case clang::Type::BlockPointer:
5178     return lldb::eFormatHex;
5179   case clang::Type::Pointer:
5180     return lldb::eFormatHex;
5181   case clang::Type::LValueReference:
5182   case clang::Type::RValueReference:
5183     return lldb::eFormatHex;
5184   case clang::Type::MemberPointer:
5185     break;
5186   case clang::Type::Complex: {
5187     if (qual_type->isComplexType())
5188       return lldb::eFormatComplex;
5189     else
5190       return lldb::eFormatComplexInteger;
5191   }
5192   case clang::Type::ObjCInterface:
5193     break;
5194   case clang::Type::Record:
5195     break;
5196   case clang::Type::Enum:
5197     return lldb::eFormatEnum;
5198   case clang::Type::Typedef:
5199     return CompilerType(getASTContext(),
5200                         llvm::cast<clang::TypedefType>(qual_type)
5201                             ->getDecl()
5202                             ->getUnderlyingType())
5203         .GetFormat();
5204   case clang::Type::Auto:
5205     return CompilerType(getASTContext(),
5206                         llvm::cast<clang::AutoType>(qual_type)->desugar())
5207         .GetFormat();
5208   case clang::Type::Paren:
5209     return CompilerType(getASTContext(),
5210                         llvm::cast<clang::ParenType>(qual_type)->desugar())
5211         .GetFormat();
5212   case clang::Type::Elaborated:
5213     return CompilerType(
5214                getASTContext(),
5215                llvm::cast<clang::ElaboratedType>(qual_type)->getNamedType())
5216         .GetFormat();
5217   case clang::Type::DependentSizedArray:
5218   case clang::Type::DependentSizedExtVector:
5219   case clang::Type::UnresolvedUsing:
5220   case clang::Type::Attributed:
5221   case clang::Type::TemplateTypeParm:
5222   case clang::Type::SubstTemplateTypeParm:
5223   case clang::Type::SubstTemplateTypeParmPack:
5224   case clang::Type::InjectedClassName:
5225   case clang::Type::DependentName:
5226   case clang::Type::DependentTemplateSpecialization:
5227   case clang::Type::PackExpansion:
5228   case clang::Type::ObjCObject:
5229 
5230   case clang::Type::TypeOfExpr:
5231   case clang::Type::TypeOf:
5232   case clang::Type::Decltype:
5233   case clang::Type::TemplateSpecialization:
5234   case clang::Type::DeducedTemplateSpecialization:
5235   case clang::Type::Atomic:
5236   case clang::Type::Adjusted:
5237   case clang::Type::Pipe:
5238     break;
5239 
5240   // pointer type decayed from an array or function type.
5241   case clang::Type::Decayed:
5242     break;
5243   case clang::Type::ObjCTypeParam:
5244     break;
5245 
5246   case clang::Type::DependentAddressSpace:
5247     break;
5248   }
5249   // We don't know hot to display this type...
5250   return lldb::eFormatBytes;
5251 }
5252 
5253 static bool ObjCDeclHasIVars(clang::ObjCInterfaceDecl *class_interface_decl,
5254                              bool check_superclass) {
5255   while (class_interface_decl) {
5256     if (class_interface_decl->ivar_size() > 0)
5257       return true;
5258 
5259     if (check_superclass)
5260       class_interface_decl = class_interface_decl->getSuperClass();
5261     else
5262       break;
5263   }
5264   return false;
5265 }
5266 
5267 uint32_t ClangASTContext::GetNumChildren(lldb::opaque_compiler_type_t type,
5268                                          bool omit_empty_base_classes) {
5269   if (!type)
5270     return 0;
5271 
5272   uint32_t num_children = 0;
5273   clang::QualType qual_type(GetQualType(type));
5274   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5275   switch (type_class) {
5276   case clang::Type::Builtin:
5277     switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
5278     case clang::BuiltinType::ObjCId:    // child is Class
5279     case clang::BuiltinType::ObjCClass: // child is Class
5280       num_children = 1;
5281       break;
5282 
5283     default:
5284       break;
5285     }
5286     break;
5287 
5288   case clang::Type::Complex:
5289     return 0;
5290 
5291   case clang::Type::Record:
5292     if (GetCompleteQualType(getASTContext(), qual_type)) {
5293       const clang::RecordType *record_type =
5294           llvm::cast<clang::RecordType>(qual_type.getTypePtr());
5295       const clang::RecordDecl *record_decl = record_type->getDecl();
5296       assert(record_decl);
5297       const clang::CXXRecordDecl *cxx_record_decl =
5298           llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
5299       if (cxx_record_decl) {
5300         if (omit_empty_base_classes) {
5301           // Check each base classes to see if it or any of its
5302           // base classes contain any fields. This can help
5303           // limit the noise in variable views by not having to
5304           // show base classes that contain no members.
5305           clang::CXXRecordDecl::base_class_const_iterator base_class,
5306               base_class_end;
5307           for (base_class = cxx_record_decl->bases_begin(),
5308               base_class_end = cxx_record_decl->bases_end();
5309                base_class != base_class_end; ++base_class) {
5310             const clang::CXXRecordDecl *base_class_decl =
5311                 llvm::cast<clang::CXXRecordDecl>(
5312                     base_class->getType()
5313                         ->getAs<clang::RecordType>()
5314                         ->getDecl());
5315 
5316             // Skip empty base classes
5317             if (ClangASTContext::RecordHasFields(base_class_decl) == false)
5318               continue;
5319 
5320             num_children++;
5321           }
5322         } else {
5323           // Include all base classes
5324           num_children += cxx_record_decl->getNumBases();
5325         }
5326       }
5327       clang::RecordDecl::field_iterator field, field_end;
5328       for (field = record_decl->field_begin(),
5329           field_end = record_decl->field_end();
5330            field != field_end; ++field)
5331         ++num_children;
5332     }
5333     break;
5334 
5335   case clang::Type::ObjCObject:
5336   case clang::Type::ObjCInterface:
5337     if (GetCompleteQualType(getASTContext(), qual_type)) {
5338       const clang::ObjCObjectType *objc_class_type =
5339           llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
5340       assert(objc_class_type);
5341       if (objc_class_type) {
5342         clang::ObjCInterfaceDecl *class_interface_decl =
5343             objc_class_type->getInterface();
5344 
5345         if (class_interface_decl) {
5346 
5347           clang::ObjCInterfaceDecl *superclass_interface_decl =
5348               class_interface_decl->getSuperClass();
5349           if (superclass_interface_decl) {
5350             if (omit_empty_base_classes) {
5351               if (ObjCDeclHasIVars(superclass_interface_decl, true))
5352                 ++num_children;
5353             } else
5354               ++num_children;
5355           }
5356 
5357           num_children += class_interface_decl->ivar_size();
5358         }
5359       }
5360     }
5361     break;
5362 
5363   case clang::Type::ObjCObjectPointer: {
5364     const clang::ObjCObjectPointerType *pointer_type =
5365         llvm::cast<clang::ObjCObjectPointerType>(qual_type.getTypePtr());
5366     clang::QualType pointee_type = pointer_type->getPointeeType();
5367     uint32_t num_pointee_children =
5368         CompilerType(getASTContext(), pointee_type)
5369             .GetNumChildren(omit_empty_base_classes);
5370     // If this type points to a simple type, then it has 1 child
5371     if (num_pointee_children == 0)
5372       num_children = 1;
5373     else
5374       num_children = num_pointee_children;
5375   } break;
5376 
5377   case clang::Type::Vector:
5378   case clang::Type::ExtVector:
5379     num_children =
5380         llvm::cast<clang::VectorType>(qual_type.getTypePtr())->getNumElements();
5381     break;
5382 
5383   case clang::Type::ConstantArray:
5384     num_children = llvm::cast<clang::ConstantArrayType>(qual_type.getTypePtr())
5385                        ->getSize()
5386                        .getLimitedValue();
5387     break;
5388 
5389   case clang::Type::Pointer: {
5390     const clang::PointerType *pointer_type =
5391         llvm::cast<clang::PointerType>(qual_type.getTypePtr());
5392     clang::QualType pointee_type(pointer_type->getPointeeType());
5393     uint32_t num_pointee_children =
5394         CompilerType(getASTContext(), pointee_type)
5395             .GetNumChildren(omit_empty_base_classes);
5396     if (num_pointee_children == 0) {
5397       // We have a pointer to a pointee type that claims it has no children.
5398       // We will want to look at
5399       num_children = GetNumPointeeChildren(pointee_type);
5400     } else
5401       num_children = num_pointee_children;
5402   } break;
5403 
5404   case clang::Type::LValueReference:
5405   case clang::Type::RValueReference: {
5406     const clang::ReferenceType *reference_type =
5407         llvm::cast<clang::ReferenceType>(qual_type.getTypePtr());
5408     clang::QualType pointee_type = reference_type->getPointeeType();
5409     uint32_t num_pointee_children =
5410         CompilerType(getASTContext(), pointee_type)
5411             .GetNumChildren(omit_empty_base_classes);
5412     // If this type points to a simple type, then it has 1 child
5413     if (num_pointee_children == 0)
5414       num_children = 1;
5415     else
5416       num_children = num_pointee_children;
5417   } break;
5418 
5419   case clang::Type::Typedef:
5420     num_children =
5421         CompilerType(getASTContext(), llvm::cast<clang::TypedefType>(qual_type)
5422                                           ->getDecl()
5423                                           ->getUnderlyingType())
5424             .GetNumChildren(omit_empty_base_classes);
5425     break;
5426 
5427   case clang::Type::Auto:
5428     num_children =
5429         CompilerType(getASTContext(),
5430                      llvm::cast<clang::AutoType>(qual_type)->getDeducedType())
5431             .GetNumChildren(omit_empty_base_classes);
5432     break;
5433 
5434   case clang::Type::Elaborated:
5435     num_children =
5436         CompilerType(
5437             getASTContext(),
5438             llvm::cast<clang::ElaboratedType>(qual_type)->getNamedType())
5439             .GetNumChildren(omit_empty_base_classes);
5440     break;
5441 
5442   case clang::Type::Paren:
5443     num_children =
5444         CompilerType(getASTContext(),
5445                      llvm::cast<clang::ParenType>(qual_type)->desugar())
5446             .GetNumChildren(omit_empty_base_classes);
5447     break;
5448   default:
5449     break;
5450   }
5451   return num_children;
5452 }
5453 
5454 CompilerType ClangASTContext::GetBuiltinTypeByName(const ConstString &name) {
5455   return GetBasicType(GetBasicTypeEnumeration(name));
5456 }
5457 
5458 lldb::BasicType
5459 ClangASTContext::GetBasicTypeEnumeration(lldb::opaque_compiler_type_t type) {
5460   if (type) {
5461     clang::QualType qual_type(GetQualType(type));
5462     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5463     if (type_class == clang::Type::Builtin) {
5464       switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
5465       case clang::BuiltinType::Void:
5466         return eBasicTypeVoid;
5467       case clang::BuiltinType::Bool:
5468         return eBasicTypeBool;
5469       case clang::BuiltinType::Char_S:
5470         return eBasicTypeSignedChar;
5471       case clang::BuiltinType::Char_U:
5472         return eBasicTypeUnsignedChar;
5473       case clang::BuiltinType::Char16:
5474         return eBasicTypeChar16;
5475       case clang::BuiltinType::Char32:
5476         return eBasicTypeChar32;
5477       case clang::BuiltinType::UChar:
5478         return eBasicTypeUnsignedChar;
5479       case clang::BuiltinType::SChar:
5480         return eBasicTypeSignedChar;
5481       case clang::BuiltinType::WChar_S:
5482         return eBasicTypeSignedWChar;
5483       case clang::BuiltinType::WChar_U:
5484         return eBasicTypeUnsignedWChar;
5485       case clang::BuiltinType::Short:
5486         return eBasicTypeShort;
5487       case clang::BuiltinType::UShort:
5488         return eBasicTypeUnsignedShort;
5489       case clang::BuiltinType::Int:
5490         return eBasicTypeInt;
5491       case clang::BuiltinType::UInt:
5492         return eBasicTypeUnsignedInt;
5493       case clang::BuiltinType::Long:
5494         return eBasicTypeLong;
5495       case clang::BuiltinType::ULong:
5496         return eBasicTypeUnsignedLong;
5497       case clang::BuiltinType::LongLong:
5498         return eBasicTypeLongLong;
5499       case clang::BuiltinType::ULongLong:
5500         return eBasicTypeUnsignedLongLong;
5501       case clang::BuiltinType::Int128:
5502         return eBasicTypeInt128;
5503       case clang::BuiltinType::UInt128:
5504         return eBasicTypeUnsignedInt128;
5505 
5506       case clang::BuiltinType::Half:
5507         return eBasicTypeHalf;
5508       case clang::BuiltinType::Float:
5509         return eBasicTypeFloat;
5510       case clang::BuiltinType::Double:
5511         return eBasicTypeDouble;
5512       case clang::BuiltinType::LongDouble:
5513         return eBasicTypeLongDouble;
5514 
5515       case clang::BuiltinType::NullPtr:
5516         return eBasicTypeNullPtr;
5517       case clang::BuiltinType::ObjCId:
5518         return eBasicTypeObjCID;
5519       case clang::BuiltinType::ObjCClass:
5520         return eBasicTypeObjCClass;
5521       case clang::BuiltinType::ObjCSel:
5522         return eBasicTypeObjCSel;
5523       default:
5524         return eBasicTypeOther;
5525       }
5526     }
5527   }
5528   return eBasicTypeInvalid;
5529 }
5530 
5531 void ClangASTContext::ForEachEnumerator(
5532     lldb::opaque_compiler_type_t type,
5533     std::function<bool(const CompilerType &integer_type,
5534                        const ConstString &name,
5535                        const llvm::APSInt &value)> const &callback) {
5536   const clang::EnumType *enum_type =
5537       llvm::dyn_cast<clang::EnumType>(GetCanonicalQualType(type));
5538   if (enum_type) {
5539     const clang::EnumDecl *enum_decl = enum_type->getDecl();
5540     if (enum_decl) {
5541       CompilerType integer_type(this,
5542                                 enum_decl->getIntegerType().getAsOpaquePtr());
5543 
5544       clang::EnumDecl::enumerator_iterator enum_pos, enum_end_pos;
5545       for (enum_pos = enum_decl->enumerator_begin(),
5546           enum_end_pos = enum_decl->enumerator_end();
5547            enum_pos != enum_end_pos; ++enum_pos) {
5548         ConstString name(enum_pos->getNameAsString().c_str());
5549         if (!callback(integer_type, name, enum_pos->getInitVal()))
5550           break;
5551       }
5552     }
5553   }
5554 }
5555 
5556 #pragma mark Aggregate Types
5557 
5558 uint32_t ClangASTContext::GetNumFields(lldb::opaque_compiler_type_t type) {
5559   if (!type)
5560     return 0;
5561 
5562   uint32_t count = 0;
5563   clang::QualType qual_type(GetCanonicalQualType(type));
5564   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5565   switch (type_class) {
5566   case clang::Type::Record:
5567     if (GetCompleteType(type)) {
5568       const clang::RecordType *record_type =
5569           llvm::dyn_cast<clang::RecordType>(qual_type.getTypePtr());
5570       if (record_type) {
5571         clang::RecordDecl *record_decl = record_type->getDecl();
5572         if (record_decl) {
5573           uint32_t field_idx = 0;
5574           clang::RecordDecl::field_iterator field, field_end;
5575           for (field = record_decl->field_begin(),
5576               field_end = record_decl->field_end();
5577                field != field_end; ++field)
5578             ++field_idx;
5579           count = field_idx;
5580         }
5581       }
5582     }
5583     break;
5584 
5585   case clang::Type::Typedef:
5586     count =
5587         CompilerType(getASTContext(), llvm::cast<clang::TypedefType>(qual_type)
5588                                           ->getDecl()
5589                                           ->getUnderlyingType())
5590             .GetNumFields();
5591     break;
5592 
5593   case clang::Type::Auto:
5594     count =
5595         CompilerType(getASTContext(),
5596                      llvm::cast<clang::AutoType>(qual_type)->getDeducedType())
5597             .GetNumFields();
5598     break;
5599 
5600   case clang::Type::Elaborated:
5601     count = CompilerType(
5602                 getASTContext(),
5603                 llvm::cast<clang::ElaboratedType>(qual_type)->getNamedType())
5604                 .GetNumFields();
5605     break;
5606 
5607   case clang::Type::Paren:
5608     count = CompilerType(getASTContext(),
5609                          llvm::cast<clang::ParenType>(qual_type)->desugar())
5610                 .GetNumFields();
5611     break;
5612 
5613   case clang::Type::ObjCObjectPointer: {
5614     const clang::ObjCObjectPointerType *objc_class_type =
5615         qual_type->getAs<clang::ObjCObjectPointerType>();
5616     const clang::ObjCInterfaceType *objc_interface_type =
5617         objc_class_type->getInterfaceType();
5618     if (objc_interface_type &&
5619         GetCompleteType(static_cast<lldb::opaque_compiler_type_t>(
5620             const_cast<clang::ObjCInterfaceType *>(objc_interface_type)))) {
5621       clang::ObjCInterfaceDecl *class_interface_decl =
5622           objc_interface_type->getDecl();
5623       if (class_interface_decl) {
5624         count = class_interface_decl->ivar_size();
5625       }
5626     }
5627     break;
5628   }
5629 
5630   case clang::Type::ObjCObject:
5631   case clang::Type::ObjCInterface:
5632     if (GetCompleteType(type)) {
5633       const clang::ObjCObjectType *objc_class_type =
5634           llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
5635       if (objc_class_type) {
5636         clang::ObjCInterfaceDecl *class_interface_decl =
5637             objc_class_type->getInterface();
5638 
5639         if (class_interface_decl)
5640           count = class_interface_decl->ivar_size();
5641       }
5642     }
5643     break;
5644 
5645   default:
5646     break;
5647   }
5648   return count;
5649 }
5650 
5651 static lldb::opaque_compiler_type_t
5652 GetObjCFieldAtIndex(clang::ASTContext *ast,
5653                     clang::ObjCInterfaceDecl *class_interface_decl, size_t idx,
5654                     std::string &name, uint64_t *bit_offset_ptr,
5655                     uint32_t *bitfield_bit_size_ptr, bool *is_bitfield_ptr) {
5656   if (class_interface_decl) {
5657     if (idx < (class_interface_decl->ivar_size())) {
5658       clang::ObjCInterfaceDecl::ivar_iterator ivar_pos,
5659           ivar_end = class_interface_decl->ivar_end();
5660       uint32_t ivar_idx = 0;
5661 
5662       for (ivar_pos = class_interface_decl->ivar_begin(); ivar_pos != ivar_end;
5663            ++ivar_pos, ++ivar_idx) {
5664         if (ivar_idx == idx) {
5665           const clang::ObjCIvarDecl *ivar_decl = *ivar_pos;
5666 
5667           clang::QualType ivar_qual_type(ivar_decl->getType());
5668 
5669           name.assign(ivar_decl->getNameAsString());
5670 
5671           if (bit_offset_ptr) {
5672             const clang::ASTRecordLayout &interface_layout =
5673                 ast->getASTObjCInterfaceLayout(class_interface_decl);
5674             *bit_offset_ptr = interface_layout.getFieldOffset(ivar_idx);
5675           }
5676 
5677           const bool is_bitfield = ivar_pos->isBitField();
5678 
5679           if (bitfield_bit_size_ptr) {
5680             *bitfield_bit_size_ptr = 0;
5681 
5682             if (is_bitfield && ast) {
5683               clang::Expr *bitfield_bit_size_expr = ivar_pos->getBitWidth();
5684               llvm::APSInt bitfield_apsint;
5685               if (bitfield_bit_size_expr &&
5686                   bitfield_bit_size_expr->EvaluateAsInt(bitfield_apsint,
5687                                                         *ast)) {
5688                 *bitfield_bit_size_ptr = bitfield_apsint.getLimitedValue();
5689               }
5690             }
5691           }
5692           if (is_bitfield_ptr)
5693             *is_bitfield_ptr = is_bitfield;
5694 
5695           return ivar_qual_type.getAsOpaquePtr();
5696         }
5697       }
5698     }
5699   }
5700   return nullptr;
5701 }
5702 
5703 CompilerType ClangASTContext::GetFieldAtIndex(lldb::opaque_compiler_type_t type,
5704                                               size_t idx, std::string &name,
5705                                               uint64_t *bit_offset_ptr,
5706                                               uint32_t *bitfield_bit_size_ptr,
5707                                               bool *is_bitfield_ptr) {
5708   if (!type)
5709     return CompilerType();
5710 
5711   clang::QualType qual_type(GetCanonicalQualType(type));
5712   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5713   switch (type_class) {
5714   case clang::Type::Record:
5715     if (GetCompleteType(type)) {
5716       const clang::RecordType *record_type =
5717           llvm::cast<clang::RecordType>(qual_type.getTypePtr());
5718       const clang::RecordDecl *record_decl = record_type->getDecl();
5719       uint32_t field_idx = 0;
5720       clang::RecordDecl::field_iterator field, field_end;
5721       for (field = record_decl->field_begin(),
5722           field_end = record_decl->field_end();
5723            field != field_end; ++field, ++field_idx) {
5724         if (idx == field_idx) {
5725           // Print the member type if requested
5726           // Print the member name and equal sign
5727           name.assign(field->getNameAsString());
5728 
5729           // Figure out the type byte size (field_type_info.first) and
5730           // alignment (field_type_info.second) from the AST context.
5731           if (bit_offset_ptr) {
5732             const clang::ASTRecordLayout &record_layout =
5733                 getASTContext()->getASTRecordLayout(record_decl);
5734             *bit_offset_ptr = record_layout.getFieldOffset(field_idx);
5735           }
5736 
5737           const bool is_bitfield = field->isBitField();
5738 
5739           if (bitfield_bit_size_ptr) {
5740             *bitfield_bit_size_ptr = 0;
5741 
5742             if (is_bitfield) {
5743               clang::Expr *bitfield_bit_size_expr = field->getBitWidth();
5744               llvm::APSInt bitfield_apsint;
5745               if (bitfield_bit_size_expr &&
5746                   bitfield_bit_size_expr->EvaluateAsInt(bitfield_apsint,
5747                                                         *getASTContext())) {
5748                 *bitfield_bit_size_ptr = bitfield_apsint.getLimitedValue();
5749               }
5750             }
5751           }
5752           if (is_bitfield_ptr)
5753             *is_bitfield_ptr = is_bitfield;
5754 
5755           return CompilerType(getASTContext(), field->getType());
5756         }
5757       }
5758     }
5759     break;
5760 
5761   case clang::Type::ObjCObjectPointer: {
5762     const clang::ObjCObjectPointerType *objc_class_type =
5763         qual_type->getAs<clang::ObjCObjectPointerType>();
5764     const clang::ObjCInterfaceType *objc_interface_type =
5765         objc_class_type->getInterfaceType();
5766     if (objc_interface_type &&
5767         GetCompleteType(static_cast<lldb::opaque_compiler_type_t>(
5768             const_cast<clang::ObjCInterfaceType *>(objc_interface_type)))) {
5769       clang::ObjCInterfaceDecl *class_interface_decl =
5770           objc_interface_type->getDecl();
5771       if (class_interface_decl) {
5772         return CompilerType(
5773             this, GetObjCFieldAtIndex(getASTContext(), class_interface_decl,
5774                                       idx, name, bit_offset_ptr,
5775                                       bitfield_bit_size_ptr, is_bitfield_ptr));
5776       }
5777     }
5778     break;
5779   }
5780 
5781   case clang::Type::ObjCObject:
5782   case clang::Type::ObjCInterface:
5783     if (GetCompleteType(type)) {
5784       const clang::ObjCObjectType *objc_class_type =
5785           llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
5786       assert(objc_class_type);
5787       if (objc_class_type) {
5788         clang::ObjCInterfaceDecl *class_interface_decl =
5789             objc_class_type->getInterface();
5790         return CompilerType(
5791             this, GetObjCFieldAtIndex(getASTContext(), class_interface_decl,
5792                                       idx, name, bit_offset_ptr,
5793                                       bitfield_bit_size_ptr, is_bitfield_ptr));
5794       }
5795     }
5796     break;
5797 
5798   case clang::Type::Typedef:
5799     return CompilerType(getASTContext(),
5800                         llvm::cast<clang::TypedefType>(qual_type)
5801                             ->getDecl()
5802                             ->getUnderlyingType())
5803         .GetFieldAtIndex(idx, name, bit_offset_ptr, bitfield_bit_size_ptr,
5804                          is_bitfield_ptr);
5805 
5806   case clang::Type::Auto:
5807     return CompilerType(
5808                getASTContext(),
5809                llvm::cast<clang::AutoType>(qual_type)->getDeducedType())
5810         .GetFieldAtIndex(idx, name, bit_offset_ptr, bitfield_bit_size_ptr,
5811                          is_bitfield_ptr);
5812 
5813   case clang::Type::Elaborated:
5814     return CompilerType(
5815                getASTContext(),
5816                llvm::cast<clang::ElaboratedType>(qual_type)->getNamedType())
5817         .GetFieldAtIndex(idx, name, bit_offset_ptr, bitfield_bit_size_ptr,
5818                          is_bitfield_ptr);
5819 
5820   case clang::Type::Paren:
5821     return CompilerType(getASTContext(),
5822                         llvm::cast<clang::ParenType>(qual_type)->desugar())
5823         .GetFieldAtIndex(idx, name, bit_offset_ptr, bitfield_bit_size_ptr,
5824                          is_bitfield_ptr);
5825 
5826   default:
5827     break;
5828   }
5829   return CompilerType();
5830 }
5831 
5832 uint32_t
5833 ClangASTContext::GetNumDirectBaseClasses(lldb::opaque_compiler_type_t type) {
5834   uint32_t count = 0;
5835   clang::QualType qual_type(GetCanonicalQualType(type));
5836   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5837   switch (type_class) {
5838   case clang::Type::Record:
5839     if (GetCompleteType(type)) {
5840       const clang::CXXRecordDecl *cxx_record_decl =
5841           qual_type->getAsCXXRecordDecl();
5842       if (cxx_record_decl)
5843         count = cxx_record_decl->getNumBases();
5844     }
5845     break;
5846 
5847   case clang::Type::ObjCObjectPointer:
5848     count = GetPointeeType(type).GetNumDirectBaseClasses();
5849     break;
5850 
5851   case clang::Type::ObjCObject:
5852     if (GetCompleteType(type)) {
5853       const clang::ObjCObjectType *objc_class_type =
5854           qual_type->getAsObjCQualifiedInterfaceType();
5855       if (objc_class_type) {
5856         clang::ObjCInterfaceDecl *class_interface_decl =
5857             objc_class_type->getInterface();
5858 
5859         if (class_interface_decl && class_interface_decl->getSuperClass())
5860           count = 1;
5861       }
5862     }
5863     break;
5864   case clang::Type::ObjCInterface:
5865     if (GetCompleteType(type)) {
5866       const clang::ObjCInterfaceType *objc_interface_type =
5867           qual_type->getAs<clang::ObjCInterfaceType>();
5868       if (objc_interface_type) {
5869         clang::ObjCInterfaceDecl *class_interface_decl =
5870             objc_interface_type->getInterface();
5871 
5872         if (class_interface_decl && class_interface_decl->getSuperClass())
5873           count = 1;
5874       }
5875     }
5876     break;
5877 
5878   case clang::Type::Typedef:
5879     count = GetNumDirectBaseClasses(llvm::cast<clang::TypedefType>(qual_type)
5880                                         ->getDecl()
5881                                         ->getUnderlyingType()
5882                                         .getAsOpaquePtr());
5883     break;
5884 
5885   case clang::Type::Auto:
5886     count = GetNumDirectBaseClasses(llvm::cast<clang::AutoType>(qual_type)
5887                                         ->getDeducedType()
5888                                         .getAsOpaquePtr());
5889     break;
5890 
5891   case clang::Type::Elaborated:
5892     count = GetNumDirectBaseClasses(llvm::cast<clang::ElaboratedType>(qual_type)
5893                                         ->getNamedType()
5894                                         .getAsOpaquePtr());
5895     break;
5896 
5897   case clang::Type::Paren:
5898     return GetNumDirectBaseClasses(
5899         llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr());
5900 
5901   default:
5902     break;
5903   }
5904   return count;
5905 }
5906 
5907 uint32_t
5908 ClangASTContext::GetNumVirtualBaseClasses(lldb::opaque_compiler_type_t type) {
5909   uint32_t count = 0;
5910   clang::QualType qual_type(GetCanonicalQualType(type));
5911   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5912   switch (type_class) {
5913   case clang::Type::Record:
5914     if (GetCompleteType(type)) {
5915       const clang::CXXRecordDecl *cxx_record_decl =
5916           qual_type->getAsCXXRecordDecl();
5917       if (cxx_record_decl)
5918         count = cxx_record_decl->getNumVBases();
5919     }
5920     break;
5921 
5922   case clang::Type::Typedef:
5923     count = GetNumVirtualBaseClasses(llvm::cast<clang::TypedefType>(qual_type)
5924                                          ->getDecl()
5925                                          ->getUnderlyingType()
5926                                          .getAsOpaquePtr());
5927     break;
5928 
5929   case clang::Type::Auto:
5930     count = GetNumVirtualBaseClasses(llvm::cast<clang::AutoType>(qual_type)
5931                                          ->getDeducedType()
5932                                          .getAsOpaquePtr());
5933     break;
5934 
5935   case clang::Type::Elaborated:
5936     count =
5937         GetNumVirtualBaseClasses(llvm::cast<clang::ElaboratedType>(qual_type)
5938                                      ->getNamedType()
5939                                      .getAsOpaquePtr());
5940     break;
5941 
5942   case clang::Type::Paren:
5943     count = GetNumVirtualBaseClasses(
5944         llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr());
5945     break;
5946 
5947   default:
5948     break;
5949   }
5950   return count;
5951 }
5952 
5953 CompilerType ClangASTContext::GetDirectBaseClassAtIndex(
5954     lldb::opaque_compiler_type_t type, size_t idx, uint32_t *bit_offset_ptr) {
5955   clang::QualType qual_type(GetCanonicalQualType(type));
5956   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5957   switch (type_class) {
5958   case clang::Type::Record:
5959     if (GetCompleteType(type)) {
5960       const clang::CXXRecordDecl *cxx_record_decl =
5961           qual_type->getAsCXXRecordDecl();
5962       if (cxx_record_decl) {
5963         uint32_t curr_idx = 0;
5964         clang::CXXRecordDecl::base_class_const_iterator base_class,
5965             base_class_end;
5966         for (base_class = cxx_record_decl->bases_begin(),
5967             base_class_end = cxx_record_decl->bases_end();
5968              base_class != base_class_end; ++base_class, ++curr_idx) {
5969           if (curr_idx == idx) {
5970             if (bit_offset_ptr) {
5971               const clang::ASTRecordLayout &record_layout =
5972                   getASTContext()->getASTRecordLayout(cxx_record_decl);
5973               const clang::CXXRecordDecl *base_class_decl =
5974                   llvm::cast<clang::CXXRecordDecl>(
5975                       base_class->getType()
5976                           ->getAs<clang::RecordType>()
5977                           ->getDecl());
5978               if (base_class->isVirtual())
5979                 *bit_offset_ptr =
5980                     record_layout.getVBaseClassOffset(base_class_decl)
5981                         .getQuantity() *
5982                     8;
5983               else
5984                 *bit_offset_ptr =
5985                     record_layout.getBaseClassOffset(base_class_decl)
5986                         .getQuantity() *
5987                     8;
5988             }
5989             return CompilerType(this, base_class->getType().getAsOpaquePtr());
5990           }
5991         }
5992       }
5993     }
5994     break;
5995 
5996   case clang::Type::ObjCObjectPointer:
5997     return GetPointeeType(type).GetDirectBaseClassAtIndex(idx, bit_offset_ptr);
5998 
5999   case clang::Type::ObjCObject:
6000     if (idx == 0 && GetCompleteType(type)) {
6001       const clang::ObjCObjectType *objc_class_type =
6002           qual_type->getAsObjCQualifiedInterfaceType();
6003       if (objc_class_type) {
6004         clang::ObjCInterfaceDecl *class_interface_decl =
6005             objc_class_type->getInterface();
6006 
6007         if (class_interface_decl) {
6008           clang::ObjCInterfaceDecl *superclass_interface_decl =
6009               class_interface_decl->getSuperClass();
6010           if (superclass_interface_decl) {
6011             if (bit_offset_ptr)
6012               *bit_offset_ptr = 0;
6013             return CompilerType(getASTContext(),
6014                                 getASTContext()->getObjCInterfaceType(
6015                                     superclass_interface_decl));
6016           }
6017         }
6018       }
6019     }
6020     break;
6021   case clang::Type::ObjCInterface:
6022     if (idx == 0 && GetCompleteType(type)) {
6023       const clang::ObjCObjectType *objc_interface_type =
6024           qual_type->getAs<clang::ObjCInterfaceType>();
6025       if (objc_interface_type) {
6026         clang::ObjCInterfaceDecl *class_interface_decl =
6027             objc_interface_type->getInterface();
6028 
6029         if (class_interface_decl) {
6030           clang::ObjCInterfaceDecl *superclass_interface_decl =
6031               class_interface_decl->getSuperClass();
6032           if (superclass_interface_decl) {
6033             if (bit_offset_ptr)
6034               *bit_offset_ptr = 0;
6035             return CompilerType(getASTContext(),
6036                                 getASTContext()->getObjCInterfaceType(
6037                                     superclass_interface_decl));
6038           }
6039         }
6040       }
6041     }
6042     break;
6043 
6044   case clang::Type::Typedef:
6045     return GetDirectBaseClassAtIndex(llvm::cast<clang::TypedefType>(qual_type)
6046                                          ->getDecl()
6047                                          ->getUnderlyingType()
6048                                          .getAsOpaquePtr(),
6049                                      idx, bit_offset_ptr);
6050 
6051   case clang::Type::Auto:
6052     return GetDirectBaseClassAtIndex(llvm::cast<clang::AutoType>(qual_type)
6053                                          ->getDeducedType()
6054                                          .getAsOpaquePtr(),
6055                                      idx, bit_offset_ptr);
6056 
6057   case clang::Type::Elaborated:
6058     return GetDirectBaseClassAtIndex(
6059         llvm::cast<clang::ElaboratedType>(qual_type)
6060             ->getNamedType()
6061             .getAsOpaquePtr(),
6062         idx, bit_offset_ptr);
6063 
6064   case clang::Type::Paren:
6065     return GetDirectBaseClassAtIndex(
6066         llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr(),
6067         idx, bit_offset_ptr);
6068 
6069   default:
6070     break;
6071   }
6072   return CompilerType();
6073 }
6074 
6075 CompilerType ClangASTContext::GetVirtualBaseClassAtIndex(
6076     lldb::opaque_compiler_type_t type, size_t idx, uint32_t *bit_offset_ptr) {
6077   clang::QualType qual_type(GetCanonicalQualType(type));
6078   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
6079   switch (type_class) {
6080   case clang::Type::Record:
6081     if (GetCompleteType(type)) {
6082       const clang::CXXRecordDecl *cxx_record_decl =
6083           qual_type->getAsCXXRecordDecl();
6084       if (cxx_record_decl) {
6085         uint32_t curr_idx = 0;
6086         clang::CXXRecordDecl::base_class_const_iterator base_class,
6087             base_class_end;
6088         for (base_class = cxx_record_decl->vbases_begin(),
6089             base_class_end = cxx_record_decl->vbases_end();
6090              base_class != base_class_end; ++base_class, ++curr_idx) {
6091           if (curr_idx == idx) {
6092             if (bit_offset_ptr) {
6093               const clang::ASTRecordLayout &record_layout =
6094                   getASTContext()->getASTRecordLayout(cxx_record_decl);
6095               const clang::CXXRecordDecl *base_class_decl =
6096                   llvm::cast<clang::CXXRecordDecl>(
6097                       base_class->getType()
6098                           ->getAs<clang::RecordType>()
6099                           ->getDecl());
6100               *bit_offset_ptr =
6101                   record_layout.getVBaseClassOffset(base_class_decl)
6102                       .getQuantity() *
6103                   8;
6104             }
6105             return CompilerType(this, base_class->getType().getAsOpaquePtr());
6106           }
6107         }
6108       }
6109     }
6110     break;
6111 
6112   case clang::Type::Typedef:
6113     return GetVirtualBaseClassAtIndex(llvm::cast<clang::TypedefType>(qual_type)
6114                                           ->getDecl()
6115                                           ->getUnderlyingType()
6116                                           .getAsOpaquePtr(),
6117                                       idx, bit_offset_ptr);
6118 
6119   case clang::Type::Auto:
6120     return GetVirtualBaseClassAtIndex(llvm::cast<clang::AutoType>(qual_type)
6121                                           ->getDeducedType()
6122                                           .getAsOpaquePtr(),
6123                                       idx, bit_offset_ptr);
6124 
6125   case clang::Type::Elaborated:
6126     return GetVirtualBaseClassAtIndex(
6127         llvm::cast<clang::ElaboratedType>(qual_type)
6128             ->getNamedType()
6129             .getAsOpaquePtr(),
6130         idx, bit_offset_ptr);
6131 
6132   case clang::Type::Paren:
6133     return GetVirtualBaseClassAtIndex(
6134         llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr(),
6135         idx, bit_offset_ptr);
6136 
6137   default:
6138     break;
6139   }
6140   return CompilerType();
6141 }
6142 
6143 // If a pointer to a pointee type (the clang_type arg) says that it has no
6144 // children, then we either need to trust it, or override it and return a
6145 // different result. For example, an "int *" has one child that is an integer,
6146 // but a function pointer doesn't have any children. Likewise if a Record type
6147 // claims it has no children, then there really is nothing to show.
6148 uint32_t ClangASTContext::GetNumPointeeChildren(clang::QualType type) {
6149   if (type.isNull())
6150     return 0;
6151 
6152   clang::QualType qual_type(type.getCanonicalType());
6153   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
6154   switch (type_class) {
6155   case clang::Type::Builtin:
6156     switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
6157     case clang::BuiltinType::UnknownAny:
6158     case clang::BuiltinType::Void:
6159     case clang::BuiltinType::NullPtr:
6160     case clang::BuiltinType::OCLEvent:
6161     case clang::BuiltinType::OCLImage1dRO:
6162     case clang::BuiltinType::OCLImage1dWO:
6163     case clang::BuiltinType::OCLImage1dRW:
6164     case clang::BuiltinType::OCLImage1dArrayRO:
6165     case clang::BuiltinType::OCLImage1dArrayWO:
6166     case clang::BuiltinType::OCLImage1dArrayRW:
6167     case clang::BuiltinType::OCLImage1dBufferRO:
6168     case clang::BuiltinType::OCLImage1dBufferWO:
6169     case clang::BuiltinType::OCLImage1dBufferRW:
6170     case clang::BuiltinType::OCLImage2dRO:
6171     case clang::BuiltinType::OCLImage2dWO:
6172     case clang::BuiltinType::OCLImage2dRW:
6173     case clang::BuiltinType::OCLImage2dArrayRO:
6174     case clang::BuiltinType::OCLImage2dArrayWO:
6175     case clang::BuiltinType::OCLImage2dArrayRW:
6176     case clang::BuiltinType::OCLImage3dRO:
6177     case clang::BuiltinType::OCLImage3dWO:
6178     case clang::BuiltinType::OCLImage3dRW:
6179     case clang::BuiltinType::OCLSampler:
6180       return 0;
6181     case clang::BuiltinType::Bool:
6182     case clang::BuiltinType::Char_U:
6183     case clang::BuiltinType::UChar:
6184     case clang::BuiltinType::WChar_U:
6185     case clang::BuiltinType::Char16:
6186     case clang::BuiltinType::Char32:
6187     case clang::BuiltinType::UShort:
6188     case clang::BuiltinType::UInt:
6189     case clang::BuiltinType::ULong:
6190     case clang::BuiltinType::ULongLong:
6191     case clang::BuiltinType::UInt128:
6192     case clang::BuiltinType::Char_S:
6193     case clang::BuiltinType::SChar:
6194     case clang::BuiltinType::WChar_S:
6195     case clang::BuiltinType::Short:
6196     case clang::BuiltinType::Int:
6197     case clang::BuiltinType::Long:
6198     case clang::BuiltinType::LongLong:
6199     case clang::BuiltinType::Int128:
6200     case clang::BuiltinType::Float:
6201     case clang::BuiltinType::Double:
6202     case clang::BuiltinType::LongDouble:
6203     case clang::BuiltinType::Dependent:
6204     case clang::BuiltinType::Overload:
6205     case clang::BuiltinType::ObjCId:
6206     case clang::BuiltinType::ObjCClass:
6207     case clang::BuiltinType::ObjCSel:
6208     case clang::BuiltinType::BoundMember:
6209     case clang::BuiltinType::Half:
6210     case clang::BuiltinType::ARCUnbridgedCast:
6211     case clang::BuiltinType::PseudoObject:
6212     case clang::BuiltinType::BuiltinFn:
6213     case clang::BuiltinType::OMPArraySection:
6214       return 1;
6215     default:
6216       return 0;
6217     }
6218     break;
6219 
6220   case clang::Type::Complex:
6221     return 1;
6222   case clang::Type::Pointer:
6223     return 1;
6224   case clang::Type::BlockPointer:
6225     return 0; // If block pointers don't have debug info, then no children for
6226               // them
6227   case clang::Type::LValueReference:
6228     return 1;
6229   case clang::Type::RValueReference:
6230     return 1;
6231   case clang::Type::MemberPointer:
6232     return 0;
6233   case clang::Type::ConstantArray:
6234     return 0;
6235   case clang::Type::IncompleteArray:
6236     return 0;
6237   case clang::Type::VariableArray:
6238     return 0;
6239   case clang::Type::DependentSizedArray:
6240     return 0;
6241   case clang::Type::DependentSizedExtVector:
6242     return 0;
6243   case clang::Type::Vector:
6244     return 0;
6245   case clang::Type::ExtVector:
6246     return 0;
6247   case clang::Type::FunctionProto:
6248     return 0; // When we function pointers, they have no children...
6249   case clang::Type::FunctionNoProto:
6250     return 0; // When we function pointers, they have no children...
6251   case clang::Type::UnresolvedUsing:
6252     return 0;
6253   case clang::Type::Paren:
6254     return GetNumPointeeChildren(
6255         llvm::cast<clang::ParenType>(qual_type)->desugar());
6256   case clang::Type::Typedef:
6257     return GetNumPointeeChildren(llvm::cast<clang::TypedefType>(qual_type)
6258                                      ->getDecl()
6259                                      ->getUnderlyingType());
6260   case clang::Type::Auto:
6261     return GetNumPointeeChildren(
6262         llvm::cast<clang::AutoType>(qual_type)->getDeducedType());
6263   case clang::Type::Elaborated:
6264     return GetNumPointeeChildren(
6265         llvm::cast<clang::ElaboratedType>(qual_type)->getNamedType());
6266   case clang::Type::TypeOfExpr:
6267     return 0;
6268   case clang::Type::TypeOf:
6269     return 0;
6270   case clang::Type::Decltype:
6271     return 0;
6272   case clang::Type::Record:
6273     return 0;
6274   case clang::Type::Enum:
6275     return 1;
6276   case clang::Type::TemplateTypeParm:
6277     return 1;
6278   case clang::Type::SubstTemplateTypeParm:
6279     return 1;
6280   case clang::Type::TemplateSpecialization:
6281     return 1;
6282   case clang::Type::InjectedClassName:
6283     return 0;
6284   case clang::Type::DependentName:
6285     return 1;
6286   case clang::Type::DependentTemplateSpecialization:
6287     return 1;
6288   case clang::Type::ObjCObject:
6289     return 0;
6290   case clang::Type::ObjCInterface:
6291     return 0;
6292   case clang::Type::ObjCObjectPointer:
6293     return 1;
6294   default:
6295     break;
6296   }
6297   return 0;
6298 }
6299 
6300 CompilerType ClangASTContext::GetChildCompilerTypeAtIndex(
6301     lldb::opaque_compiler_type_t type, ExecutionContext *exe_ctx, size_t idx,
6302     bool transparent_pointers, bool omit_empty_base_classes,
6303     bool ignore_array_bounds, std::string &child_name,
6304     uint32_t &child_byte_size, int32_t &child_byte_offset,
6305     uint32_t &child_bitfield_bit_size, uint32_t &child_bitfield_bit_offset,
6306     bool &child_is_base_class, bool &child_is_deref_of_parent,
6307     ValueObject *valobj, uint64_t &language_flags) {
6308   if (!type)
6309     return CompilerType();
6310 
6311   clang::QualType parent_qual_type(GetCanonicalQualType(type));
6312   const clang::Type::TypeClass parent_type_class =
6313       parent_qual_type->getTypeClass();
6314   child_bitfield_bit_size = 0;
6315   child_bitfield_bit_offset = 0;
6316   child_is_base_class = false;
6317   language_flags = 0;
6318 
6319   const bool idx_is_valid = idx < GetNumChildren(type, omit_empty_base_classes);
6320   uint32_t bit_offset;
6321   switch (parent_type_class) {
6322   case clang::Type::Builtin:
6323     if (idx_is_valid) {
6324       switch (llvm::cast<clang::BuiltinType>(parent_qual_type)->getKind()) {
6325       case clang::BuiltinType::ObjCId:
6326       case clang::BuiltinType::ObjCClass:
6327         child_name = "isa";
6328         child_byte_size =
6329             getASTContext()->getTypeSize(getASTContext()->ObjCBuiltinClassTy) /
6330             CHAR_BIT;
6331         return CompilerType(getASTContext(),
6332                             getASTContext()->ObjCBuiltinClassTy);
6333 
6334       default:
6335         break;
6336       }
6337     }
6338     break;
6339 
6340   case clang::Type::Record:
6341     if (idx_is_valid && GetCompleteType(type)) {
6342       const clang::RecordType *record_type =
6343           llvm::cast<clang::RecordType>(parent_qual_type.getTypePtr());
6344       const clang::RecordDecl *record_decl = record_type->getDecl();
6345       assert(record_decl);
6346       const clang::ASTRecordLayout &record_layout =
6347           getASTContext()->getASTRecordLayout(record_decl);
6348       uint32_t child_idx = 0;
6349 
6350       const clang::CXXRecordDecl *cxx_record_decl =
6351           llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
6352       if (cxx_record_decl) {
6353         // We might have base classes to print out first
6354         clang::CXXRecordDecl::base_class_const_iterator base_class,
6355             base_class_end;
6356         for (base_class = cxx_record_decl->bases_begin(),
6357             base_class_end = cxx_record_decl->bases_end();
6358              base_class != base_class_end; ++base_class) {
6359           const clang::CXXRecordDecl *base_class_decl = nullptr;
6360 
6361           // Skip empty base classes
6362           if (omit_empty_base_classes) {
6363             base_class_decl = llvm::cast<clang::CXXRecordDecl>(
6364                 base_class->getType()->getAs<clang::RecordType>()->getDecl());
6365             if (ClangASTContext::RecordHasFields(base_class_decl) == false)
6366               continue;
6367           }
6368 
6369           if (idx == child_idx) {
6370             if (base_class_decl == nullptr)
6371               base_class_decl = llvm::cast<clang::CXXRecordDecl>(
6372                   base_class->getType()->getAs<clang::RecordType>()->getDecl());
6373 
6374             if (base_class->isVirtual()) {
6375               bool handled = false;
6376               if (valobj) {
6377                 Status err;
6378                 AddressType addr_type = eAddressTypeInvalid;
6379                 lldb::addr_t vtable_ptr_addr =
6380                     valobj->GetCPPVTableAddress(addr_type);
6381 
6382                 if (vtable_ptr_addr != LLDB_INVALID_ADDRESS &&
6383                     addr_type == eAddressTypeLoad) {
6384 
6385                   ExecutionContext exe_ctx(valobj->GetExecutionContextRef());
6386                   Process *process = exe_ctx.GetProcessPtr();
6387                   if (process) {
6388                     clang::VTableContextBase *vtable_ctx =
6389                         getASTContext()->getVTableContext();
6390                     if (vtable_ctx) {
6391                       if (vtable_ctx->isMicrosoft()) {
6392                         clang::MicrosoftVTableContext *msoft_vtable_ctx =
6393                             static_cast<clang::MicrosoftVTableContext *>(
6394                                 vtable_ctx);
6395 
6396                         if (vtable_ptr_addr) {
6397                           const lldb::addr_t vbtable_ptr_addr =
6398                               vtable_ptr_addr +
6399                               record_layout.getVBPtrOffset().getQuantity();
6400 
6401                           const lldb::addr_t vbtable_ptr =
6402                               process->ReadPointerFromMemory(vbtable_ptr_addr,
6403                                                              err);
6404                           if (vbtable_ptr != LLDB_INVALID_ADDRESS) {
6405                             // Get the index into the virtual base table. The
6406                             // index is the index in uint32_t from vbtable_ptr
6407                             const unsigned vbtable_index =
6408                                 msoft_vtable_ctx->getVBTableIndex(
6409                                     cxx_record_decl, base_class_decl);
6410                             const lldb::addr_t base_offset_addr =
6411                                 vbtable_ptr + vbtable_index * 4;
6412                             const uint32_t base_offset =
6413                                 process->ReadUnsignedIntegerFromMemory(
6414                                     base_offset_addr, 4, UINT32_MAX, err);
6415                             if (base_offset != UINT32_MAX) {
6416                               handled = true;
6417                               bit_offset = base_offset * 8;
6418                             }
6419                           }
6420                         }
6421                       } else {
6422                         clang::ItaniumVTableContext *itanium_vtable_ctx =
6423                             static_cast<clang::ItaniumVTableContext *>(
6424                                 vtable_ctx);
6425                         if (vtable_ptr_addr) {
6426                           const lldb::addr_t vtable_ptr =
6427                               process->ReadPointerFromMemory(vtable_ptr_addr,
6428                                                              err);
6429                           if (vtable_ptr != LLDB_INVALID_ADDRESS) {
6430                             clang::CharUnits base_offset_offset =
6431                                 itanium_vtable_ctx->getVirtualBaseOffsetOffset(
6432                                     cxx_record_decl, base_class_decl);
6433                             const lldb::addr_t base_offset_addr =
6434                                 vtable_ptr + base_offset_offset.getQuantity();
6435                             const uint32_t base_offset_size =
6436                                 process->GetAddressByteSize();
6437                             const uint64_t base_offset =
6438                                 process->ReadUnsignedIntegerFromMemory(
6439                                     base_offset_addr, base_offset_size,
6440                                     UINT32_MAX, err);
6441                             if (base_offset < UINT32_MAX) {
6442                               handled = true;
6443                               bit_offset = base_offset * 8;
6444                             }
6445                           }
6446                         }
6447                       }
6448                     }
6449                   }
6450                 }
6451               }
6452               if (!handled)
6453                 bit_offset = record_layout.getVBaseClassOffset(base_class_decl)
6454                                  .getQuantity() *
6455                              8;
6456             } else
6457               bit_offset = record_layout.getBaseClassOffset(base_class_decl)
6458                                .getQuantity() *
6459                            8;
6460 
6461             // Base classes should be a multiple of 8 bits in size
6462             child_byte_offset = bit_offset / 8;
6463             CompilerType base_class_clang_type(getASTContext(),
6464                                                base_class->getType());
6465             child_name = base_class_clang_type.GetTypeName().AsCString("");
6466             uint64_t base_class_clang_type_bit_size =
6467                 base_class_clang_type.GetBitSize(
6468                     exe_ctx ? exe_ctx->GetBestExecutionContextScope() : NULL);
6469 
6470             // Base classes bit sizes should be a multiple of 8 bits in size
6471             assert(base_class_clang_type_bit_size % 8 == 0);
6472             child_byte_size = base_class_clang_type_bit_size / 8;
6473             child_is_base_class = true;
6474             return base_class_clang_type;
6475           }
6476           // We don't increment the child index in the for loop since we might
6477           // be skipping empty base classes
6478           ++child_idx;
6479         }
6480       }
6481       // Make sure index is in range...
6482       uint32_t field_idx = 0;
6483       clang::RecordDecl::field_iterator field, field_end;
6484       for (field = record_decl->field_begin(),
6485           field_end = record_decl->field_end();
6486            field != field_end; ++field, ++field_idx, ++child_idx) {
6487         if (idx == child_idx) {
6488           // Print the member type if requested
6489           // Print the member name and equal sign
6490           child_name.assign(field->getNameAsString());
6491 
6492           // Figure out the type byte size (field_type_info.first) and
6493           // alignment (field_type_info.second) from the AST context.
6494           CompilerType field_clang_type(getASTContext(), field->getType());
6495           assert(field_idx < record_layout.getFieldCount());
6496           child_byte_size = field_clang_type.GetByteSize(
6497               exe_ctx ? exe_ctx->GetBestExecutionContextScope() : NULL);
6498           const uint32_t child_bit_size = child_byte_size * 8;
6499 
6500           // Figure out the field offset within the current struct/union/class
6501           // type
6502           bit_offset = record_layout.getFieldOffset(field_idx);
6503           if (ClangASTContext::FieldIsBitfield(getASTContext(), *field,
6504                                                child_bitfield_bit_size)) {
6505             child_bitfield_bit_offset = bit_offset % child_bit_size;
6506             const uint32_t child_bit_offset =
6507                 bit_offset - child_bitfield_bit_offset;
6508             child_byte_offset = child_bit_offset / 8;
6509           } else {
6510             child_byte_offset = bit_offset / 8;
6511           }
6512 
6513           return field_clang_type;
6514         }
6515       }
6516     }
6517     break;
6518 
6519   case clang::Type::ObjCObject:
6520   case clang::Type::ObjCInterface:
6521     if (idx_is_valid && GetCompleteType(type)) {
6522       const clang::ObjCObjectType *objc_class_type =
6523           llvm::dyn_cast<clang::ObjCObjectType>(parent_qual_type.getTypePtr());
6524       assert(objc_class_type);
6525       if (objc_class_type) {
6526         uint32_t child_idx = 0;
6527         clang::ObjCInterfaceDecl *class_interface_decl =
6528             objc_class_type->getInterface();
6529 
6530         if (class_interface_decl) {
6531 
6532           const clang::ASTRecordLayout &interface_layout =
6533               getASTContext()->getASTObjCInterfaceLayout(class_interface_decl);
6534           clang::ObjCInterfaceDecl *superclass_interface_decl =
6535               class_interface_decl->getSuperClass();
6536           if (superclass_interface_decl) {
6537             if (omit_empty_base_classes) {
6538               CompilerType base_class_clang_type(
6539                   getASTContext(), getASTContext()->getObjCInterfaceType(
6540                                        superclass_interface_decl));
6541               if (base_class_clang_type.GetNumChildren(
6542                       omit_empty_base_classes) > 0) {
6543                 if (idx == 0) {
6544                   clang::QualType ivar_qual_type(
6545                       getASTContext()->getObjCInterfaceType(
6546                           superclass_interface_decl));
6547 
6548                   child_name.assign(
6549                       superclass_interface_decl->getNameAsString());
6550 
6551                   clang::TypeInfo ivar_type_info =
6552                       getASTContext()->getTypeInfo(ivar_qual_type.getTypePtr());
6553 
6554                   child_byte_size = ivar_type_info.Width / 8;
6555                   child_byte_offset = 0;
6556                   child_is_base_class = true;
6557 
6558                   return CompilerType(getASTContext(), ivar_qual_type);
6559                 }
6560 
6561                 ++child_idx;
6562               }
6563             } else
6564               ++child_idx;
6565           }
6566 
6567           const uint32_t superclass_idx = child_idx;
6568 
6569           if (idx < (child_idx + class_interface_decl->ivar_size())) {
6570             clang::ObjCInterfaceDecl::ivar_iterator ivar_pos,
6571                 ivar_end = class_interface_decl->ivar_end();
6572 
6573             for (ivar_pos = class_interface_decl->ivar_begin();
6574                  ivar_pos != ivar_end; ++ivar_pos) {
6575               if (child_idx == idx) {
6576                 clang::ObjCIvarDecl *ivar_decl = *ivar_pos;
6577 
6578                 clang::QualType ivar_qual_type(ivar_decl->getType());
6579 
6580                 child_name.assign(ivar_decl->getNameAsString());
6581 
6582                 clang::TypeInfo ivar_type_info =
6583                     getASTContext()->getTypeInfo(ivar_qual_type.getTypePtr());
6584 
6585                 child_byte_size = ivar_type_info.Width / 8;
6586 
6587                 // Figure out the field offset within the current
6588                 // struct/union/class type
6589                 // For ObjC objects, we can't trust the bit offset we get from
6590                 // the Clang AST, since
6591                 // that doesn't account for the space taken up by unbacked
6592                 // properties, or from
6593                 // the changing size of base classes that are newer than this
6594                 // class.
6595                 // So if we have a process around that we can ask about this
6596                 // object, do so.
6597                 child_byte_offset = LLDB_INVALID_IVAR_OFFSET;
6598                 Process *process = nullptr;
6599                 if (exe_ctx)
6600                   process = exe_ctx->GetProcessPtr();
6601                 if (process) {
6602                   ObjCLanguageRuntime *objc_runtime =
6603                       process->GetObjCLanguageRuntime();
6604                   if (objc_runtime != nullptr) {
6605                     CompilerType parent_ast_type(getASTContext(),
6606                                                  parent_qual_type);
6607                     child_byte_offset = objc_runtime->GetByteOffsetForIvar(
6608                         parent_ast_type, ivar_decl->getNameAsString().c_str());
6609                   }
6610                 }
6611 
6612                 // Setting this to UINT32_MAX to make sure we don't compute it
6613                 // twice...
6614                 bit_offset = UINT32_MAX;
6615 
6616                 if (child_byte_offset ==
6617                     static_cast<int32_t>(LLDB_INVALID_IVAR_OFFSET)) {
6618                   bit_offset = interface_layout.getFieldOffset(child_idx -
6619                                                                superclass_idx);
6620                   child_byte_offset = bit_offset / 8;
6621                 }
6622 
6623                 // Note, the ObjC Ivar Byte offset is just that, it doesn't
6624                 // account for the bit offset
6625                 // of a bitfield within its containing object.  So regardless of
6626                 // where we get the byte
6627                 // offset from, we still need to get the bit offset for
6628                 // bitfields from the layout.
6629 
6630                 if (ClangASTContext::FieldIsBitfield(getASTContext(), ivar_decl,
6631                                                      child_bitfield_bit_size)) {
6632                   if (bit_offset == UINT32_MAX)
6633                     bit_offset = interface_layout.getFieldOffset(
6634                         child_idx - superclass_idx);
6635 
6636                   child_bitfield_bit_offset = bit_offset % 8;
6637                 }
6638                 return CompilerType(getASTContext(), ivar_qual_type);
6639               }
6640               ++child_idx;
6641             }
6642           }
6643         }
6644       }
6645     }
6646     break;
6647 
6648   case clang::Type::ObjCObjectPointer:
6649     if (idx_is_valid) {
6650       CompilerType pointee_clang_type(GetPointeeType(type));
6651 
6652       if (transparent_pointers && pointee_clang_type.IsAggregateType()) {
6653         child_is_deref_of_parent = false;
6654         bool tmp_child_is_deref_of_parent = false;
6655         return pointee_clang_type.GetChildCompilerTypeAtIndex(
6656             exe_ctx, idx, transparent_pointers, omit_empty_base_classes,
6657             ignore_array_bounds, child_name, child_byte_size, child_byte_offset,
6658             child_bitfield_bit_size, child_bitfield_bit_offset,
6659             child_is_base_class, tmp_child_is_deref_of_parent, valobj,
6660             language_flags);
6661       } else {
6662         child_is_deref_of_parent = true;
6663         const char *parent_name =
6664             valobj ? valobj->GetName().GetCString() : NULL;
6665         if (parent_name) {
6666           child_name.assign(1, '*');
6667           child_name += parent_name;
6668         }
6669 
6670         // We have a pointer to an simple type
6671         if (idx == 0 && pointee_clang_type.GetCompleteType()) {
6672           child_byte_size = pointee_clang_type.GetByteSize(
6673               exe_ctx ? exe_ctx->GetBestExecutionContextScope() : NULL);
6674           child_byte_offset = 0;
6675           return pointee_clang_type;
6676         }
6677       }
6678     }
6679     break;
6680 
6681   case clang::Type::Vector:
6682   case clang::Type::ExtVector:
6683     if (idx_is_valid) {
6684       const clang::VectorType *array =
6685           llvm::cast<clang::VectorType>(parent_qual_type.getTypePtr());
6686       if (array) {
6687         CompilerType element_type(getASTContext(), array->getElementType());
6688         if (element_type.GetCompleteType()) {
6689           char element_name[64];
6690           ::snprintf(element_name, sizeof(element_name), "[%" PRIu64 "]",
6691                      static_cast<uint64_t>(idx));
6692           child_name.assign(element_name);
6693           child_byte_size = element_type.GetByteSize(
6694               exe_ctx ? exe_ctx->GetBestExecutionContextScope() : NULL);
6695           child_byte_offset = (int32_t)idx * (int32_t)child_byte_size;
6696           return element_type;
6697         }
6698       }
6699     }
6700     break;
6701 
6702   case clang::Type::ConstantArray:
6703   case clang::Type::IncompleteArray:
6704     if (ignore_array_bounds || idx_is_valid) {
6705       const clang::ArrayType *array = GetQualType(type)->getAsArrayTypeUnsafe();
6706       if (array) {
6707         CompilerType element_type(getASTContext(), array->getElementType());
6708         if (element_type.GetCompleteType()) {
6709           child_name = llvm::formatv("[{0}]", idx);
6710           child_byte_size = element_type.GetByteSize(
6711               exe_ctx ? exe_ctx->GetBestExecutionContextScope() : NULL);
6712           child_byte_offset = (int32_t)idx * (int32_t)child_byte_size;
6713           return element_type;
6714         }
6715       }
6716     }
6717     break;
6718 
6719   case clang::Type::Pointer: {
6720     CompilerType pointee_clang_type(GetPointeeType(type));
6721 
6722     // Don't dereference "void *" pointers
6723     if (pointee_clang_type.IsVoidType())
6724       return CompilerType();
6725 
6726     if (transparent_pointers && pointee_clang_type.IsAggregateType()) {
6727       child_is_deref_of_parent = false;
6728       bool tmp_child_is_deref_of_parent = false;
6729       return pointee_clang_type.GetChildCompilerTypeAtIndex(
6730           exe_ctx, idx, transparent_pointers, omit_empty_base_classes,
6731           ignore_array_bounds, child_name, child_byte_size, child_byte_offset,
6732           child_bitfield_bit_size, child_bitfield_bit_offset,
6733           child_is_base_class, tmp_child_is_deref_of_parent, valobj,
6734           language_flags);
6735     } else {
6736       child_is_deref_of_parent = true;
6737 
6738       const char *parent_name =
6739           valobj ? valobj->GetName().GetCString() : NULL;
6740       if (parent_name) {
6741         child_name.assign(1, '*');
6742         child_name += parent_name;
6743       }
6744 
6745       // We have a pointer to an simple type
6746       if (idx == 0) {
6747         child_byte_size = pointee_clang_type.GetByteSize(
6748             exe_ctx ? exe_ctx->GetBestExecutionContextScope() : NULL);
6749         child_byte_offset = 0;
6750         return pointee_clang_type;
6751       }
6752     }
6753     break;
6754   }
6755 
6756   case clang::Type::LValueReference:
6757   case clang::Type::RValueReference:
6758     if (idx_is_valid) {
6759       const clang::ReferenceType *reference_type =
6760           llvm::cast<clang::ReferenceType>(parent_qual_type.getTypePtr());
6761       CompilerType pointee_clang_type(getASTContext(),
6762                                       reference_type->getPointeeType());
6763       if (transparent_pointers && pointee_clang_type.IsAggregateType()) {
6764         child_is_deref_of_parent = false;
6765         bool tmp_child_is_deref_of_parent = false;
6766         return pointee_clang_type.GetChildCompilerTypeAtIndex(
6767             exe_ctx, idx, transparent_pointers, omit_empty_base_classes,
6768             ignore_array_bounds, child_name, child_byte_size, child_byte_offset,
6769             child_bitfield_bit_size, child_bitfield_bit_offset,
6770             child_is_base_class, tmp_child_is_deref_of_parent, valobj,
6771             language_flags);
6772       } else {
6773         const char *parent_name =
6774             valobj ? valobj->GetName().GetCString() : NULL;
6775         if (parent_name) {
6776           child_name.assign(1, '&');
6777           child_name += parent_name;
6778         }
6779 
6780         // We have a pointer to an simple type
6781         if (idx == 0) {
6782           child_byte_size = pointee_clang_type.GetByteSize(
6783               exe_ctx ? exe_ctx->GetBestExecutionContextScope() : NULL);
6784           child_byte_offset = 0;
6785           return pointee_clang_type;
6786         }
6787       }
6788     }
6789     break;
6790 
6791   case clang::Type::Typedef: {
6792     CompilerType typedefed_clang_type(
6793         getASTContext(), llvm::cast<clang::TypedefType>(parent_qual_type)
6794                              ->getDecl()
6795                              ->getUnderlyingType());
6796     return typedefed_clang_type.GetChildCompilerTypeAtIndex(
6797         exe_ctx, idx, transparent_pointers, omit_empty_base_classes,
6798         ignore_array_bounds, child_name, child_byte_size, child_byte_offset,
6799         child_bitfield_bit_size, child_bitfield_bit_offset, child_is_base_class,
6800         child_is_deref_of_parent, valobj, language_flags);
6801   } break;
6802 
6803   case clang::Type::Auto: {
6804     CompilerType elaborated_clang_type(
6805         getASTContext(),
6806         llvm::cast<clang::AutoType>(parent_qual_type)->getDeducedType());
6807     return elaborated_clang_type.GetChildCompilerTypeAtIndex(
6808         exe_ctx, idx, transparent_pointers, omit_empty_base_classes,
6809         ignore_array_bounds, child_name, child_byte_size, child_byte_offset,
6810         child_bitfield_bit_size, child_bitfield_bit_offset, child_is_base_class,
6811         child_is_deref_of_parent, valobj, language_flags);
6812   }
6813 
6814   case clang::Type::Elaborated: {
6815     CompilerType elaborated_clang_type(
6816         getASTContext(),
6817         llvm::cast<clang::ElaboratedType>(parent_qual_type)->getNamedType());
6818     return elaborated_clang_type.GetChildCompilerTypeAtIndex(
6819         exe_ctx, idx, transparent_pointers, omit_empty_base_classes,
6820         ignore_array_bounds, child_name, child_byte_size, child_byte_offset,
6821         child_bitfield_bit_size, child_bitfield_bit_offset, child_is_base_class,
6822         child_is_deref_of_parent, valobj, language_flags);
6823   }
6824 
6825   case clang::Type::Paren: {
6826     CompilerType paren_clang_type(
6827         getASTContext(),
6828         llvm::cast<clang::ParenType>(parent_qual_type)->desugar());
6829     return paren_clang_type.GetChildCompilerTypeAtIndex(
6830         exe_ctx, idx, transparent_pointers, omit_empty_base_classes,
6831         ignore_array_bounds, child_name, child_byte_size, child_byte_offset,
6832         child_bitfield_bit_size, child_bitfield_bit_offset, child_is_base_class,
6833         child_is_deref_of_parent, valobj, language_flags);
6834   }
6835 
6836   default:
6837     break;
6838   }
6839   return CompilerType();
6840 }
6841 
6842 static uint32_t GetIndexForRecordBase(const clang::RecordDecl *record_decl,
6843                                       const clang::CXXBaseSpecifier *base_spec,
6844                                       bool omit_empty_base_classes) {
6845   uint32_t child_idx = 0;
6846 
6847   const clang::CXXRecordDecl *cxx_record_decl =
6848       llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
6849 
6850   //    const char *super_name = record_decl->getNameAsCString();
6851   //    const char *base_name =
6852   //    base_spec->getType()->getAs<clang::RecordType>()->getDecl()->getNameAsCString();
6853   //    printf ("GetIndexForRecordChild (%s, %s)\n", super_name, base_name);
6854   //
6855   if (cxx_record_decl) {
6856     clang::CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
6857     for (base_class = cxx_record_decl->bases_begin(),
6858         base_class_end = cxx_record_decl->bases_end();
6859          base_class != base_class_end; ++base_class) {
6860       if (omit_empty_base_classes) {
6861         if (BaseSpecifierIsEmpty(base_class))
6862           continue;
6863       }
6864 
6865       //            printf ("GetIndexForRecordChild (%s, %s) base[%u] = %s\n",
6866       //            super_name, base_name,
6867       //                    child_idx,
6868       //                    base_class->getType()->getAs<clang::RecordType>()->getDecl()->getNameAsCString());
6869       //
6870       //
6871       if (base_class == base_spec)
6872         return child_idx;
6873       ++child_idx;
6874     }
6875   }
6876 
6877   return UINT32_MAX;
6878 }
6879 
6880 static uint32_t GetIndexForRecordChild(const clang::RecordDecl *record_decl,
6881                                        clang::NamedDecl *canonical_decl,
6882                                        bool omit_empty_base_classes) {
6883   uint32_t child_idx = ClangASTContext::GetNumBaseClasses(
6884       llvm::dyn_cast<clang::CXXRecordDecl>(record_decl),
6885       omit_empty_base_classes);
6886 
6887   clang::RecordDecl::field_iterator field, field_end;
6888   for (field = record_decl->field_begin(), field_end = record_decl->field_end();
6889        field != field_end; ++field, ++child_idx) {
6890     if (field->getCanonicalDecl() == canonical_decl)
6891       return child_idx;
6892   }
6893 
6894   return UINT32_MAX;
6895 }
6896 
6897 // Look for a child member (doesn't include base classes, but it does include
6898 // their members) in the type hierarchy. Returns an index path into "clang_type"
6899 // on how to reach the appropriate member.
6900 //
6901 //    class A
6902 //    {
6903 //    public:
6904 //        int m_a;
6905 //        int m_b;
6906 //    };
6907 //
6908 //    class B
6909 //    {
6910 //    };
6911 //
6912 //    class C :
6913 //        public B,
6914 //        public A
6915 //    {
6916 //    };
6917 //
6918 // If we have a clang type that describes "class C", and we wanted to looked
6919 // "m_b" in it:
6920 //
6921 // With omit_empty_base_classes == false we would get an integer array back
6922 // with:
6923 // { 1,  1 }
6924 // The first index 1 is the child index for "class A" within class C
6925 // The second index 1 is the child index for "m_b" within class A
6926 //
6927 // With omit_empty_base_classes == true we would get an integer array back with:
6928 // { 0,  1 }
6929 // The first index 0 is the child index for "class A" within class C (since
6930 // class B doesn't have any members it doesn't count)
6931 // The second index 1 is the child index for "m_b" within class A
6932 
6933 size_t ClangASTContext::GetIndexOfChildMemberWithName(
6934     lldb::opaque_compiler_type_t type, const char *name,
6935     bool omit_empty_base_classes, std::vector<uint32_t> &child_indexes) {
6936   if (type && name && name[0]) {
6937     clang::QualType qual_type(GetCanonicalQualType(type));
6938     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
6939     switch (type_class) {
6940     case clang::Type::Record:
6941       if (GetCompleteType(type)) {
6942         const clang::RecordType *record_type =
6943             llvm::cast<clang::RecordType>(qual_type.getTypePtr());
6944         const clang::RecordDecl *record_decl = record_type->getDecl();
6945 
6946         assert(record_decl);
6947         uint32_t child_idx = 0;
6948 
6949         const clang::CXXRecordDecl *cxx_record_decl =
6950             llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
6951 
6952         // Try and find a field that matches NAME
6953         clang::RecordDecl::field_iterator field, field_end;
6954         llvm::StringRef name_sref(name);
6955         for (field = record_decl->field_begin(),
6956             field_end = record_decl->field_end();
6957              field != field_end; ++field, ++child_idx) {
6958           llvm::StringRef field_name = field->getName();
6959           if (field_name.empty()) {
6960             CompilerType field_type(getASTContext(), field->getType());
6961             child_indexes.push_back(child_idx);
6962             if (field_type.GetIndexOfChildMemberWithName(
6963                     name, omit_empty_base_classes, child_indexes))
6964               return child_indexes.size();
6965             child_indexes.pop_back();
6966 
6967           } else if (field_name.equals(name_sref)) {
6968             // We have to add on the number of base classes to this index!
6969             child_indexes.push_back(
6970                 child_idx + ClangASTContext::GetNumBaseClasses(
6971                                 cxx_record_decl, omit_empty_base_classes));
6972             return child_indexes.size();
6973           }
6974         }
6975 
6976         if (cxx_record_decl) {
6977           const clang::RecordDecl *parent_record_decl = cxx_record_decl;
6978 
6979           // printf ("parent = %s\n", parent_record_decl->getNameAsCString());
6980 
6981           // const Decl *root_cdecl = cxx_record_decl->getCanonicalDecl();
6982           // Didn't find things easily, lets let clang do its thang...
6983           clang::IdentifierInfo &ident_ref =
6984               getASTContext()->Idents.get(name_sref);
6985           clang::DeclarationName decl_name(&ident_ref);
6986 
6987           clang::CXXBasePaths paths;
6988           if (cxx_record_decl->lookupInBases(
6989                   [decl_name](const clang::CXXBaseSpecifier *specifier,
6990                               clang::CXXBasePath &path) {
6991                     return clang::CXXRecordDecl::FindOrdinaryMember(
6992                         specifier, path, decl_name);
6993                   },
6994                   paths)) {
6995             clang::CXXBasePaths::const_paths_iterator path,
6996                 path_end = paths.end();
6997             for (path = paths.begin(); path != path_end; ++path) {
6998               const size_t num_path_elements = path->size();
6999               for (size_t e = 0; e < num_path_elements; ++e) {
7000                 clang::CXXBasePathElement elem = (*path)[e];
7001 
7002                 child_idx = GetIndexForRecordBase(parent_record_decl, elem.Base,
7003                                                   omit_empty_base_classes);
7004                 if (child_idx == UINT32_MAX) {
7005                   child_indexes.clear();
7006                   return 0;
7007                 } else {
7008                   child_indexes.push_back(child_idx);
7009                   parent_record_decl = llvm::cast<clang::RecordDecl>(
7010                       elem.Base->getType()
7011                           ->getAs<clang::RecordType>()
7012                           ->getDecl());
7013                 }
7014               }
7015               for (clang::NamedDecl *path_decl : path->Decls) {
7016                 child_idx = GetIndexForRecordChild(
7017                     parent_record_decl, path_decl, omit_empty_base_classes);
7018                 if (child_idx == UINT32_MAX) {
7019                   child_indexes.clear();
7020                   return 0;
7021                 } else {
7022                   child_indexes.push_back(child_idx);
7023                 }
7024               }
7025             }
7026             return child_indexes.size();
7027           }
7028         }
7029       }
7030       break;
7031 
7032     case clang::Type::ObjCObject:
7033     case clang::Type::ObjCInterface:
7034       if (GetCompleteType(type)) {
7035         llvm::StringRef name_sref(name);
7036         const clang::ObjCObjectType *objc_class_type =
7037             llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
7038         assert(objc_class_type);
7039         if (objc_class_type) {
7040           uint32_t child_idx = 0;
7041           clang::ObjCInterfaceDecl *class_interface_decl =
7042               objc_class_type->getInterface();
7043 
7044           if (class_interface_decl) {
7045             clang::ObjCInterfaceDecl::ivar_iterator ivar_pos,
7046                 ivar_end = class_interface_decl->ivar_end();
7047             clang::ObjCInterfaceDecl *superclass_interface_decl =
7048                 class_interface_decl->getSuperClass();
7049 
7050             for (ivar_pos = class_interface_decl->ivar_begin();
7051                  ivar_pos != ivar_end; ++ivar_pos, ++child_idx) {
7052               const clang::ObjCIvarDecl *ivar_decl = *ivar_pos;
7053 
7054               if (ivar_decl->getName().equals(name_sref)) {
7055                 if ((!omit_empty_base_classes && superclass_interface_decl) ||
7056                     (omit_empty_base_classes &&
7057                      ObjCDeclHasIVars(superclass_interface_decl, true)))
7058                   ++child_idx;
7059 
7060                 child_indexes.push_back(child_idx);
7061                 return child_indexes.size();
7062               }
7063             }
7064 
7065             if (superclass_interface_decl) {
7066               // The super class index is always zero for ObjC classes,
7067               // so we push it onto the child indexes in case we find
7068               // an ivar in our superclass...
7069               child_indexes.push_back(0);
7070 
7071               CompilerType superclass_clang_type(
7072                   getASTContext(), getASTContext()->getObjCInterfaceType(
7073                                        superclass_interface_decl));
7074               if (superclass_clang_type.GetIndexOfChildMemberWithName(
7075                       name, omit_empty_base_classes, child_indexes)) {
7076                 // We did find an ivar in a superclass so just
7077                 // return the results!
7078                 return child_indexes.size();
7079               }
7080 
7081               // We didn't find an ivar matching "name" in our
7082               // superclass, pop the superclass zero index that
7083               // we pushed on above.
7084               child_indexes.pop_back();
7085             }
7086           }
7087         }
7088       }
7089       break;
7090 
7091     case clang::Type::ObjCObjectPointer: {
7092       CompilerType objc_object_clang_type(
7093           getASTContext(),
7094           llvm::cast<clang::ObjCObjectPointerType>(qual_type.getTypePtr())
7095               ->getPointeeType());
7096       return objc_object_clang_type.GetIndexOfChildMemberWithName(
7097           name, omit_empty_base_classes, child_indexes);
7098     } break;
7099 
7100     case clang::Type::ConstantArray: {
7101       //                const clang::ConstantArrayType *array =
7102       //                llvm::cast<clang::ConstantArrayType>(parent_qual_type.getTypePtr());
7103       //                const uint64_t element_count =
7104       //                array->getSize().getLimitedValue();
7105       //
7106       //                if (idx < element_count)
7107       //                {
7108       //                    std::pair<uint64_t, unsigned> field_type_info =
7109       //                    ast->getTypeInfo(array->getElementType());
7110       //
7111       //                    char element_name[32];
7112       //                    ::snprintf (element_name, sizeof (element_name),
7113       //                    "%s[%u]", parent_name ? parent_name : "", idx);
7114       //
7115       //                    child_name.assign(element_name);
7116       //                    assert(field_type_info.first % 8 == 0);
7117       //                    child_byte_size = field_type_info.first / 8;
7118       //                    child_byte_offset = idx * child_byte_size;
7119       //                    return array->getElementType().getAsOpaquePtr();
7120       //                }
7121     } break;
7122 
7123     //        case clang::Type::MemberPointerType:
7124     //            {
7125     //                MemberPointerType *mem_ptr_type =
7126     //                llvm::cast<MemberPointerType>(qual_type.getTypePtr());
7127     //                clang::QualType pointee_type =
7128     //                mem_ptr_type->getPointeeType();
7129     //
7130     //                if (ClangASTContext::IsAggregateType
7131     //                (pointee_type.getAsOpaquePtr()))
7132     //                {
7133     //                    return GetIndexOfChildWithName (ast,
7134     //                                                    mem_ptr_type->getPointeeType().getAsOpaquePtr(),
7135     //                                                    name);
7136     //                }
7137     //            }
7138     //            break;
7139     //
7140     case clang::Type::LValueReference:
7141     case clang::Type::RValueReference: {
7142       const clang::ReferenceType *reference_type =
7143           llvm::cast<clang::ReferenceType>(qual_type.getTypePtr());
7144       clang::QualType pointee_type(reference_type->getPointeeType());
7145       CompilerType pointee_clang_type(getASTContext(), pointee_type);
7146 
7147       if (pointee_clang_type.IsAggregateType()) {
7148         return pointee_clang_type.GetIndexOfChildMemberWithName(
7149             name, omit_empty_base_classes, child_indexes);
7150       }
7151     } break;
7152 
7153     case clang::Type::Pointer: {
7154       CompilerType pointee_clang_type(GetPointeeType(type));
7155 
7156       if (pointee_clang_type.IsAggregateType()) {
7157         return pointee_clang_type.GetIndexOfChildMemberWithName(
7158             name, omit_empty_base_classes, child_indexes);
7159       }
7160     } break;
7161 
7162     case clang::Type::Typedef:
7163       return CompilerType(getASTContext(),
7164                           llvm::cast<clang::TypedefType>(qual_type)
7165                               ->getDecl()
7166                               ->getUnderlyingType())
7167           .GetIndexOfChildMemberWithName(name, omit_empty_base_classes,
7168                                          child_indexes);
7169 
7170     case clang::Type::Auto:
7171       return CompilerType(
7172                  getASTContext(),
7173                  llvm::cast<clang::AutoType>(qual_type)->getDeducedType())
7174           .GetIndexOfChildMemberWithName(name, omit_empty_base_classes,
7175                                          child_indexes);
7176 
7177     case clang::Type::Elaborated:
7178       return CompilerType(
7179                  getASTContext(),
7180                  llvm::cast<clang::ElaboratedType>(qual_type)->getNamedType())
7181           .GetIndexOfChildMemberWithName(name, omit_empty_base_classes,
7182                                          child_indexes);
7183 
7184     case clang::Type::Paren:
7185       return CompilerType(getASTContext(),
7186                           llvm::cast<clang::ParenType>(qual_type)->desugar())
7187           .GetIndexOfChildMemberWithName(name, omit_empty_base_classes,
7188                                          child_indexes);
7189 
7190     default:
7191       break;
7192     }
7193   }
7194   return 0;
7195 }
7196 
7197 // Get the index of the child of "clang_type" whose name matches. This function
7198 // doesn't descend into the children, but only looks one level deep and name
7199 // matches can include base class names.
7200 
7201 uint32_t
7202 ClangASTContext::GetIndexOfChildWithName(lldb::opaque_compiler_type_t type,
7203                                          const char *name,
7204                                          bool omit_empty_base_classes) {
7205   if (type && name && name[0]) {
7206     clang::QualType qual_type(GetCanonicalQualType(type));
7207 
7208     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
7209 
7210     switch (type_class) {
7211     case clang::Type::Record:
7212       if (GetCompleteType(type)) {
7213         const clang::RecordType *record_type =
7214             llvm::cast<clang::RecordType>(qual_type.getTypePtr());
7215         const clang::RecordDecl *record_decl = record_type->getDecl();
7216 
7217         assert(record_decl);
7218         uint32_t child_idx = 0;
7219 
7220         const clang::CXXRecordDecl *cxx_record_decl =
7221             llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
7222 
7223         if (cxx_record_decl) {
7224           clang::CXXRecordDecl::base_class_const_iterator base_class,
7225               base_class_end;
7226           for (base_class = cxx_record_decl->bases_begin(),
7227               base_class_end = cxx_record_decl->bases_end();
7228                base_class != base_class_end; ++base_class) {
7229             // Skip empty base classes
7230             clang::CXXRecordDecl *base_class_decl =
7231                 llvm::cast<clang::CXXRecordDecl>(
7232                     base_class->getType()
7233                         ->getAs<clang::RecordType>()
7234                         ->getDecl());
7235             if (omit_empty_base_classes &&
7236                 ClangASTContext::RecordHasFields(base_class_decl) == false)
7237               continue;
7238 
7239             CompilerType base_class_clang_type(getASTContext(),
7240                                                base_class->getType());
7241             std::string base_class_type_name(
7242                 base_class_clang_type.GetTypeName().AsCString(""));
7243             if (base_class_type_name.compare(name) == 0)
7244               return child_idx;
7245             ++child_idx;
7246           }
7247         }
7248 
7249         // Try and find a field that matches NAME
7250         clang::RecordDecl::field_iterator field, field_end;
7251         llvm::StringRef name_sref(name);
7252         for (field = record_decl->field_begin(),
7253             field_end = record_decl->field_end();
7254              field != field_end; ++field, ++child_idx) {
7255           if (field->getName().equals(name_sref))
7256             return child_idx;
7257         }
7258       }
7259       break;
7260 
7261     case clang::Type::ObjCObject:
7262     case clang::Type::ObjCInterface:
7263       if (GetCompleteType(type)) {
7264         llvm::StringRef name_sref(name);
7265         const clang::ObjCObjectType *objc_class_type =
7266             llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
7267         assert(objc_class_type);
7268         if (objc_class_type) {
7269           uint32_t child_idx = 0;
7270           clang::ObjCInterfaceDecl *class_interface_decl =
7271               objc_class_type->getInterface();
7272 
7273           if (class_interface_decl) {
7274             clang::ObjCInterfaceDecl::ivar_iterator ivar_pos,
7275                 ivar_end = class_interface_decl->ivar_end();
7276             clang::ObjCInterfaceDecl *superclass_interface_decl =
7277                 class_interface_decl->getSuperClass();
7278 
7279             for (ivar_pos = class_interface_decl->ivar_begin();
7280                  ivar_pos != ivar_end; ++ivar_pos, ++child_idx) {
7281               const clang::ObjCIvarDecl *ivar_decl = *ivar_pos;
7282 
7283               if (ivar_decl->getName().equals(name_sref)) {
7284                 if ((!omit_empty_base_classes && superclass_interface_decl) ||
7285                     (omit_empty_base_classes &&
7286                      ObjCDeclHasIVars(superclass_interface_decl, true)))
7287                   ++child_idx;
7288 
7289                 return child_idx;
7290               }
7291             }
7292 
7293             if (superclass_interface_decl) {
7294               if (superclass_interface_decl->getName().equals(name_sref))
7295                 return 0;
7296             }
7297           }
7298         }
7299       }
7300       break;
7301 
7302     case clang::Type::ObjCObjectPointer: {
7303       CompilerType pointee_clang_type(
7304           getASTContext(),
7305           llvm::cast<clang::ObjCObjectPointerType>(qual_type.getTypePtr())
7306               ->getPointeeType());
7307       return pointee_clang_type.GetIndexOfChildWithName(
7308           name, omit_empty_base_classes);
7309     } break;
7310 
7311     case clang::Type::ConstantArray: {
7312       //                const clang::ConstantArrayType *array =
7313       //                llvm::cast<clang::ConstantArrayType>(parent_qual_type.getTypePtr());
7314       //                const uint64_t element_count =
7315       //                array->getSize().getLimitedValue();
7316       //
7317       //                if (idx < element_count)
7318       //                {
7319       //                    std::pair<uint64_t, unsigned> field_type_info =
7320       //                    ast->getTypeInfo(array->getElementType());
7321       //
7322       //                    char element_name[32];
7323       //                    ::snprintf (element_name, sizeof (element_name),
7324       //                    "%s[%u]", parent_name ? parent_name : "", idx);
7325       //
7326       //                    child_name.assign(element_name);
7327       //                    assert(field_type_info.first % 8 == 0);
7328       //                    child_byte_size = field_type_info.first / 8;
7329       //                    child_byte_offset = idx * child_byte_size;
7330       //                    return array->getElementType().getAsOpaquePtr();
7331       //                }
7332     } break;
7333 
7334     //        case clang::Type::MemberPointerType:
7335     //            {
7336     //                MemberPointerType *mem_ptr_type =
7337     //                llvm::cast<MemberPointerType>(qual_type.getTypePtr());
7338     //                clang::QualType pointee_type =
7339     //                mem_ptr_type->getPointeeType();
7340     //
7341     //                if (ClangASTContext::IsAggregateType
7342     //                (pointee_type.getAsOpaquePtr()))
7343     //                {
7344     //                    return GetIndexOfChildWithName (ast,
7345     //                                                    mem_ptr_type->getPointeeType().getAsOpaquePtr(),
7346     //                                                    name);
7347     //                }
7348     //            }
7349     //            break;
7350     //
7351     case clang::Type::LValueReference:
7352     case clang::Type::RValueReference: {
7353       const clang::ReferenceType *reference_type =
7354           llvm::cast<clang::ReferenceType>(qual_type.getTypePtr());
7355       CompilerType pointee_type(getASTContext(),
7356                                 reference_type->getPointeeType());
7357 
7358       if (pointee_type.IsAggregateType()) {
7359         return pointee_type.GetIndexOfChildWithName(name,
7360                                                     omit_empty_base_classes);
7361       }
7362     } break;
7363 
7364     case clang::Type::Pointer: {
7365       const clang::PointerType *pointer_type =
7366           llvm::cast<clang::PointerType>(qual_type.getTypePtr());
7367       CompilerType pointee_type(getASTContext(),
7368                                 pointer_type->getPointeeType());
7369 
7370       if (pointee_type.IsAggregateType()) {
7371         return pointee_type.GetIndexOfChildWithName(name,
7372                                                     omit_empty_base_classes);
7373       } else {
7374         //                    if (parent_name)
7375         //                    {
7376         //                        child_name.assign(1, '*');
7377         //                        child_name += parent_name;
7378         //                    }
7379         //
7380         //                    // We have a pointer to an simple type
7381         //                    if (idx == 0)
7382         //                    {
7383         //                        std::pair<uint64_t, unsigned> clang_type_info
7384         //                        = ast->getTypeInfo(pointee_type);
7385         //                        assert(clang_type_info.first % 8 == 0);
7386         //                        child_byte_size = clang_type_info.first / 8;
7387         //                        child_byte_offset = 0;
7388         //                        return pointee_type.getAsOpaquePtr();
7389         //                    }
7390       }
7391     } break;
7392 
7393     case clang::Type::Auto:
7394       return CompilerType(
7395                  getASTContext(),
7396                  llvm::cast<clang::AutoType>(qual_type)->getDeducedType())
7397           .GetIndexOfChildWithName(name, omit_empty_base_classes);
7398 
7399     case clang::Type::Elaborated:
7400       return CompilerType(
7401                  getASTContext(),
7402                  llvm::cast<clang::ElaboratedType>(qual_type)->getNamedType())
7403           .GetIndexOfChildWithName(name, omit_empty_base_classes);
7404 
7405     case clang::Type::Paren:
7406       return CompilerType(getASTContext(),
7407                           llvm::cast<clang::ParenType>(qual_type)->desugar())
7408           .GetIndexOfChildWithName(name, omit_empty_base_classes);
7409 
7410     case clang::Type::Typedef:
7411       return CompilerType(getASTContext(),
7412                           llvm::cast<clang::TypedefType>(qual_type)
7413                               ->getDecl()
7414                               ->getUnderlyingType())
7415           .GetIndexOfChildWithName(name, omit_empty_base_classes);
7416 
7417     default:
7418       break;
7419     }
7420   }
7421   return UINT32_MAX;
7422 }
7423 
7424 size_t
7425 ClangASTContext::GetNumTemplateArguments(lldb::opaque_compiler_type_t type) {
7426   if (!type)
7427     return 0;
7428 
7429   clang::QualType qual_type(GetCanonicalQualType(type));
7430   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
7431   switch (type_class) {
7432   case clang::Type::Record:
7433     if (GetCompleteType(type)) {
7434       const clang::CXXRecordDecl *cxx_record_decl =
7435           qual_type->getAsCXXRecordDecl();
7436       if (cxx_record_decl) {
7437         const clang::ClassTemplateSpecializationDecl *template_decl =
7438             llvm::dyn_cast<clang::ClassTemplateSpecializationDecl>(
7439                 cxx_record_decl);
7440         if (template_decl)
7441           return template_decl->getTemplateArgs().size();
7442       }
7443     }
7444     break;
7445 
7446   case clang::Type::Typedef:
7447     return (CompilerType(getASTContext(),
7448                          llvm::cast<clang::TypedefType>(qual_type)
7449                              ->getDecl()
7450                              ->getUnderlyingType()))
7451         .GetNumTemplateArguments();
7452 
7453   case clang::Type::Auto:
7454     return (CompilerType(
7455                 getASTContext(),
7456                 llvm::cast<clang::AutoType>(qual_type)->getDeducedType()))
7457         .GetNumTemplateArguments();
7458 
7459   case clang::Type::Elaborated:
7460     return (CompilerType(
7461                 getASTContext(),
7462                 llvm::cast<clang::ElaboratedType>(qual_type)->getNamedType()))
7463         .GetNumTemplateArguments();
7464 
7465   case clang::Type::Paren:
7466     return (CompilerType(getASTContext(),
7467                          llvm::cast<clang::ParenType>(qual_type)->desugar()))
7468         .GetNumTemplateArguments();
7469 
7470   default:
7471     break;
7472   }
7473 
7474   return 0;
7475 }
7476 
7477 const clang::ClassTemplateSpecializationDecl *
7478 ClangASTContext::GetAsTemplateSpecialization(
7479     lldb::opaque_compiler_type_t type) {
7480   if (!type)
7481     return nullptr;
7482 
7483   clang::QualType qual_type(GetCanonicalQualType(type));
7484   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
7485   switch (type_class) {
7486   case clang::Type::Record: {
7487     if (! GetCompleteType(type))
7488       return nullptr;
7489     const clang::CXXRecordDecl *cxx_record_decl =
7490         qual_type->getAsCXXRecordDecl();
7491     if (!cxx_record_decl)
7492       return nullptr;
7493     return llvm::dyn_cast<clang::ClassTemplateSpecializationDecl>(
7494         cxx_record_decl);
7495   }
7496 
7497   case clang::Type::Typedef:
7498     return GetAsTemplateSpecialization(llvm::cast<clang::TypedefType>(qual_type)
7499                                            ->getDecl()
7500                                            ->getUnderlyingType()
7501                                            .getAsOpaquePtr());
7502 
7503   case clang::Type::Auto:
7504     return GetAsTemplateSpecialization(llvm::cast<clang::AutoType>(qual_type)
7505                                            ->getDeducedType()
7506                                            .getAsOpaquePtr());
7507 
7508   case clang::Type::Elaborated:
7509     return GetAsTemplateSpecialization(
7510         llvm::cast<clang::ElaboratedType>(qual_type)
7511             ->getNamedType()
7512             .getAsOpaquePtr());
7513 
7514   case clang::Type::Paren:
7515     return GetAsTemplateSpecialization(
7516         llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr());
7517 
7518   default:
7519     return nullptr;
7520   }
7521 }
7522 
7523 lldb::TemplateArgumentKind
7524 ClangASTContext::GetTemplateArgumentKind(lldb::opaque_compiler_type_t type,
7525                                          size_t arg_idx) {
7526   const clang::ClassTemplateSpecializationDecl *template_decl =
7527       GetAsTemplateSpecialization(type);
7528   if (! template_decl || arg_idx >= template_decl->getTemplateArgs().size())
7529     return eTemplateArgumentKindNull;
7530 
7531   switch (template_decl->getTemplateArgs()[arg_idx].getKind()) {
7532   case clang::TemplateArgument::Null:
7533     return eTemplateArgumentKindNull;
7534 
7535   case clang::TemplateArgument::NullPtr:
7536     return eTemplateArgumentKindNullPtr;
7537 
7538   case clang::TemplateArgument::Type:
7539     return eTemplateArgumentKindType;
7540 
7541   case clang::TemplateArgument::Declaration:
7542     return eTemplateArgumentKindDeclaration;
7543 
7544   case clang::TemplateArgument::Integral:
7545     return eTemplateArgumentKindIntegral;
7546 
7547   case clang::TemplateArgument::Template:
7548     return eTemplateArgumentKindTemplate;
7549 
7550   case clang::TemplateArgument::TemplateExpansion:
7551     return eTemplateArgumentKindTemplateExpansion;
7552 
7553   case clang::TemplateArgument::Expression:
7554     return eTemplateArgumentKindExpression;
7555 
7556   case clang::TemplateArgument::Pack:
7557     return eTemplateArgumentKindPack;
7558   }
7559   llvm_unreachable("Unhandled clang::TemplateArgument::ArgKind");
7560 }
7561 
7562 CompilerType
7563 ClangASTContext::GetTypeTemplateArgument(lldb::opaque_compiler_type_t type,
7564                                          size_t idx) {
7565   const clang::ClassTemplateSpecializationDecl *template_decl =
7566       GetAsTemplateSpecialization(type);
7567   if (!template_decl || idx >= template_decl->getTemplateArgs().size())
7568     return CompilerType();
7569 
7570   const clang::TemplateArgument &template_arg =
7571       template_decl->getTemplateArgs()[idx];
7572   if (template_arg.getKind() != clang::TemplateArgument::Type)
7573     return CompilerType();
7574 
7575   return CompilerType(getASTContext(), template_arg.getAsType());
7576 }
7577 
7578 llvm::Optional<CompilerType::IntegralTemplateArgument>
7579 ClangASTContext::GetIntegralTemplateArgument(lldb::opaque_compiler_type_t type,
7580                                              size_t idx) {
7581   const clang::ClassTemplateSpecializationDecl *template_decl =
7582       GetAsTemplateSpecialization(type);
7583   if (! template_decl || idx >= template_decl->getTemplateArgs().size())
7584     return llvm::None;
7585 
7586   const clang::TemplateArgument &template_arg =
7587       template_decl->getTemplateArgs()[idx];
7588   if (template_arg.getKind() != clang::TemplateArgument::Integral)
7589     return llvm::None;
7590 
7591   return {{template_arg.getAsIntegral(),
7592            CompilerType(getASTContext(), template_arg.getIntegralType())}};
7593 }
7594 
7595 CompilerType ClangASTContext::GetTypeForFormatters(void *type) {
7596   if (type)
7597     return ClangUtil::RemoveFastQualifiers(CompilerType(this, type));
7598   return CompilerType();
7599 }
7600 
7601 clang::EnumDecl *ClangASTContext::GetAsEnumDecl(const CompilerType &type) {
7602   const clang::EnumType *enutype =
7603       llvm::dyn_cast<clang::EnumType>(ClangUtil::GetCanonicalQualType(type));
7604   if (enutype)
7605     return enutype->getDecl();
7606   return NULL;
7607 }
7608 
7609 clang::RecordDecl *ClangASTContext::GetAsRecordDecl(const CompilerType &type) {
7610   const clang::RecordType *record_type =
7611       llvm::dyn_cast<clang::RecordType>(ClangUtil::GetCanonicalQualType(type));
7612   if (record_type)
7613     return record_type->getDecl();
7614   return nullptr;
7615 }
7616 
7617 clang::TagDecl *ClangASTContext::GetAsTagDecl(const CompilerType &type) {
7618   clang::QualType qual_type = ClangUtil::GetCanonicalQualType(type);
7619   if (qual_type.isNull())
7620     return nullptr;
7621   else
7622     return qual_type->getAsTagDecl();
7623 }
7624 
7625 clang::CXXRecordDecl *
7626 ClangASTContext::GetAsCXXRecordDecl(lldb::opaque_compiler_type_t type) {
7627   return GetCanonicalQualType(type)->getAsCXXRecordDecl();
7628 }
7629 
7630 clang::ObjCInterfaceDecl *
7631 ClangASTContext::GetAsObjCInterfaceDecl(const CompilerType &type) {
7632   const clang::ObjCObjectType *objc_class_type =
7633       llvm::dyn_cast<clang::ObjCObjectType>(
7634           ClangUtil::GetCanonicalQualType(type));
7635   if (objc_class_type)
7636     return objc_class_type->getInterface();
7637   return nullptr;
7638 }
7639 
7640 clang::FieldDecl *ClangASTContext::AddFieldToRecordType(
7641     const CompilerType &type, const char *name,
7642     const CompilerType &field_clang_type, AccessType access,
7643     uint32_t bitfield_bit_size) {
7644   if (!type.IsValid() || !field_clang_type.IsValid())
7645     return nullptr;
7646   ClangASTContext *ast =
7647       llvm::dyn_cast_or_null<ClangASTContext>(type.GetTypeSystem());
7648   if (!ast)
7649     return nullptr;
7650   clang::ASTContext *clang_ast = ast->getASTContext();
7651 
7652   clang::FieldDecl *field = nullptr;
7653 
7654   clang::Expr *bit_width = nullptr;
7655   if (bitfield_bit_size != 0) {
7656     llvm::APInt bitfield_bit_size_apint(
7657         clang_ast->getTypeSize(clang_ast->IntTy), bitfield_bit_size);
7658     bit_width = new (*clang_ast)
7659         clang::IntegerLiteral(*clang_ast, bitfield_bit_size_apint,
7660                               clang_ast->IntTy, clang::SourceLocation());
7661   }
7662 
7663   clang::RecordDecl *record_decl = ast->GetAsRecordDecl(type);
7664   if (record_decl) {
7665     field = clang::FieldDecl::Create(
7666         *clang_ast, record_decl, clang::SourceLocation(),
7667         clang::SourceLocation(),
7668         name ? &clang_ast->Idents.get(name) : nullptr, // Identifier
7669         ClangUtil::GetQualType(field_clang_type),      // Field type
7670         nullptr,                                       // TInfo *
7671         bit_width,                                     // BitWidth
7672         false,                                         // Mutable
7673         clang::ICIS_NoInit);                           // HasInit
7674 
7675     if (!name) {
7676       // Determine whether this field corresponds to an anonymous
7677       // struct or union.
7678       if (const clang::TagType *TagT =
7679               field->getType()->getAs<clang::TagType>()) {
7680         if (clang::RecordDecl *Rec =
7681                 llvm::dyn_cast<clang::RecordDecl>(TagT->getDecl()))
7682           if (!Rec->getDeclName()) {
7683             Rec->setAnonymousStructOrUnion(true);
7684             field->setImplicit();
7685           }
7686       }
7687     }
7688 
7689     if (field) {
7690       field->setAccess(
7691           ClangASTContext::ConvertAccessTypeToAccessSpecifier(access));
7692 
7693       record_decl->addDecl(field);
7694 
7695 #ifdef LLDB_CONFIGURATION_DEBUG
7696       VerifyDecl(field);
7697 #endif
7698     }
7699   } else {
7700     clang::ObjCInterfaceDecl *class_interface_decl =
7701         ast->GetAsObjCInterfaceDecl(type);
7702 
7703     if (class_interface_decl) {
7704       const bool is_synthesized = false;
7705 
7706       field_clang_type.GetCompleteType();
7707 
7708       field = clang::ObjCIvarDecl::Create(
7709           *clang_ast, class_interface_decl, clang::SourceLocation(),
7710           clang::SourceLocation(),
7711           name ? &clang_ast->Idents.get(name) : nullptr, // Identifier
7712           ClangUtil::GetQualType(field_clang_type),      // Field type
7713           nullptr,                                       // TypeSourceInfo *
7714           ConvertAccessTypeToObjCIvarAccessControl(access), bit_width,
7715           is_synthesized);
7716 
7717       if (field) {
7718         class_interface_decl->addDecl(field);
7719 
7720 #ifdef LLDB_CONFIGURATION_DEBUG
7721         VerifyDecl(field);
7722 #endif
7723       }
7724     }
7725   }
7726   return field;
7727 }
7728 
7729 void ClangASTContext::BuildIndirectFields(const CompilerType &type) {
7730   if (!type)
7731     return;
7732 
7733   ClangASTContext *ast = llvm::dyn_cast<ClangASTContext>(type.GetTypeSystem());
7734   if (!ast)
7735     return;
7736 
7737   clang::RecordDecl *record_decl = ast->GetAsRecordDecl(type);
7738 
7739   if (!record_decl)
7740     return;
7741 
7742   typedef llvm::SmallVector<clang::IndirectFieldDecl *, 1> IndirectFieldVector;
7743 
7744   IndirectFieldVector indirect_fields;
7745   clang::RecordDecl::field_iterator field_pos;
7746   clang::RecordDecl::field_iterator field_end_pos = record_decl->field_end();
7747   clang::RecordDecl::field_iterator last_field_pos = field_end_pos;
7748   for (field_pos = record_decl->field_begin(); field_pos != field_end_pos;
7749        last_field_pos = field_pos++) {
7750     if (field_pos->isAnonymousStructOrUnion()) {
7751       clang::QualType field_qual_type = field_pos->getType();
7752 
7753       const clang::RecordType *field_record_type =
7754           field_qual_type->getAs<clang::RecordType>();
7755 
7756       if (!field_record_type)
7757         continue;
7758 
7759       clang::RecordDecl *field_record_decl = field_record_type->getDecl();
7760 
7761       if (!field_record_decl)
7762         continue;
7763 
7764       for (clang::RecordDecl::decl_iterator
7765                di = field_record_decl->decls_begin(),
7766                de = field_record_decl->decls_end();
7767            di != de; ++di) {
7768         if (clang::FieldDecl *nested_field_decl =
7769                 llvm::dyn_cast<clang::FieldDecl>(*di)) {
7770           clang::NamedDecl **chain =
7771               new (*ast->getASTContext()) clang::NamedDecl *[2];
7772           chain[0] = *field_pos;
7773           chain[1] = nested_field_decl;
7774           clang::IndirectFieldDecl *indirect_field =
7775               clang::IndirectFieldDecl::Create(
7776                   *ast->getASTContext(), record_decl, clang::SourceLocation(),
7777                   nested_field_decl->getIdentifier(),
7778                   nested_field_decl->getType(), {chain, 2});
7779 
7780           indirect_field->setImplicit();
7781 
7782           indirect_field->setAccess(ClangASTContext::UnifyAccessSpecifiers(
7783               field_pos->getAccess(), nested_field_decl->getAccess()));
7784 
7785           indirect_fields.push_back(indirect_field);
7786         } else if (clang::IndirectFieldDecl *nested_indirect_field_decl =
7787                        llvm::dyn_cast<clang::IndirectFieldDecl>(*di)) {
7788           size_t nested_chain_size =
7789               nested_indirect_field_decl->getChainingSize();
7790           clang::NamedDecl **chain = new (*ast->getASTContext())
7791               clang::NamedDecl *[nested_chain_size + 1];
7792           chain[0] = *field_pos;
7793 
7794           int chain_index = 1;
7795           for (clang::IndirectFieldDecl::chain_iterator
7796                    nci = nested_indirect_field_decl->chain_begin(),
7797                    nce = nested_indirect_field_decl->chain_end();
7798                nci < nce; ++nci) {
7799             chain[chain_index] = *nci;
7800             chain_index++;
7801           }
7802 
7803           clang::IndirectFieldDecl *indirect_field =
7804               clang::IndirectFieldDecl::Create(
7805                   *ast->getASTContext(), record_decl, clang::SourceLocation(),
7806                   nested_indirect_field_decl->getIdentifier(),
7807                   nested_indirect_field_decl->getType(),
7808                   {chain, nested_chain_size + 1});
7809 
7810           indirect_field->setImplicit();
7811 
7812           indirect_field->setAccess(ClangASTContext::UnifyAccessSpecifiers(
7813               field_pos->getAccess(), nested_indirect_field_decl->getAccess()));
7814 
7815           indirect_fields.push_back(indirect_field);
7816         }
7817       }
7818     }
7819   }
7820 
7821   // Check the last field to see if it has an incomplete array type as its
7822   // last member and if it does, the tell the record decl about it
7823   if (last_field_pos != field_end_pos) {
7824     if (last_field_pos->getType()->isIncompleteArrayType())
7825       record_decl->hasFlexibleArrayMember();
7826   }
7827 
7828   for (IndirectFieldVector::iterator ifi = indirect_fields.begin(),
7829                                      ife = indirect_fields.end();
7830        ifi < ife; ++ifi) {
7831     record_decl->addDecl(*ifi);
7832   }
7833 }
7834 
7835 void ClangASTContext::SetIsPacked(const CompilerType &type) {
7836   if (type) {
7837     ClangASTContext *ast =
7838         llvm::dyn_cast<ClangASTContext>(type.GetTypeSystem());
7839     if (ast) {
7840       clang::RecordDecl *record_decl = GetAsRecordDecl(type);
7841 
7842       if (!record_decl)
7843         return;
7844 
7845       record_decl->addAttr(
7846           clang::PackedAttr::CreateImplicit(*ast->getASTContext()));
7847     }
7848   }
7849 }
7850 
7851 clang::VarDecl *ClangASTContext::AddVariableToRecordType(
7852     const CompilerType &type, const char *name, const CompilerType &var_type,
7853     AccessType access) {
7854   clang::VarDecl *var_decl = nullptr;
7855 
7856   if (!type.IsValid() || !var_type.IsValid())
7857     return nullptr;
7858   ClangASTContext *ast = llvm::dyn_cast<ClangASTContext>(type.GetTypeSystem());
7859   if (!ast)
7860     return nullptr;
7861 
7862   clang::RecordDecl *record_decl = ast->GetAsRecordDecl(type);
7863   if (record_decl) {
7864     var_decl = clang::VarDecl::Create(
7865         *ast->getASTContext(),   // ASTContext &
7866         record_decl,             // DeclContext *
7867         clang::SourceLocation(), // clang::SourceLocation StartLoc
7868         clang::SourceLocation(), // clang::SourceLocation IdLoc
7869         name ? &ast->getASTContext()->Idents.get(name)
7870              : nullptr,                   // clang::IdentifierInfo *
7871         ClangUtil::GetQualType(var_type), // Variable clang::QualType
7872         nullptr,                          // TypeSourceInfo *
7873         clang::SC_Static);                // StorageClass
7874     if (var_decl) {
7875       var_decl->setAccess(
7876           ClangASTContext::ConvertAccessTypeToAccessSpecifier(access));
7877       record_decl->addDecl(var_decl);
7878 
7879 #ifdef LLDB_CONFIGURATION_DEBUG
7880       VerifyDecl(var_decl);
7881 #endif
7882     }
7883   }
7884   return var_decl;
7885 }
7886 
7887 clang::CXXMethodDecl *ClangASTContext::AddMethodToCXXRecordType(
7888     lldb::opaque_compiler_type_t type, const char *name,
7889     const CompilerType &method_clang_type, lldb::AccessType access,
7890     bool is_virtual, bool is_static, bool is_inline, bool is_explicit,
7891     bool is_attr_used, bool is_artificial) {
7892   if (!type || !method_clang_type.IsValid() || name == nullptr ||
7893       name[0] == '\0')
7894     return nullptr;
7895 
7896   clang::QualType record_qual_type(GetCanonicalQualType(type));
7897 
7898   clang::CXXRecordDecl *cxx_record_decl =
7899       record_qual_type->getAsCXXRecordDecl();
7900 
7901   if (cxx_record_decl == nullptr)
7902     return nullptr;
7903 
7904   clang::QualType method_qual_type(ClangUtil::GetQualType(method_clang_type));
7905 
7906   clang::CXXMethodDecl *cxx_method_decl = nullptr;
7907 
7908   clang::DeclarationName decl_name(&getASTContext()->Idents.get(name));
7909 
7910   const clang::FunctionType *function_type =
7911       llvm::dyn_cast<clang::FunctionType>(method_qual_type.getTypePtr());
7912 
7913   if (function_type == nullptr)
7914     return nullptr;
7915 
7916   const clang::FunctionProtoType *method_function_prototype(
7917       llvm::dyn_cast<clang::FunctionProtoType>(function_type));
7918 
7919   if (!method_function_prototype)
7920     return nullptr;
7921 
7922   unsigned int num_params = method_function_prototype->getNumParams();
7923 
7924   clang::CXXDestructorDecl *cxx_dtor_decl(nullptr);
7925   clang::CXXConstructorDecl *cxx_ctor_decl(nullptr);
7926 
7927   if (is_artificial)
7928     return nullptr; // skip everything artificial
7929 
7930   if (name[0] == '~') {
7931     cxx_dtor_decl = clang::CXXDestructorDecl::Create(
7932         *getASTContext(), cxx_record_decl, clang::SourceLocation(),
7933         clang::DeclarationNameInfo(
7934             getASTContext()->DeclarationNames.getCXXDestructorName(
7935                 getASTContext()->getCanonicalType(record_qual_type)),
7936             clang::SourceLocation()),
7937         method_qual_type, nullptr, is_inline, is_artificial);
7938     cxx_method_decl = cxx_dtor_decl;
7939   } else if (decl_name == cxx_record_decl->getDeclName()) {
7940     cxx_ctor_decl = clang::CXXConstructorDecl::Create(
7941         *getASTContext(), cxx_record_decl, clang::SourceLocation(),
7942         clang::DeclarationNameInfo(
7943             getASTContext()->DeclarationNames.getCXXConstructorName(
7944                 getASTContext()->getCanonicalType(record_qual_type)),
7945             clang::SourceLocation()),
7946         method_qual_type,
7947         nullptr, // TypeSourceInfo *
7948         is_explicit, is_inline, is_artificial, false /*is_constexpr*/);
7949     cxx_method_decl = cxx_ctor_decl;
7950   } else {
7951     clang::StorageClass SC = is_static ? clang::SC_Static : clang::SC_None;
7952     clang::OverloadedOperatorKind op_kind = clang::NUM_OVERLOADED_OPERATORS;
7953 
7954     if (IsOperator(name, op_kind)) {
7955       if (op_kind != clang::NUM_OVERLOADED_OPERATORS) {
7956         // Check the number of operator parameters. Sometimes we have
7957         // seen bad DWARF that doesn't correctly describe operators and
7958         // if we try to create a method and add it to the class, clang
7959         // will assert and crash, so we need to make sure things are
7960         // acceptable.
7961         const bool is_method = true;
7962         if (!ClangASTContext::CheckOverloadedOperatorKindParameterCount(
7963                 is_method, op_kind, num_params))
7964           return nullptr;
7965         cxx_method_decl = clang::CXXMethodDecl::Create(
7966             *getASTContext(), cxx_record_decl, clang::SourceLocation(),
7967             clang::DeclarationNameInfo(
7968                 getASTContext()->DeclarationNames.getCXXOperatorName(op_kind),
7969                 clang::SourceLocation()),
7970             method_qual_type,
7971             nullptr, // TypeSourceInfo *
7972             SC, is_inline, false /*is_constexpr*/, clang::SourceLocation());
7973       } else if (num_params == 0) {
7974         // Conversion operators don't take params...
7975         cxx_method_decl = clang::CXXConversionDecl::Create(
7976             *getASTContext(), cxx_record_decl, clang::SourceLocation(),
7977             clang::DeclarationNameInfo(
7978                 getASTContext()->DeclarationNames.getCXXConversionFunctionName(
7979                     getASTContext()->getCanonicalType(
7980                         function_type->getReturnType())),
7981                 clang::SourceLocation()),
7982             method_qual_type,
7983             nullptr, // TypeSourceInfo *
7984             is_inline, is_explicit, false /*is_constexpr*/,
7985             clang::SourceLocation());
7986       }
7987     }
7988 
7989     if (cxx_method_decl == nullptr) {
7990       cxx_method_decl = clang::CXXMethodDecl::Create(
7991           *getASTContext(), cxx_record_decl, clang::SourceLocation(),
7992           clang::DeclarationNameInfo(decl_name, clang::SourceLocation()),
7993           method_qual_type,
7994           nullptr, // TypeSourceInfo *
7995           SC, is_inline, false /*is_constexpr*/, clang::SourceLocation());
7996     }
7997   }
7998 
7999   clang::AccessSpecifier access_specifier =
8000       ClangASTContext::ConvertAccessTypeToAccessSpecifier(access);
8001 
8002   cxx_method_decl->setAccess(access_specifier);
8003   cxx_method_decl->setVirtualAsWritten(is_virtual);
8004 
8005   if (is_attr_used)
8006     cxx_method_decl->addAttr(clang::UsedAttr::CreateImplicit(*getASTContext()));
8007 
8008   // Populate the method decl with parameter decls
8009 
8010   llvm::SmallVector<clang::ParmVarDecl *, 12> params;
8011 
8012   for (unsigned param_index = 0; param_index < num_params; ++param_index) {
8013     params.push_back(clang::ParmVarDecl::Create(
8014         *getASTContext(), cxx_method_decl, clang::SourceLocation(),
8015         clang::SourceLocation(),
8016         nullptr, // anonymous
8017         method_function_prototype->getParamType(param_index), nullptr,
8018         clang::SC_None, nullptr));
8019   }
8020 
8021   cxx_method_decl->setParams(llvm::ArrayRef<clang::ParmVarDecl *>(params));
8022 
8023   cxx_record_decl->addDecl(cxx_method_decl);
8024 
8025   // Sometimes the debug info will mention a constructor (default/copy/move),
8026   // destructor, or assignment operator (copy/move) but there won't be any
8027   // version of this in the code. So we check if the function was artificially
8028   // generated and if it is trivial and this lets the compiler/backend know
8029   // that it can inline the IR for these when it needs to and we can avoid a
8030   // "missing function" error when running expressions.
8031 
8032   if (is_artificial) {
8033     if (cxx_ctor_decl && ((cxx_ctor_decl->isDefaultConstructor() &&
8034                            cxx_record_decl->hasTrivialDefaultConstructor()) ||
8035                           (cxx_ctor_decl->isCopyConstructor() &&
8036                            cxx_record_decl->hasTrivialCopyConstructor()) ||
8037                           (cxx_ctor_decl->isMoveConstructor() &&
8038                            cxx_record_decl->hasTrivialMoveConstructor()))) {
8039       cxx_ctor_decl->setDefaulted();
8040       cxx_ctor_decl->setTrivial(true);
8041     } else if (cxx_dtor_decl) {
8042       if (cxx_record_decl->hasTrivialDestructor()) {
8043         cxx_dtor_decl->setDefaulted();
8044         cxx_dtor_decl->setTrivial(true);
8045       }
8046     } else if ((cxx_method_decl->isCopyAssignmentOperator() &&
8047                 cxx_record_decl->hasTrivialCopyAssignment()) ||
8048                (cxx_method_decl->isMoveAssignmentOperator() &&
8049                 cxx_record_decl->hasTrivialMoveAssignment())) {
8050       cxx_method_decl->setDefaulted();
8051       cxx_method_decl->setTrivial(true);
8052     }
8053   }
8054 
8055 #ifdef LLDB_CONFIGURATION_DEBUG
8056   VerifyDecl(cxx_method_decl);
8057 #endif
8058 
8059   //    printf ("decl->isPolymorphic()             = %i\n",
8060   //    cxx_record_decl->isPolymorphic());
8061   //    printf ("decl->isAggregate()               = %i\n",
8062   //    cxx_record_decl->isAggregate());
8063   //    printf ("decl->isPOD()                     = %i\n",
8064   //    cxx_record_decl->isPOD());
8065   //    printf ("decl->isEmpty()                   = %i\n",
8066   //    cxx_record_decl->isEmpty());
8067   //    printf ("decl->isAbstract()                = %i\n",
8068   //    cxx_record_decl->isAbstract());
8069   //    printf ("decl->hasTrivialConstructor()     = %i\n",
8070   //    cxx_record_decl->hasTrivialConstructor());
8071   //    printf ("decl->hasTrivialCopyConstructor() = %i\n",
8072   //    cxx_record_decl->hasTrivialCopyConstructor());
8073   //    printf ("decl->hasTrivialCopyAssignment()  = %i\n",
8074   //    cxx_record_decl->hasTrivialCopyAssignment());
8075   //    printf ("decl->hasTrivialDestructor()      = %i\n",
8076   //    cxx_record_decl->hasTrivialDestructor());
8077   return cxx_method_decl;
8078 }
8079 
8080 #pragma mark C++ Base Classes
8081 
8082 clang::CXXBaseSpecifier *
8083 ClangASTContext::CreateBaseClassSpecifier(lldb::opaque_compiler_type_t type,
8084                                           AccessType access, bool is_virtual,
8085                                           bool base_of_class) {
8086   if (type)
8087     return new clang::CXXBaseSpecifier(
8088         clang::SourceRange(), is_virtual, base_of_class,
8089         ClangASTContext::ConvertAccessTypeToAccessSpecifier(access),
8090         getASTContext()->getTrivialTypeSourceInfo(GetQualType(type)),
8091         clang::SourceLocation());
8092   return nullptr;
8093 }
8094 
8095 void ClangASTContext::DeleteBaseClassSpecifiers(
8096     clang::CXXBaseSpecifier **base_classes, unsigned num_base_classes) {
8097   for (unsigned i = 0; i < num_base_classes; ++i) {
8098     delete base_classes[i];
8099     base_classes[i] = nullptr;
8100   }
8101 }
8102 
8103 bool ClangASTContext::SetBaseClassesForClassType(
8104     lldb::opaque_compiler_type_t type,
8105     clang::CXXBaseSpecifier const *const *base_classes,
8106     unsigned num_base_classes) {
8107   if (type) {
8108     clang::CXXRecordDecl *cxx_record_decl = GetAsCXXRecordDecl(type);
8109     if (cxx_record_decl) {
8110       cxx_record_decl->setBases(base_classes, num_base_classes);
8111       return true;
8112     }
8113   }
8114   return false;
8115 }
8116 
8117 bool ClangASTContext::SetObjCSuperClass(
8118     const CompilerType &type, const CompilerType &superclass_clang_type) {
8119   ClangASTContext *ast =
8120       llvm::dyn_cast_or_null<ClangASTContext>(type.GetTypeSystem());
8121   if (!ast)
8122     return false;
8123   clang::ASTContext *clang_ast = ast->getASTContext();
8124 
8125   if (type && superclass_clang_type.IsValid() &&
8126       superclass_clang_type.GetTypeSystem() == type.GetTypeSystem()) {
8127     clang::ObjCInterfaceDecl *class_interface_decl =
8128         GetAsObjCInterfaceDecl(type);
8129     clang::ObjCInterfaceDecl *super_interface_decl =
8130         GetAsObjCInterfaceDecl(superclass_clang_type);
8131     if (class_interface_decl && super_interface_decl) {
8132       class_interface_decl->setSuperClass(clang_ast->getTrivialTypeSourceInfo(
8133           clang_ast->getObjCInterfaceType(super_interface_decl)));
8134       return true;
8135     }
8136   }
8137   return false;
8138 }
8139 
8140 bool ClangASTContext::AddObjCClassProperty(
8141     const CompilerType &type, const char *property_name,
8142     const CompilerType &property_clang_type, clang::ObjCIvarDecl *ivar_decl,
8143     const char *property_setter_name, const char *property_getter_name,
8144     uint32_t property_attributes, ClangASTMetadata *metadata) {
8145   if (!type || !property_clang_type.IsValid() || property_name == nullptr ||
8146       property_name[0] == '\0')
8147     return false;
8148   ClangASTContext *ast = llvm::dyn_cast<ClangASTContext>(type.GetTypeSystem());
8149   if (!ast)
8150     return false;
8151   clang::ASTContext *clang_ast = ast->getASTContext();
8152 
8153   clang::ObjCInterfaceDecl *class_interface_decl = GetAsObjCInterfaceDecl(type);
8154 
8155   if (class_interface_decl) {
8156     CompilerType property_clang_type_to_access;
8157 
8158     if (property_clang_type.IsValid())
8159       property_clang_type_to_access = property_clang_type;
8160     else if (ivar_decl)
8161       property_clang_type_to_access =
8162           CompilerType(clang_ast, ivar_decl->getType());
8163 
8164     if (class_interface_decl && property_clang_type_to_access.IsValid()) {
8165       clang::TypeSourceInfo *prop_type_source;
8166       if (ivar_decl)
8167         prop_type_source =
8168             clang_ast->getTrivialTypeSourceInfo(ivar_decl->getType());
8169       else
8170         prop_type_source = clang_ast->getTrivialTypeSourceInfo(
8171             ClangUtil::GetQualType(property_clang_type));
8172 
8173       clang::ObjCPropertyDecl *property_decl = clang::ObjCPropertyDecl::Create(
8174           *clang_ast, class_interface_decl,
8175           clang::SourceLocation(), // Source Location
8176           &clang_ast->Idents.get(property_name),
8177           clang::SourceLocation(), // Source Location for AT
8178           clang::SourceLocation(), // Source location for (
8179           ivar_decl ? ivar_decl->getType()
8180                     : ClangUtil::GetQualType(property_clang_type),
8181           prop_type_source);
8182 
8183       if (property_decl) {
8184         if (metadata)
8185           ClangASTContext::SetMetadata(clang_ast, property_decl, *metadata);
8186 
8187         class_interface_decl->addDecl(property_decl);
8188 
8189         clang::Selector setter_sel, getter_sel;
8190 
8191         if (property_setter_name != nullptr) {
8192           std::string property_setter_no_colon(
8193               property_setter_name, strlen(property_setter_name) - 1);
8194           clang::IdentifierInfo *setter_ident =
8195               &clang_ast->Idents.get(property_setter_no_colon);
8196           setter_sel = clang_ast->Selectors.getSelector(1, &setter_ident);
8197         } else if (!(property_attributes & DW_APPLE_PROPERTY_readonly)) {
8198           std::string setter_sel_string("set");
8199           setter_sel_string.push_back(::toupper(property_name[0]));
8200           setter_sel_string.append(&property_name[1]);
8201           clang::IdentifierInfo *setter_ident =
8202               &clang_ast->Idents.get(setter_sel_string);
8203           setter_sel = clang_ast->Selectors.getSelector(1, &setter_ident);
8204         }
8205         property_decl->setSetterName(setter_sel);
8206         property_decl->setPropertyAttributes(
8207             clang::ObjCPropertyDecl::OBJC_PR_setter);
8208 
8209         if (property_getter_name != nullptr) {
8210           clang::IdentifierInfo *getter_ident =
8211               &clang_ast->Idents.get(property_getter_name);
8212           getter_sel = clang_ast->Selectors.getSelector(0, &getter_ident);
8213         } else {
8214           clang::IdentifierInfo *getter_ident =
8215               &clang_ast->Idents.get(property_name);
8216           getter_sel = clang_ast->Selectors.getSelector(0, &getter_ident);
8217         }
8218         property_decl->setGetterName(getter_sel);
8219         property_decl->setPropertyAttributes(
8220             clang::ObjCPropertyDecl::OBJC_PR_getter);
8221 
8222         if (ivar_decl)
8223           property_decl->setPropertyIvarDecl(ivar_decl);
8224 
8225         if (property_attributes & DW_APPLE_PROPERTY_readonly)
8226           property_decl->setPropertyAttributes(
8227               clang::ObjCPropertyDecl::OBJC_PR_readonly);
8228         if (property_attributes & DW_APPLE_PROPERTY_readwrite)
8229           property_decl->setPropertyAttributes(
8230               clang::ObjCPropertyDecl::OBJC_PR_readwrite);
8231         if (property_attributes & DW_APPLE_PROPERTY_assign)
8232           property_decl->setPropertyAttributes(
8233               clang::ObjCPropertyDecl::OBJC_PR_assign);
8234         if (property_attributes & DW_APPLE_PROPERTY_retain)
8235           property_decl->setPropertyAttributes(
8236               clang::ObjCPropertyDecl::OBJC_PR_retain);
8237         if (property_attributes & DW_APPLE_PROPERTY_copy)
8238           property_decl->setPropertyAttributes(
8239               clang::ObjCPropertyDecl::OBJC_PR_copy);
8240         if (property_attributes & DW_APPLE_PROPERTY_nonatomic)
8241           property_decl->setPropertyAttributes(
8242               clang::ObjCPropertyDecl::OBJC_PR_nonatomic);
8243         if (property_attributes & clang::ObjCPropertyDecl::OBJC_PR_nullability)
8244           property_decl->setPropertyAttributes(
8245               clang::ObjCPropertyDecl::OBJC_PR_nullability);
8246         if (property_attributes &
8247             clang::ObjCPropertyDecl::OBJC_PR_null_resettable)
8248           property_decl->setPropertyAttributes(
8249               clang::ObjCPropertyDecl::OBJC_PR_null_resettable);
8250         if (property_attributes & clang::ObjCPropertyDecl::OBJC_PR_class)
8251           property_decl->setPropertyAttributes(
8252               clang::ObjCPropertyDecl::OBJC_PR_class);
8253 
8254         const bool isInstance =
8255             (property_attributes & clang::ObjCPropertyDecl::OBJC_PR_class) == 0;
8256 
8257         if (!getter_sel.isNull() &&
8258             !(isInstance
8259                   ? class_interface_decl->lookupInstanceMethod(getter_sel)
8260                   : class_interface_decl->lookupClassMethod(getter_sel))) {
8261           const bool isVariadic = false;
8262           const bool isSynthesized = false;
8263           const bool isImplicitlyDeclared = true;
8264           const bool isDefined = false;
8265           const clang::ObjCMethodDecl::ImplementationControl impControl =
8266               clang::ObjCMethodDecl::None;
8267           const bool HasRelatedResultType = false;
8268 
8269           clang::ObjCMethodDecl *getter = clang::ObjCMethodDecl::Create(
8270               *clang_ast, clang::SourceLocation(), clang::SourceLocation(),
8271               getter_sel, ClangUtil::GetQualType(property_clang_type_to_access),
8272               nullptr, class_interface_decl, isInstance, isVariadic,
8273               isSynthesized, isImplicitlyDeclared, isDefined, impControl,
8274               HasRelatedResultType);
8275 
8276           if (getter && metadata)
8277             ClangASTContext::SetMetadata(clang_ast, getter, *metadata);
8278 
8279           if (getter) {
8280             getter->setMethodParams(*clang_ast,
8281                                     llvm::ArrayRef<clang::ParmVarDecl *>(),
8282                                     llvm::ArrayRef<clang::SourceLocation>());
8283 
8284             class_interface_decl->addDecl(getter);
8285           }
8286         }
8287 
8288         if (!setter_sel.isNull() &&
8289             !(isInstance
8290                   ? class_interface_decl->lookupInstanceMethod(setter_sel)
8291                   : class_interface_decl->lookupClassMethod(setter_sel))) {
8292           clang::QualType result_type = clang_ast->VoidTy;
8293           const bool isVariadic = false;
8294           const bool isSynthesized = false;
8295           const bool isImplicitlyDeclared = true;
8296           const bool isDefined = false;
8297           const clang::ObjCMethodDecl::ImplementationControl impControl =
8298               clang::ObjCMethodDecl::None;
8299           const bool HasRelatedResultType = false;
8300 
8301           clang::ObjCMethodDecl *setter = clang::ObjCMethodDecl::Create(
8302               *clang_ast, clang::SourceLocation(), clang::SourceLocation(),
8303               setter_sel, result_type, nullptr, class_interface_decl,
8304               isInstance, isVariadic, isSynthesized, isImplicitlyDeclared,
8305               isDefined, impControl, HasRelatedResultType);
8306 
8307           if (setter && metadata)
8308             ClangASTContext::SetMetadata(clang_ast, setter, *metadata);
8309 
8310           llvm::SmallVector<clang::ParmVarDecl *, 1> params;
8311 
8312           params.push_back(clang::ParmVarDecl::Create(
8313               *clang_ast, setter, clang::SourceLocation(),
8314               clang::SourceLocation(),
8315               nullptr, // anonymous
8316               ClangUtil::GetQualType(property_clang_type_to_access), nullptr,
8317               clang::SC_Auto, nullptr));
8318 
8319           if (setter) {
8320             setter->setMethodParams(
8321                 *clang_ast, llvm::ArrayRef<clang::ParmVarDecl *>(params),
8322                 llvm::ArrayRef<clang::SourceLocation>());
8323 
8324             class_interface_decl->addDecl(setter);
8325           }
8326         }
8327 
8328         return true;
8329       }
8330     }
8331   }
8332   return false;
8333 }
8334 
8335 bool ClangASTContext::IsObjCClassTypeAndHasIVars(const CompilerType &type,
8336                                                  bool check_superclass) {
8337   clang::ObjCInterfaceDecl *class_interface_decl = GetAsObjCInterfaceDecl(type);
8338   if (class_interface_decl)
8339     return ObjCDeclHasIVars(class_interface_decl, check_superclass);
8340   return false;
8341 }
8342 
8343 clang::ObjCMethodDecl *ClangASTContext::AddMethodToObjCObjectType(
8344     const CompilerType &type,
8345     const char *name, // the full symbol name as seen in the symbol table
8346                       // (lldb::opaque_compiler_type_t type, "-[NString
8347                       // stringWithCString:]")
8348     const CompilerType &method_clang_type, lldb::AccessType access,
8349     bool is_artificial, bool is_variadic) {
8350   if (!type || !method_clang_type.IsValid())
8351     return nullptr;
8352 
8353   clang::ObjCInterfaceDecl *class_interface_decl = GetAsObjCInterfaceDecl(type);
8354 
8355   if (class_interface_decl == nullptr)
8356     return nullptr;
8357   ClangASTContext *lldb_ast =
8358       llvm::dyn_cast<ClangASTContext>(type.GetTypeSystem());
8359   if (lldb_ast == nullptr)
8360     return nullptr;
8361   clang::ASTContext *ast = lldb_ast->getASTContext();
8362 
8363   const char *selector_start = ::strchr(name, ' ');
8364   if (selector_start == nullptr)
8365     return nullptr;
8366 
8367   selector_start++;
8368   llvm::SmallVector<clang::IdentifierInfo *, 12> selector_idents;
8369 
8370   size_t len = 0;
8371   const char *start;
8372   // printf ("name = '%s'\n", name);
8373 
8374   unsigned num_selectors_with_args = 0;
8375   for (start = selector_start; start && *start != '\0' && *start != ']';
8376        start += len) {
8377     len = ::strcspn(start, ":]");
8378     bool has_arg = (start[len] == ':');
8379     if (has_arg)
8380       ++num_selectors_with_args;
8381     selector_idents.push_back(&ast->Idents.get(llvm::StringRef(start, len)));
8382     if (has_arg)
8383       len += 1;
8384   }
8385 
8386   if (selector_idents.size() == 0)
8387     return nullptr;
8388 
8389   clang::Selector method_selector = ast->Selectors.getSelector(
8390       num_selectors_with_args ? selector_idents.size() : 0,
8391       selector_idents.data());
8392 
8393   clang::QualType method_qual_type(ClangUtil::GetQualType(method_clang_type));
8394 
8395   // Populate the method decl with parameter decls
8396   const clang::Type *method_type(method_qual_type.getTypePtr());
8397 
8398   if (method_type == nullptr)
8399     return nullptr;
8400 
8401   const clang::FunctionProtoType *method_function_prototype(
8402       llvm::dyn_cast<clang::FunctionProtoType>(method_type));
8403 
8404   if (!method_function_prototype)
8405     return nullptr;
8406 
8407   bool is_synthesized = false;
8408   bool is_defined = false;
8409   clang::ObjCMethodDecl::ImplementationControl imp_control =
8410       clang::ObjCMethodDecl::None;
8411 
8412   const unsigned num_args = method_function_prototype->getNumParams();
8413 
8414   if (num_args != num_selectors_with_args)
8415     return nullptr; // some debug information is corrupt.  We are not going to
8416                     // deal with it.
8417 
8418   clang::ObjCMethodDecl *objc_method_decl = clang::ObjCMethodDecl::Create(
8419       *ast,
8420       clang::SourceLocation(), // beginLoc,
8421       clang::SourceLocation(), // endLoc,
8422       method_selector, method_function_prototype->getReturnType(),
8423       nullptr, // TypeSourceInfo *ResultTInfo,
8424       ClangASTContext::GetASTContext(ast)->GetDeclContextForType(
8425           ClangUtil::GetQualType(type)),
8426       name[0] == '-', is_variadic, is_synthesized,
8427       true, // is_implicitly_declared; we force this to true because we don't
8428             // have source locations
8429       is_defined, imp_control, false /*has_related_result_type*/);
8430 
8431   if (objc_method_decl == nullptr)
8432     return nullptr;
8433 
8434   if (num_args > 0) {
8435     llvm::SmallVector<clang::ParmVarDecl *, 12> params;
8436 
8437     for (unsigned param_index = 0; param_index < num_args; ++param_index) {
8438       params.push_back(clang::ParmVarDecl::Create(
8439           *ast, objc_method_decl, clang::SourceLocation(),
8440           clang::SourceLocation(),
8441           nullptr, // anonymous
8442           method_function_prototype->getParamType(param_index), nullptr,
8443           clang::SC_Auto, nullptr));
8444     }
8445 
8446     objc_method_decl->setMethodParams(
8447         *ast, llvm::ArrayRef<clang::ParmVarDecl *>(params),
8448         llvm::ArrayRef<clang::SourceLocation>());
8449   }
8450 
8451   class_interface_decl->addDecl(objc_method_decl);
8452 
8453 #ifdef LLDB_CONFIGURATION_DEBUG
8454   VerifyDecl(objc_method_decl);
8455 #endif
8456 
8457   return objc_method_decl;
8458 }
8459 
8460 bool ClangASTContext::GetHasExternalStorage(const CompilerType &type) {
8461   if (ClangUtil::IsClangType(type))
8462     return false;
8463 
8464   clang::QualType qual_type(ClangUtil::GetCanonicalQualType(type));
8465 
8466   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
8467   switch (type_class) {
8468   case clang::Type::Record: {
8469     clang::CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
8470     if (cxx_record_decl)
8471       return cxx_record_decl->hasExternalLexicalStorage() ||
8472              cxx_record_decl->hasExternalVisibleStorage();
8473   } break;
8474 
8475   case clang::Type::Enum: {
8476     clang::EnumDecl *enum_decl =
8477         llvm::cast<clang::EnumType>(qual_type)->getDecl();
8478     if (enum_decl)
8479       return enum_decl->hasExternalLexicalStorage() ||
8480              enum_decl->hasExternalVisibleStorage();
8481   } break;
8482 
8483   case clang::Type::ObjCObject:
8484   case clang::Type::ObjCInterface: {
8485     const clang::ObjCObjectType *objc_class_type =
8486         llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
8487     assert(objc_class_type);
8488     if (objc_class_type) {
8489       clang::ObjCInterfaceDecl *class_interface_decl =
8490           objc_class_type->getInterface();
8491 
8492       if (class_interface_decl)
8493         return class_interface_decl->hasExternalLexicalStorage() ||
8494                class_interface_decl->hasExternalVisibleStorage();
8495     }
8496   } break;
8497 
8498   case clang::Type::Typedef:
8499     return GetHasExternalStorage(CompilerType(
8500         type.GetTypeSystem(), llvm::cast<clang::TypedefType>(qual_type)
8501                                   ->getDecl()
8502                                   ->getUnderlyingType()
8503                                   .getAsOpaquePtr()));
8504 
8505   case clang::Type::Auto:
8506     return GetHasExternalStorage(CompilerType(
8507         type.GetTypeSystem(), llvm::cast<clang::AutoType>(qual_type)
8508                                   ->getDeducedType()
8509                                   .getAsOpaquePtr()));
8510 
8511   case clang::Type::Elaborated:
8512     return GetHasExternalStorage(CompilerType(
8513         type.GetTypeSystem(), llvm::cast<clang::ElaboratedType>(qual_type)
8514                                   ->getNamedType()
8515                                   .getAsOpaquePtr()));
8516 
8517   case clang::Type::Paren:
8518     return GetHasExternalStorage(CompilerType(
8519         type.GetTypeSystem(),
8520         llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr()));
8521 
8522   default:
8523     break;
8524   }
8525   return false;
8526 }
8527 
8528 bool ClangASTContext::SetHasExternalStorage(lldb::opaque_compiler_type_t type,
8529                                             bool has_extern) {
8530   if (!type)
8531     return false;
8532 
8533   clang::QualType qual_type(GetCanonicalQualType(type));
8534 
8535   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
8536   switch (type_class) {
8537   case clang::Type::Record: {
8538     clang::CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
8539     if (cxx_record_decl) {
8540       cxx_record_decl->setHasExternalLexicalStorage(has_extern);
8541       cxx_record_decl->setHasExternalVisibleStorage(has_extern);
8542       return true;
8543     }
8544   } break;
8545 
8546   case clang::Type::Enum: {
8547     clang::EnumDecl *enum_decl =
8548         llvm::cast<clang::EnumType>(qual_type)->getDecl();
8549     if (enum_decl) {
8550       enum_decl->setHasExternalLexicalStorage(has_extern);
8551       enum_decl->setHasExternalVisibleStorage(has_extern);
8552       return true;
8553     }
8554   } break;
8555 
8556   case clang::Type::ObjCObject:
8557   case clang::Type::ObjCInterface: {
8558     const clang::ObjCObjectType *objc_class_type =
8559         llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
8560     assert(objc_class_type);
8561     if (objc_class_type) {
8562       clang::ObjCInterfaceDecl *class_interface_decl =
8563           objc_class_type->getInterface();
8564 
8565       if (class_interface_decl) {
8566         class_interface_decl->setHasExternalLexicalStorage(has_extern);
8567         class_interface_decl->setHasExternalVisibleStorage(has_extern);
8568         return true;
8569       }
8570     }
8571   } break;
8572 
8573   case clang::Type::Typedef:
8574     return SetHasExternalStorage(llvm::cast<clang::TypedefType>(qual_type)
8575                                      ->getDecl()
8576                                      ->getUnderlyingType()
8577                                      .getAsOpaquePtr(),
8578                                  has_extern);
8579 
8580   case clang::Type::Auto:
8581     return SetHasExternalStorage(llvm::cast<clang::AutoType>(qual_type)
8582                                      ->getDeducedType()
8583                                      .getAsOpaquePtr(),
8584                                  has_extern);
8585 
8586   case clang::Type::Elaborated:
8587     return SetHasExternalStorage(llvm::cast<clang::ElaboratedType>(qual_type)
8588                                      ->getNamedType()
8589                                      .getAsOpaquePtr(),
8590                                  has_extern);
8591 
8592   case clang::Type::Paren:
8593     return SetHasExternalStorage(
8594         llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr(),
8595         has_extern);
8596 
8597   default:
8598     break;
8599   }
8600   return false;
8601 }
8602 
8603 #pragma mark TagDecl
8604 
8605 bool ClangASTContext::StartTagDeclarationDefinition(const CompilerType &type) {
8606   clang::QualType qual_type(ClangUtil::GetQualType(type));
8607   if (!qual_type.isNull()) {
8608     const clang::TagType *tag_type = qual_type->getAs<clang::TagType>();
8609     if (tag_type) {
8610       clang::TagDecl *tag_decl = tag_type->getDecl();
8611       if (tag_decl) {
8612         tag_decl->startDefinition();
8613         return true;
8614       }
8615     }
8616 
8617     const clang::ObjCObjectType *object_type =
8618         qual_type->getAs<clang::ObjCObjectType>();
8619     if (object_type) {
8620       clang::ObjCInterfaceDecl *interface_decl = object_type->getInterface();
8621       if (interface_decl) {
8622         interface_decl->startDefinition();
8623         return true;
8624       }
8625     }
8626   }
8627   return false;
8628 }
8629 
8630 bool ClangASTContext::CompleteTagDeclarationDefinition(
8631     const CompilerType &type) {
8632   clang::QualType qual_type(ClangUtil::GetQualType(type));
8633   if (!qual_type.isNull()) {
8634     // Make sure we use the same methodology as
8635     // ClangASTContext::StartTagDeclarationDefinition()
8636     // as to how we start/end the definition. Previously we were calling
8637     const clang::TagType *tag_type = qual_type->getAs<clang::TagType>();
8638     if (tag_type) {
8639       clang::TagDecl *tag_decl = tag_type->getDecl();
8640       if (tag_decl) {
8641         clang::CXXRecordDecl *cxx_record_decl =
8642             llvm::dyn_cast_or_null<clang::CXXRecordDecl>(tag_decl);
8643 
8644         if (cxx_record_decl) {
8645           if (!cxx_record_decl->isCompleteDefinition())
8646             cxx_record_decl->completeDefinition();
8647           cxx_record_decl->setHasLoadedFieldsFromExternalStorage(true);
8648           cxx_record_decl->setHasExternalLexicalStorage(false);
8649           cxx_record_decl->setHasExternalVisibleStorage(false);
8650           return true;
8651         }
8652       }
8653     }
8654 
8655     const clang::EnumType *enutype = qual_type->getAs<clang::EnumType>();
8656 
8657     if (enutype) {
8658       clang::EnumDecl *enum_decl = enutype->getDecl();
8659 
8660       if (enum_decl) {
8661         if (!enum_decl->isCompleteDefinition()) {
8662           ClangASTContext *lldb_ast =
8663               llvm::dyn_cast<ClangASTContext>(type.GetTypeSystem());
8664           if (lldb_ast == nullptr)
8665             return false;
8666           clang::ASTContext *ast = lldb_ast->getASTContext();
8667 
8668           /// TODO This really needs to be fixed.
8669 
8670           QualType integer_type(enum_decl->getIntegerType());
8671           if (!integer_type.isNull()) {
8672             unsigned NumPositiveBits = 1;
8673             unsigned NumNegativeBits = 0;
8674 
8675             clang::QualType promotion_qual_type;
8676             // If the enum integer type is less than an integer in bit width,
8677             // then we must promote it to an integer size.
8678             if (ast->getTypeSize(enum_decl->getIntegerType()) <
8679                 ast->getTypeSize(ast->IntTy)) {
8680               if (enum_decl->getIntegerType()->isSignedIntegerType())
8681                 promotion_qual_type = ast->IntTy;
8682               else
8683                 promotion_qual_type = ast->UnsignedIntTy;
8684             } else
8685               promotion_qual_type = enum_decl->getIntegerType();
8686 
8687             enum_decl->completeDefinition(enum_decl->getIntegerType(),
8688                                           promotion_qual_type, NumPositiveBits,
8689                                           NumNegativeBits);
8690           }
8691         }
8692         return true;
8693       }
8694     }
8695   }
8696   return false;
8697 }
8698 
8699 bool ClangASTContext::AddEnumerationValueToEnumerationType(
8700     lldb::opaque_compiler_type_t type,
8701     const CompilerType &enumerator_clang_type, const Declaration &decl,
8702     const char *name, int64_t enum_value, uint32_t enum_value_bit_size) {
8703   if (type && enumerator_clang_type.IsValid() && name && name[0]) {
8704     clang::QualType enum_qual_type(GetCanonicalQualType(type));
8705 
8706     bool is_signed = false;
8707     enumerator_clang_type.IsIntegerType(is_signed);
8708     const clang::Type *clang_type = enum_qual_type.getTypePtr();
8709     if (clang_type) {
8710       const clang::EnumType *enutype =
8711           llvm::dyn_cast<clang::EnumType>(clang_type);
8712 
8713       if (enutype) {
8714         llvm::APSInt enum_llvm_apsint(enum_value_bit_size, is_signed);
8715         enum_llvm_apsint = enum_value;
8716         clang::EnumConstantDecl *enumerator_decl =
8717             clang::EnumConstantDecl::Create(
8718                 *getASTContext(), enutype->getDecl(), clang::SourceLocation(),
8719                 name ? &getASTContext()->Idents.get(name)
8720                      : nullptr, // Identifier
8721                 ClangUtil::GetQualType(enumerator_clang_type),
8722                 nullptr, enum_llvm_apsint);
8723 
8724         if (enumerator_decl) {
8725           enutype->getDecl()->addDecl(enumerator_decl);
8726 
8727 #ifdef LLDB_CONFIGURATION_DEBUG
8728           VerifyDecl(enumerator_decl);
8729 #endif
8730 
8731           return true;
8732         }
8733       }
8734     }
8735   }
8736   return false;
8737 }
8738 
8739 CompilerType
8740 ClangASTContext::GetEnumerationIntegerType(lldb::opaque_compiler_type_t type) {
8741   clang::QualType enum_qual_type(GetCanonicalQualType(type));
8742   const clang::Type *clang_type = enum_qual_type.getTypePtr();
8743   if (clang_type) {
8744     const clang::EnumType *enutype =
8745         llvm::dyn_cast<clang::EnumType>(clang_type);
8746     if (enutype) {
8747       clang::EnumDecl *enum_decl = enutype->getDecl();
8748       if (enum_decl)
8749         return CompilerType(getASTContext(), enum_decl->getIntegerType());
8750     }
8751   }
8752   return CompilerType();
8753 }
8754 
8755 CompilerType
8756 ClangASTContext::CreateMemberPointerType(const CompilerType &type,
8757                                          const CompilerType &pointee_type) {
8758   if (type && pointee_type.IsValid() &&
8759       type.GetTypeSystem() == pointee_type.GetTypeSystem()) {
8760     ClangASTContext *ast =
8761         llvm::dyn_cast<ClangASTContext>(type.GetTypeSystem());
8762     if (!ast)
8763       return CompilerType();
8764     return CompilerType(ast->getASTContext(),
8765                         ast->getASTContext()->getMemberPointerType(
8766                             ClangUtil::GetQualType(pointee_type),
8767                             ClangUtil::GetQualType(type).getTypePtr()));
8768   }
8769   return CompilerType();
8770 }
8771 
8772 size_t
8773 ClangASTContext::ConvertStringToFloatValue(lldb::opaque_compiler_type_t type,
8774                                            const char *s, uint8_t *dst,
8775                                            size_t dst_size) {
8776   if (type) {
8777     clang::QualType qual_type(GetCanonicalQualType(type));
8778     uint32_t count = 0;
8779     bool is_complex = false;
8780     if (IsFloatingPointType(type, count, is_complex)) {
8781       // TODO: handle complex and vector types
8782       if (count != 1)
8783         return false;
8784 
8785       llvm::StringRef s_sref(s);
8786       llvm::APFloat ap_float(getASTContext()->getFloatTypeSemantics(qual_type),
8787                              s_sref);
8788 
8789       const uint64_t bit_size = getASTContext()->getTypeSize(qual_type);
8790       const uint64_t byte_size = bit_size / 8;
8791       if (dst_size >= byte_size) {
8792         Scalar scalar = ap_float.bitcastToAPInt().zextOrTrunc(
8793             llvm::NextPowerOf2(byte_size) * 8);
8794         lldb_private::Status get_data_error;
8795         if (scalar.GetAsMemoryData(dst, byte_size,
8796                                    lldb_private::endian::InlHostByteOrder(),
8797                                    get_data_error))
8798           return byte_size;
8799       }
8800     }
8801   }
8802   return 0;
8803 }
8804 
8805 //----------------------------------------------------------------------
8806 // Dumping types
8807 //----------------------------------------------------------------------
8808 #define DEPTH_INCREMENT 2
8809 
8810 void ClangASTContext::DumpValue(
8811     lldb::opaque_compiler_type_t type, ExecutionContext *exe_ctx, Stream *s,
8812     lldb::Format format, const DataExtractor &data,
8813     lldb::offset_t data_byte_offset, size_t data_byte_size,
8814     uint32_t bitfield_bit_size, uint32_t bitfield_bit_offset, bool show_types,
8815     bool show_summary, bool verbose, uint32_t depth) {
8816   if (!type)
8817     return;
8818 
8819   clang::QualType qual_type(GetQualType(type));
8820   switch (qual_type->getTypeClass()) {
8821   case clang::Type::Record:
8822     if (GetCompleteType(type)) {
8823       const clang::RecordType *record_type =
8824           llvm::cast<clang::RecordType>(qual_type.getTypePtr());
8825       const clang::RecordDecl *record_decl = record_type->getDecl();
8826       assert(record_decl);
8827       uint32_t field_bit_offset = 0;
8828       uint32_t field_byte_offset = 0;
8829       const clang::ASTRecordLayout &record_layout =
8830           getASTContext()->getASTRecordLayout(record_decl);
8831       uint32_t child_idx = 0;
8832 
8833       const clang::CXXRecordDecl *cxx_record_decl =
8834           llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
8835       if (cxx_record_decl) {
8836         // We might have base classes to print out first
8837         clang::CXXRecordDecl::base_class_const_iterator base_class,
8838             base_class_end;
8839         for (base_class = cxx_record_decl->bases_begin(),
8840             base_class_end = cxx_record_decl->bases_end();
8841              base_class != base_class_end; ++base_class) {
8842           const clang::CXXRecordDecl *base_class_decl =
8843               llvm::cast<clang::CXXRecordDecl>(
8844                   base_class->getType()->getAs<clang::RecordType>()->getDecl());
8845 
8846           // Skip empty base classes
8847           if (verbose == false &&
8848               ClangASTContext::RecordHasFields(base_class_decl) == false)
8849             continue;
8850 
8851           if (base_class->isVirtual())
8852             field_bit_offset =
8853                 record_layout.getVBaseClassOffset(base_class_decl)
8854                     .getQuantity() *
8855                 8;
8856           else
8857             field_bit_offset = record_layout.getBaseClassOffset(base_class_decl)
8858                                    .getQuantity() *
8859                                8;
8860           field_byte_offset = field_bit_offset / 8;
8861           assert(field_bit_offset % 8 == 0);
8862           if (child_idx == 0)
8863             s->PutChar('{');
8864           else
8865             s->PutChar(',');
8866 
8867           clang::QualType base_class_qual_type = base_class->getType();
8868           std::string base_class_type_name(base_class_qual_type.getAsString());
8869 
8870           // Indent and print the base class type name
8871           s->Format("\n{0}{1}", llvm::fmt_repeat(" ", depth + DEPTH_INCREMENT),
8872                     base_class_type_name);
8873 
8874           clang::TypeInfo base_class_type_info =
8875               getASTContext()->getTypeInfo(base_class_qual_type);
8876 
8877           // Dump the value of the member
8878           CompilerType base_clang_type(getASTContext(), base_class_qual_type);
8879           base_clang_type.DumpValue(
8880               exe_ctx,
8881               s, // Stream to dump to
8882               base_clang_type
8883                   .GetFormat(), // The format with which to display the member
8884               data, // Data buffer containing all bytes for this type
8885               data_byte_offset + field_byte_offset, // Offset into "data" where
8886                                                     // to grab value from
8887               base_class_type_info.Width / 8, // Size of this type in bytes
8888               0,                              // Bitfield bit size
8889               0,                              // Bitfield bit offset
8890               show_types,   // Boolean indicating if we should show the variable
8891                             // types
8892               show_summary, // Boolean indicating if we should show a summary
8893                             // for the current type
8894               verbose,      // Verbose output?
8895               depth + DEPTH_INCREMENT); // Scope depth for any types that have
8896                                         // children
8897 
8898           ++child_idx;
8899         }
8900       }
8901       uint32_t field_idx = 0;
8902       clang::RecordDecl::field_iterator field, field_end;
8903       for (field = record_decl->field_begin(),
8904           field_end = record_decl->field_end();
8905            field != field_end; ++field, ++field_idx, ++child_idx) {
8906         // Print the starting squiggly bracket (if this is the
8907         // first member) or comma (for member 2 and beyond) for
8908         // the struct/union/class member.
8909         if (child_idx == 0)
8910           s->PutChar('{');
8911         else
8912           s->PutChar(',');
8913 
8914         // Indent
8915         s->Printf("\n%*s", depth + DEPTH_INCREMENT, "");
8916 
8917         clang::QualType field_type = field->getType();
8918         // Print the member type if requested
8919         // Figure out the type byte size (field_type_info.first) and
8920         // alignment (field_type_info.second) from the AST context.
8921         clang::TypeInfo field_type_info =
8922             getASTContext()->getTypeInfo(field_type);
8923         assert(field_idx < record_layout.getFieldCount());
8924         // Figure out the field offset within the current struct/union/class
8925         // type
8926         field_bit_offset = record_layout.getFieldOffset(field_idx);
8927         field_byte_offset = field_bit_offset / 8;
8928         uint32_t field_bitfield_bit_size = 0;
8929         uint32_t field_bitfield_bit_offset = 0;
8930         if (ClangASTContext::FieldIsBitfield(getASTContext(), *field,
8931                                              field_bitfield_bit_size))
8932           field_bitfield_bit_offset = field_bit_offset % 8;
8933 
8934         if (show_types) {
8935           std::string field_type_name(field_type.getAsString());
8936           if (field_bitfield_bit_size > 0)
8937             s->Printf("(%s:%u) ", field_type_name.c_str(),
8938                       field_bitfield_bit_size);
8939           else
8940             s->Printf("(%s) ", field_type_name.c_str());
8941         }
8942         // Print the member name and equal sign
8943         s->Printf("%s = ", field->getNameAsString().c_str());
8944 
8945         // Dump the value of the member
8946         CompilerType field_clang_type(getASTContext(), field_type);
8947         field_clang_type.DumpValue(
8948             exe_ctx,
8949             s, // Stream to dump to
8950             field_clang_type
8951                 .GetFormat(), // The format with which to display the member
8952             data,             // Data buffer containing all bytes for this type
8953             data_byte_offset + field_byte_offset, // Offset into "data" where to
8954                                                   // grab value from
8955             field_type_info.Width / 8,            // Size of this type in bytes
8956             field_bitfield_bit_size,              // Bitfield bit size
8957             field_bitfield_bit_offset,            // Bitfield bit offset
8958             show_types,   // Boolean indicating if we should show the variable
8959                           // types
8960             show_summary, // Boolean indicating if we should show a summary for
8961                           // the current type
8962             verbose,      // Verbose output?
8963             depth + DEPTH_INCREMENT); // Scope depth for any types that have
8964                                       // children
8965       }
8966 
8967       // Indent the trailing squiggly bracket
8968       if (child_idx > 0)
8969         s->Printf("\n%*s}", depth, "");
8970     }
8971     return;
8972 
8973   case clang::Type::Enum:
8974     if (GetCompleteType(type)) {
8975       const clang::EnumType *enutype =
8976           llvm::cast<clang::EnumType>(qual_type.getTypePtr());
8977       const clang::EnumDecl *enum_decl = enutype->getDecl();
8978       assert(enum_decl);
8979       clang::EnumDecl::enumerator_iterator enum_pos, enum_end_pos;
8980       lldb::offset_t offset = data_byte_offset;
8981       const int64_t enum_value = data.GetMaxU64Bitfield(
8982           &offset, data_byte_size, bitfield_bit_size, bitfield_bit_offset);
8983       for (enum_pos = enum_decl->enumerator_begin(),
8984           enum_end_pos = enum_decl->enumerator_end();
8985            enum_pos != enum_end_pos; ++enum_pos) {
8986         if (enum_pos->getInitVal() == enum_value) {
8987           s->Printf("%s", enum_pos->getNameAsString().c_str());
8988           return;
8989         }
8990       }
8991       // If we have gotten here we didn't get find the enumerator in the
8992       // enum decl, so just print the integer.
8993       s->Printf("%" PRIi64, enum_value);
8994     }
8995     return;
8996 
8997   case clang::Type::ConstantArray: {
8998     const clang::ConstantArrayType *array =
8999         llvm::cast<clang::ConstantArrayType>(qual_type.getTypePtr());
9000     bool is_array_of_characters = false;
9001     clang::QualType element_qual_type = array->getElementType();
9002 
9003     const clang::Type *canonical_type =
9004         element_qual_type->getCanonicalTypeInternal().getTypePtr();
9005     if (canonical_type)
9006       is_array_of_characters = canonical_type->isCharType();
9007 
9008     const uint64_t element_count = array->getSize().getLimitedValue();
9009 
9010     clang::TypeInfo field_type_info =
9011         getASTContext()->getTypeInfo(element_qual_type);
9012 
9013     uint32_t element_idx = 0;
9014     uint32_t element_offset = 0;
9015     uint64_t element_byte_size = field_type_info.Width / 8;
9016     uint32_t element_stride = element_byte_size;
9017 
9018     if (is_array_of_characters) {
9019       s->PutChar('"');
9020       DumpDataExtractor(data, s, data_byte_offset, lldb::eFormatChar,
9021                         element_byte_size, element_count, UINT32_MAX,
9022                         LLDB_INVALID_ADDRESS, 0, 0);
9023       s->PutChar('"');
9024       return;
9025     } else {
9026       CompilerType element_clang_type(getASTContext(), element_qual_type);
9027       lldb::Format element_format = element_clang_type.GetFormat();
9028 
9029       for (element_idx = 0; element_idx < element_count; ++element_idx) {
9030         // Print the starting squiggly bracket (if this is the
9031         // first member) or comman (for member 2 and beyong) for
9032         // the struct/union/class member.
9033         if (element_idx == 0)
9034           s->PutChar('{');
9035         else
9036           s->PutChar(',');
9037 
9038         // Indent and print the index
9039         s->Printf("\n%*s[%u] ", depth + DEPTH_INCREMENT, "", element_idx);
9040 
9041         // Figure out the field offset within the current struct/union/class
9042         // type
9043         element_offset = element_idx * element_stride;
9044 
9045         // Dump the value of the member
9046         element_clang_type.DumpValue(
9047             exe_ctx,
9048             s,              // Stream to dump to
9049             element_format, // The format with which to display the element
9050             data,           // Data buffer containing all bytes for this type
9051             data_byte_offset +
9052                 element_offset, // Offset into "data" where to grab value from
9053             element_byte_size,  // Size of this type in bytes
9054             0,                  // Bitfield bit size
9055             0,                  // Bitfield bit offset
9056             show_types,   // Boolean indicating if we should show the variable
9057                           // types
9058             show_summary, // Boolean indicating if we should show a summary for
9059                           // the current type
9060             verbose,      // Verbose output?
9061             depth + DEPTH_INCREMENT); // Scope depth for any types that have
9062                                       // children
9063       }
9064 
9065       // Indent the trailing squiggly bracket
9066       if (element_idx > 0)
9067         s->Printf("\n%*s}", depth, "");
9068     }
9069   }
9070     return;
9071 
9072   case clang::Type::Typedef: {
9073     clang::QualType typedef_qual_type =
9074         llvm::cast<clang::TypedefType>(qual_type)
9075             ->getDecl()
9076             ->getUnderlyingType();
9077 
9078     CompilerType typedef_clang_type(getASTContext(), typedef_qual_type);
9079     lldb::Format typedef_format = typedef_clang_type.GetFormat();
9080     clang::TypeInfo typedef_type_info =
9081         getASTContext()->getTypeInfo(typedef_qual_type);
9082     uint64_t typedef_byte_size = typedef_type_info.Width / 8;
9083 
9084     return typedef_clang_type.DumpValue(
9085         exe_ctx,
9086         s,                   // Stream to dump to
9087         typedef_format,      // The format with which to display the element
9088         data,                // Data buffer containing all bytes for this type
9089         data_byte_offset,    // Offset into "data" where to grab value from
9090         typedef_byte_size,   // Size of this type in bytes
9091         bitfield_bit_size,   // Bitfield bit size
9092         bitfield_bit_offset, // Bitfield bit offset
9093         show_types,   // Boolean indicating if we should show the variable types
9094         show_summary, // Boolean indicating if we should show a summary for the
9095                       // current type
9096         verbose,      // Verbose output?
9097         depth);       // Scope depth for any types that have children
9098   } break;
9099 
9100   case clang::Type::Auto: {
9101     clang::QualType elaborated_qual_type =
9102         llvm::cast<clang::AutoType>(qual_type)->getDeducedType();
9103     CompilerType elaborated_clang_type(getASTContext(), elaborated_qual_type);
9104     lldb::Format elaborated_format = elaborated_clang_type.GetFormat();
9105     clang::TypeInfo elaborated_type_info =
9106         getASTContext()->getTypeInfo(elaborated_qual_type);
9107     uint64_t elaborated_byte_size = elaborated_type_info.Width / 8;
9108 
9109     return elaborated_clang_type.DumpValue(
9110         exe_ctx,
9111         s,                    // Stream to dump to
9112         elaborated_format,    // The format with which to display the element
9113         data,                 // Data buffer containing all bytes for this type
9114         data_byte_offset,     // Offset into "data" where to grab value from
9115         elaborated_byte_size, // Size of this type in bytes
9116         bitfield_bit_size,    // Bitfield bit size
9117         bitfield_bit_offset,  // Bitfield bit offset
9118         show_types,   // Boolean indicating if we should show the variable types
9119         show_summary, // Boolean indicating if we should show a summary for the
9120                       // current type
9121         verbose,      // Verbose output?
9122         depth);       // Scope depth for any types that have children
9123   } break;
9124 
9125   case clang::Type::Elaborated: {
9126     clang::QualType elaborated_qual_type =
9127         llvm::cast<clang::ElaboratedType>(qual_type)->getNamedType();
9128     CompilerType elaborated_clang_type(getASTContext(), elaborated_qual_type);
9129     lldb::Format elaborated_format = elaborated_clang_type.GetFormat();
9130     clang::TypeInfo elaborated_type_info =
9131         getASTContext()->getTypeInfo(elaborated_qual_type);
9132     uint64_t elaborated_byte_size = elaborated_type_info.Width / 8;
9133 
9134     return elaborated_clang_type.DumpValue(
9135         exe_ctx,
9136         s,                    // Stream to dump to
9137         elaborated_format,    // The format with which to display the element
9138         data,                 // Data buffer containing all bytes for this type
9139         data_byte_offset,     // Offset into "data" where to grab value from
9140         elaborated_byte_size, // Size of this type in bytes
9141         bitfield_bit_size,    // Bitfield bit size
9142         bitfield_bit_offset,  // Bitfield bit offset
9143         show_types,   // Boolean indicating if we should show the variable types
9144         show_summary, // Boolean indicating if we should show a summary for the
9145                       // current type
9146         verbose,      // Verbose output?
9147         depth);       // Scope depth for any types that have children
9148   } break;
9149 
9150   case clang::Type::Paren: {
9151     clang::QualType desugar_qual_type =
9152         llvm::cast<clang::ParenType>(qual_type)->desugar();
9153     CompilerType desugar_clang_type(getASTContext(), desugar_qual_type);
9154 
9155     lldb::Format desugar_format = desugar_clang_type.GetFormat();
9156     clang::TypeInfo desugar_type_info =
9157         getASTContext()->getTypeInfo(desugar_qual_type);
9158     uint64_t desugar_byte_size = desugar_type_info.Width / 8;
9159 
9160     return desugar_clang_type.DumpValue(
9161         exe_ctx,
9162         s,                   // Stream to dump to
9163         desugar_format,      // The format with which to display the element
9164         data,                // Data buffer containing all bytes for this type
9165         data_byte_offset,    // Offset into "data" where to grab value from
9166         desugar_byte_size,   // Size of this type in bytes
9167         bitfield_bit_size,   // Bitfield bit size
9168         bitfield_bit_offset, // Bitfield bit offset
9169         show_types,   // Boolean indicating if we should show the variable types
9170         show_summary, // Boolean indicating if we should show a summary for the
9171                       // current type
9172         verbose,      // Verbose output?
9173         depth);       // Scope depth for any types that have children
9174   } break;
9175 
9176   default:
9177     // We are down to a scalar type that we just need to display.
9178     DumpDataExtractor(data, s, data_byte_offset, format, data_byte_size, 1,
9179                       UINT32_MAX, LLDB_INVALID_ADDRESS, bitfield_bit_size,
9180                       bitfield_bit_offset);
9181 
9182     if (show_summary)
9183       DumpSummary(type, exe_ctx, s, data, data_byte_offset, data_byte_size);
9184     break;
9185   }
9186 }
9187 
9188 bool ClangASTContext::DumpTypeValue(
9189     lldb::opaque_compiler_type_t type, Stream *s, lldb::Format format,
9190     const DataExtractor &data, lldb::offset_t byte_offset, size_t byte_size,
9191     uint32_t bitfield_bit_size, uint32_t bitfield_bit_offset,
9192     ExecutionContextScope *exe_scope) {
9193   if (!type)
9194     return false;
9195   if (IsAggregateType(type)) {
9196     return false;
9197   } else {
9198     clang::QualType qual_type(GetQualType(type));
9199 
9200     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
9201     switch (type_class) {
9202     case clang::Type::Typedef: {
9203       clang::QualType typedef_qual_type =
9204           llvm::cast<clang::TypedefType>(qual_type)
9205               ->getDecl()
9206               ->getUnderlyingType();
9207       CompilerType typedef_clang_type(getASTContext(), typedef_qual_type);
9208       if (format == eFormatDefault)
9209         format = typedef_clang_type.GetFormat();
9210       clang::TypeInfo typedef_type_info =
9211           getASTContext()->getTypeInfo(typedef_qual_type);
9212       uint64_t typedef_byte_size = typedef_type_info.Width / 8;
9213 
9214       return typedef_clang_type.DumpTypeValue(
9215           s,
9216           format,            // The format with which to display the element
9217           data,              // Data buffer containing all bytes for this type
9218           byte_offset,       // Offset into "data" where to grab value from
9219           typedef_byte_size, // Size of this type in bytes
9220           bitfield_bit_size, // Size in bits of a bitfield value, if zero don't
9221                              // treat as a bitfield
9222           bitfield_bit_offset, // Offset in bits of a bitfield value if
9223                                // bitfield_bit_size != 0
9224           exe_scope);
9225     } break;
9226 
9227     case clang::Type::Enum:
9228       // If our format is enum or default, show the enumeration value as
9229       // its enumeration string value, else just display it as requested.
9230       if ((format == eFormatEnum || format == eFormatDefault) &&
9231           GetCompleteType(type)) {
9232         const clang::EnumType *enutype =
9233             llvm::cast<clang::EnumType>(qual_type.getTypePtr());
9234         const clang::EnumDecl *enum_decl = enutype->getDecl();
9235         assert(enum_decl);
9236         clang::EnumDecl::enumerator_iterator enum_pos, enum_end_pos;
9237         const bool is_signed = qual_type->isSignedIntegerOrEnumerationType();
9238         lldb::offset_t offset = byte_offset;
9239         if (is_signed) {
9240           const int64_t enum_svalue = data.GetMaxS64Bitfield(
9241               &offset, byte_size, bitfield_bit_size, bitfield_bit_offset);
9242           for (enum_pos = enum_decl->enumerator_begin(),
9243               enum_end_pos = enum_decl->enumerator_end();
9244                enum_pos != enum_end_pos; ++enum_pos) {
9245             if (enum_pos->getInitVal().getSExtValue() == enum_svalue) {
9246               s->PutCString(enum_pos->getNameAsString());
9247               return true;
9248             }
9249           }
9250           // If we have gotten here we didn't get find the enumerator in the
9251           // enum decl, so just print the integer.
9252           s->Printf("%" PRIi64, enum_svalue);
9253         } else {
9254           const uint64_t enum_uvalue = data.GetMaxU64Bitfield(
9255               &offset, byte_size, bitfield_bit_size, bitfield_bit_offset);
9256           for (enum_pos = enum_decl->enumerator_begin(),
9257               enum_end_pos = enum_decl->enumerator_end();
9258                enum_pos != enum_end_pos; ++enum_pos) {
9259             if (enum_pos->getInitVal().getZExtValue() == enum_uvalue) {
9260               s->PutCString(enum_pos->getNameAsString());
9261               return true;
9262             }
9263           }
9264           // If we have gotten here we didn't get find the enumerator in the
9265           // enum decl, so just print the integer.
9266           s->Printf("%" PRIu64, enum_uvalue);
9267         }
9268         return true;
9269       }
9270       // format was not enum, just fall through and dump the value as
9271       // requested....
9272       LLVM_FALLTHROUGH;
9273 
9274     default:
9275       // We are down to a scalar type that we just need to display.
9276       {
9277         uint32_t item_count = 1;
9278         // A few formats, we might need to modify our size and count for
9279         // depending
9280         // on how we are trying to display the value...
9281         switch (format) {
9282         default:
9283         case eFormatBoolean:
9284         case eFormatBinary:
9285         case eFormatComplex:
9286         case eFormatCString: // NULL terminated C strings
9287         case eFormatDecimal:
9288         case eFormatEnum:
9289         case eFormatHex:
9290         case eFormatHexUppercase:
9291         case eFormatFloat:
9292         case eFormatOctal:
9293         case eFormatOSType:
9294         case eFormatUnsigned:
9295         case eFormatPointer:
9296         case eFormatVectorOfChar:
9297         case eFormatVectorOfSInt8:
9298         case eFormatVectorOfUInt8:
9299         case eFormatVectorOfSInt16:
9300         case eFormatVectorOfUInt16:
9301         case eFormatVectorOfSInt32:
9302         case eFormatVectorOfUInt32:
9303         case eFormatVectorOfSInt64:
9304         case eFormatVectorOfUInt64:
9305         case eFormatVectorOfFloat32:
9306         case eFormatVectorOfFloat64:
9307         case eFormatVectorOfUInt128:
9308           break;
9309 
9310         case eFormatChar:
9311         case eFormatCharPrintable:
9312         case eFormatCharArray:
9313         case eFormatBytes:
9314         case eFormatBytesWithASCII:
9315           item_count = byte_size;
9316           byte_size = 1;
9317           break;
9318 
9319         case eFormatUnicode16:
9320           item_count = byte_size / 2;
9321           byte_size = 2;
9322           break;
9323 
9324         case eFormatUnicode32:
9325           item_count = byte_size / 4;
9326           byte_size = 4;
9327           break;
9328         }
9329         return DumpDataExtractor(data, s, byte_offset, format, byte_size,
9330                                  item_count, UINT32_MAX, LLDB_INVALID_ADDRESS,
9331                                  bitfield_bit_size, bitfield_bit_offset,
9332                                  exe_scope);
9333       }
9334       break;
9335     }
9336   }
9337   return 0;
9338 }
9339 
9340 void ClangASTContext::DumpSummary(lldb::opaque_compiler_type_t type,
9341                                   ExecutionContext *exe_ctx, Stream *s,
9342                                   const lldb_private::DataExtractor &data,
9343                                   lldb::offset_t data_byte_offset,
9344                                   size_t data_byte_size) {
9345   uint32_t length = 0;
9346   if (IsCStringType(type, length)) {
9347     if (exe_ctx) {
9348       Process *process = exe_ctx->GetProcessPtr();
9349       if (process) {
9350         lldb::offset_t offset = data_byte_offset;
9351         lldb::addr_t pointer_address = data.GetMaxU64(&offset, data_byte_size);
9352         std::vector<uint8_t> buf;
9353         if (length > 0)
9354           buf.resize(length);
9355         else
9356           buf.resize(256);
9357 
9358         DataExtractor cstr_data(&buf.front(), buf.size(),
9359                                 process->GetByteOrder(), 4);
9360         buf.back() = '\0';
9361         size_t bytes_read;
9362         size_t total_cstr_len = 0;
9363         Status error;
9364         while ((bytes_read = process->ReadMemory(pointer_address, &buf.front(),
9365                                                  buf.size(), error)) > 0) {
9366           const size_t len = strlen((const char *)&buf.front());
9367           if (len == 0)
9368             break;
9369           if (total_cstr_len == 0)
9370             s->PutCString(" \"");
9371           DumpDataExtractor(cstr_data, s, 0, lldb::eFormatChar, 1, len,
9372                             UINT32_MAX, LLDB_INVALID_ADDRESS, 0, 0);
9373           total_cstr_len += len;
9374           if (len < buf.size())
9375             break;
9376           pointer_address += total_cstr_len;
9377         }
9378         if (total_cstr_len > 0)
9379           s->PutChar('"');
9380       }
9381     }
9382   }
9383 }
9384 
9385 void ClangASTContext::DumpTypeDescription(lldb::opaque_compiler_type_t type) {
9386   StreamFile s(stdout, false);
9387   DumpTypeDescription(type, &s);
9388   ClangASTMetadata *metadata =
9389       ClangASTContext::GetMetadata(getASTContext(), type);
9390   if (metadata) {
9391     metadata->Dump(&s);
9392   }
9393 }
9394 
9395 void ClangASTContext::DumpTypeDescription(lldb::opaque_compiler_type_t type,
9396                                           Stream *s) {
9397   if (type) {
9398     clang::QualType qual_type(GetQualType(type));
9399 
9400     llvm::SmallVector<char, 1024> buf;
9401     llvm::raw_svector_ostream llvm_ostrm(buf);
9402 
9403     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
9404     switch (type_class) {
9405     case clang::Type::ObjCObject:
9406     case clang::Type::ObjCInterface: {
9407       GetCompleteType(type);
9408 
9409       const clang::ObjCObjectType *objc_class_type =
9410           llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
9411       assert(objc_class_type);
9412       if (objc_class_type) {
9413         clang::ObjCInterfaceDecl *class_interface_decl =
9414             objc_class_type->getInterface();
9415         if (class_interface_decl) {
9416           clang::PrintingPolicy policy = getASTContext()->getPrintingPolicy();
9417           class_interface_decl->print(llvm_ostrm, policy, s->GetIndentLevel());
9418         }
9419       }
9420     } break;
9421 
9422     case clang::Type::Typedef: {
9423       const clang::TypedefType *typedef_type =
9424           qual_type->getAs<clang::TypedefType>();
9425       if (typedef_type) {
9426         const clang::TypedefNameDecl *typedef_decl = typedef_type->getDecl();
9427         std::string clang_typedef_name(
9428             typedef_decl->getQualifiedNameAsString());
9429         if (!clang_typedef_name.empty()) {
9430           s->PutCString("typedef ");
9431           s->PutCString(clang_typedef_name);
9432         }
9433       }
9434     } break;
9435 
9436     case clang::Type::Auto:
9437       CompilerType(getASTContext(),
9438                    llvm::cast<clang::AutoType>(qual_type)->getDeducedType())
9439           .DumpTypeDescription(s);
9440       return;
9441 
9442     case clang::Type::Elaborated:
9443       CompilerType(getASTContext(),
9444                    llvm::cast<clang::ElaboratedType>(qual_type)->getNamedType())
9445           .DumpTypeDescription(s);
9446       return;
9447 
9448     case clang::Type::Paren:
9449       CompilerType(getASTContext(),
9450                    llvm::cast<clang::ParenType>(qual_type)->desugar())
9451           .DumpTypeDescription(s);
9452       return;
9453 
9454     case clang::Type::Record: {
9455       GetCompleteType(type);
9456 
9457       const clang::RecordType *record_type =
9458           llvm::cast<clang::RecordType>(qual_type.getTypePtr());
9459       const clang::RecordDecl *record_decl = record_type->getDecl();
9460       const clang::CXXRecordDecl *cxx_record_decl =
9461           llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
9462 
9463       if (cxx_record_decl)
9464         cxx_record_decl->print(llvm_ostrm, getASTContext()->getPrintingPolicy(),
9465                                s->GetIndentLevel());
9466       else
9467         record_decl->print(llvm_ostrm, getASTContext()->getPrintingPolicy(),
9468                            s->GetIndentLevel());
9469     } break;
9470 
9471     default: {
9472       const clang::TagType *tag_type =
9473           llvm::dyn_cast<clang::TagType>(qual_type.getTypePtr());
9474       if (tag_type) {
9475         clang::TagDecl *tag_decl = tag_type->getDecl();
9476         if (tag_decl)
9477           tag_decl->print(llvm_ostrm, 0);
9478       } else {
9479         std::string clang_type_name(qual_type.getAsString());
9480         if (!clang_type_name.empty())
9481           s->PutCString(clang_type_name);
9482       }
9483     }
9484     }
9485 
9486     if (buf.size() > 0) {
9487       s->Write(buf.data(), buf.size());
9488     }
9489   }
9490 }
9491 
9492 void ClangASTContext::DumpTypeName(const CompilerType &type) {
9493   if (ClangUtil::IsClangType(type)) {
9494     clang::QualType qual_type(
9495         ClangUtil::GetCanonicalQualType(ClangUtil::RemoveFastQualifiers(type)));
9496 
9497     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
9498     switch (type_class) {
9499     case clang::Type::Record: {
9500       const clang::CXXRecordDecl *cxx_record_decl =
9501           qual_type->getAsCXXRecordDecl();
9502       if (cxx_record_decl)
9503         printf("class %s", cxx_record_decl->getName().str().c_str());
9504     } break;
9505 
9506     case clang::Type::Enum: {
9507       clang::EnumDecl *enum_decl =
9508           llvm::cast<clang::EnumType>(qual_type)->getDecl();
9509       if (enum_decl) {
9510         printf("enum %s", enum_decl->getName().str().c_str());
9511       }
9512     } break;
9513 
9514     case clang::Type::ObjCObject:
9515     case clang::Type::ObjCInterface: {
9516       const clang::ObjCObjectType *objc_class_type =
9517           llvm::dyn_cast<clang::ObjCObjectType>(qual_type);
9518       if (objc_class_type) {
9519         clang::ObjCInterfaceDecl *class_interface_decl =
9520             objc_class_type->getInterface();
9521         // We currently can't complete objective C types through the newly added
9522         // ASTContext
9523         // because it only supports TagDecl objects right now...
9524         if (class_interface_decl)
9525           printf("@class %s", class_interface_decl->getName().str().c_str());
9526       }
9527     } break;
9528 
9529     case clang::Type::Typedef:
9530       printf("typedef %s", llvm::cast<clang::TypedefType>(qual_type)
9531                                ->getDecl()
9532                                ->getName()
9533                                .str()
9534                                .c_str());
9535       break;
9536 
9537     case clang::Type::Auto:
9538       printf("auto ");
9539       return DumpTypeName(CompilerType(type.GetTypeSystem(),
9540                                        llvm::cast<clang::AutoType>(qual_type)
9541                                            ->getDeducedType()
9542                                            .getAsOpaquePtr()));
9543 
9544     case clang::Type::Elaborated:
9545       printf("elaborated ");
9546       return DumpTypeName(CompilerType(
9547           type.GetTypeSystem(), llvm::cast<clang::ElaboratedType>(qual_type)
9548                                     ->getNamedType()
9549                                     .getAsOpaquePtr()));
9550 
9551     case clang::Type::Paren:
9552       printf("paren ");
9553       return DumpTypeName(CompilerType(
9554           type.GetTypeSystem(),
9555           llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr()));
9556 
9557     default:
9558       printf("ClangASTContext::DumpTypeName() type_class = %u", type_class);
9559       break;
9560     }
9561   }
9562 }
9563 
9564 clang::ClassTemplateDecl *ClangASTContext::ParseClassTemplateDecl(
9565     clang::DeclContext *decl_ctx, lldb::AccessType access_type,
9566     const char *parent_name, int tag_decl_kind,
9567     const ClangASTContext::TemplateParameterInfos &template_param_infos) {
9568   if (template_param_infos.IsValid()) {
9569     std::string template_basename(parent_name);
9570     template_basename.erase(template_basename.find('<'));
9571 
9572     return CreateClassTemplateDecl(decl_ctx, access_type,
9573                                    template_basename.c_str(), tag_decl_kind,
9574                                    template_param_infos);
9575   }
9576   return NULL;
9577 }
9578 
9579 void ClangASTContext::CompleteTagDecl(void *baton, clang::TagDecl *decl) {
9580   ClangASTContext *ast = (ClangASTContext *)baton;
9581   SymbolFile *sym_file = ast->GetSymbolFile();
9582   if (sym_file) {
9583     CompilerType clang_type = GetTypeForDecl(decl);
9584     if (clang_type)
9585       sym_file->CompleteType(clang_type);
9586   }
9587 }
9588 
9589 void ClangASTContext::CompleteObjCInterfaceDecl(
9590     void *baton, clang::ObjCInterfaceDecl *decl) {
9591   ClangASTContext *ast = (ClangASTContext *)baton;
9592   SymbolFile *sym_file = ast->GetSymbolFile();
9593   if (sym_file) {
9594     CompilerType clang_type = GetTypeForDecl(decl);
9595     if (clang_type)
9596       sym_file->CompleteType(clang_type);
9597   }
9598 }
9599 
9600 DWARFASTParser *ClangASTContext::GetDWARFParser() {
9601   if (!m_dwarf_ast_parser_ap)
9602     m_dwarf_ast_parser_ap.reset(new DWARFASTParserClang(*this));
9603   return m_dwarf_ast_parser_ap.get();
9604 }
9605 
9606 #if 0
9607 PDBASTParser *ClangASTContext::GetPDBParser() {
9608   if (!m_pdb_ast_parser_ap)
9609     m_pdb_ast_parser_ap.reset(new PDBASTParser(*this));
9610   return m_pdb_ast_parser_ap.get();
9611 }
9612 #endif
9613 
9614 bool ClangASTContext::LayoutRecordType(
9615     void *baton, const clang::RecordDecl *record_decl, uint64_t &bit_size,
9616     uint64_t &alignment,
9617     llvm::DenseMap<const clang::FieldDecl *, uint64_t> &field_offsets,
9618     llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits>
9619         &base_offsets,
9620     llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits>
9621         &vbase_offsets) {
9622   ClangASTContext *ast = (ClangASTContext *)baton;
9623   DWARFASTParserClang *dwarf_ast_parser =
9624       (DWARFASTParserClang *)ast->GetDWARFParser();
9625   return dwarf_ast_parser->GetClangASTImporter().LayoutRecordType(
9626       record_decl, bit_size, alignment, field_offsets, base_offsets,
9627       vbase_offsets);
9628 }
9629 
9630 //----------------------------------------------------------------------
9631 // CompilerDecl override functions
9632 //----------------------------------------------------------------------
9633 
9634 ConstString ClangASTContext::DeclGetName(void *opaque_decl) {
9635   if (opaque_decl) {
9636     clang::NamedDecl *nd =
9637         llvm::dyn_cast<NamedDecl>((clang::Decl *)opaque_decl);
9638     if (nd != nullptr)
9639       return ConstString(nd->getDeclName().getAsString());
9640   }
9641   return ConstString();
9642 }
9643 
9644 ConstString ClangASTContext::DeclGetMangledName(void *opaque_decl) {
9645   if (opaque_decl) {
9646     clang::NamedDecl *nd =
9647         llvm::dyn_cast<clang::NamedDecl>((clang::Decl *)opaque_decl);
9648     if (nd != nullptr && !llvm::isa<clang::ObjCMethodDecl>(nd)) {
9649       clang::MangleContext *mc = getMangleContext();
9650       if (mc && mc->shouldMangleCXXName(nd)) {
9651         llvm::SmallVector<char, 1024> buf;
9652         llvm::raw_svector_ostream llvm_ostrm(buf);
9653         if (llvm::isa<clang::CXXConstructorDecl>(nd)) {
9654           mc->mangleCXXCtor(llvm::dyn_cast<clang::CXXConstructorDecl>(nd),
9655                             Ctor_Complete, llvm_ostrm);
9656         } else if (llvm::isa<clang::CXXDestructorDecl>(nd)) {
9657           mc->mangleCXXDtor(llvm::dyn_cast<clang::CXXDestructorDecl>(nd),
9658                             Dtor_Complete, llvm_ostrm);
9659         } else {
9660           mc->mangleName(nd, llvm_ostrm);
9661         }
9662         if (buf.size() > 0)
9663           return ConstString(buf.data(), buf.size());
9664       }
9665     }
9666   }
9667   return ConstString();
9668 }
9669 
9670 CompilerDeclContext ClangASTContext::DeclGetDeclContext(void *opaque_decl) {
9671   if (opaque_decl)
9672     return CompilerDeclContext(this,
9673                                ((clang::Decl *)opaque_decl)->getDeclContext());
9674   else
9675     return CompilerDeclContext();
9676 }
9677 
9678 CompilerType ClangASTContext::DeclGetFunctionReturnType(void *opaque_decl) {
9679   if (clang::FunctionDecl *func_decl =
9680           llvm::dyn_cast<clang::FunctionDecl>((clang::Decl *)opaque_decl))
9681     return CompilerType(this, func_decl->getReturnType().getAsOpaquePtr());
9682   if (clang::ObjCMethodDecl *objc_method =
9683           llvm::dyn_cast<clang::ObjCMethodDecl>((clang::Decl *)opaque_decl))
9684     return CompilerType(this, objc_method->getReturnType().getAsOpaquePtr());
9685   else
9686     return CompilerType();
9687 }
9688 
9689 size_t ClangASTContext::DeclGetFunctionNumArguments(void *opaque_decl) {
9690   if (clang::FunctionDecl *func_decl =
9691           llvm::dyn_cast<clang::FunctionDecl>((clang::Decl *)opaque_decl))
9692     return func_decl->param_size();
9693   if (clang::ObjCMethodDecl *objc_method =
9694           llvm::dyn_cast<clang::ObjCMethodDecl>((clang::Decl *)opaque_decl))
9695     return objc_method->param_size();
9696   else
9697     return 0;
9698 }
9699 
9700 CompilerType ClangASTContext::DeclGetFunctionArgumentType(void *opaque_decl,
9701                                                           size_t idx) {
9702   if (clang::FunctionDecl *func_decl =
9703           llvm::dyn_cast<clang::FunctionDecl>((clang::Decl *)opaque_decl)) {
9704     if (idx < func_decl->param_size()) {
9705       ParmVarDecl *var_decl = func_decl->getParamDecl(idx);
9706       if (var_decl)
9707         return CompilerType(this, var_decl->getOriginalType().getAsOpaquePtr());
9708     }
9709   } else if (clang::ObjCMethodDecl *objc_method =
9710                  llvm::dyn_cast<clang::ObjCMethodDecl>(
9711                      (clang::Decl *)opaque_decl)) {
9712     if (idx < objc_method->param_size())
9713       return CompilerType(
9714           this,
9715           objc_method->parameters()[idx]->getOriginalType().getAsOpaquePtr());
9716   }
9717   return CompilerType();
9718 }
9719 
9720 //----------------------------------------------------------------------
9721 // CompilerDeclContext functions
9722 //----------------------------------------------------------------------
9723 
9724 std::vector<CompilerDecl> ClangASTContext::DeclContextFindDeclByName(
9725     void *opaque_decl_ctx, ConstString name, const bool ignore_using_decls) {
9726   std::vector<CompilerDecl> found_decls;
9727   if (opaque_decl_ctx) {
9728     DeclContext *root_decl_ctx = (DeclContext *)opaque_decl_ctx;
9729     std::set<DeclContext *> searched;
9730     std::multimap<DeclContext *, DeclContext *> search_queue;
9731     SymbolFile *symbol_file = GetSymbolFile();
9732 
9733     for (clang::DeclContext *decl_context = root_decl_ctx;
9734          decl_context != nullptr && found_decls.empty();
9735          decl_context = decl_context->getParent()) {
9736       search_queue.insert(std::make_pair(decl_context, decl_context));
9737 
9738       for (auto it = search_queue.find(decl_context); it != search_queue.end();
9739            it++) {
9740         if (!searched.insert(it->second).second)
9741           continue;
9742         symbol_file->ParseDeclsForContext(
9743             CompilerDeclContext(this, it->second));
9744 
9745         for (clang::Decl *child : it->second->decls()) {
9746           if (clang::UsingDirectiveDecl *ud =
9747                   llvm::dyn_cast<clang::UsingDirectiveDecl>(child)) {
9748             if (ignore_using_decls)
9749               continue;
9750             clang::DeclContext *from = ud->getCommonAncestor();
9751             if (searched.find(ud->getNominatedNamespace()) == searched.end())
9752               search_queue.insert(
9753                   std::make_pair(from, ud->getNominatedNamespace()));
9754           } else if (clang::UsingDecl *ud =
9755                          llvm::dyn_cast<clang::UsingDecl>(child)) {
9756             if (ignore_using_decls)
9757               continue;
9758             for (clang::UsingShadowDecl *usd : ud->shadows()) {
9759               clang::Decl *target = usd->getTargetDecl();
9760               if (clang::NamedDecl *nd =
9761                       llvm::dyn_cast<clang::NamedDecl>(target)) {
9762                 IdentifierInfo *ii = nd->getIdentifier();
9763                 if (ii != nullptr &&
9764                     ii->getName().equals(name.AsCString(nullptr)))
9765                   found_decls.push_back(CompilerDecl(this, nd));
9766               }
9767             }
9768           } else if (clang::NamedDecl *nd =
9769                          llvm::dyn_cast<clang::NamedDecl>(child)) {
9770             IdentifierInfo *ii = nd->getIdentifier();
9771             if (ii != nullptr && ii->getName().equals(name.AsCString(nullptr)))
9772               found_decls.push_back(CompilerDecl(this, nd));
9773           }
9774         }
9775       }
9776     }
9777   }
9778   return found_decls;
9779 }
9780 
9781 // Look for child_decl_ctx's lookup scope in frame_decl_ctx and its parents,
9782 // and return the number of levels it took to find it, or
9783 // LLDB_INVALID_DECL_LEVEL
9784 // if not found.  If the decl was imported via a using declaration, its name
9785 // and/or
9786 // type, if set, will be used to check that the decl found in the scope is a
9787 // match.
9788 //
9789 // The optional name is required by languages (like C++) to handle using
9790 // declarations
9791 // like:
9792 //
9793 //     void poo();
9794 //     namespace ns {
9795 //         void foo();
9796 //         void goo();
9797 //     }
9798 //     void bar() {
9799 //         using ns::foo;
9800 //         // CountDeclLevels returns 0 for 'foo', 1 for 'poo', and
9801 //         // LLDB_INVALID_DECL_LEVEL for 'goo'.
9802 //     }
9803 //
9804 // The optional type is useful in the case that there's a specific overload
9805 // that we're looking for that might otherwise be shadowed, like:
9806 //
9807 //     void foo(int);
9808 //     namespace ns {
9809 //         void foo();
9810 //     }
9811 //     void bar() {
9812 //         using ns::foo;
9813 //         // CountDeclLevels returns 0 for { 'foo', void() },
9814 //         // 1 for { 'foo', void(int) }, and
9815 //         // LLDB_INVALID_DECL_LEVEL for { 'foo', void(int, int) }.
9816 //     }
9817 //
9818 // NOTE: Because file statics are at the TranslationUnit along with globals, a
9819 // function at file scope will return the same level as a function at global
9820 // scope.
9821 // Ideally we'd like to treat the file scope as an additional scope just below
9822 // the
9823 // global scope.  More work needs to be done to recognise that, if the decl
9824 // we're
9825 // trying to look up is static, we should compare its source file with that of
9826 // the
9827 // current scope and return a lower number for it.
9828 uint32_t ClangASTContext::CountDeclLevels(clang::DeclContext *frame_decl_ctx,
9829                                           clang::DeclContext *child_decl_ctx,
9830                                           ConstString *child_name,
9831                                           CompilerType *child_type) {
9832   if (frame_decl_ctx) {
9833     std::set<DeclContext *> searched;
9834     std::multimap<DeclContext *, DeclContext *> search_queue;
9835     SymbolFile *symbol_file = GetSymbolFile();
9836 
9837     // Get the lookup scope for the decl we're trying to find.
9838     clang::DeclContext *parent_decl_ctx = child_decl_ctx->getParent();
9839 
9840     // Look for it in our scope's decl context and its parents.
9841     uint32_t level = 0;
9842     for (clang::DeclContext *decl_ctx = frame_decl_ctx; decl_ctx != nullptr;
9843          decl_ctx = decl_ctx->getParent()) {
9844       if (!decl_ctx->isLookupContext())
9845         continue;
9846       if (decl_ctx == parent_decl_ctx)
9847         // Found it!
9848         return level;
9849       search_queue.insert(std::make_pair(decl_ctx, decl_ctx));
9850       for (auto it = search_queue.find(decl_ctx); it != search_queue.end();
9851            it++) {
9852         if (searched.find(it->second) != searched.end())
9853           continue;
9854 
9855         // Currently DWARF has one shared translation unit for all Decls at top
9856         // level, so this
9857         // would erroneously find using statements anywhere.  So don't look at
9858         // the top-level
9859         // translation unit.
9860         // TODO fix this and add a testcase that depends on it.
9861 
9862         if (llvm::isa<clang::TranslationUnitDecl>(it->second))
9863           continue;
9864 
9865         searched.insert(it->second);
9866         symbol_file->ParseDeclsForContext(
9867             CompilerDeclContext(this, it->second));
9868 
9869         for (clang::Decl *child : it->second->decls()) {
9870           if (clang::UsingDirectiveDecl *ud =
9871                   llvm::dyn_cast<clang::UsingDirectiveDecl>(child)) {
9872             clang::DeclContext *ns = ud->getNominatedNamespace();
9873             if (ns == parent_decl_ctx)
9874               // Found it!
9875               return level;
9876             clang::DeclContext *from = ud->getCommonAncestor();
9877             if (searched.find(ns) == searched.end())
9878               search_queue.insert(std::make_pair(from, ns));
9879           } else if (child_name) {
9880             if (clang::UsingDecl *ud =
9881                     llvm::dyn_cast<clang::UsingDecl>(child)) {
9882               for (clang::UsingShadowDecl *usd : ud->shadows()) {
9883                 clang::Decl *target = usd->getTargetDecl();
9884                 clang::NamedDecl *nd = llvm::dyn_cast<clang::NamedDecl>(target);
9885                 if (!nd)
9886                   continue;
9887                 // Check names.
9888                 IdentifierInfo *ii = nd->getIdentifier();
9889                 if (ii == nullptr ||
9890                     !ii->getName().equals(child_name->AsCString(nullptr)))
9891                   continue;
9892                 // Check types, if one was provided.
9893                 if (child_type) {
9894                   CompilerType clang_type = ClangASTContext::GetTypeForDecl(nd);
9895                   if (!AreTypesSame(clang_type, *child_type,
9896                                     /*ignore_qualifiers=*/true))
9897                     continue;
9898                 }
9899                 // Found it!
9900                 return level;
9901               }
9902             }
9903           }
9904         }
9905       }
9906       ++level;
9907     }
9908   }
9909   return LLDB_INVALID_DECL_LEVEL;
9910 }
9911 
9912 bool ClangASTContext::DeclContextIsStructUnionOrClass(void *opaque_decl_ctx) {
9913   if (opaque_decl_ctx)
9914     return ((clang::DeclContext *)opaque_decl_ctx)->isRecord();
9915   else
9916     return false;
9917 }
9918 
9919 ConstString ClangASTContext::DeclContextGetName(void *opaque_decl_ctx) {
9920   if (opaque_decl_ctx) {
9921     clang::NamedDecl *named_decl =
9922         llvm::dyn_cast<clang::NamedDecl>((clang::DeclContext *)opaque_decl_ctx);
9923     if (named_decl)
9924       return ConstString(named_decl->getName());
9925   }
9926   return ConstString();
9927 }
9928 
9929 ConstString
9930 ClangASTContext::DeclContextGetScopeQualifiedName(void *opaque_decl_ctx) {
9931   if (opaque_decl_ctx) {
9932     clang::NamedDecl *named_decl =
9933         llvm::dyn_cast<clang::NamedDecl>((clang::DeclContext *)opaque_decl_ctx);
9934     if (named_decl)
9935       return ConstString(
9936           llvm::StringRef(named_decl->getQualifiedNameAsString()));
9937   }
9938   return ConstString();
9939 }
9940 
9941 bool ClangASTContext::DeclContextIsClassMethod(
9942     void *opaque_decl_ctx, lldb::LanguageType *language_ptr,
9943     bool *is_instance_method_ptr, ConstString *language_object_name_ptr) {
9944   if (opaque_decl_ctx) {
9945     clang::DeclContext *decl_ctx = (clang::DeclContext *)opaque_decl_ctx;
9946     if (ObjCMethodDecl *objc_method =
9947             llvm::dyn_cast<clang::ObjCMethodDecl>(decl_ctx)) {
9948       if (is_instance_method_ptr)
9949         *is_instance_method_ptr = objc_method->isInstanceMethod();
9950       if (language_ptr)
9951         *language_ptr = eLanguageTypeObjC;
9952       if (language_object_name_ptr)
9953         language_object_name_ptr->SetCString("self");
9954       return true;
9955     } else if (CXXMethodDecl *cxx_method =
9956                    llvm::dyn_cast<clang::CXXMethodDecl>(decl_ctx)) {
9957       if (is_instance_method_ptr)
9958         *is_instance_method_ptr = cxx_method->isInstance();
9959       if (language_ptr)
9960         *language_ptr = eLanguageTypeC_plus_plus;
9961       if (language_object_name_ptr)
9962         language_object_name_ptr->SetCString("this");
9963       return true;
9964     } else if (clang::FunctionDecl *function_decl =
9965                    llvm::dyn_cast<clang::FunctionDecl>(decl_ctx)) {
9966       ClangASTMetadata *metadata =
9967           GetMetadata(&decl_ctx->getParentASTContext(), function_decl);
9968       if (metadata && metadata->HasObjectPtr()) {
9969         if (is_instance_method_ptr)
9970           *is_instance_method_ptr = true;
9971         if (language_ptr)
9972           *language_ptr = eLanguageTypeObjC;
9973         if (language_object_name_ptr)
9974           language_object_name_ptr->SetCString(metadata->GetObjectPtrName());
9975         return true;
9976       }
9977     }
9978   }
9979   return false;
9980 }
9981 
9982 clang::DeclContext *
9983 ClangASTContext::DeclContextGetAsDeclContext(const CompilerDeclContext &dc) {
9984   if (dc.IsClang())
9985     return (clang::DeclContext *)dc.GetOpaqueDeclContext();
9986   return nullptr;
9987 }
9988 
9989 ObjCMethodDecl *
9990 ClangASTContext::DeclContextGetAsObjCMethodDecl(const CompilerDeclContext &dc) {
9991   if (dc.IsClang())
9992     return llvm::dyn_cast<clang::ObjCMethodDecl>(
9993         (clang::DeclContext *)dc.GetOpaqueDeclContext());
9994   return nullptr;
9995 }
9996 
9997 CXXMethodDecl *
9998 ClangASTContext::DeclContextGetAsCXXMethodDecl(const CompilerDeclContext &dc) {
9999   if (dc.IsClang())
10000     return llvm::dyn_cast<clang::CXXMethodDecl>(
10001         (clang::DeclContext *)dc.GetOpaqueDeclContext());
10002   return nullptr;
10003 }
10004 
10005 clang::FunctionDecl *
10006 ClangASTContext::DeclContextGetAsFunctionDecl(const CompilerDeclContext &dc) {
10007   if (dc.IsClang())
10008     return llvm::dyn_cast<clang::FunctionDecl>(
10009         (clang::DeclContext *)dc.GetOpaqueDeclContext());
10010   return nullptr;
10011 }
10012 
10013 clang::NamespaceDecl *
10014 ClangASTContext::DeclContextGetAsNamespaceDecl(const CompilerDeclContext &dc) {
10015   if (dc.IsClang())
10016     return llvm::dyn_cast<clang::NamespaceDecl>(
10017         (clang::DeclContext *)dc.GetOpaqueDeclContext());
10018   return nullptr;
10019 }
10020 
10021 ClangASTMetadata *
10022 ClangASTContext::DeclContextGetMetaData(const CompilerDeclContext &dc,
10023                                         const void *object) {
10024   clang::ASTContext *ast = DeclContextGetClangASTContext(dc);
10025   if (ast)
10026     return ClangASTContext::GetMetadata(ast, object);
10027   return nullptr;
10028 }
10029 
10030 clang::ASTContext *
10031 ClangASTContext::DeclContextGetClangASTContext(const CompilerDeclContext &dc) {
10032   ClangASTContext *ast =
10033       llvm::dyn_cast_or_null<ClangASTContext>(dc.GetTypeSystem());
10034   if (ast)
10035     return ast->getASTContext();
10036   return nullptr;
10037 }
10038 
10039 ClangASTContextForExpressions::ClangASTContextForExpressions(Target &target)
10040     : ClangASTContext(target.GetArchitecture().GetTriple().getTriple().c_str()),
10041       m_target_wp(target.shared_from_this()),
10042       m_persistent_variables(new ClangPersistentVariables) {}
10043 
10044 UserExpression *ClangASTContextForExpressions::GetUserExpression(
10045     llvm::StringRef expr, llvm::StringRef prefix, lldb::LanguageType language,
10046     Expression::ResultType desired_type,
10047     const EvaluateExpressionOptions &options) {
10048   TargetSP target_sp = m_target_wp.lock();
10049   if (!target_sp)
10050     return nullptr;
10051 
10052   return new ClangUserExpression(*target_sp.get(), expr, prefix, language,
10053                                  desired_type, options);
10054 }
10055 
10056 FunctionCaller *ClangASTContextForExpressions::GetFunctionCaller(
10057     const CompilerType &return_type, const Address &function_address,
10058     const ValueList &arg_value_list, const char *name) {
10059   TargetSP target_sp = m_target_wp.lock();
10060   if (!target_sp)
10061     return nullptr;
10062 
10063   Process *process = target_sp->GetProcessSP().get();
10064   if (!process)
10065     return nullptr;
10066 
10067   return new ClangFunctionCaller(*process, return_type, function_address,
10068                                  arg_value_list, name);
10069 }
10070 
10071 UtilityFunction *
10072 ClangASTContextForExpressions::GetUtilityFunction(const char *text,
10073                                                   const char *name) {
10074   TargetSP target_sp = m_target_wp.lock();
10075   if (!target_sp)
10076     return nullptr;
10077 
10078   return new ClangUtilityFunction(*target_sp.get(), text, name);
10079 }
10080 
10081 PersistentExpressionState *
10082 ClangASTContextForExpressions::GetPersistentExpressionState() {
10083   return m_persistent_variables.get();
10084 }
10085 
10086 clang::ExternalASTMerger &
10087 ClangASTContextForExpressions::GetMergerUnchecked() {
10088   lldbassert(m_scratch_ast_source_ap != nullptr);
10089   return m_scratch_ast_source_ap->GetMergerUnchecked();
10090 }
10091 
10092