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