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