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