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