ClangASTContext.cpp revision f95fc9e09fa0a32de0a3904a1517266df37e8bff
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 <string>
15
16// Other libraries and framework includes
17
18// Clang headers like to use NDEBUG inside of them to enable/disable debug
19// releated features using "#ifndef NDEBUG" preprocessor blocks to do one thing
20// or another. This is bad because it means that if clang was built in release
21// mode, it assumes that you are building in release mode which is not always
22// the case. You can end up with functions that are defined as empty in header
23// files when NDEBUG is not defined, and this can cause link errors with the
24// clang .a files that you have since you might be missing functions in the .a
25// file. So we have to define NDEBUG when including clang headers to avoid any
26// mismatches. This is covered by rdar://problem/8691220
27
28#if !defined(NDEBUG) && !defined(LLVM_NDEBUG_OFF)
29#define LLDB_DEFINED_NDEBUG_FOR_CLANG
30#define NDEBUG
31// Need to include assert.h so it is as clang would expect it to be (disabled)
32#include <assert.h>
33#endif
34
35#include "clang/AST/ASTContext.h"
36#include "clang/AST/ASTImporter.h"
37#include "clang/AST/Attr.h"
38#include "clang/AST/CXXInheritance.h"
39#include "clang/AST/DeclObjC.h"
40#include "clang/AST/DeclTemplate.h"
41#include "clang/AST/RecordLayout.h"
42#include "clang/AST/Type.h"
43#include "clang/Basic/Builtins.h"
44#include "clang/Basic/Diagnostic.h"
45#include "clang/Basic/FileManager.h"
46#include "clang/Basic/FileSystemOptions.h"
47#include "clang/Basic/SourceManager.h"
48#include "clang/Basic/TargetInfo.h"
49#include "clang/Basic/TargetOptions.h"
50#include "clang/Frontend/FrontendOptions.h"
51#include "clang/Frontend/LangStandard.h"
52
53#ifdef LLDB_DEFINED_NDEBUG_FOR_CLANG
54#undef NDEBUG
55#undef LLDB_DEFINED_NDEBUG_FOR_CLANG
56// Need to re-include assert.h so it is as _we_ would expect it to be (enabled)
57#include <assert.h>
58#endif
59
60#include "lldb/Core/ArchSpec.h"
61#include "lldb/Core/dwarf.h"
62#include "lldb/Core/Flags.h"
63#include "lldb/Core/Log.h"
64#include "lldb/Core/RegularExpression.h"
65#include "lldb/Expression/ASTDumper.h"
66#include "lldb/Symbol/ClangExternalASTSourceCommon.h"
67#include "lldb/Symbol/VerifyDecl.h"
68#include "lldb/Target/ExecutionContext.h"
69#include "lldb/Target/Process.h"
70#include "lldb/Target/ObjCLanguageRuntime.h"
71
72
73#include <stdio.h>
74
75using namespace lldb;
76using namespace lldb_private;
77using namespace llvm;
78using namespace clang;
79
80
81static bool
82GetCompleteQualType (clang::ASTContext *ast, clang::QualType qual_type, bool allow_completion = true)
83{
84    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
85    switch (type_class)
86    {
87    case clang::Type::ConstantArray:
88        {
89            const clang::ArrayType *array_type = dyn_cast<clang::ArrayType>(qual_type.getTypePtr());
90
91            if (array_type)
92                return GetCompleteQualType (ast, array_type->getElementType(), allow_completion);
93        }
94        break;
95
96    case clang::Type::Record:
97    case clang::Type::Enum:
98        {
99            const clang::TagType *tag_type = dyn_cast<clang::TagType>(qual_type.getTypePtr());
100            if (tag_type)
101            {
102                clang::TagDecl *tag_decl = tag_type->getDecl();
103                if (tag_decl)
104                {
105                    if (tag_decl->isCompleteDefinition())
106                        return true;
107
108                    if (!allow_completion)
109                        return false;
110
111                    if (tag_decl->hasExternalLexicalStorage())
112                    {
113                        if (ast)
114                        {
115                            ExternalASTSource *external_ast_source = ast->getExternalSource();
116                            if (external_ast_source)
117                            {
118                                external_ast_source->CompleteType(tag_decl);
119                                return !tag_type->isIncompleteType();
120                            }
121                        }
122                    }
123                    return false;
124                }
125            }
126
127        }
128        break;
129
130    case clang::Type::ObjCObject:
131    case clang::Type::ObjCInterface:
132        {
133            const clang::ObjCObjectType *objc_class_type = dyn_cast<clang::ObjCObjectType>(qual_type);
134            if (objc_class_type)
135            {
136                clang::ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
137                // We currently can't complete objective C types through the newly added ASTContext
138                // because it only supports TagDecl objects right now...
139                if (class_interface_decl)
140                {
141                    if (class_interface_decl->getDefinition())
142                        return true;
143
144                    if (!allow_completion)
145                        return false;
146
147                    if (class_interface_decl->hasExternalLexicalStorage())
148                    {
149                        if (ast)
150                        {
151                            ExternalASTSource *external_ast_source = ast->getExternalSource();
152                            if (external_ast_source)
153                            {
154                                external_ast_source->CompleteType (class_interface_decl);
155                                return !objc_class_type->isIncompleteType();
156                            }
157                        }
158                    }
159                    return false;
160                }
161            }
162        }
163        break;
164
165    case clang::Type::Typedef:
166        return GetCompleteQualType (ast, cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType(), allow_completion);
167
168    case clang::Type::Elaborated:
169        return GetCompleteQualType (ast, cast<ElaboratedType>(qual_type)->getNamedType(), allow_completion);
170
171    default:
172        break;
173    }
174
175    return true;
176}
177
178static AccessSpecifier
179ConvertAccessTypeToAccessSpecifier (AccessType access)
180{
181    switch (access)
182    {
183    default:               break;
184    case eAccessNone:      return AS_none;
185    case eAccessPublic:    return AS_public;
186    case eAccessPrivate:   return AS_private;
187    case eAccessProtected: return AS_protected;
188    }
189    return AS_none;
190}
191
192static ObjCIvarDecl::AccessControl
193ConvertAccessTypeToObjCIvarAccessControl (AccessType access)
194{
195    switch (access)
196    {
197    case eAccessNone:      return ObjCIvarDecl::None;
198    case eAccessPublic:    return ObjCIvarDecl::Public;
199    case eAccessPrivate:   return ObjCIvarDecl::Private;
200    case eAccessProtected: return ObjCIvarDecl::Protected;
201    case eAccessPackage:   return ObjCIvarDecl::Package;
202    }
203    return ObjCIvarDecl::None;
204}
205
206
207static void
208ParseLangArgs
209(
210    LangOptions &Opts,
211    InputKind IK
212)
213{
214    // FIXME: Cleanup per-file based stuff.
215
216    // Set some properties which depend soley on the input kind; it would be nice
217    // to move these to the language standard, and have the driver resolve the
218    // input kind + language standard.
219    if (IK == IK_Asm) {
220        Opts.AsmPreprocessor = 1;
221    } else if (IK == IK_ObjC ||
222               IK == IK_ObjCXX ||
223               IK == IK_PreprocessedObjC ||
224               IK == IK_PreprocessedObjCXX) {
225        Opts.ObjC1 = Opts.ObjC2 = 1;
226    }
227
228    LangStandard::Kind LangStd = LangStandard::lang_unspecified;
229
230    if (LangStd == LangStandard::lang_unspecified) {
231        // Based on the base language, pick one.
232        switch (IK) {
233            case IK_None:
234            case IK_AST:
235            case IK_LLVM_IR:
236                assert (!"Invalid input kind!");
237            case IK_OpenCL:
238                LangStd = LangStandard::lang_opencl;
239                break;
240            case IK_CUDA:
241                LangStd = LangStandard::lang_cuda;
242                break;
243            case IK_Asm:
244            case IK_C:
245            case IK_PreprocessedC:
246            case IK_ObjC:
247            case IK_PreprocessedObjC:
248                LangStd = LangStandard::lang_gnu99;
249                break;
250            case IK_CXX:
251            case IK_PreprocessedCXX:
252            case IK_ObjCXX:
253            case IK_PreprocessedObjCXX:
254                LangStd = LangStandard::lang_gnucxx98;
255                break;
256        }
257    }
258
259    const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd);
260    Opts.LineComment = Std.hasLineComments();
261    Opts.C99 = Std.isC99();
262    Opts.CPlusPlus = Std.isCPlusPlus();
263    Opts.CPlusPlus11 = Std.isCPlusPlus11();
264    Opts.Digraphs = Std.hasDigraphs();
265    Opts.GNUMode = Std.isGNUMode();
266    Opts.GNUInline = !Std.isC99();
267    Opts.HexFloats = Std.hasHexFloats();
268    Opts.ImplicitInt = Std.hasImplicitInt();
269
270    Opts.WChar = true;
271
272    // OpenCL has some additional defaults.
273    if (LangStd == LangStandard::lang_opencl) {
274        Opts.OpenCL = 1;
275        Opts.AltiVec = 1;
276        Opts.CXXOperatorNames = 1;
277        Opts.LaxVectorConversions = 1;
278    }
279
280    // OpenCL and C++ both have bool, true, false keywords.
281    Opts.Bool = Opts.OpenCL || Opts.CPlusPlus;
282
283//    if (Opts.CPlusPlus)
284//        Opts.CXXOperatorNames = !Args.hasArg(OPT_fno_operator_names);
285//
286//    if (Args.hasArg(OPT_fobjc_gc_only))
287//        Opts.setGCMode(LangOptions::GCOnly);
288//    else if (Args.hasArg(OPT_fobjc_gc))
289//        Opts.setGCMode(LangOptions::HybridGC);
290//
291//    if (Args.hasArg(OPT_print_ivar_layout))
292//        Opts.ObjCGCBitmapPrint = 1;
293//
294//    if (Args.hasArg(OPT_faltivec))
295//        Opts.AltiVec = 1;
296//
297//    if (Args.hasArg(OPT_pthread))
298//        Opts.POSIXThreads = 1;
299//
300//    llvm::StringRef Vis = getLastArgValue(Args, OPT_fvisibility,
301//                                          "default");
302//    if (Vis == "default")
303        Opts.setValueVisibilityMode(DefaultVisibility);
304//    else if (Vis == "hidden")
305//        Opts.setVisibilityMode(LangOptions::Hidden);
306//    else if (Vis == "protected")
307//        Opts.setVisibilityMode(LangOptions::Protected);
308//    else
309//        Diags.Report(diag::err_drv_invalid_value)
310//        << Args.getLastArg(OPT_fvisibility)->getAsString(Args) << Vis;
311
312//    Opts.OverflowChecking = Args.hasArg(OPT_ftrapv);
313
314    // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs
315    // is specified, or -std is set to a conforming mode.
316    Opts.Trigraphs = !Opts.GNUMode;
317//    if (Args.hasArg(OPT_trigraphs))
318//        Opts.Trigraphs = 1;
319//
320//    Opts.DollarIdents = Args.hasFlag(OPT_fdollars_in_identifiers,
321//                                     OPT_fno_dollars_in_identifiers,
322//                                     !Opts.AsmPreprocessor);
323//    Opts.PascalStrings = Args.hasArg(OPT_fpascal_strings);
324//    Opts.Microsoft = Args.hasArg(OPT_fms_extensions);
325//    Opts.WritableStrings = Args.hasArg(OPT_fwritable_strings);
326//    if (Args.hasArg(OPT_fno_lax_vector_conversions))
327//        Opts.LaxVectorConversions = 0;
328//    Opts.Exceptions = Args.hasArg(OPT_fexceptions);
329//    Opts.RTTI = !Args.hasArg(OPT_fno_rtti);
330//    Opts.Blocks = Args.hasArg(OPT_fblocks);
331//    Opts.CharIsSigned = !Args.hasArg(OPT_fno_signed_char);
332//    Opts.ShortWChar = Args.hasArg(OPT_fshort_wchar);
333//    Opts.Freestanding = Args.hasArg(OPT_ffreestanding);
334//    Opts.NoBuiltin = Args.hasArg(OPT_fno_builtin) || Opts.Freestanding;
335//    Opts.AssumeSaneOperatorNew = !Args.hasArg(OPT_fno_assume_sane_operator_new);
336//    Opts.HeinousExtensions = Args.hasArg(OPT_fheinous_gnu_extensions);
337//    Opts.AccessControl = Args.hasArg(OPT_faccess_control);
338//    Opts.ElideConstructors = !Args.hasArg(OPT_fno_elide_constructors);
339//    Opts.MathErrno = !Args.hasArg(OPT_fno_math_errno);
340//    Opts.InstantiationDepth = getLastArgIntValue(Args, OPT_ftemplate_depth, 99,
341//                                                 Diags);
342//    Opts.NeXTRuntime = !Args.hasArg(OPT_fgnu_runtime);
343//    Opts.ObjCConstantStringClass = getLastArgValue(Args,
344//                                                   OPT_fconstant_string_class);
345//    Opts.ObjCNonFragileABI = Args.hasArg(OPT_fobjc_nonfragile_abi);
346//    Opts.CatchUndefined = Args.hasArg(OPT_fcatch_undefined_behavior);
347//    Opts.EmitAllDecls = Args.hasArg(OPT_femit_all_decls);
348//    Opts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags);
349//    Opts.Static = Args.hasArg(OPT_static_define);
350    Opts.OptimizeSize = 0;
351
352    // FIXME: Eliminate this dependency.
353//    unsigned Opt =
354//    Args.hasArg(OPT_Os) ? 2 : getLastArgIntValue(Args, OPT_O, 0, Diags);
355//    Opts.Optimize = Opt != 0;
356    unsigned Opt = 0;
357
358    // This is the __NO_INLINE__ define, which just depends on things like the
359    // optimization level and -fno-inline, not actually whether the backend has
360    // inlining enabled.
361    //
362    // FIXME: This is affected by other options (-fno-inline).
363    Opts.NoInlineDefine = !Opt;
364
365//    unsigned SSP = getLastArgIntValue(Args, OPT_stack_protector, 0, Diags);
366//    switch (SSP) {
367//        default:
368//            Diags.Report(diag::err_drv_invalid_value)
369//            << Args.getLastArg(OPT_stack_protector)->getAsString(Args) << SSP;
370//            break;
371//        case 0: Opts.setStackProtectorMode(LangOptions::SSPOff); break;
372//        case 1: Opts.setStackProtectorMode(LangOptions::SSPOn);  break;
373//        case 2: Opts.setStackProtectorMode(LangOptions::SSPReq); break;
374//    }
375}
376
377
378ClangASTContext::ClangASTContext (const char *target_triple) :
379    m_target_triple(),
380    m_ast_ap(),
381    m_language_options_ap(),
382    m_source_manager_ap(),
383    m_diagnostics_engine_ap(),
384    m_target_options_rp(),
385    m_target_info_ap(),
386    m_identifier_table_ap(),
387    m_selector_table_ap(),
388    m_builtins_ap(),
389    m_callback_tag_decl (NULL),
390    m_callback_objc_decl (NULL),
391    m_callback_baton (NULL)
392
393{
394    if (target_triple && target_triple[0])
395        SetTargetTriple (target_triple);
396}
397
398//----------------------------------------------------------------------
399// Destructor
400//----------------------------------------------------------------------
401ClangASTContext::~ClangASTContext()
402{
403    m_builtins_ap.reset();
404    m_selector_table_ap.reset();
405    m_identifier_table_ap.reset();
406    m_target_info_ap.reset();
407    m_target_options_rp.reset();
408    m_diagnostics_engine_ap.reset();
409    m_source_manager_ap.reset();
410    m_language_options_ap.reset();
411    m_ast_ap.reset();
412}
413
414
415void
416ClangASTContext::Clear()
417{
418    m_ast_ap.reset();
419    m_language_options_ap.reset();
420    m_source_manager_ap.reset();
421    m_diagnostics_engine_ap.reset();
422    m_target_options_rp.reset();
423    m_target_info_ap.reset();
424    m_identifier_table_ap.reset();
425    m_selector_table_ap.reset();
426    m_builtins_ap.reset();
427}
428
429const char *
430ClangASTContext::GetTargetTriple ()
431{
432    return m_target_triple.c_str();
433}
434
435void
436ClangASTContext::SetTargetTriple (const char *target_triple)
437{
438    Clear();
439    m_target_triple.assign(target_triple);
440}
441
442void
443ClangASTContext::SetArchitecture (const ArchSpec &arch)
444{
445    SetTargetTriple(arch.GetTriple().str().c_str());
446}
447
448bool
449ClangASTContext::HasExternalSource ()
450{
451    ASTContext *ast = getASTContext();
452    if (ast)
453        return ast->getExternalSource () != NULL;
454    return false;
455}
456
457void
458ClangASTContext::SetExternalSource (llvm::OwningPtr<ExternalASTSource> &ast_source_ap)
459{
460    ASTContext *ast = getASTContext();
461    if (ast)
462    {
463        ast->setExternalSource (ast_source_ap);
464        ast->getTranslationUnitDecl()->setHasExternalLexicalStorage(true);
465        //ast->getTranslationUnitDecl()->setHasExternalVisibleStorage(true);
466    }
467}
468
469void
470ClangASTContext::RemoveExternalSource ()
471{
472    ASTContext *ast = getASTContext();
473
474    if (ast)
475    {
476        llvm::OwningPtr<ExternalASTSource> empty_ast_source_ap;
477        ast->setExternalSource (empty_ast_source_ap);
478        ast->getTranslationUnitDecl()->setHasExternalLexicalStorage(false);
479        //ast->getTranslationUnitDecl()->setHasExternalVisibleStorage(false);
480    }
481}
482
483
484
485ASTContext *
486ClangASTContext::getASTContext()
487{
488    if (m_ast_ap.get() == NULL)
489    {
490        m_ast_ap.reset(new ASTContext (*getLanguageOptions(),
491                                       *getSourceManager(),
492                                       getTargetInfo(),
493                                       *getIdentifierTable(),
494                                       *getSelectorTable(),
495                                       *getBuiltinContext(),
496                                       0));
497
498        if ((m_callback_tag_decl || m_callback_objc_decl) && m_callback_baton)
499        {
500            m_ast_ap->getTranslationUnitDecl()->setHasExternalLexicalStorage();
501            //m_ast_ap->getTranslationUnitDecl()->setHasExternalVisibleStorage();
502        }
503
504        m_ast_ap->getDiagnostics().setClient(getDiagnosticConsumer(), false);
505    }
506    return m_ast_ap.get();
507}
508
509Builtin::Context *
510ClangASTContext::getBuiltinContext()
511{
512    if (m_builtins_ap.get() == NULL)
513        m_builtins_ap.reset (new Builtin::Context());
514    return m_builtins_ap.get();
515}
516
517IdentifierTable *
518ClangASTContext::getIdentifierTable()
519{
520    if (m_identifier_table_ap.get() == NULL)
521        m_identifier_table_ap.reset(new IdentifierTable (*ClangASTContext::getLanguageOptions(), NULL));
522    return m_identifier_table_ap.get();
523}
524
525LangOptions *
526ClangASTContext::getLanguageOptions()
527{
528    if (m_language_options_ap.get() == NULL)
529    {
530        m_language_options_ap.reset(new LangOptions());
531        ParseLangArgs(*m_language_options_ap, IK_ObjCXX);
532//        InitializeLangOptions(*m_language_options_ap, IK_ObjCXX);
533    }
534    return m_language_options_ap.get();
535}
536
537SelectorTable *
538ClangASTContext::getSelectorTable()
539{
540    if (m_selector_table_ap.get() == NULL)
541        m_selector_table_ap.reset (new SelectorTable());
542    return m_selector_table_ap.get();
543}
544
545clang::FileManager *
546ClangASTContext::getFileManager()
547{
548    if (m_file_manager_ap.get() == NULL)
549    {
550        clang::FileSystemOptions file_system_options;
551        m_file_manager_ap.reset(new clang::FileManager(file_system_options));
552    }
553    return m_file_manager_ap.get();
554}
555
556clang::SourceManager *
557ClangASTContext::getSourceManager()
558{
559    if (m_source_manager_ap.get() == NULL)
560        m_source_manager_ap.reset(new clang::SourceManager(*getDiagnosticsEngine(), *getFileManager()));
561    return m_source_manager_ap.get();
562}
563
564clang::DiagnosticsEngine *
565ClangASTContext::getDiagnosticsEngine()
566{
567    if (m_diagnostics_engine_ap.get() == NULL)
568    {
569        llvm::IntrusiveRefCntPtr<DiagnosticIDs> diag_id_sp(new DiagnosticIDs());
570        m_diagnostics_engine_ap.reset(new DiagnosticsEngine(diag_id_sp, new DiagnosticOptions()));
571    }
572    return m_diagnostics_engine_ap.get();
573}
574
575class NullDiagnosticConsumer : public DiagnosticConsumer
576{
577public:
578    NullDiagnosticConsumer ()
579    {
580        m_log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
581    }
582
583    void HandleDiagnostic (DiagnosticsEngine::Level DiagLevel, const Diagnostic &info)
584    {
585        if (m_log)
586        {
587            llvm::SmallVector<char, 32> diag_str(10);
588            info.FormatDiagnostic(diag_str);
589            diag_str.push_back('\0');
590            m_log->Printf("Compiler diagnostic: %s\n", diag_str.data());
591        }
592    }
593
594    DiagnosticConsumer *clone (DiagnosticsEngine &Diags) const
595    {
596        return new NullDiagnosticConsumer ();
597    }
598private:
599    Log * m_log;
600};
601
602DiagnosticConsumer *
603ClangASTContext::getDiagnosticConsumer()
604{
605    if (m_diagnostic_consumer_ap.get() == NULL)
606        m_diagnostic_consumer_ap.reset(new NullDiagnosticConsumer);
607
608    return m_diagnostic_consumer_ap.get();
609}
610
611TargetOptions *
612ClangASTContext::getTargetOptions()
613{
614    if (m_target_options_rp.getPtr() == NULL && !m_target_triple.empty())
615    {
616        m_target_options_rp.reset ();
617        m_target_options_rp = new TargetOptions();
618        if (m_target_options_rp.getPtr() != NULL)
619            m_target_options_rp->Triple = m_target_triple;
620    }
621    return m_target_options_rp.getPtr();
622}
623
624
625TargetInfo *
626ClangASTContext::getTargetInfo()
627{
628    // target_triple should be something like "x86_64-apple-macosx"
629    if (m_target_info_ap.get() == NULL && !m_target_triple.empty())
630        m_target_info_ap.reset (TargetInfo::CreateTargetInfo(*getDiagnosticsEngine(), getTargetOptions()));
631    return m_target_info_ap.get();
632}
633
634#pragma mark Basic Types
635
636static inline bool
637QualTypeMatchesBitSize(const uint64_t bit_size, ASTContext *ast, QualType qual_type)
638{
639    uint64_t qual_type_bit_size = ast->getTypeSize(qual_type);
640    if (qual_type_bit_size == bit_size)
641        return true;
642    return false;
643}
644
645clang_type_t
646ClangASTContext::GetBuiltinTypeForEncodingAndBitSize (Encoding encoding, uint32_t bit_size)
647{
648    ASTContext *ast = getASTContext();
649
650    assert (ast != NULL);
651
652    return GetBuiltinTypeForEncodingAndBitSize (ast, encoding, bit_size);
653}
654
655clang_type_t
656ClangASTContext::GetBuiltinTypeForEncodingAndBitSize (ASTContext *ast, Encoding encoding, uint32_t bit_size)
657{
658    if (!ast)
659        return NULL;
660
661    switch (encoding)
662    {
663    case eEncodingInvalid:
664        if (QualTypeMatchesBitSize (bit_size, ast, ast->VoidPtrTy))
665            return ast->VoidPtrTy.getAsOpaquePtr();
666        break;
667
668    case eEncodingUint:
669        if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedCharTy))
670            return ast->UnsignedCharTy.getAsOpaquePtr();
671        if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedShortTy))
672            return ast->UnsignedShortTy.getAsOpaquePtr();
673        if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedIntTy))
674            return ast->UnsignedIntTy.getAsOpaquePtr();
675        if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedLongTy))
676            return ast->UnsignedLongTy.getAsOpaquePtr();
677        if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedLongLongTy))
678            return ast->UnsignedLongLongTy.getAsOpaquePtr();
679        if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedInt128Ty))
680            return ast->UnsignedInt128Ty.getAsOpaquePtr();
681        break;
682
683    case eEncodingSint:
684        if (QualTypeMatchesBitSize (bit_size, ast, ast->CharTy))
685            return ast->CharTy.getAsOpaquePtr();
686        if (QualTypeMatchesBitSize (bit_size, ast, ast->ShortTy))
687            return ast->ShortTy.getAsOpaquePtr();
688        if (QualTypeMatchesBitSize (bit_size, ast, ast->IntTy))
689            return ast->IntTy.getAsOpaquePtr();
690        if (QualTypeMatchesBitSize (bit_size, ast, ast->LongTy))
691            return ast->LongTy.getAsOpaquePtr();
692        if (QualTypeMatchesBitSize (bit_size, ast, ast->LongLongTy))
693            return ast->LongLongTy.getAsOpaquePtr();
694        if (QualTypeMatchesBitSize (bit_size, ast, ast->Int128Ty))
695            return ast->Int128Ty.getAsOpaquePtr();
696        break;
697
698    case eEncodingIEEE754:
699        if (QualTypeMatchesBitSize (bit_size, ast, ast->FloatTy))
700            return ast->FloatTy.getAsOpaquePtr();
701        if (QualTypeMatchesBitSize (bit_size, ast, ast->DoubleTy))
702            return ast->DoubleTy.getAsOpaquePtr();
703        if (QualTypeMatchesBitSize (bit_size, ast, ast->LongDoubleTy))
704            return ast->LongDoubleTy.getAsOpaquePtr();
705        break;
706
707    case eEncodingVector:
708        // Sanity check that bit_size is a multiple of 8's.
709        if (bit_size && !(bit_size & 0x7u))
710            return ast->getExtVectorType (ast->UnsignedCharTy, bit_size/8).getAsOpaquePtr();
711        break;
712    }
713
714    return NULL;
715}
716
717clang_type_t
718ClangASTContext::GetBuiltinTypeForDWARFEncodingAndBitSize (const char *type_name, uint32_t dw_ate, uint32_t bit_size)
719{
720    ASTContext *ast = getASTContext();
721
722#define streq(a,b) strcmp(a,b) == 0
723    assert (ast != NULL);
724    if (ast)
725    {
726        switch (dw_ate)
727        {
728            default:
729                break;
730
731            case DW_ATE_address:
732                if (QualTypeMatchesBitSize (bit_size, ast, ast->VoidPtrTy))
733                    return ast->VoidPtrTy.getAsOpaquePtr();
734                break;
735
736            case DW_ATE_boolean:
737                if (QualTypeMatchesBitSize (bit_size, ast, ast->BoolTy))
738                    return ast->BoolTy.getAsOpaquePtr();
739                if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedCharTy))
740                    return ast->UnsignedCharTy.getAsOpaquePtr();
741                if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedShortTy))
742                    return ast->UnsignedShortTy.getAsOpaquePtr();
743                if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedIntTy))
744                    return ast->UnsignedIntTy.getAsOpaquePtr();
745                break;
746
747            case DW_ATE_lo_user:
748                // This has been seen to mean DW_AT_complex_integer
749                if (type_name)
750                {
751                    if (::strstr(type_name, "complex"))
752                    {
753                        clang_type_t complex_int_clang_type = GetBuiltinTypeForDWARFEncodingAndBitSize ("int", DW_ATE_signed, bit_size/2);
754                        return ast->getComplexType (QualType::getFromOpaquePtr(complex_int_clang_type)).getAsOpaquePtr();
755                    }
756                }
757                break;
758
759            case DW_ATE_complex_float:
760                if (QualTypeMatchesBitSize (bit_size, ast, ast->FloatComplexTy))
761                    return ast->FloatComplexTy.getAsOpaquePtr();
762                else if (QualTypeMatchesBitSize (bit_size, ast, ast->DoubleComplexTy))
763                    return ast->DoubleComplexTy.getAsOpaquePtr();
764                else if (QualTypeMatchesBitSize (bit_size, ast, ast->LongDoubleComplexTy))
765                    return ast->LongDoubleComplexTy.getAsOpaquePtr();
766                else
767                {
768                    clang_type_t complex_float_clang_type = GetBuiltinTypeForDWARFEncodingAndBitSize ("float", DW_ATE_float, bit_size/2);
769                    return ast->getComplexType (QualType::getFromOpaquePtr(complex_float_clang_type)).getAsOpaquePtr();
770                }
771                break;
772
773            case DW_ATE_float:
774                if (QualTypeMatchesBitSize (bit_size, ast, ast->FloatTy))
775                    return ast->FloatTy.getAsOpaquePtr();
776                if (QualTypeMatchesBitSize (bit_size, ast, ast->DoubleTy))
777                    return ast->DoubleTy.getAsOpaquePtr();
778                if (QualTypeMatchesBitSize (bit_size, ast, ast->LongDoubleTy))
779                    return ast->LongDoubleTy.getAsOpaquePtr();
780                break;
781
782            case DW_ATE_signed:
783                if (type_name)
784                {
785                    if (streq(type_name, "wchar_t") &&
786                        QualTypeMatchesBitSize (bit_size, ast, ast->WCharTy))
787                        return ast->WCharTy.getAsOpaquePtr();
788                    if (streq(type_name, "void") &&
789                        QualTypeMatchesBitSize (bit_size, ast, ast->VoidTy))
790                        return ast->VoidTy.getAsOpaquePtr();
791                    if (strstr(type_name, "long long") &&
792                        QualTypeMatchesBitSize (bit_size, ast, ast->LongLongTy))
793                        return ast->LongLongTy.getAsOpaquePtr();
794                    if (strstr(type_name, "long") &&
795                        QualTypeMatchesBitSize (bit_size, ast, ast->LongTy))
796                        return ast->LongTy.getAsOpaquePtr();
797                    if (strstr(type_name, "short") &&
798                        QualTypeMatchesBitSize (bit_size, ast, ast->ShortTy))
799                        return ast->ShortTy.getAsOpaquePtr();
800                    if (strstr(type_name, "char"))
801                    {
802                        if (QualTypeMatchesBitSize (bit_size, ast, ast->CharTy))
803                            return ast->CharTy.getAsOpaquePtr();
804                        if (QualTypeMatchesBitSize (bit_size, ast, ast->SignedCharTy))
805                            return ast->SignedCharTy.getAsOpaquePtr();
806                    }
807                    if (strstr(type_name, "int"))
808                    {
809                        if (QualTypeMatchesBitSize (bit_size, ast, ast->IntTy))
810                            return ast->IntTy.getAsOpaquePtr();
811                        if (QualTypeMatchesBitSize (bit_size, ast, ast->Int128Ty))
812                            return ast->Int128Ty.getAsOpaquePtr();
813                    }
814                }
815                // We weren't able to match up a type name, just search by size
816                if (QualTypeMatchesBitSize (bit_size, ast, ast->CharTy))
817                    return ast->CharTy.getAsOpaquePtr();
818                if (QualTypeMatchesBitSize (bit_size, ast, ast->ShortTy))
819                    return ast->ShortTy.getAsOpaquePtr();
820                if (QualTypeMatchesBitSize (bit_size, ast, ast->IntTy))
821                    return ast->IntTy.getAsOpaquePtr();
822                if (QualTypeMatchesBitSize (bit_size, ast, ast->LongTy))
823                    return ast->LongTy.getAsOpaquePtr();
824                if (QualTypeMatchesBitSize (bit_size, ast, ast->LongLongTy))
825                    return ast->LongLongTy.getAsOpaquePtr();
826                if (QualTypeMatchesBitSize (bit_size, ast, ast->Int128Ty))
827                    return ast->Int128Ty.getAsOpaquePtr();
828                break;
829
830            case DW_ATE_signed_char:
831                if (type_name)
832                {
833                    if (streq(type_name, "signed char"))
834                    {
835                        if (QualTypeMatchesBitSize (bit_size, ast, ast->SignedCharTy))
836                            return ast->SignedCharTy.getAsOpaquePtr();
837                    }
838                }
839                if (QualTypeMatchesBitSize (bit_size, ast, ast->CharTy))
840                    return ast->CharTy.getAsOpaquePtr();
841                if (QualTypeMatchesBitSize (bit_size, ast, ast->SignedCharTy))
842                    return ast->SignedCharTy.getAsOpaquePtr();
843                break;
844
845            case DW_ATE_unsigned:
846                if (type_name)
847                {
848                    if (strstr(type_name, "long long"))
849                    {
850                        if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedLongLongTy))
851                            return ast->UnsignedLongLongTy.getAsOpaquePtr();
852                    }
853                    else if (strstr(type_name, "long"))
854                    {
855                        if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedLongTy))
856                            return ast->UnsignedLongTy.getAsOpaquePtr();
857                    }
858                    else if (strstr(type_name, "short"))
859                    {
860                        if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedShortTy))
861                            return ast->UnsignedShortTy.getAsOpaquePtr();
862                    }
863                    else if (strstr(type_name, "char"))
864                    {
865                        if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedCharTy))
866                            return ast->UnsignedCharTy.getAsOpaquePtr();
867                    }
868                    else if (strstr(type_name, "int"))
869                    {
870                        if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedIntTy))
871                            return ast->UnsignedIntTy.getAsOpaquePtr();
872                        if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedInt128Ty))
873                            return ast->UnsignedInt128Ty.getAsOpaquePtr();
874                    }
875                }
876                // We weren't able to match up a type name, just search by size
877                if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedCharTy))
878                    return ast->UnsignedCharTy.getAsOpaquePtr();
879                if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedShortTy))
880                    return ast->UnsignedShortTy.getAsOpaquePtr();
881                if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedIntTy))
882                    return ast->UnsignedIntTy.getAsOpaquePtr();
883                if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedLongTy))
884                    return ast->UnsignedLongTy.getAsOpaquePtr();
885                if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedLongLongTy))
886                    return ast->UnsignedLongLongTy.getAsOpaquePtr();
887                if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedInt128Ty))
888                    return ast->UnsignedInt128Ty.getAsOpaquePtr();
889                break;
890
891            case DW_ATE_unsigned_char:
892                if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedCharTy))
893                    return ast->UnsignedCharTy.getAsOpaquePtr();
894                if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedShortTy))
895                    return ast->UnsignedShortTy.getAsOpaquePtr();
896                break;
897
898            case DW_ATE_imaginary_float:
899                break;
900
901            case DW_ATE_UTF:
902                if (type_name)
903                {
904                    if (streq(type_name, "char16_t"))
905                    {
906                        return ast->Char16Ty.getAsOpaquePtr();
907                    }
908                    else if (streq(type_name, "char32_t"))
909                    {
910                        return ast->Char32Ty.getAsOpaquePtr();
911                    }
912                }
913                break;
914        }
915    }
916    // This assert should fire for anything that we don't catch above so we know
917    // to fix any issues we run into.
918    if (type_name)
919    {
920        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);
921    }
922    else
923    {
924        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);
925    }
926    return NULL;
927}
928
929clang_type_t
930ClangASTContext::GetBuiltInType_void(ASTContext *ast)
931{
932    return ast->VoidTy.getAsOpaquePtr();
933}
934
935clang_type_t
936ClangASTContext::GetBuiltInType_bool()
937{
938    return getASTContext()->BoolTy.getAsOpaquePtr();
939}
940
941clang_type_t
942ClangASTContext::GetBuiltInType_objc_id()
943{
944    return getASTContext()->getObjCIdType().getAsOpaquePtr();
945}
946
947lldb::clang_type_t
948ClangASTContext::GetBuiltInType_objc_id(clang::ASTContext *ast)
949{
950    return ast->getObjCIdType().getAsOpaquePtr();
951}
952
953clang_type_t
954ClangASTContext::GetBuiltInType_objc_Class()
955{
956    return getASTContext()->getObjCClassType().getAsOpaquePtr();
957}
958
959clang_type_t
960ClangASTContext::GetBuiltInType_objc_selector()
961{
962    return getASTContext()->getObjCSelType().getAsOpaquePtr();
963}
964
965clang_type_t
966ClangASTContext::GetUnknownAnyType(clang::ASTContext *ast)
967{
968    return ast->UnknownAnyTy.getAsOpaquePtr();
969}
970
971clang_type_t
972ClangASTContext::GetCStringType (bool is_const)
973{
974    QualType char_type(getASTContext()->CharTy);
975
976    if (is_const)
977        char_type.addConst();
978
979    return getASTContext()->getPointerType(char_type).getAsOpaquePtr();
980}
981
982clang_type_t
983ClangASTContext::GetVoidType()
984{
985    return GetVoidType(getASTContext());
986}
987
988clang_type_t
989ClangASTContext::GetVoidType(ASTContext *ast)
990{
991    return ast->VoidTy.getAsOpaquePtr();
992}
993
994clang_type_t
995ClangASTContext::GetVoidPtrType (bool is_const)
996{
997    return GetVoidPtrType(getASTContext(), is_const);
998}
999
1000clang_type_t
1001ClangASTContext::GetVoidPtrType (ASTContext *ast, bool is_const)
1002{
1003    QualType void_ptr_type(ast->VoidPtrTy);
1004
1005    if (is_const)
1006        void_ptr_type.addConst();
1007
1008    return void_ptr_type.getAsOpaquePtr();
1009}
1010
1011clang::DeclContext *
1012ClangASTContext::GetTranslationUnitDecl (clang::ASTContext *ast)
1013{
1014    return ast->getTranslationUnitDecl();
1015}
1016
1017clang_type_t
1018ClangASTContext::CopyType (ASTContext *dst_ast,
1019                           ASTContext *src_ast,
1020                           clang_type_t clang_type)
1021{
1022    FileSystemOptions file_system_options;
1023    FileManager file_manager (file_system_options);
1024    ASTImporter importer(*dst_ast, file_manager,
1025                         *src_ast, file_manager,
1026                         false);
1027
1028    QualType src (QualType::getFromOpaquePtr(clang_type));
1029    QualType dst (importer.Import(src));
1030
1031    return dst.getAsOpaquePtr();
1032}
1033
1034
1035clang::Decl *
1036ClangASTContext::CopyDecl (ASTContext *dst_ast,
1037                           ASTContext *src_ast,
1038                           clang::Decl *source_decl)
1039{
1040    FileSystemOptions file_system_options;
1041    FileManager file_manager (file_system_options);
1042    ASTImporter importer(*dst_ast, file_manager,
1043                         *src_ast, file_manager,
1044                         false);
1045
1046    return importer.Import(source_decl);
1047}
1048
1049bool
1050ClangASTContext::AreTypesSame (ASTContext *ast,
1051                               clang_type_t type1,
1052                               clang_type_t type2,
1053                               bool ignore_qualifiers)
1054{
1055    if (type1 == type2)
1056        return true;
1057
1058    QualType type1_qual = QualType::getFromOpaquePtr(type1);
1059    QualType type2_qual = QualType::getFromOpaquePtr(type2);
1060
1061    if (ignore_qualifiers)
1062    {
1063        type1_qual = type1_qual.getUnqualifiedType();
1064        type2_qual = type2_qual.getUnqualifiedType();
1065    }
1066
1067    return ast->hasSameType (type1_qual,
1068                             type2_qual);
1069}
1070
1071#pragma mark CVR modifiers
1072
1073clang_type_t
1074ClangASTContext::AddConstModifier (clang_type_t clang_type)
1075{
1076    if (clang_type)
1077    {
1078        QualType result(QualType::getFromOpaquePtr(clang_type));
1079        result.addConst();
1080        return result.getAsOpaquePtr();
1081    }
1082    return NULL;
1083}
1084
1085clang_type_t
1086ClangASTContext::AddRestrictModifier (clang_type_t clang_type)
1087{
1088    if (clang_type)
1089    {
1090        QualType result(QualType::getFromOpaquePtr(clang_type));
1091        result.getQualifiers().setRestrict (true);
1092        return result.getAsOpaquePtr();
1093    }
1094    return NULL;
1095}
1096
1097clang_type_t
1098ClangASTContext::AddVolatileModifier (clang_type_t clang_type)
1099{
1100    if (clang_type)
1101    {
1102        QualType result(QualType::getFromOpaquePtr(clang_type));
1103        result.getQualifiers().setVolatile (true);
1104        return result.getAsOpaquePtr();
1105    }
1106    return NULL;
1107}
1108
1109
1110clang_type_t
1111ClangASTContext::GetTypeForDecl (TagDecl *decl)
1112{
1113    // No need to call the getASTContext() accessor (which can create the AST
1114    // if it isn't created yet, because we can't have created a decl in this
1115    // AST if our AST didn't already exist...
1116    if (m_ast_ap.get())
1117        return m_ast_ap->getTagDeclType(decl).getAsOpaquePtr();
1118    return NULL;
1119}
1120
1121clang_type_t
1122ClangASTContext::GetTypeForDecl (ObjCInterfaceDecl *decl)
1123{
1124    // No need to call the getASTContext() accessor (which can create the AST
1125    // if it isn't created yet, because we can't have created a decl in this
1126    // AST if our AST didn't already exist...
1127    if (m_ast_ap.get())
1128        return m_ast_ap->getObjCInterfaceType(decl).getAsOpaquePtr();
1129    return NULL;
1130}
1131
1132#pragma mark Structure, Unions, Classes
1133
1134clang_type_t
1135ClangASTContext::CreateRecordType (DeclContext *decl_ctx,
1136                                   AccessType access_type,
1137                                   const char *name,
1138                                   int kind,
1139                                   LanguageType language,
1140                                   ClangASTMetadata *metadata)
1141{
1142    ASTContext *ast = getASTContext();
1143    assert (ast != NULL);
1144
1145    if (decl_ctx == NULL)
1146        decl_ctx = ast->getTranslationUnitDecl();
1147
1148
1149    if (language == eLanguageTypeObjC || language == eLanguageTypeObjC_plus_plus)
1150    {
1151        bool isForwardDecl = true;
1152        bool isInternal = false;
1153        return CreateObjCClass (name, decl_ctx, isForwardDecl, isInternal, metadata);
1154    }
1155
1156    // NOTE: Eventually CXXRecordDecl will be merged back into RecordDecl and
1157    // we will need to update this code. I was told to currently always use
1158    // the CXXRecordDecl class since we often don't know from debug information
1159    // if something is struct or a class, so we default to always use the more
1160    // complete definition just in case.
1161    CXXRecordDecl *decl = CXXRecordDecl::Create (*ast,
1162                                                 (TagDecl::TagKind)kind,
1163                                                 decl_ctx,
1164                                                 SourceLocation(),
1165                                                 SourceLocation(),
1166                                                 name && name[0] ? &ast->Idents.get(name) : NULL);
1167
1168    if (decl)
1169    {
1170        if (metadata)
1171            SetMetadata(ast, decl, *metadata);
1172
1173        if (access_type != eAccessNone)
1174            decl->setAccess (ConvertAccessTypeToAccessSpecifier (access_type));
1175
1176        if (decl_ctx)
1177            decl_ctx->addDecl (decl);
1178
1179        return ast->getTagDeclType(decl).getAsOpaquePtr();
1180    }
1181    return NULL;
1182}
1183
1184static TemplateParameterList *
1185CreateTemplateParameterList (ASTContext *ast,
1186                             const ClangASTContext::TemplateParameterInfos &template_param_infos,
1187                             llvm::SmallVector<NamedDecl *, 8> &template_param_decls)
1188{
1189    const bool parameter_pack = false;
1190    const bool is_typename = false;
1191    const unsigned depth = 0;
1192    const size_t num_template_params = template_param_infos.GetSize();
1193    for (size_t i=0; i<num_template_params; ++i)
1194    {
1195        const char *name = template_param_infos.names[i];
1196        if (template_param_infos.args[i].getKind() == TemplateArgument::Integral)
1197        {
1198            template_param_decls.push_back (NonTypeTemplateParmDecl::Create (*ast,
1199                                                                             ast->getTranslationUnitDecl(), // Is this the right decl context?, SourceLocation StartLoc,
1200                                                                             SourceLocation(),
1201                                                                             SourceLocation(),
1202                                                                             depth,
1203                                                                             i,
1204                                                                             &ast->Idents.get(name),
1205                                                                             template_param_infos.args[i].getIntegralType(),
1206                                                                             parameter_pack,
1207                                                                             NULL));
1208
1209        }
1210        else
1211        {
1212            template_param_decls.push_back (TemplateTypeParmDecl::Create (*ast,
1213                                                                          ast->getTranslationUnitDecl(), // Is this the right decl context?
1214                                                                          SourceLocation(),
1215                                                                          SourceLocation(),
1216                                                                          depth,
1217                                                                          i,
1218                                                                          &ast->Idents.get(name),
1219                                                                          is_typename,
1220                                                                          parameter_pack));
1221        }
1222    }
1223
1224    TemplateParameterList *template_param_list = TemplateParameterList::Create (*ast,
1225                                                                                SourceLocation(),
1226                                                                                SourceLocation(),
1227                                                                                &template_param_decls.front(),
1228                                                                                template_param_decls.size(),
1229                                                                                SourceLocation());
1230    return template_param_list;
1231}
1232
1233clang::FunctionTemplateDecl *
1234ClangASTContext::CreateFunctionTemplateDecl (clang::DeclContext *decl_ctx,
1235                                             clang::FunctionDecl *func_decl,
1236                                             const char *name,
1237                                             const TemplateParameterInfos &template_param_infos)
1238{
1239//    /// \brief Create a function template node.
1240    ASTContext *ast = getASTContext();
1241
1242    llvm::SmallVector<NamedDecl *, 8> template_param_decls;
1243
1244    TemplateParameterList *template_param_list = CreateTemplateParameterList (ast,
1245                                                                              template_param_infos,
1246                                                                              template_param_decls);
1247    FunctionTemplateDecl *func_tmpl_decl = FunctionTemplateDecl::Create (*ast,
1248                                                                         decl_ctx,
1249                                                                         func_decl->getLocation(),
1250                                                                         func_decl->getDeclName(),
1251                                                                         template_param_list,
1252                                                                         func_decl);
1253
1254    for (size_t i=0, template_param_decl_count = template_param_decls.size();
1255         i < template_param_decl_count;
1256         ++i)
1257    {
1258        // TODO: verify which decl context we should put template_param_decls into..
1259        template_param_decls[i]->setDeclContext (func_decl);
1260    }
1261
1262    return func_tmpl_decl;
1263}
1264
1265void
1266ClangASTContext::CreateFunctionTemplateSpecializationInfo (FunctionDecl *func_decl,
1267                                                           clang::FunctionTemplateDecl *func_tmpl_decl,
1268                                                           const TemplateParameterInfos &infos)
1269{
1270    TemplateArgumentList template_args (TemplateArgumentList::OnStack,
1271                                        infos.args.data(),
1272                                        infos.args.size());
1273
1274    func_decl->setFunctionTemplateSpecialization (func_tmpl_decl,
1275                                                  &template_args,
1276                                                  NULL);
1277}
1278
1279
1280ClassTemplateDecl *
1281ClangASTContext::CreateClassTemplateDecl (DeclContext *decl_ctx,
1282                                          lldb::AccessType access_type,
1283                                          const char *class_name,
1284                                          int kind,
1285                                          const TemplateParameterInfos &template_param_infos)
1286{
1287    ASTContext *ast = getASTContext();
1288
1289    ClassTemplateDecl *class_template_decl = NULL;
1290    if (decl_ctx == NULL)
1291        decl_ctx = ast->getTranslationUnitDecl();
1292
1293    IdentifierInfo &identifier_info = ast->Idents.get(class_name);
1294    DeclarationName decl_name (&identifier_info);
1295
1296    clang::DeclContext::lookup_result result = decl_ctx->lookup(decl_name);
1297
1298    for (NamedDecl *decl : result)
1299    {
1300        class_template_decl = dyn_cast<clang::ClassTemplateDecl>(decl);
1301        if (class_template_decl)
1302            return class_template_decl;
1303    }
1304
1305    llvm::SmallVector<NamedDecl *, 8> template_param_decls;
1306
1307    TemplateParameterList *template_param_list = CreateTemplateParameterList (ast,
1308                                                                              template_param_infos,
1309                                                                              template_param_decls);
1310
1311    CXXRecordDecl *template_cxx_decl = CXXRecordDecl::Create (*ast,
1312                                                              (TagDecl::TagKind)kind,
1313                                                              decl_ctx,  // What decl context do we use here? TU? The actual decl context?
1314                                                              SourceLocation(),
1315                                                              SourceLocation(),
1316                                                              &identifier_info);
1317
1318    for (size_t i=0, template_param_decl_count = template_param_decls.size();
1319         i < template_param_decl_count;
1320         ++i)
1321    {
1322        template_param_decls[i]->setDeclContext (template_cxx_decl);
1323    }
1324
1325    // With templated classes, we say that a class is templated with
1326    // specializations, but that the bare class has no functions.
1327    //template_cxx_decl->startDefinition();
1328    //template_cxx_decl->completeDefinition();
1329
1330    class_template_decl = ClassTemplateDecl::Create (*ast,
1331                                                     decl_ctx,  // What decl context do we use here? TU? The actual decl context?
1332                                                     SourceLocation(),
1333                                                     decl_name,
1334                                                     template_param_list,
1335                                                     template_cxx_decl,
1336                                                     NULL);
1337
1338    if (class_template_decl)
1339    {
1340        if (access_type != eAccessNone)
1341            class_template_decl->setAccess (ConvertAccessTypeToAccessSpecifier (access_type));
1342
1343        //if (TagDecl *ctx_tag_decl = dyn_cast<TagDecl>(decl_ctx))
1344        //    CompleteTagDeclarationDefinition(GetTypeForDecl(ctx_tag_decl));
1345
1346        decl_ctx->addDecl (class_template_decl);
1347
1348#ifdef LLDB_CONFIGURATION_DEBUG
1349        VerifyDecl(class_template_decl);
1350#endif
1351    }
1352
1353    return class_template_decl;
1354}
1355
1356
1357ClassTemplateSpecializationDecl *
1358ClangASTContext::CreateClassTemplateSpecializationDecl (DeclContext *decl_ctx,
1359                                                        ClassTemplateDecl *class_template_decl,
1360                                                        int kind,
1361                                                        const TemplateParameterInfos &template_param_infos)
1362{
1363    ASTContext *ast = getASTContext();
1364    ClassTemplateSpecializationDecl *class_template_specialization_decl = ClassTemplateSpecializationDecl::Create (*ast,
1365                                                                                                                   (TagDecl::TagKind)kind,
1366                                                                                                                   decl_ctx,
1367                                                                                                                   SourceLocation(),
1368                                                                                                                   SourceLocation(),
1369                                                                                                                   class_template_decl,
1370                                                                                                                   &template_param_infos.args.front(),
1371                                                                                                                   template_param_infos.args.size(),
1372                                                                                                                   NULL);
1373
1374    class_template_specialization_decl->setSpecializationKind(TSK_ExplicitSpecialization);
1375
1376    return class_template_specialization_decl;
1377}
1378
1379lldb::clang_type_t
1380ClangASTContext::CreateClassTemplateSpecializationType (ClassTemplateSpecializationDecl *class_template_specialization_decl)
1381{
1382    if (class_template_specialization_decl)
1383    {
1384        ASTContext *ast = getASTContext();
1385        if (ast)
1386            return ast->getTagDeclType(class_template_specialization_decl).getAsOpaquePtr();
1387    }
1388    return NULL;
1389}
1390
1391bool
1392ClangASTContext::SetHasExternalStorage (clang_type_t clang_type, bool has_extern)
1393{
1394    if (clang_type == NULL)
1395        return false;
1396
1397    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
1398
1399    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
1400    switch (type_class)
1401    {
1402    case clang::Type::Record:
1403        {
1404            CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
1405            if (cxx_record_decl)
1406            {
1407                cxx_record_decl->setHasExternalLexicalStorage (has_extern);
1408                cxx_record_decl->setHasExternalVisibleStorage (has_extern);
1409                return true;
1410            }
1411        }
1412        break;
1413
1414    case clang::Type::Enum:
1415        {
1416            EnumDecl *enum_decl = cast<EnumType>(qual_type)->getDecl();
1417            if (enum_decl)
1418            {
1419                enum_decl->setHasExternalLexicalStorage (has_extern);
1420                enum_decl->setHasExternalVisibleStorage (has_extern);
1421                return true;
1422            }
1423        }
1424        break;
1425
1426    case clang::Type::ObjCObject:
1427    case clang::Type::ObjCInterface:
1428        {
1429            const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(qual_type.getTypePtr());
1430            assert (objc_class_type);
1431            if (objc_class_type)
1432            {
1433                ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
1434
1435                if (class_interface_decl)
1436                {
1437                    class_interface_decl->setHasExternalLexicalStorage (has_extern);
1438                    class_interface_decl->setHasExternalVisibleStorage (has_extern);
1439                    return true;
1440                }
1441            }
1442        }
1443        break;
1444
1445    case clang::Type::Typedef:
1446        return ClangASTContext::SetHasExternalStorage (cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(), has_extern);
1447
1448    case clang::Type::Elaborated:
1449        return ClangASTContext::SetHasExternalStorage (cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(), has_extern);
1450
1451    default:
1452        break;
1453    }
1454    return false;
1455}
1456
1457static bool
1458IsOperator (const char *name, OverloadedOperatorKind &op_kind)
1459{
1460    if (name == NULL || name[0] == '\0')
1461        return false;
1462
1463#define OPERATOR_PREFIX "operator"
1464#define OPERATOR_PREFIX_LENGTH (sizeof (OPERATOR_PREFIX) - 1)
1465
1466    const char *post_op_name = NULL;
1467
1468    bool no_space = true;
1469
1470    if (::strncmp(name, OPERATOR_PREFIX, OPERATOR_PREFIX_LENGTH))
1471        return false;
1472
1473    post_op_name = name + OPERATOR_PREFIX_LENGTH;
1474
1475    if (post_op_name[0] == ' ')
1476    {
1477        post_op_name++;
1478        no_space = false;
1479    }
1480
1481#undef OPERATOR_PREFIX
1482#undef OPERATOR_PREFIX_LENGTH
1483
1484    // This is an operator, set the overloaded operator kind to invalid
1485    // in case this is a conversion operator...
1486    op_kind = NUM_OVERLOADED_OPERATORS;
1487
1488    switch (post_op_name[0])
1489    {
1490    default:
1491        if (no_space)
1492            return false;
1493        break;
1494    case 'n':
1495        if (no_space)
1496            return false;
1497        if  (strcmp (post_op_name, "new") == 0)
1498            op_kind = OO_New;
1499        else if (strcmp (post_op_name, "new[]") == 0)
1500            op_kind = OO_Array_New;
1501        break;
1502
1503    case 'd':
1504        if (no_space)
1505            return false;
1506        if (strcmp (post_op_name, "delete") == 0)
1507            op_kind = OO_Delete;
1508        else if (strcmp (post_op_name, "delete[]") == 0)
1509            op_kind = OO_Array_Delete;
1510        break;
1511
1512    case '+':
1513        if (post_op_name[1] == '\0')
1514            op_kind = OO_Plus;
1515        else if (post_op_name[2] == '\0')
1516        {
1517            if (post_op_name[1] == '=')
1518                op_kind = OO_PlusEqual;
1519            else if (post_op_name[1] == '+')
1520                op_kind = OO_PlusPlus;
1521        }
1522        break;
1523
1524    case '-':
1525        if (post_op_name[1] == '\0')
1526            op_kind = OO_Minus;
1527        else if (post_op_name[2] == '\0')
1528        {
1529            switch (post_op_name[1])
1530            {
1531            case '=': op_kind = OO_MinusEqual; break;
1532            case '-': op_kind = OO_MinusMinus; break;
1533            case '>': op_kind = OO_Arrow; break;
1534            }
1535        }
1536        else if (post_op_name[3] == '\0')
1537        {
1538            if (post_op_name[2] == '*')
1539                op_kind = OO_ArrowStar; break;
1540        }
1541        break;
1542
1543    case '*':
1544        if (post_op_name[1] == '\0')
1545            op_kind = OO_Star;
1546        else if (post_op_name[1] == '=' && post_op_name[2] == '\0')
1547            op_kind = OO_StarEqual;
1548        break;
1549
1550    case '/':
1551        if (post_op_name[1] == '\0')
1552            op_kind = OO_Slash;
1553        else if (post_op_name[1] == '=' && post_op_name[2] == '\0')
1554            op_kind = OO_SlashEqual;
1555        break;
1556
1557    case '%':
1558        if (post_op_name[1] == '\0')
1559            op_kind = OO_Percent;
1560        else if (post_op_name[1] == '=' && post_op_name[2] == '\0')
1561            op_kind = OO_PercentEqual;
1562        break;
1563
1564
1565    case '^':
1566        if (post_op_name[1] == '\0')
1567            op_kind = OO_Caret;
1568        else if (post_op_name[1] == '=' && post_op_name[2] == '\0')
1569            op_kind = OO_CaretEqual;
1570        break;
1571
1572    case '&':
1573        if (post_op_name[1] == '\0')
1574            op_kind = OO_Amp;
1575        else if (post_op_name[2] == '\0')
1576        {
1577            switch (post_op_name[1])
1578            {
1579            case '=': op_kind = OO_AmpEqual; break;
1580            case '&': op_kind = OO_AmpAmp; break;
1581            }
1582        }
1583        break;
1584
1585    case '|':
1586        if (post_op_name[1] == '\0')
1587            op_kind = OO_Pipe;
1588        else if (post_op_name[2] == '\0')
1589        {
1590            switch (post_op_name[1])
1591            {
1592            case '=': op_kind = OO_PipeEqual; break;
1593            case '|': op_kind = OO_PipePipe; break;
1594            }
1595        }
1596        break;
1597
1598    case '~':
1599        if (post_op_name[1] == '\0')
1600            op_kind = OO_Tilde;
1601        break;
1602
1603    case '!':
1604        if (post_op_name[1] == '\0')
1605            op_kind = OO_Exclaim;
1606        else if (post_op_name[1] == '=' && post_op_name[2] == '\0')
1607            op_kind = OO_ExclaimEqual;
1608        break;
1609
1610    case '=':
1611        if (post_op_name[1] == '\0')
1612            op_kind = OO_Equal;
1613        else if (post_op_name[1] == '=' && post_op_name[2] == '\0')
1614            op_kind = OO_EqualEqual;
1615        break;
1616
1617    case '<':
1618        if (post_op_name[1] == '\0')
1619            op_kind = OO_Less;
1620        else if (post_op_name[2] == '\0')
1621        {
1622            switch (post_op_name[1])
1623            {
1624            case '<': op_kind = OO_LessLess; break;
1625            case '=': op_kind = OO_LessEqual; break;
1626            }
1627        }
1628        else if (post_op_name[3] == '\0')
1629        {
1630            if (post_op_name[2] == '=')
1631                op_kind = OO_LessLessEqual;
1632        }
1633        break;
1634
1635    case '>':
1636        if (post_op_name[1] == '\0')
1637            op_kind = OO_Greater;
1638        else if (post_op_name[2] == '\0')
1639        {
1640            switch (post_op_name[1])
1641            {
1642            case '>': op_kind = OO_GreaterGreater; break;
1643            case '=': op_kind = OO_GreaterEqual; break;
1644            }
1645        }
1646        else if (post_op_name[1] == '>' &&
1647                 post_op_name[2] == '=' &&
1648                 post_op_name[3] == '\0')
1649        {
1650                op_kind = OO_GreaterGreaterEqual;
1651        }
1652        break;
1653
1654    case ',':
1655        if (post_op_name[1] == '\0')
1656            op_kind = OO_Comma;
1657        break;
1658
1659    case '(':
1660        if (post_op_name[1] == ')' && post_op_name[2] == '\0')
1661            op_kind = OO_Call;
1662        break;
1663
1664    case '[':
1665        if (post_op_name[1] == ']' && post_op_name[2] == '\0')
1666            op_kind = OO_Subscript;
1667        break;
1668    }
1669
1670    return true;
1671}
1672
1673static inline bool
1674check_op_param (uint32_t op_kind, bool unary, bool binary, uint32_t num_params)
1675{
1676    // Special-case call since it can take any number of operands
1677    if(op_kind == OO_Call)
1678        return true;
1679
1680    // The parameter count doens't include "this"
1681    if (num_params == 0)
1682        return unary;
1683    if (num_params == 1)
1684        return binary;
1685    else
1686    return false;
1687}
1688
1689bool
1690ClangASTContext::CheckOverloadedOperatorKindParameterCount (uint32_t op_kind, uint32_t num_params)
1691{
1692    switch (op_kind)
1693    {
1694    default:
1695        break;
1696    // C++ standard allows any number of arguments to new/delete
1697    case OO_New:
1698    case OO_Array_New:
1699    case OO_Delete:
1700    case OO_Array_Delete:
1701        return true;
1702    }
1703
1704#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) case OO_##Name: return check_op_param (op_kind, Unary, Binary, num_params);
1705    switch (op_kind)
1706    {
1707#include "clang/Basic/OperatorKinds.def"
1708        default: break;
1709    }
1710    return false;
1711}
1712
1713CXXMethodDecl *
1714ClangASTContext::AddMethodToCXXRecordType
1715(
1716    ASTContext *ast,
1717    clang_type_t record_opaque_type,
1718    const char *name,
1719    clang_type_t method_opaque_type,
1720    lldb::AccessType access,
1721    bool is_virtual,
1722    bool is_static,
1723    bool is_inline,
1724    bool is_explicit,
1725    bool is_attr_used,
1726    bool is_artificial
1727)
1728{
1729    if (!record_opaque_type || !method_opaque_type || !name)
1730        return NULL;
1731
1732    assert(ast);
1733
1734    IdentifierTable *identifier_table = &ast->Idents;
1735
1736    assert(identifier_table);
1737
1738    QualType record_qual_type(QualType::getFromOpaquePtr(record_opaque_type));
1739
1740    CXXRecordDecl *cxx_record_decl = record_qual_type->getAsCXXRecordDecl();
1741
1742    if (cxx_record_decl == NULL)
1743        return NULL;
1744
1745    QualType method_qual_type (QualType::getFromOpaquePtr (method_opaque_type));
1746
1747    CXXMethodDecl *cxx_method_decl = NULL;
1748
1749    DeclarationName decl_name (&identifier_table->get(name));
1750
1751    const clang::FunctionType *function_Type = dyn_cast<FunctionType>(method_qual_type.getTypePtr());
1752
1753    if (function_Type == NULL)
1754        return NULL;
1755
1756    const FunctionProtoType *method_function_prototype (dyn_cast<FunctionProtoType>(function_Type));
1757
1758    if (!method_function_prototype)
1759        return NULL;
1760
1761    unsigned int num_params = method_function_prototype->getNumArgs();
1762
1763    CXXDestructorDecl *cxx_dtor_decl(NULL);
1764    CXXConstructorDecl *cxx_ctor_decl(NULL);
1765
1766    if (name[0] == '~')
1767    {
1768        cxx_dtor_decl = CXXDestructorDecl::Create (*ast,
1769                                                   cxx_record_decl,
1770                                                   SourceLocation(),
1771                                                   DeclarationNameInfo (ast->DeclarationNames.getCXXDestructorName (ast->getCanonicalType (record_qual_type)), SourceLocation()),
1772                                                   method_qual_type,
1773                                                   NULL,
1774                                                   is_inline,
1775                                                   is_artificial);
1776        cxx_method_decl = cxx_dtor_decl;
1777    }
1778    else if (decl_name == cxx_record_decl->getDeclName())
1779    {
1780       if (is_artificial && method_function_prototype->getNumArgs() == 1)
1781          return NULL; // skip artificial copy constructors
1782
1783       cxx_ctor_decl = CXXConstructorDecl::Create (*ast,
1784                                                   cxx_record_decl,
1785                                                   SourceLocation(),
1786                                                   DeclarationNameInfo (ast->DeclarationNames.getCXXConstructorName (ast->getCanonicalType (record_qual_type)), SourceLocation()),
1787                                                   method_qual_type,
1788                                                   NULL, // TypeSourceInfo *
1789                                                   is_explicit,
1790                                                   is_inline,
1791                                                   is_artificial,
1792                                                   false /*is_constexpr*/);
1793        cxx_method_decl = cxx_ctor_decl;
1794    }
1795    else
1796    {
1797
1798        OverloadedOperatorKind op_kind = NUM_OVERLOADED_OPERATORS;
1799        if (IsOperator (name, op_kind))
1800        {
1801            if (op_kind != NUM_OVERLOADED_OPERATORS)
1802            {
1803                // Check the number of operator parameters. Sometimes we have
1804                // seen bad DWARF that doesn't correctly describe operators and
1805                // if we try to create a methed and add it to the class, clang
1806                // will assert and crash, so we need to make sure things are
1807                // acceptable.
1808                if (!ClangASTContext::CheckOverloadedOperatorKindParameterCount (op_kind, num_params))
1809                    return NULL;
1810                cxx_method_decl = CXXMethodDecl::Create (*ast,
1811                                                         cxx_record_decl,
1812                                                         SourceLocation(),
1813                                                         DeclarationNameInfo (ast->DeclarationNames.getCXXOperatorName (op_kind), SourceLocation()),
1814                                                         method_qual_type,
1815                                                         NULL, // TypeSourceInfo *
1816                                                         SC_None,
1817                                                         is_inline,
1818                                                         false /*is_constexpr*/,
1819                                                         SourceLocation());
1820            }
1821            else if (num_params == 0)
1822            {
1823                // Conversion operators don't take params...
1824                cxx_method_decl = CXXConversionDecl::Create (*ast,
1825                                                             cxx_record_decl,
1826                                                             SourceLocation(),
1827                                                             DeclarationNameInfo (ast->DeclarationNames.getCXXConversionFunctionName (ast->getCanonicalType (function_Type->getResultType())), SourceLocation()),
1828                                                             method_qual_type,
1829                                                             NULL, // TypeSourceInfo *
1830                                                             is_inline,
1831                                                             is_explicit,
1832                                                             false /*is_constexpr*/,
1833                                                             SourceLocation());
1834            }
1835        }
1836
1837        if (cxx_method_decl == NULL)
1838        {
1839            cxx_method_decl = CXXMethodDecl::Create (*ast,
1840                                                     cxx_record_decl,
1841                                                     SourceLocation(),
1842                                                     DeclarationNameInfo (decl_name, SourceLocation()),
1843                                                     method_qual_type,
1844                                                     NULL, // TypeSourceInfo *
1845                                                     SC_None,
1846                                                     is_inline,
1847                                                     false /*is_constexpr*/,
1848                                                     SourceLocation());
1849        }
1850    }
1851
1852    AccessSpecifier access_specifier = ConvertAccessTypeToAccessSpecifier (access);
1853
1854    cxx_method_decl->setAccess (access_specifier);
1855    cxx_method_decl->setVirtualAsWritten (is_virtual);
1856
1857    if (is_attr_used)
1858        cxx_method_decl->addAttr(::new (*ast) UsedAttr(SourceRange(), *ast));
1859
1860    // Populate the method decl with parameter decls
1861
1862    llvm::SmallVector<ParmVarDecl *, 12> params;
1863
1864    for (int param_index = 0;
1865         param_index < num_params;
1866         ++param_index)
1867    {
1868        params.push_back (ParmVarDecl::Create (*ast,
1869                                               cxx_method_decl,
1870                                               SourceLocation(),
1871                                               SourceLocation(),
1872                                               NULL, // anonymous
1873                                               method_function_prototype->getArgType(param_index),
1874                                               NULL,
1875                                               SC_None,
1876                                               NULL));
1877    }
1878
1879    cxx_method_decl->setParams (ArrayRef<ParmVarDecl*>(params));
1880
1881    cxx_record_decl->addDecl (cxx_method_decl);
1882
1883    // Sometimes the debug info will mention a constructor (default/copy/move),
1884    // destructor, or assignment operator (copy/move) but there won't be any
1885    // version of this in the code. So we check if the function was artificially
1886    // generated and if it is trivial and this lets the compiler/backend know
1887    // that it can inline the IR for these when it needs to and we can avoid a
1888    // "missing function" error when running expressions.
1889
1890    if (is_artificial)
1891    {
1892        if (cxx_ctor_decl &&
1893            ((cxx_ctor_decl->isDefaultConstructor() && cxx_record_decl->hasTrivialDefaultConstructor ()) ||
1894             (cxx_ctor_decl->isCopyConstructor()    && cxx_record_decl->hasTrivialCopyConstructor    ()) ||
1895             (cxx_ctor_decl->isMoveConstructor()    && cxx_record_decl->hasTrivialMoveConstructor    ()) ))
1896        {
1897            cxx_ctor_decl->setDefaulted();
1898            cxx_ctor_decl->setTrivial(true);
1899        }
1900        else if (cxx_dtor_decl)
1901        {
1902            if (cxx_record_decl->hasTrivialDestructor())
1903            {
1904                cxx_dtor_decl->setDefaulted();
1905                cxx_dtor_decl->setTrivial(true);
1906            }
1907        }
1908        else if ((cxx_method_decl->isCopyAssignmentOperator() && cxx_record_decl->hasTrivialCopyAssignment()) ||
1909                 (cxx_method_decl->isMoveAssignmentOperator() && cxx_record_decl->hasTrivialMoveAssignment()))
1910        {
1911            cxx_method_decl->setDefaulted();
1912            cxx_method_decl->setTrivial(true);
1913        }
1914    }
1915
1916#ifdef LLDB_CONFIGURATION_DEBUG
1917    VerifyDecl(cxx_method_decl);
1918#endif
1919
1920//    printf ("decl->isPolymorphic()             = %i\n", cxx_record_decl->isPolymorphic());
1921//    printf ("decl->isAggregate()               = %i\n", cxx_record_decl->isAggregate());
1922//    printf ("decl->isPOD()                     = %i\n", cxx_record_decl->isPOD());
1923//    printf ("decl->isEmpty()                   = %i\n", cxx_record_decl->isEmpty());
1924//    printf ("decl->isAbstract()                = %i\n", cxx_record_decl->isAbstract());
1925//    printf ("decl->hasTrivialConstructor()     = %i\n", cxx_record_decl->hasTrivialConstructor());
1926//    printf ("decl->hasTrivialCopyConstructor() = %i\n", cxx_record_decl->hasTrivialCopyConstructor());
1927//    printf ("decl->hasTrivialCopyAssignment()  = %i\n", cxx_record_decl->hasTrivialCopyAssignment());
1928//    printf ("decl->hasTrivialDestructor()      = %i\n", cxx_record_decl->hasTrivialDestructor());
1929    return cxx_method_decl;
1930}
1931
1932clang::FieldDecl *
1933ClangASTContext::AddFieldToRecordType
1934(
1935    ASTContext *ast,
1936    clang_type_t record_clang_type,
1937    const char *name,
1938    clang_type_t field_type,
1939    AccessType access,
1940    uint32_t bitfield_bit_size
1941)
1942{
1943    if (record_clang_type == NULL || field_type == NULL)
1944        return NULL;
1945
1946    FieldDecl *field = NULL;
1947    IdentifierTable *identifier_table = &ast->Idents;
1948
1949    assert (ast != NULL);
1950    assert (identifier_table != NULL);
1951
1952    QualType record_qual_type(QualType::getFromOpaquePtr(record_clang_type));
1953
1954    const clang::Type *clang_type = record_qual_type.getTypePtr();
1955    if (clang_type)
1956    {
1957        const RecordType *record_type = dyn_cast<RecordType>(clang_type);
1958
1959        if (record_type)
1960        {
1961            RecordDecl *record_decl = record_type->getDecl();
1962
1963            clang::Expr *bit_width = NULL;
1964            if (bitfield_bit_size != 0)
1965            {
1966                APInt bitfield_bit_size_apint(ast->getTypeSize(ast->IntTy), bitfield_bit_size);
1967                bit_width = new (*ast)IntegerLiteral (*ast, bitfield_bit_size_apint, ast->IntTy, SourceLocation());
1968            }
1969            field = FieldDecl::Create (*ast,
1970                                       record_decl,
1971                                       SourceLocation(),
1972                                       SourceLocation(),
1973                                       name ? &identifier_table->get(name) : NULL, // Identifier
1974                                       QualType::getFromOpaquePtr(field_type), // Field type
1975                                       NULL,            // TInfo *
1976                                       bit_width,       // BitWidth
1977                                       false,           // Mutable
1978                                       ICIS_NoInit);    // HasInit
1979
1980            if (!name) {
1981                // Determine whether this field corresponds to an anonymous
1982                // struct or union.
1983                if (const TagType *TagT = field->getType()->getAs<TagType>()) {
1984                  if (RecordDecl *Rec = dyn_cast<RecordDecl>(TagT->getDecl()))
1985                    if (!Rec->getDeclName()) {
1986                      Rec->setAnonymousStructOrUnion(true);
1987                      field->setImplicit();
1988
1989                    }
1990                }
1991            }
1992
1993            field->setAccess (ConvertAccessTypeToAccessSpecifier (access));
1994
1995            if (field)
1996            {
1997                record_decl->addDecl(field);
1998
1999#ifdef LLDB_CONFIGURATION_DEBUG
2000                VerifyDecl(field);
2001#endif
2002            }
2003        }
2004        else
2005        {
2006            const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(clang_type);
2007            if (objc_class_type)
2008            {
2009                bool is_synthesized = false;
2010                field = ClangASTContext::AddObjCClassIVar (ast,
2011                                                   record_clang_type,
2012                                                   name,
2013                                                   field_type,
2014                                                   access,
2015                                                   bitfield_bit_size,
2016                                                   is_synthesized);
2017            }
2018        }
2019    }
2020    return field;
2021}
2022
2023static clang::AccessSpecifier UnifyAccessSpecifiers (clang::AccessSpecifier lhs,
2024                                                     clang::AccessSpecifier rhs)
2025{
2026    clang::AccessSpecifier ret = lhs;
2027
2028    // Make the access equal to the stricter of the field and the nested field's access
2029    switch (ret)
2030    {
2031        case clang::AS_none:
2032            break;
2033        case clang::AS_private:
2034            break;
2035        case clang::AS_protected:
2036            if (rhs == AS_private)
2037                ret = AS_private;
2038            break;
2039        case clang::AS_public:
2040            ret = rhs;
2041            break;
2042    }
2043
2044    return ret;
2045}
2046
2047void
2048ClangASTContext::BuildIndirectFields (clang::ASTContext *ast,
2049                                      lldb::clang_type_t record_clang_type)
2050{
2051    QualType record_qual_type(QualType::getFromOpaquePtr(record_clang_type));
2052
2053    const RecordType *record_type = record_qual_type->getAs<RecordType>();
2054
2055    if (!record_type)
2056        return;
2057
2058    RecordDecl *record_decl = record_type->getDecl();
2059
2060    if (!record_decl)
2061        return;
2062
2063    typedef llvm::SmallVector <IndirectFieldDecl *, 1> IndirectFieldVector;
2064
2065    IndirectFieldVector indirect_fields;
2066    RecordDecl::field_iterator field_pos;
2067    RecordDecl::field_iterator field_end_pos = record_decl->field_end();
2068    RecordDecl::field_iterator last_field_pos = field_end_pos;
2069    for (field_pos = record_decl->field_begin(); field_pos != field_end_pos; last_field_pos = field_pos++)
2070    {
2071        if (field_pos->isAnonymousStructOrUnion())
2072        {
2073            QualType field_qual_type = field_pos->getType();
2074
2075            const RecordType *field_record_type = field_qual_type->getAs<RecordType>();
2076
2077            if (!field_record_type)
2078                continue;
2079
2080            RecordDecl *field_record_decl = field_record_type->getDecl();
2081
2082            if (!field_record_decl)
2083                continue;
2084
2085            for (RecordDecl::decl_iterator di = field_record_decl->decls_begin(), de = field_record_decl->decls_end();
2086                 di != de;
2087                 ++di)
2088            {
2089                if (FieldDecl *nested_field_decl = dyn_cast<FieldDecl>(*di))
2090                {
2091                    NamedDecl **chain = new (*ast) NamedDecl*[2];
2092                    chain[0] = *field_pos;
2093                    chain[1] = nested_field_decl;
2094                    IndirectFieldDecl *indirect_field = IndirectFieldDecl::Create(*ast,
2095                                                                                  record_decl,
2096                                                                                  SourceLocation(),
2097                                                                                  nested_field_decl->getIdentifier(),
2098                                                                                  nested_field_decl->getType(),
2099                                                                                  chain,
2100                                                                                  2);
2101
2102                    indirect_field->setAccess(UnifyAccessSpecifiers(field_pos->getAccess(),
2103                                                                    nested_field_decl->getAccess()));
2104
2105                    indirect_fields.push_back(indirect_field);
2106                }
2107                else if (IndirectFieldDecl *nested_indirect_field_decl = dyn_cast<IndirectFieldDecl>(*di))
2108                {
2109                    int nested_chain_size = nested_indirect_field_decl->getChainingSize();
2110                    NamedDecl **chain = new (*ast) NamedDecl*[nested_chain_size + 1];
2111                    chain[0] = *field_pos;
2112
2113                    int chain_index = 1;
2114                    for (IndirectFieldDecl::chain_iterator nci = nested_indirect_field_decl->chain_begin(),
2115                         nce = nested_indirect_field_decl->chain_end();
2116                         nci < nce;
2117                         ++nci)
2118                    {
2119                        chain[chain_index] = *nci;
2120                        chain_index++;
2121                    }
2122
2123                    IndirectFieldDecl *indirect_field = IndirectFieldDecl::Create(*ast,
2124                                                                                  record_decl,
2125                                                                                  SourceLocation(),
2126                                                                                  nested_indirect_field_decl->getIdentifier(),
2127                                                                                  nested_indirect_field_decl->getType(),
2128                                                                                  chain,
2129                                                                                  nested_chain_size + 1);
2130
2131                    indirect_field->setAccess(UnifyAccessSpecifiers(field_pos->getAccess(),
2132                                                                    nested_indirect_field_decl->getAccess()));
2133
2134                    indirect_fields.push_back(indirect_field);
2135                }
2136            }
2137        }
2138    }
2139
2140    // Check the last field to see if it has an incomplete array type as its
2141    // last member and if it does, the tell the record decl about it
2142    if (last_field_pos != field_end_pos)
2143    {
2144        if (last_field_pos->getType()->isIncompleteArrayType())
2145            record_decl->hasFlexibleArrayMember();
2146    }
2147
2148    for (IndirectFieldVector::iterator ifi = indirect_fields.begin(), ife = indirect_fields.end();
2149         ifi < ife;
2150         ++ifi)
2151    {
2152        record_decl->addDecl(*ifi);
2153    }
2154}
2155
2156bool
2157ClangASTContext::FieldIsBitfield (FieldDecl* field, uint32_t& bitfield_bit_size)
2158{
2159    return FieldIsBitfield(getASTContext(), field, bitfield_bit_size);
2160}
2161
2162bool
2163ClangASTContext::FieldIsBitfield
2164(
2165    ASTContext *ast,
2166    FieldDecl* field,
2167    uint32_t& bitfield_bit_size
2168)
2169{
2170    if (ast == NULL || field == NULL)
2171        return false;
2172
2173    if (field->isBitField())
2174    {
2175        Expr* bit_width_expr = field->getBitWidth();
2176        if (bit_width_expr)
2177        {
2178            llvm::APSInt bit_width_apsint;
2179            if (bit_width_expr->isIntegerConstantExpr(bit_width_apsint, *ast))
2180            {
2181                bitfield_bit_size = bit_width_apsint.getLimitedValue(UINT32_MAX);
2182                return true;
2183            }
2184        }
2185    }
2186    return false;
2187}
2188
2189bool
2190ClangASTContext::RecordHasFields (const RecordDecl *record_decl)
2191{
2192    if (record_decl == NULL)
2193        return false;
2194
2195    if (!record_decl->field_empty())
2196        return true;
2197
2198    // No fields, lets check this is a CXX record and check the base classes
2199    const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
2200    if (cxx_record_decl)
2201    {
2202        CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
2203        for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
2204             base_class != base_class_end;
2205             ++base_class)
2206        {
2207            const CXXRecordDecl *base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
2208            if (RecordHasFields(base_class_decl))
2209                return true;
2210        }
2211    }
2212    return false;
2213}
2214
2215void
2216ClangASTContext::SetDefaultAccessForRecordFields (clang_type_t clang_type, int default_accessibility, int *assigned_accessibilities, size_t num_assigned_accessibilities)
2217{
2218    if (clang_type)
2219    {
2220        QualType qual_type(QualType::getFromOpaquePtr(clang_type));
2221
2222        const RecordType *record_type = dyn_cast<RecordType>(qual_type.getTypePtr());
2223        if (record_type)
2224        {
2225            RecordDecl *record_decl = record_type->getDecl();
2226            if (record_decl)
2227            {
2228                uint32_t field_idx;
2229                RecordDecl::field_iterator field, field_end;
2230                for (field = record_decl->field_begin(), field_end = record_decl->field_end(), field_idx = 0;
2231                     field != field_end;
2232                     ++field, ++field_idx)
2233                {
2234                    // If no accessibility was assigned, assign the correct one
2235                    if (field_idx < num_assigned_accessibilities && assigned_accessibilities[field_idx] == clang::AS_none)
2236                        field->setAccess ((AccessSpecifier)default_accessibility);
2237                }
2238            }
2239        }
2240    }
2241}
2242
2243#pragma mark C++ Base Classes
2244
2245CXXBaseSpecifier *
2246ClangASTContext::CreateBaseClassSpecifier (clang_type_t base_class_type, AccessType access, bool is_virtual, bool base_of_class)
2247{
2248    if (base_class_type)
2249        return new CXXBaseSpecifier (SourceRange(),
2250                                     is_virtual,
2251                                     base_of_class,
2252                                     ConvertAccessTypeToAccessSpecifier (access),
2253                                     getASTContext()->getTrivialTypeSourceInfo (QualType::getFromOpaquePtr(base_class_type)),
2254                                     SourceLocation());
2255    return NULL;
2256}
2257
2258void
2259ClangASTContext::DeleteBaseClassSpecifiers (CXXBaseSpecifier **base_classes, unsigned num_base_classes)
2260{
2261    for (unsigned i=0; i<num_base_classes; ++i)
2262    {
2263        delete base_classes[i];
2264        base_classes[i] = NULL;
2265    }
2266}
2267
2268bool
2269ClangASTContext::SetBaseClassesForClassType (clang_type_t class_clang_type, CXXBaseSpecifier const * const *base_classes, unsigned num_base_classes)
2270{
2271    if (class_clang_type)
2272    {
2273        CXXRecordDecl *cxx_record_decl = QualType::getFromOpaquePtr(class_clang_type)->getAsCXXRecordDecl();
2274        if (cxx_record_decl)
2275        {
2276            cxx_record_decl->setBases(base_classes, num_base_classes);
2277            return true;
2278        }
2279    }
2280    return false;
2281}
2282#pragma mark Objective C Classes
2283
2284clang_type_t
2285ClangASTContext::CreateObjCClass
2286(
2287    const char *name,
2288    DeclContext *decl_ctx,
2289    bool isForwardDecl,
2290    bool isInternal,
2291    ClangASTMetadata *metadata
2292)
2293{
2294    ASTContext *ast = getASTContext();
2295    assert (ast != NULL);
2296    assert (name && name[0]);
2297    if (decl_ctx == NULL)
2298        decl_ctx = ast->getTranslationUnitDecl();
2299
2300    // NOTE: Eventually CXXRecordDecl will be merged back into RecordDecl and
2301    // we will need to update this code. I was told to currently always use
2302    // the CXXRecordDecl class since we often don't know from debug information
2303    // if something is struct or a class, so we default to always use the more
2304    // complete definition just in case.
2305    ObjCInterfaceDecl *decl = ObjCInterfaceDecl::Create (*ast,
2306                                                         decl_ctx,
2307                                                         SourceLocation(),
2308                                                         &ast->Idents.get(name),
2309                                                         NULL,
2310                                                         SourceLocation(),
2311                                                         /*isForwardDecl,*/
2312                                                         isInternal);
2313
2314    if (decl && metadata)
2315        SetMetadata(ast, decl, *metadata);
2316
2317    return ast->getObjCInterfaceType(decl).getAsOpaquePtr();
2318}
2319
2320bool
2321ClangASTContext::SetObjCSuperClass (clang_type_t class_opaque_type, clang_type_t super_opaque_type)
2322{
2323    if (class_opaque_type && super_opaque_type)
2324    {
2325        QualType class_qual_type(QualType::getFromOpaquePtr(class_opaque_type));
2326        QualType super_qual_type(QualType::getFromOpaquePtr(super_opaque_type));
2327        const clang::Type *class_type = class_qual_type.getTypePtr();
2328        const clang::Type *super_type = super_qual_type.getTypePtr();
2329        if (class_type && super_type)
2330        {
2331            const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(class_type);
2332            const ObjCObjectType *objc_super_type = dyn_cast<ObjCObjectType>(super_type);
2333            if (objc_class_type && objc_super_type)
2334            {
2335                ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
2336                ObjCInterfaceDecl *super_interface_decl = objc_super_type->getInterface();
2337                if (class_interface_decl && super_interface_decl)
2338                {
2339                    class_interface_decl->setSuperClass(super_interface_decl);
2340                    return true;
2341                }
2342            }
2343        }
2344    }
2345    return false;
2346}
2347
2348
2349FieldDecl *
2350ClangASTContext::AddObjCClassIVar
2351(
2352    ASTContext *ast,
2353    clang_type_t class_opaque_type,
2354    const char *name,
2355    clang_type_t ivar_opaque_type,
2356    AccessType access,
2357    uint32_t bitfield_bit_size,
2358    bool is_synthesized
2359)
2360{
2361    if (class_opaque_type == NULL || ivar_opaque_type == NULL)
2362        return NULL;
2363
2364    ObjCIvarDecl *field = NULL;
2365
2366    IdentifierTable *identifier_table = &ast->Idents;
2367
2368    assert (ast != NULL);
2369    assert (identifier_table != NULL);
2370
2371    QualType class_qual_type(QualType::getFromOpaquePtr(class_opaque_type));
2372
2373    const clang::Type *class_type = class_qual_type.getTypePtr();
2374    if (class_type)
2375    {
2376        const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(class_type);
2377
2378        if (objc_class_type)
2379        {
2380            ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
2381
2382            if (class_interface_decl)
2383            {
2384                clang::Expr *bit_width = NULL;
2385                if (bitfield_bit_size != 0)
2386                {
2387                    APInt bitfield_bit_size_apint(ast->getTypeSize(ast->IntTy), bitfield_bit_size);
2388                    bit_width = new (*ast)IntegerLiteral (*ast, bitfield_bit_size_apint, ast->IntTy, SourceLocation());
2389                }
2390
2391                field = ObjCIvarDecl::Create (*ast,
2392                                              class_interface_decl,
2393                                              SourceLocation(),
2394                                              SourceLocation(),
2395                                              name ? &identifier_table->get(name) : NULL, // Identifier
2396                                              QualType::getFromOpaquePtr(ivar_opaque_type), // Field type
2397                                              NULL, // TypeSourceInfo *
2398                                              ConvertAccessTypeToObjCIvarAccessControl (access),
2399                                              bit_width,
2400                                              is_synthesized);
2401
2402                if (field)
2403                {
2404                    class_interface_decl->addDecl(field);
2405
2406#ifdef LLDB_CONFIGURATION_DEBUG
2407                    VerifyDecl(field);
2408#endif
2409
2410                    return field;
2411                }
2412            }
2413        }
2414    }
2415    return NULL;
2416}
2417
2418bool
2419ClangASTContext::AddObjCClassProperty
2420(
2421    ASTContext *ast,
2422    clang_type_t class_opaque_type,
2423    const char *property_name,
2424    clang_type_t property_opaque_type,
2425    ObjCIvarDecl *ivar_decl,
2426    const char *property_setter_name,
2427    const char *property_getter_name,
2428    uint32_t property_attributes,
2429    ClangASTMetadata *metadata
2430)
2431{
2432    if (class_opaque_type == NULL || property_name == NULL || property_name[0] == '\0')
2433        return false;
2434
2435    IdentifierTable *identifier_table = &ast->Idents;
2436
2437    assert (ast != NULL);
2438    assert (identifier_table != NULL);
2439
2440    QualType class_qual_type(QualType::getFromOpaquePtr(class_opaque_type));
2441    const clang::Type *class_type = class_qual_type.getTypePtr();
2442    if (class_type)
2443    {
2444        const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(class_type);
2445
2446        if (objc_class_type)
2447        {
2448            ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
2449
2450            clang_type_t property_opaque_type_to_access = NULL;
2451
2452            if (property_opaque_type)
2453                property_opaque_type_to_access = property_opaque_type;
2454            else if (ivar_decl)
2455                property_opaque_type_to_access = ivar_decl->getType().getAsOpaquePtr();
2456
2457            if (class_interface_decl && property_opaque_type_to_access)
2458            {
2459                clang::TypeSourceInfo *prop_type_source;
2460                if (ivar_decl)
2461                    prop_type_source = ast->getTrivialTypeSourceInfo (ivar_decl->getType());
2462                else
2463                    prop_type_source = ast->getTrivialTypeSourceInfo (QualType::getFromOpaquePtr(property_opaque_type));
2464
2465                ObjCPropertyDecl *property_decl = ObjCPropertyDecl::Create(*ast,
2466                                                                           class_interface_decl,
2467                                                                           SourceLocation(), // Source Location
2468                                                                           &identifier_table->get(property_name),
2469                                                                           SourceLocation(), //Source Location for AT
2470                                                                           SourceLocation(), //Source location for (
2471                                                                           prop_type_source
2472                                                                           );
2473
2474                if (property_decl)
2475                {
2476                    if (metadata)
2477                        SetMetadata(ast, property_decl, *metadata);
2478
2479                    class_interface_decl->addDecl (property_decl);
2480
2481                    Selector setter_sel, getter_sel;
2482
2483                    if (property_setter_name != NULL)
2484                    {
2485                        std::string property_setter_no_colon(property_setter_name, strlen(property_setter_name) - 1);
2486                        clang::IdentifierInfo *setter_ident = &identifier_table->get(property_setter_no_colon.c_str());
2487                        setter_sel = ast->Selectors.getSelector(1, &setter_ident);
2488                    }
2489                    else if (!(property_attributes & DW_APPLE_PROPERTY_readonly))
2490                    {
2491                        std::string setter_sel_string("set");
2492                        setter_sel_string.push_back(::toupper(property_name[0]));
2493                        setter_sel_string.append(&property_name[1]);
2494                        clang::IdentifierInfo *setter_ident = &identifier_table->get(setter_sel_string.c_str());
2495                        setter_sel = ast->Selectors.getSelector(1, &setter_ident);
2496                    }
2497                    property_decl->setSetterName(setter_sel);
2498                    property_decl->setPropertyAttributes (clang::ObjCPropertyDecl::OBJC_PR_setter);
2499
2500                    if (property_getter_name != NULL)
2501                    {
2502                        clang::IdentifierInfo *getter_ident = &identifier_table->get(property_getter_name);
2503                        getter_sel = ast->Selectors.getSelector(0, &getter_ident);
2504                    }
2505                    else
2506                    {
2507                        clang::IdentifierInfo *getter_ident = &identifier_table->get(property_name);
2508                        getter_sel = ast->Selectors.getSelector(0, &getter_ident);
2509                    }
2510                    property_decl->setGetterName(getter_sel);
2511                    property_decl->setPropertyAttributes (clang::ObjCPropertyDecl::OBJC_PR_getter);
2512
2513                    if (ivar_decl)
2514                        property_decl->setPropertyIvarDecl (ivar_decl);
2515
2516                    if (property_attributes & DW_APPLE_PROPERTY_readonly)
2517                        property_decl->setPropertyAttributes (clang::ObjCPropertyDecl::OBJC_PR_readonly);
2518                    if (property_attributes & DW_APPLE_PROPERTY_readwrite)
2519                        property_decl->setPropertyAttributes (clang::ObjCPropertyDecl::OBJC_PR_readwrite);
2520                    if (property_attributes & DW_APPLE_PROPERTY_assign)
2521                        property_decl->setPropertyAttributes (clang::ObjCPropertyDecl::OBJC_PR_assign);
2522                    if (property_attributes & DW_APPLE_PROPERTY_retain)
2523                        property_decl->setPropertyAttributes (clang::ObjCPropertyDecl::OBJC_PR_retain);
2524                    if (property_attributes & DW_APPLE_PROPERTY_copy)
2525                        property_decl->setPropertyAttributes (clang::ObjCPropertyDecl::OBJC_PR_copy);
2526                    if (property_attributes & DW_APPLE_PROPERTY_nonatomic)
2527                        property_decl->setPropertyAttributes (clang::ObjCPropertyDecl::OBJC_PR_nonatomic);
2528
2529                    if (!getter_sel.isNull() && !class_interface_decl->lookupInstanceMethod(getter_sel))
2530                    {
2531                        QualType result_type = QualType::getFromOpaquePtr(property_opaque_type_to_access);
2532
2533                        const bool isInstance = true;
2534                        const bool isVariadic = false;
2535                        const bool isSynthesized = false;
2536                        const bool isImplicitlyDeclared = true;
2537                        const bool isDefined = false;
2538                        const ObjCMethodDecl::ImplementationControl impControl = ObjCMethodDecl::None;
2539                        const bool HasRelatedResultType = false;
2540
2541                        ObjCMethodDecl *getter = ObjCMethodDecl::Create(*ast,
2542                                                                        SourceLocation(),
2543                                                                        SourceLocation(),
2544                                                                        getter_sel,
2545                                                                        result_type,
2546                                                                        NULL,
2547                                                                        class_interface_decl,
2548                                                                        isInstance,
2549                                                                        isVariadic,
2550                                                                        isSynthesized,
2551                                                                        isImplicitlyDeclared,
2552                                                                        isDefined,
2553                                                                        impControl,
2554                                                                        HasRelatedResultType);
2555
2556                        if (getter && metadata)
2557                            SetMetadata(ast, getter, *metadata);
2558
2559                        getter->setMethodParams(*ast, ArrayRef<ParmVarDecl*>(), ArrayRef<SourceLocation>());
2560
2561                        class_interface_decl->addDecl(getter);
2562                    }
2563
2564                    if (!setter_sel.isNull() && !class_interface_decl->lookupInstanceMethod(setter_sel))
2565                    {
2566                        QualType result_type = ast->VoidTy;
2567
2568                        const bool isInstance = true;
2569                        const bool isVariadic = false;
2570                        const bool isSynthesized = false;
2571                        const bool isImplicitlyDeclared = true;
2572                        const bool isDefined = false;
2573                        const ObjCMethodDecl::ImplementationControl impControl = ObjCMethodDecl::None;
2574                        const bool HasRelatedResultType = false;
2575
2576                        ObjCMethodDecl *setter = ObjCMethodDecl::Create(*ast,
2577                                                                        SourceLocation(),
2578                                                                        SourceLocation(),
2579                                                                        setter_sel,
2580                                                                        result_type,
2581                                                                        NULL,
2582                                                                        class_interface_decl,
2583                                                                        isInstance,
2584                                                                        isVariadic,
2585                                                                        isSynthesized,
2586                                                                        isImplicitlyDeclared,
2587                                                                        isDefined,
2588                                                                        impControl,
2589                                                                        HasRelatedResultType);
2590
2591                        if (setter && metadata)
2592                            SetMetadata(ast, setter, *metadata);
2593
2594                        llvm::SmallVector<ParmVarDecl *, 1> params;
2595
2596                        params.push_back (ParmVarDecl::Create (*ast,
2597                                                               setter,
2598                                                               SourceLocation(),
2599                                                               SourceLocation(),
2600                                                               NULL, // anonymous
2601                                                               QualType::getFromOpaquePtr(property_opaque_type_to_access),
2602                                                               NULL,
2603                                                               SC_Auto,
2604                                                               NULL));
2605
2606                        setter->setMethodParams(*ast, ArrayRef<ParmVarDecl*>(params), ArrayRef<SourceLocation>());
2607
2608                        class_interface_decl->addDecl(setter);
2609                    }
2610
2611                    return true;
2612                }
2613            }
2614        }
2615    }
2616    return false;
2617}
2618
2619bool
2620ClangASTContext::ObjCTypeHasIVars (clang_type_t class_opaque_type, bool check_superclass)
2621{
2622    QualType class_qual_type(QualType::getFromOpaquePtr(class_opaque_type));
2623
2624    const clang::Type *class_type = class_qual_type.getTypePtr();
2625    if (class_type)
2626    {
2627        const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(class_type);
2628
2629        if (objc_class_type)
2630            return ObjCDeclHasIVars (objc_class_type->getInterface(), check_superclass);
2631    }
2632    return false;
2633}
2634
2635bool
2636ClangASTContext::ObjCDeclHasIVars (ObjCInterfaceDecl *class_interface_decl, bool check_superclass)
2637{
2638    while (class_interface_decl)
2639    {
2640        if (class_interface_decl->ivar_size() > 0)
2641            return true;
2642
2643        if (check_superclass)
2644            class_interface_decl = class_interface_decl->getSuperClass();
2645        else
2646            break;
2647    }
2648    return false;
2649}
2650
2651ObjCMethodDecl *
2652ClangASTContext::AddMethodToObjCObjectType (ASTContext *ast,
2653                                            clang_type_t class_opaque_type,
2654                                            const char *name,  // the full symbol name as seen in the symbol table ("-[NString stringWithCString:]")
2655                                            clang_type_t method_opaque_type,
2656                                            lldb::AccessType access,
2657                                            bool is_artificial)
2658{
2659    if (class_opaque_type == NULL || method_opaque_type == NULL)
2660        return NULL;
2661
2662    IdentifierTable *identifier_table = &ast->Idents;
2663
2664    assert (ast != NULL);
2665    assert (identifier_table != NULL);
2666
2667    QualType class_qual_type(QualType::getFromOpaquePtr(class_opaque_type));
2668
2669    const clang::Type *class_type = class_qual_type.getTypePtr();
2670    if (class_type == NULL)
2671        return NULL;
2672
2673    const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(class_type);
2674
2675    if (objc_class_type == NULL)
2676        return NULL;
2677
2678    ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
2679
2680    if (class_interface_decl == NULL)
2681        return NULL;
2682
2683    const char *selector_start = ::strchr (name, ' ');
2684    if (selector_start == NULL)
2685        return NULL;
2686
2687    selector_start++;
2688    llvm::SmallVector<IdentifierInfo *, 12> selector_idents;
2689
2690    size_t len = 0;
2691    const char *start;
2692    //printf ("name = '%s'\n", name);
2693
2694    unsigned num_selectors_with_args = 0;
2695    for (start = selector_start;
2696         start && *start != '\0' && *start != ']';
2697         start += len)
2698    {
2699        len = ::strcspn(start, ":]");
2700        bool has_arg = (start[len] == ':');
2701        if (has_arg)
2702            ++num_selectors_with_args;
2703        selector_idents.push_back (&identifier_table->get (StringRef (start, len)));
2704        if (has_arg)
2705            len += 1;
2706    }
2707
2708
2709    if (selector_idents.size() == 0)
2710        return 0;
2711
2712    clang::Selector method_selector = ast->Selectors.getSelector (num_selectors_with_args ? selector_idents.size() : 0,
2713                                                                          selector_idents.data());
2714
2715    QualType method_qual_type (QualType::getFromOpaquePtr (method_opaque_type));
2716
2717    // Populate the method decl with parameter decls
2718    const clang::Type *method_type(method_qual_type.getTypePtr());
2719
2720    if (method_type == NULL)
2721        return NULL;
2722
2723    const FunctionProtoType *method_function_prototype (dyn_cast<FunctionProtoType>(method_type));
2724
2725    if (!method_function_prototype)
2726        return NULL;
2727
2728
2729    bool is_variadic = false;
2730    bool is_synthesized = false;
2731    bool is_defined = false;
2732    ObjCMethodDecl::ImplementationControl imp_control = ObjCMethodDecl::None;
2733
2734    const unsigned num_args = method_function_prototype->getNumArgs();
2735
2736    if (num_args != num_selectors_with_args)
2737        return NULL; // some debug information is corrupt.  We are not going to deal with it.
2738
2739    ObjCMethodDecl *objc_method_decl = ObjCMethodDecl::Create (*ast,
2740                                                               SourceLocation(), // beginLoc,
2741                                                               SourceLocation(), // endLoc,
2742                                                               method_selector,
2743                                                               method_function_prototype->getResultType(),
2744                                                               NULL, // TypeSourceInfo *ResultTInfo,
2745                                                               GetDeclContextForType (class_opaque_type),
2746                                                               name[0] == '-',
2747                                                               is_variadic,
2748                                                               is_synthesized,
2749                                                               true, // is_implicitly_declared; we force this to true because we don't have source locations
2750                                                               is_defined,
2751                                                               imp_control,
2752                                                               false /*has_related_result_type*/);
2753
2754
2755    if (objc_method_decl == NULL)
2756        return NULL;
2757
2758    if (num_args > 0)
2759    {
2760        llvm::SmallVector<ParmVarDecl *, 12> params;
2761
2762        for (int param_index = 0; param_index < num_args; ++param_index)
2763        {
2764            params.push_back (ParmVarDecl::Create (*ast,
2765                                                   objc_method_decl,
2766                                                   SourceLocation(),
2767                                                   SourceLocation(),
2768                                                   NULL, // anonymous
2769                                                   method_function_prototype->getArgType(param_index),
2770                                                   NULL,
2771                                                   SC_Auto,
2772                                                   NULL));
2773        }
2774
2775        objc_method_decl->setMethodParams(*ast, ArrayRef<ParmVarDecl*>(params), ArrayRef<SourceLocation>());
2776    }
2777
2778    class_interface_decl->addDecl (objc_method_decl);
2779
2780#ifdef LLDB_CONFIGURATION_DEBUG
2781    VerifyDecl(objc_method_decl);
2782#endif
2783
2784    return objc_method_decl;
2785}
2786
2787size_t
2788ClangASTContext::GetNumTemplateArguments (clang::ASTContext *ast, clang_type_t clang_type)
2789{
2790    if (clang_type)
2791    {
2792        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
2793
2794        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2795        switch (type_class)
2796        {
2797            case clang::Type::Record:
2798                if (GetCompleteQualType (ast, qual_type))
2799                {
2800                    const CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
2801                    if (cxx_record_decl)
2802                    {
2803                        const ClassTemplateSpecializationDecl *template_decl = dyn_cast<ClassTemplateSpecializationDecl>(cxx_record_decl);
2804                        if (template_decl)
2805                            return template_decl->getTemplateArgs().size();
2806                    }
2807                }
2808                break;
2809
2810            case clang::Type::Typedef:
2811                return ClangASTContext::GetNumTemplateArguments (ast, cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
2812
2813            case clang::Type::Elaborated:
2814                return ClangASTContext::GetNumTemplateArguments (ast, cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
2815
2816            default:
2817                break;
2818        }
2819    }
2820    return 0;
2821}
2822
2823clang_type_t
2824ClangASTContext::GetTemplateArgument (clang::ASTContext *ast, clang_type_t clang_type, size_t arg_idx, lldb::TemplateArgumentKind &kind)
2825{
2826    if (clang_type)
2827    {
2828        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
2829
2830        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2831        switch (type_class)
2832        {
2833            case clang::Type::Record:
2834                if (GetCompleteQualType (ast, qual_type))
2835                {
2836                    const CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
2837                    if (cxx_record_decl)
2838                    {
2839                        const ClassTemplateSpecializationDecl *template_decl = dyn_cast<ClassTemplateSpecializationDecl>(cxx_record_decl);
2840                        if (template_decl && arg_idx < template_decl->getTemplateArgs().size())
2841                        {
2842                            const TemplateArgument &template_arg = template_decl->getTemplateArgs()[arg_idx];
2843                            switch (template_arg.getKind())
2844                            {
2845                                case clang::TemplateArgument::Null:
2846                                    kind = eTemplateArgumentKindNull;
2847                                    return NULL;
2848
2849                                case clang::TemplateArgument::Type:
2850                                    kind = eTemplateArgumentKindType;
2851                                    return template_arg.getAsType().getAsOpaquePtr();
2852
2853                                case clang::TemplateArgument::Declaration:
2854                                    kind = eTemplateArgumentKindDeclaration;
2855                                    return NULL;
2856
2857                                case clang::TemplateArgument::Integral:
2858                                    kind = eTemplateArgumentKindIntegral;
2859                                    return template_arg.getIntegralType().getAsOpaquePtr();
2860
2861                                case clang::TemplateArgument::Template:
2862                                    kind = eTemplateArgumentKindTemplate;
2863                                    return NULL;
2864
2865                                case clang::TemplateArgument::TemplateExpansion:
2866                                    kind = eTemplateArgumentKindTemplateExpansion;
2867                                    return NULL;
2868
2869                                case clang::TemplateArgument::Expression:
2870                                    kind = eTemplateArgumentKindExpression;
2871                                    return NULL;
2872
2873                                case clang::TemplateArgument::Pack:
2874                                    kind = eTemplateArgumentKindPack;
2875                                    return NULL;
2876
2877                                default:
2878                                    assert (!"Unhandled TemplateArgument::ArgKind");
2879                                    kind = eTemplateArgumentKindNull;
2880                                    return NULL;
2881                            }
2882                        }
2883                    }
2884                }
2885                break;
2886
2887            case clang::Type::Typedef:
2888                return ClangASTContext::GetTemplateArgument (ast, cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(), arg_idx, kind);
2889
2890            case clang::Type::Elaborated:
2891                return ClangASTContext::GetTemplateArgument (ast, cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(), arg_idx, kind);
2892
2893            default:
2894                break;
2895        }
2896    }
2897    kind = eTemplateArgumentKindNull;
2898    return NULL;
2899}
2900
2901uint32_t
2902ClangASTContext::GetTypeInfo
2903(
2904    clang_type_t clang_type,
2905    clang::ASTContext *ast,
2906    clang_type_t *pointee_or_element_clang_type
2907)
2908{
2909    if (clang_type == NULL)
2910        return 0;
2911
2912    if (pointee_or_element_clang_type)
2913        *pointee_or_element_clang_type = NULL;
2914
2915    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
2916
2917    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2918    switch (type_class)
2919    {
2920    case clang::Type::Builtin:
2921        {
2922            const BuiltinType *builtin_type = dyn_cast<BuiltinType>(qual_type->getCanonicalTypeInternal());
2923
2924            uint32_t builtin_type_flags = eTypeIsBuiltIn | eTypeHasValue;
2925            switch (builtin_type->getKind())
2926            {
2927            case clang::BuiltinType::ObjCId:
2928            case clang::BuiltinType::ObjCClass:
2929                if (ast && pointee_or_element_clang_type)
2930                    *pointee_or_element_clang_type = ast->ObjCBuiltinClassTy.getAsOpaquePtr();
2931                builtin_type_flags |= eTypeIsPointer | eTypeIsObjC;
2932                break;
2933
2934            case clang::BuiltinType::ObjCSel:
2935            case clang::BuiltinType::Bool:
2936            case clang::BuiltinType::Char_U:
2937            case clang::BuiltinType::UChar:
2938            case clang::BuiltinType::WChar_U:
2939            case clang::BuiltinType::Char16:
2940            case clang::BuiltinType::Char32:
2941            case clang::BuiltinType::UShort:
2942            case clang::BuiltinType::UInt:
2943            case clang::BuiltinType::ULong:
2944            case clang::BuiltinType::ULongLong:
2945            case clang::BuiltinType::UInt128:
2946            case clang::BuiltinType::Char_S:
2947            case clang::BuiltinType::SChar:
2948            case clang::BuiltinType::WChar_S:
2949            case clang::BuiltinType::Short:
2950            case clang::BuiltinType::Int:
2951            case clang::BuiltinType::Long:
2952            case clang::BuiltinType::LongLong:
2953            case clang::BuiltinType::Int128:
2954            case clang::BuiltinType::Float:
2955            case clang::BuiltinType::Double:
2956            case clang::BuiltinType::LongDouble:
2957                builtin_type_flags |= eTypeIsScalar;
2958                if (builtin_type->isInteger())
2959                {
2960                    builtin_type_flags |= eTypeIsInteger;
2961                    if (builtin_type->isSignedInteger())
2962                        builtin_type_flags |= eTypeIsSigned;
2963                }
2964                else if (builtin_type->isFloatingPoint())
2965                    builtin_type_flags |= eTypeIsFloat;
2966                break;
2967            default:
2968                break;
2969            }
2970            return builtin_type_flags;
2971        }
2972
2973    case clang::Type::BlockPointer:
2974        if (pointee_or_element_clang_type)
2975            *pointee_or_element_clang_type = qual_type->getPointeeType().getAsOpaquePtr();
2976        return eTypeIsPointer | eTypeHasChildren | eTypeIsBlock;
2977
2978    case clang::Type::Complex:
2979        {
2980            uint32_t complex_type_flags = eTypeIsBuiltIn | eTypeHasValue | eTypeIsComplex;
2981            const ComplexType *complex_type = dyn_cast<ComplexType>(qual_type->getCanonicalTypeInternal());
2982            if (complex_type)
2983            {
2984                QualType complex_element_type (complex_type->getElementType());
2985                if (complex_element_type->isIntegerType())
2986                    complex_type_flags |= eTypeIsFloat;
2987                else if (complex_element_type->isFloatingType())
2988                    complex_type_flags |= eTypeIsInteger;
2989            }
2990            return complex_type_flags;
2991        }
2992        break;
2993
2994    case clang::Type::ConstantArray:
2995    case clang::Type::DependentSizedArray:
2996    case clang::Type::IncompleteArray:
2997    case clang::Type::VariableArray:
2998        if (pointee_or_element_clang_type)
2999            *pointee_or_element_clang_type = cast<ArrayType>(qual_type.getTypePtr())->getElementType().getAsOpaquePtr();
3000        return eTypeHasChildren | eTypeIsArray;
3001
3002    case clang::Type::DependentName:                    return 0;
3003    case clang::Type::DependentSizedExtVector:          return eTypeHasChildren | eTypeIsVector;
3004    case clang::Type::DependentTemplateSpecialization:  return eTypeIsTemplate;
3005    case clang::Type::Decltype:                         return 0;
3006
3007    case clang::Type::Enum:
3008        if (pointee_or_element_clang_type)
3009            *pointee_or_element_clang_type = cast<EnumType>(qual_type)->getDecl()->getIntegerType().getAsOpaquePtr();
3010        return eTypeIsEnumeration | eTypeHasValue;
3011
3012    case clang::Type::Elaborated:
3013        return ClangASTContext::GetTypeInfo (cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(),
3014                                             ast,
3015                                             pointee_or_element_clang_type);
3016    case clang::Type::FunctionProto:                    return eTypeIsFuncPrototype | eTypeHasValue;
3017    case clang::Type::FunctionNoProto:                  return eTypeIsFuncPrototype | eTypeHasValue;
3018    case clang::Type::InjectedClassName:                return 0;
3019
3020    case clang::Type::LValueReference:
3021    case clang::Type::RValueReference:
3022        if (pointee_or_element_clang_type)
3023            *pointee_or_element_clang_type = cast<ReferenceType>(qual_type.getTypePtr())->getPointeeType().getAsOpaquePtr();
3024        return eTypeHasChildren | eTypeIsReference | eTypeHasValue;
3025
3026    case clang::Type::MemberPointer:                    return eTypeIsPointer   | eTypeIsMember | eTypeHasValue;
3027
3028    case clang::Type::ObjCObjectPointer:
3029        if (pointee_or_element_clang_type)
3030            *pointee_or_element_clang_type = qual_type->getPointeeType().getAsOpaquePtr();
3031        return eTypeHasChildren | eTypeIsObjC | eTypeIsClass | eTypeIsPointer | eTypeHasValue;
3032
3033    case clang::Type::ObjCObject:                       return eTypeHasChildren | eTypeIsObjC | eTypeIsClass;
3034    case clang::Type::ObjCInterface:                    return eTypeHasChildren | eTypeIsObjC | eTypeIsClass;
3035
3036    case clang::Type::Pointer:
3037        if (pointee_or_element_clang_type)
3038            *pointee_or_element_clang_type = qual_type->getPointeeType().getAsOpaquePtr();
3039        return eTypeHasChildren | eTypeIsPointer | eTypeHasValue;
3040
3041    case clang::Type::Record:
3042        if (qual_type->getAsCXXRecordDecl())
3043            return eTypeHasChildren | eTypeIsClass | eTypeIsCPlusPlus;
3044        else
3045            return eTypeHasChildren | eTypeIsStructUnion;
3046        break;
3047    case clang::Type::SubstTemplateTypeParm:            return eTypeIsTemplate;
3048    case clang::Type::TemplateTypeParm:                 return eTypeIsTemplate;
3049    case clang::Type::TemplateSpecialization:           return eTypeIsTemplate;
3050
3051    case clang::Type::Typedef:
3052        return eTypeIsTypedef | ClangASTContext::GetTypeInfo (cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(),
3053                                                                  ast,
3054                                                                  pointee_or_element_clang_type);
3055
3056    case clang::Type::TypeOfExpr:                       return 0;
3057    case clang::Type::TypeOf:                           return 0;
3058    case clang::Type::UnresolvedUsing:                  return 0;
3059
3060    case clang::Type::ExtVector:
3061    case clang::Type::Vector:
3062        {
3063            uint32_t vector_type_flags = eTypeHasChildren | eTypeIsVector;
3064            const VectorType *vector_type = dyn_cast<VectorType>(qual_type->getCanonicalTypeInternal());
3065            if (vector_type)
3066            {
3067                if (vector_type->isIntegerType())
3068                    vector_type_flags |= eTypeIsFloat;
3069                else if (vector_type->isFloatingType())
3070                    vector_type_flags |= eTypeIsInteger;
3071            }
3072            return vector_type_flags;
3073        }
3074    default:                                            return 0;
3075    }
3076    return 0;
3077}
3078
3079
3080#pragma mark Aggregate Types
3081
3082bool
3083ClangASTContext::IsAggregateType (clang_type_t clang_type)
3084{
3085    if (clang_type == NULL)
3086        return false;
3087
3088    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
3089
3090    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3091    switch (type_class)
3092    {
3093    case clang::Type::IncompleteArray:
3094    case clang::Type::VariableArray:
3095    case clang::Type::ConstantArray:
3096    case clang::Type::ExtVector:
3097    case clang::Type::Vector:
3098    case clang::Type::Record:
3099    case clang::Type::ObjCObject:
3100    case clang::Type::ObjCInterface:
3101        return true;
3102    case clang::Type::Elaborated:
3103        return ClangASTContext::IsAggregateType (cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
3104    case clang::Type::Typedef:
3105        return ClangASTContext::IsAggregateType (cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
3106
3107    default:
3108        break;
3109    }
3110    // The clang type does have a value
3111    return false;
3112}
3113
3114uint32_t
3115ClangASTContext::GetNumChildren (clang::ASTContext *ast, clang_type_t clang_type, bool omit_empty_base_classes)
3116{
3117    if (clang_type == NULL)
3118        return 0;
3119
3120    uint32_t num_children = 0;
3121    QualType qual_type(QualType::getFromOpaquePtr(clang_type));
3122    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3123    switch (type_class)
3124    {
3125    case clang::Type::Builtin:
3126        switch (cast<clang::BuiltinType>(qual_type)->getKind())
3127        {
3128        case clang::BuiltinType::ObjCId:    // child is Class
3129        case clang::BuiltinType::ObjCClass: // child is Class
3130            num_children = 1;
3131            break;
3132
3133        default:
3134            break;
3135        }
3136        break;
3137
3138    case clang::Type::Complex: return 0;
3139
3140    case clang::Type::Record:
3141        if (GetCompleteQualType (ast, qual_type))
3142        {
3143            const RecordType *record_type = cast<RecordType>(qual_type.getTypePtr());
3144            const RecordDecl *record_decl = record_type->getDecl();
3145            assert(record_decl);
3146            const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
3147            if (cxx_record_decl)
3148            {
3149                if (omit_empty_base_classes)
3150                {
3151                    // Check each base classes to see if it or any of its
3152                    // base classes contain any fields. This can help
3153                    // limit the noise in variable views by not having to
3154                    // show base classes that contain no members.
3155                    CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
3156                    for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
3157                         base_class != base_class_end;
3158                         ++base_class)
3159                    {
3160                        const CXXRecordDecl *base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
3161
3162                        // Skip empty base classes
3163                        if (RecordHasFields(base_class_decl) == false)
3164                            continue;
3165
3166                        num_children++;
3167                    }
3168                }
3169                else
3170                {
3171                    // Include all base classes
3172                    num_children += cxx_record_decl->getNumBases();
3173                }
3174
3175            }
3176            RecordDecl::field_iterator field, field_end;
3177            for (field = record_decl->field_begin(), field_end = record_decl->field_end(); field != field_end; ++field)
3178                ++num_children;
3179        }
3180        break;
3181
3182    case clang::Type::ObjCObject:
3183    case clang::Type::ObjCInterface:
3184        if (GetCompleteQualType (ast, qual_type))
3185        {
3186            const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(qual_type.getTypePtr());
3187            assert (objc_class_type);
3188            if (objc_class_type)
3189            {
3190                ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
3191
3192                if (class_interface_decl)
3193                {
3194
3195                    ObjCInterfaceDecl *superclass_interface_decl = class_interface_decl->getSuperClass();
3196                    if (superclass_interface_decl)
3197                    {
3198                        if (omit_empty_base_classes)
3199                        {
3200                            if (ClangASTContext::ObjCDeclHasIVars (superclass_interface_decl, true))
3201                                ++num_children;
3202                        }
3203                        else
3204                            ++num_children;
3205                    }
3206
3207                    num_children += class_interface_decl->ivar_size();
3208                }
3209            }
3210        }
3211        break;
3212
3213    case clang::Type::ObjCObjectPointer:
3214        {
3215            const ObjCObjectPointerType *pointer_type = cast<ObjCObjectPointerType>(qual_type.getTypePtr());
3216            QualType pointee_type = pointer_type->getPointeeType();
3217            uint32_t num_pointee_children = ClangASTContext::GetNumChildren (ast,
3218                                                                             pointee_type.getAsOpaquePtr(),
3219                                                                             omit_empty_base_classes);
3220            // If this type points to a simple type, then it has 1 child
3221            if (num_pointee_children == 0)
3222                num_children = 1;
3223            else
3224                num_children = num_pointee_children;
3225        }
3226        break;
3227
3228    case clang::Type::Vector:
3229    case clang::Type::ExtVector:
3230        num_children = cast<VectorType>(qual_type.getTypePtr())->getNumElements();
3231        break;
3232
3233    case clang::Type::ConstantArray:
3234        num_children = cast<ConstantArrayType>(qual_type.getTypePtr())->getSize().getLimitedValue();
3235        break;
3236
3237    case clang::Type::Pointer:
3238        {
3239            const PointerType *pointer_type = cast<PointerType>(qual_type.getTypePtr());
3240            QualType pointee_type (pointer_type->getPointeeType());
3241            uint32_t num_pointee_children = ClangASTContext::GetNumChildren (ast,
3242                                                                             pointee_type.getAsOpaquePtr(),
3243                                                                             omit_empty_base_classes);
3244            if (num_pointee_children == 0)
3245            {
3246                // We have a pointer to a pointee type that claims it has no children.
3247                // We will want to look at
3248                num_children = ClangASTContext::GetNumPointeeChildren (pointee_type.getAsOpaquePtr());
3249            }
3250            else
3251                num_children = num_pointee_children;
3252        }
3253        break;
3254
3255    case clang::Type::LValueReference:
3256    case clang::Type::RValueReference:
3257        {
3258            const ReferenceType *reference_type = cast<ReferenceType>(qual_type.getTypePtr());
3259            QualType pointee_type = reference_type->getPointeeType();
3260            uint32_t num_pointee_children = ClangASTContext::GetNumChildren (ast,
3261                                                                             pointee_type.getAsOpaquePtr(),
3262                                                                             omit_empty_base_classes);
3263            // If this type points to a simple type, then it has 1 child
3264            if (num_pointee_children == 0)
3265                num_children = 1;
3266            else
3267                num_children = num_pointee_children;
3268        }
3269        break;
3270
3271
3272    case clang::Type::Typedef:
3273        num_children = ClangASTContext::GetNumChildren (ast,
3274                                                        cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(),
3275                                                        omit_empty_base_classes);
3276        break;
3277
3278    case clang::Type::Elaborated:
3279        num_children = ClangASTContext::GetNumChildren (ast,
3280                                                        cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(),
3281                                                        omit_empty_base_classes);
3282        break;
3283
3284    default:
3285        break;
3286    }
3287    return num_children;
3288}
3289
3290uint32_t
3291ClangASTContext::GetNumDirectBaseClasses (clang::ASTContext *ast, clang_type_t clang_type)
3292{
3293    if (clang_type == NULL)
3294        return 0;
3295
3296    uint32_t count = 0;
3297    QualType qual_type(QualType::getFromOpaquePtr(clang_type));
3298    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3299    switch (type_class)
3300    {
3301        case clang::Type::Record:
3302            if (GetCompleteQualType (ast, qual_type))
3303            {
3304                const CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
3305                if (cxx_record_decl)
3306                    count = cxx_record_decl->getNumBases();
3307            }
3308            break;
3309
3310        case clang::Type::ObjCObject:
3311        case clang::Type::ObjCInterface:
3312            if (GetCompleteQualType (ast, qual_type))
3313            {
3314                const ObjCObjectType *objc_class_type = qual_type->getAsObjCQualifiedInterfaceType();
3315                if (objc_class_type)
3316                {
3317                    ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
3318
3319                    if (class_interface_decl && class_interface_decl->getSuperClass())
3320                        count = 1;
3321                }
3322            }
3323            break;
3324
3325
3326        case clang::Type::Typedef:
3327            count = ClangASTContext::GetNumDirectBaseClasses (ast, cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
3328            break;
3329
3330        case clang::Type::Elaborated:
3331            count = ClangASTContext::GetNumDirectBaseClasses (ast, cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
3332            break;
3333
3334        default:
3335            break;
3336    }
3337    return count;
3338}
3339
3340uint32_t
3341ClangASTContext::GetNumVirtualBaseClasses (clang::ASTContext *ast,
3342                                           clang_type_t clang_type)
3343{
3344    if (clang_type == NULL)
3345        return 0;
3346
3347    uint32_t count = 0;
3348    QualType qual_type(QualType::getFromOpaquePtr(clang_type));
3349    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3350    switch (type_class)
3351    {
3352        case clang::Type::Record:
3353            if (GetCompleteQualType (ast, qual_type))
3354            {
3355                const CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
3356                if (cxx_record_decl)
3357                    count = cxx_record_decl->getNumVBases();
3358            }
3359            break;
3360
3361        case clang::Type::Typedef:
3362            count = ClangASTContext::GetNumVirtualBaseClasses (ast, cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
3363            break;
3364
3365        case clang::Type::Elaborated:
3366            count = ClangASTContext::GetNumVirtualBaseClasses (ast, cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
3367            break;
3368
3369        default:
3370            break;
3371    }
3372    return count;
3373}
3374
3375uint32_t
3376ClangASTContext::GetNumFields (clang::ASTContext *ast, clang_type_t clang_type)
3377{
3378    if (clang_type == NULL)
3379        return 0;
3380
3381    uint32_t count = 0;
3382    QualType qual_type(QualType::getFromOpaquePtr(clang_type));
3383    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3384    switch (type_class)
3385    {
3386        case clang::Type::Record:
3387            if (GetCompleteQualType (ast, qual_type))
3388            {
3389                const RecordType *record_type = dyn_cast<RecordType>(qual_type.getTypePtr());
3390                if (record_type)
3391                {
3392                    RecordDecl *record_decl = record_type->getDecl();
3393                    if (record_decl)
3394                    {
3395                        uint32_t field_idx = 0;
3396                        RecordDecl::field_iterator field, field_end;
3397                        for (field = record_decl->field_begin(), field_end = record_decl->field_end(); field != field_end; ++field)
3398                            ++field_idx;
3399                        count = field_idx;
3400                    }
3401                }
3402            }
3403            break;
3404
3405        case clang::Type::Typedef:
3406            count = ClangASTContext::GetNumFields (ast, cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
3407            break;
3408
3409        case clang::Type::Elaborated:
3410            count = ClangASTContext::GetNumFields (ast, cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
3411            break;
3412
3413        case clang::Type::ObjCObject:
3414        case clang::Type::ObjCInterface:
3415            if (GetCompleteQualType (ast, qual_type))
3416            {
3417                const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(qual_type.getTypePtr());
3418                if (objc_class_type)
3419                {
3420                    ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
3421
3422                    if (class_interface_decl)
3423                        count = class_interface_decl->ivar_size();
3424                }
3425            }
3426            break;
3427
3428        default:
3429            break;
3430    }
3431    return count;
3432}
3433
3434clang_type_t
3435ClangASTContext::GetDirectBaseClassAtIndex (clang::ASTContext *ast,
3436                                            clang_type_t clang_type,
3437                                            size_t idx,
3438                                            uint32_t *bit_offset_ptr)
3439{
3440    if (clang_type == NULL)
3441        return 0;
3442
3443    QualType qual_type(QualType::getFromOpaquePtr(clang_type));
3444    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3445    switch (type_class)
3446    {
3447        case clang::Type::Record:
3448            if (GetCompleteQualType (ast, qual_type))
3449            {
3450                const CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
3451                if (cxx_record_decl)
3452                {
3453                    uint32_t curr_idx = 0;
3454                    CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
3455                    for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
3456                         base_class != base_class_end;
3457                         ++base_class, ++curr_idx)
3458                    {
3459                        if (curr_idx == idx)
3460                        {
3461                            if (bit_offset_ptr)
3462                            {
3463                                const ASTRecordLayout &record_layout = ast->getASTRecordLayout(cxx_record_decl);
3464                                const CXXRecordDecl *base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
3465//                                if (base_class->isVirtual())
3466//                                    *bit_offset_ptr = record_layout.getVBaseClassOffset(base_class_decl).getQuantity() * 8;
3467//                                else
3468                                    *bit_offset_ptr = record_layout.getBaseClassOffset(base_class_decl).getQuantity() * 8;
3469                            }
3470                            return base_class->getType().getAsOpaquePtr();
3471                        }
3472                    }
3473                }
3474            }
3475            break;
3476
3477        case clang::Type::ObjCObject:
3478        case clang::Type::ObjCInterface:
3479            if (idx == 0 && GetCompleteQualType (ast, qual_type))
3480            {
3481                const ObjCObjectType *objc_class_type = qual_type->getAsObjCQualifiedInterfaceType();
3482                if (objc_class_type)
3483                {
3484                    ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
3485
3486                    if (class_interface_decl)
3487                    {
3488                        ObjCInterfaceDecl *superclass_interface_decl = class_interface_decl->getSuperClass();
3489                        if (superclass_interface_decl)
3490                        {
3491                            if (bit_offset_ptr)
3492                                *bit_offset_ptr = 0;
3493                            return ast->getObjCInterfaceType(superclass_interface_decl).getAsOpaquePtr();
3494                        }
3495                    }
3496                }
3497            }
3498            break;
3499
3500
3501        case clang::Type::Typedef:
3502            return ClangASTContext::GetDirectBaseClassAtIndex (ast,
3503                                                               cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(),
3504                                                               idx,
3505                                                               bit_offset_ptr);
3506
3507        case clang::Type::Elaborated:
3508            return  ClangASTContext::GetDirectBaseClassAtIndex (ast,
3509                                                                cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(),
3510                                                                idx,
3511                                                                bit_offset_ptr);
3512
3513        default:
3514            break;
3515    }
3516    return NULL;
3517}
3518
3519clang_type_t
3520ClangASTContext::GetVirtualBaseClassAtIndex (clang::ASTContext *ast,
3521                                             clang_type_t clang_type,
3522                                             size_t idx,
3523                                             uint32_t *bit_offset_ptr)
3524{
3525    if (clang_type == NULL)
3526        return 0;
3527
3528    QualType qual_type(QualType::getFromOpaquePtr(clang_type));
3529    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3530    switch (type_class)
3531    {
3532        case clang::Type::Record:
3533            if (GetCompleteQualType (ast, qual_type))
3534            {
3535                const CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
3536                if (cxx_record_decl)
3537                {
3538                    uint32_t curr_idx = 0;
3539                    CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
3540                    for (base_class = cxx_record_decl->vbases_begin(), base_class_end = cxx_record_decl->vbases_end();
3541                         base_class != base_class_end;
3542                         ++base_class, ++curr_idx)
3543                    {
3544                        if (curr_idx == idx)
3545                        {
3546                            if (bit_offset_ptr)
3547                            {
3548                                const ASTRecordLayout &record_layout = ast->getASTRecordLayout(cxx_record_decl);
3549                                const CXXRecordDecl *base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
3550                                *bit_offset_ptr = record_layout.getVBaseClassOffset(base_class_decl).getQuantity() * 8;
3551
3552                            }
3553                            return base_class->getType().getAsOpaquePtr();
3554                        }
3555                    }
3556                }
3557            }
3558            break;
3559
3560        case clang::Type::Typedef:
3561            return ClangASTContext::GetVirtualBaseClassAtIndex (ast,
3562                                                                cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(),
3563                                                                idx,
3564                                                                bit_offset_ptr);
3565
3566        case clang::Type::Elaborated:
3567            return  ClangASTContext::GetVirtualBaseClassAtIndex (ast,
3568                                                                 cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(),
3569                                                                 idx,
3570                                                                 bit_offset_ptr);
3571
3572        default:
3573            break;
3574    }
3575    return NULL;
3576}
3577
3578clang_type_t
3579ClangASTContext::GetFieldAtIndex (clang::ASTContext *ast,
3580                                  clang_type_t clang_type,
3581                                  size_t idx,
3582                                  std::string& name,
3583                                  uint64_t *bit_offset_ptr,
3584                                  uint32_t *bitfield_bit_size_ptr,
3585                                  bool *is_bitfield_ptr)
3586{
3587    if (clang_type == NULL)
3588        return 0;
3589
3590    QualType qual_type(QualType::getFromOpaquePtr(clang_type));
3591    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3592    switch (type_class)
3593    {
3594        case clang::Type::Record:
3595            if (GetCompleteQualType (ast, qual_type))
3596            {
3597                const RecordType *record_type = cast<RecordType>(qual_type.getTypePtr());
3598                const RecordDecl *record_decl = record_type->getDecl();
3599                uint32_t field_idx = 0;
3600                RecordDecl::field_iterator field, field_end;
3601                for (field = record_decl->field_begin(), field_end = record_decl->field_end(); field != field_end; ++field, ++field_idx)
3602                {
3603                    if (idx == field_idx)
3604                    {
3605                        // Print the member type if requested
3606                        // Print the member name and equal sign
3607                        name.assign(field->getNameAsString());
3608
3609                        // Figure out the type byte size (field_type_info.first) and
3610                        // alignment (field_type_info.second) from the AST context.
3611                        if (bit_offset_ptr)
3612                        {
3613                            const ASTRecordLayout &record_layout = ast->getASTRecordLayout(record_decl);
3614                            *bit_offset_ptr = record_layout.getFieldOffset (field_idx);
3615                        }
3616
3617                        const bool is_bitfield = field->isBitField();
3618
3619                        if (bitfield_bit_size_ptr)
3620                        {
3621                            *bitfield_bit_size_ptr = 0;
3622
3623                            if (is_bitfield && ast)
3624                            {
3625                                Expr *bitfield_bit_size_expr = field->getBitWidth();
3626                                llvm::APSInt bitfield_apsint;
3627                                if (bitfield_bit_size_expr && bitfield_bit_size_expr->EvaluateAsInt(bitfield_apsint, *ast))
3628                                {
3629                                    *bitfield_bit_size_ptr = bitfield_apsint.getLimitedValue();
3630                                }
3631                            }
3632                        }
3633                        if (is_bitfield_ptr)
3634                            *is_bitfield_ptr = is_bitfield;
3635
3636                        return field->getType().getAsOpaquePtr();
3637                    }
3638                }
3639            }
3640            break;
3641
3642        case clang::Type::ObjCObject:
3643        case clang::Type::ObjCInterface:
3644            if (GetCompleteQualType (ast, qual_type))
3645            {
3646                const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(qual_type.getTypePtr());
3647                assert (objc_class_type);
3648                if (objc_class_type)
3649                {
3650                    ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
3651
3652                    if (class_interface_decl)
3653                    {
3654                        if (idx < (class_interface_decl->ivar_size()))
3655                        {
3656                            ObjCInterfaceDecl::ivar_iterator ivar_pos, ivar_end = class_interface_decl->ivar_end();
3657                            uint32_t ivar_idx = 0;
3658
3659                            for (ivar_pos = class_interface_decl->ivar_begin(); ivar_pos != ivar_end; ++ivar_pos, ++ivar_idx)
3660                            {
3661                                if (ivar_idx == idx)
3662                                {
3663                                    const ObjCIvarDecl* ivar_decl = *ivar_pos;
3664
3665                                    QualType ivar_qual_type(ivar_decl->getType());
3666
3667                                    name.assign(ivar_decl->getNameAsString());
3668
3669                                    if (bit_offset_ptr)
3670                                    {
3671                                        const ASTRecordLayout &interface_layout = ast->getASTObjCInterfaceLayout(class_interface_decl);
3672                                        *bit_offset_ptr = interface_layout.getFieldOffset (ivar_idx);
3673                                    }
3674
3675                                    const bool is_bitfield = ivar_pos->isBitField();
3676
3677                                    if (bitfield_bit_size_ptr)
3678                                    {
3679                                        *bitfield_bit_size_ptr = 0;
3680
3681                                        if (is_bitfield && ast)
3682                                        {
3683                                            Expr *bitfield_bit_size_expr = ivar_pos->getBitWidth();
3684                                            llvm::APSInt bitfield_apsint;
3685                                            if (bitfield_bit_size_expr && bitfield_bit_size_expr->EvaluateAsInt(bitfield_apsint, *ast))
3686                                            {
3687                                                *bitfield_bit_size_ptr = bitfield_apsint.getLimitedValue();
3688                                            }
3689                                        }
3690                                    }
3691                                    if (is_bitfield_ptr)
3692                                        *is_bitfield_ptr = is_bitfield;
3693
3694                                    return ivar_qual_type.getAsOpaquePtr();
3695                                }
3696                            }
3697                        }
3698                    }
3699                }
3700            }
3701            break;
3702
3703
3704        case clang::Type::Typedef:
3705            return ClangASTContext::GetFieldAtIndex (ast,
3706                                                     cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(),
3707                                                     idx,
3708                                                     name,
3709                                                     bit_offset_ptr,
3710                                                     bitfield_bit_size_ptr,
3711                                                     is_bitfield_ptr);
3712
3713        case clang::Type::Elaborated:
3714            return  ClangASTContext::GetFieldAtIndex (ast,
3715                                                      cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(),
3716                                                      idx,
3717                                                      name,
3718                                                      bit_offset_ptr,
3719                                                      bitfield_bit_size_ptr,
3720                                                      is_bitfield_ptr);
3721
3722        default:
3723            break;
3724    }
3725    return NULL;
3726}
3727
3728size_t
3729ClangASTContext::GetIndexOfFieldWithName (clang::ASTContext *ast,
3730                                          lldb::clang_type_t clang_type,
3731                                          const char* name,
3732                                          lldb::clang_type_t* field_clang_type,
3733                                          uint64_t *bit_offset_ptr,
3734                                          uint32_t *bitfield_bit_size_ptr,
3735                                          bool *is_bitfield_ptr)
3736{
3737    auto count = ClangASTContext::GetNumFields(ast, clang_type);
3738    lldb::clang_type_t field_clang_type_internal;
3739    std::string field_name;
3740    for (auto index = 0; index < count; index++)
3741    {
3742        field_clang_type_internal = ClangASTContext::GetFieldAtIndex(ast, clang_type, index, field_name, bit_offset_ptr, bitfield_bit_size_ptr, is_bitfield_ptr);
3743        if ( strcmp(field_name.c_str(), name) == 0 )
3744        {
3745            if (field_clang_type)
3746                *field_clang_type = field_clang_type_internal;
3747            return index;
3748        }
3749    }
3750    return UINT32_MAX;
3751}
3752
3753lldb::BasicType
3754ClangASTContext::GetLLDBBasicTypeEnumeration (clang_type_t clang_type)
3755{
3756    if (clang_type)
3757    {
3758        QualType qual_type(QualType::getFromOpaquePtr(clang_type));
3759        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3760        if (type_class == clang::Type::Builtin)
3761        {
3762            switch (cast<clang::BuiltinType>(qual_type)->getKind())
3763            {
3764            case clang::BuiltinType::Void:      return eBasicTypeVoid;
3765            case clang::BuiltinType::Bool:      return eBasicTypeBool;
3766            case clang::BuiltinType::Char_S:    return eBasicTypeSignedChar;
3767            case clang::BuiltinType::Char_U:    return eBasicTypeUnsignedChar;
3768            case clang::BuiltinType::Char16:    return eBasicTypeChar16;
3769            case clang::BuiltinType::Char32:    return eBasicTypeChar32;
3770            case clang::BuiltinType::UChar:     return eBasicTypeUnsignedChar;
3771            case clang::BuiltinType::SChar:     return eBasicTypeSignedChar;
3772            case clang::BuiltinType::WChar_S:   return eBasicTypeSignedWChar;
3773            case clang::BuiltinType::WChar_U:   return eBasicTypeUnsignedWChar;
3774            case clang::BuiltinType::Short:     return eBasicTypeShort;
3775            case clang::BuiltinType::UShort:    return eBasicTypeUnsignedShort;
3776            case clang::BuiltinType::Int:       return eBasicTypeInt;
3777            case clang::BuiltinType::UInt:      return eBasicTypeUnsignedInt;
3778            case clang::BuiltinType::Long:      return eBasicTypeLong;
3779            case clang::BuiltinType::ULong:     return eBasicTypeUnsignedLong;
3780            case clang::BuiltinType::LongLong:  return eBasicTypeLongLong;
3781            case clang::BuiltinType::ULongLong: return eBasicTypeUnsignedLongLong;
3782            case clang::BuiltinType::Int128:    return eBasicTypeInt128;
3783            case clang::BuiltinType::UInt128:   return eBasicTypeUnsignedInt128;
3784
3785            case clang::BuiltinType::Half:      return eBasicTypeHalf;
3786            case clang::BuiltinType::Float:     return eBasicTypeFloat;
3787            case clang::BuiltinType::Double:    return eBasicTypeDouble;
3788            case clang::BuiltinType::LongDouble:return eBasicTypeLongDouble;
3789
3790            case clang::BuiltinType::NullPtr:   return eBasicTypeNullPtr;
3791            case clang::BuiltinType::ObjCId:    return eBasicTypeObjCID;
3792            case clang::BuiltinType::ObjCClass: return eBasicTypeObjCClass;
3793            case clang::BuiltinType::ObjCSel:   return eBasicTypeObjCSel;
3794            case clang::BuiltinType::Dependent:
3795            case clang::BuiltinType::Overload:
3796            case clang::BuiltinType::BoundMember:
3797            case clang::BuiltinType::PseudoObject:
3798            case clang::BuiltinType::UnknownAny:
3799            case clang::BuiltinType::BuiltinFn:
3800            case clang::BuiltinType::ARCUnbridgedCast:
3801            case clang::BuiltinType::OCLEvent:
3802            case clang::BuiltinType::OCLImage1d:
3803            case clang::BuiltinType::OCLImage1dArray:
3804            case clang::BuiltinType::OCLImage1dBuffer:
3805            case clang::BuiltinType::OCLImage2d:
3806            case clang::BuiltinType::OCLImage2dArray:
3807            case clang::BuiltinType::OCLImage3d:
3808            case clang::BuiltinType::OCLSampler:
3809                return eBasicTypeOther;
3810            }
3811        }
3812    }
3813
3814    return eBasicTypeInvalid;
3815}
3816
3817
3818
3819// If a pointer to a pointee type (the clang_type arg) says that it has no
3820// children, then we either need to trust it, or override it and return a
3821// different result. For example, an "int *" has one child that is an integer,
3822// but a function pointer doesn't have any children. Likewise if a Record type
3823// claims it has no children, then there really is nothing to show.
3824uint32_t
3825ClangASTContext::GetNumPointeeChildren (clang_type_t clang_type)
3826{
3827    if (clang_type == NULL)
3828        return 0;
3829
3830    QualType qual_type(QualType::getFromOpaquePtr(clang_type));
3831    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3832    switch (type_class)
3833    {
3834    case clang::Type::Builtin:
3835        switch (cast<clang::BuiltinType>(qual_type)->getKind())
3836        {
3837        case clang::BuiltinType::UnknownAny:
3838        case clang::BuiltinType::Void:
3839        case clang::BuiltinType::NullPtr:
3840        case clang::BuiltinType::OCLEvent:
3841        case clang::BuiltinType::OCLImage1d:
3842        case clang::BuiltinType::OCLImage1dArray:
3843        case clang::BuiltinType::OCLImage1dBuffer:
3844        case clang::BuiltinType::OCLImage2d:
3845        case clang::BuiltinType::OCLImage2dArray:
3846        case clang::BuiltinType::OCLImage3d:
3847        case clang::BuiltinType::OCLSampler:
3848            return 0;
3849        case clang::BuiltinType::Bool:
3850        case clang::BuiltinType::Char_U:
3851        case clang::BuiltinType::UChar:
3852        case clang::BuiltinType::WChar_U:
3853        case clang::BuiltinType::Char16:
3854        case clang::BuiltinType::Char32:
3855        case clang::BuiltinType::UShort:
3856        case clang::BuiltinType::UInt:
3857        case clang::BuiltinType::ULong:
3858        case clang::BuiltinType::ULongLong:
3859        case clang::BuiltinType::UInt128:
3860        case clang::BuiltinType::Char_S:
3861        case clang::BuiltinType::SChar:
3862        case clang::BuiltinType::WChar_S:
3863        case clang::BuiltinType::Short:
3864        case clang::BuiltinType::Int:
3865        case clang::BuiltinType::Long:
3866        case clang::BuiltinType::LongLong:
3867        case clang::BuiltinType::Int128:
3868        case clang::BuiltinType::Float:
3869        case clang::BuiltinType::Double:
3870        case clang::BuiltinType::LongDouble:
3871        case clang::BuiltinType::Dependent:
3872        case clang::BuiltinType::Overload:
3873        case clang::BuiltinType::ObjCId:
3874        case clang::BuiltinType::ObjCClass:
3875        case clang::BuiltinType::ObjCSel:
3876        case clang::BuiltinType::BoundMember:
3877        case clang::BuiltinType::Half:
3878        case clang::BuiltinType::ARCUnbridgedCast:
3879        case clang::BuiltinType::PseudoObject:
3880        case clang::BuiltinType::BuiltinFn:
3881            return 1;
3882        }
3883        break;
3884
3885    case clang::Type::Complex:                  return 1;
3886    case clang::Type::Pointer:                  return 1;
3887    case clang::Type::BlockPointer:             return 0;   // If block pointers don't have debug info, then no children for them
3888    case clang::Type::LValueReference:          return 1;
3889    case clang::Type::RValueReference:          return 1;
3890    case clang::Type::MemberPointer:            return 0;
3891    case clang::Type::ConstantArray:            return 0;
3892    case clang::Type::IncompleteArray:          return 0;
3893    case clang::Type::VariableArray:            return 0;
3894    case clang::Type::DependentSizedArray:      return 0;
3895    case clang::Type::DependentSizedExtVector:  return 0;
3896    case clang::Type::Vector:                   return 0;
3897    case clang::Type::ExtVector:                return 0;
3898    case clang::Type::FunctionProto:            return 0;   // When we function pointers, they have no children...
3899    case clang::Type::FunctionNoProto:          return 0;   // When we function pointers, they have no children...
3900    case clang::Type::UnresolvedUsing:          return 0;
3901    case clang::Type::Paren:                    return 0;
3902    case clang::Type::Typedef:                  return ClangASTContext::GetNumPointeeChildren (cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
3903    case clang::Type::Elaborated:               return ClangASTContext::GetNumPointeeChildren (cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
3904    case clang::Type::TypeOfExpr:               return 0;
3905    case clang::Type::TypeOf:                   return 0;
3906    case clang::Type::Decltype:                 return 0;
3907    case clang::Type::Record:                   return 0;
3908    case clang::Type::Enum:                     return 1;
3909    case clang::Type::TemplateTypeParm:         return 1;
3910    case clang::Type::SubstTemplateTypeParm:    return 1;
3911    case clang::Type::TemplateSpecialization:   return 1;
3912    case clang::Type::InjectedClassName:        return 0;
3913    case clang::Type::DependentName:            return 1;
3914    case clang::Type::DependentTemplateSpecialization:  return 1;
3915    case clang::Type::ObjCObject:               return 0;
3916    case clang::Type::ObjCInterface:            return 0;
3917    case clang::Type::ObjCObjectPointer:        return 1;
3918    default:
3919        break;
3920    }
3921    return 0;
3922}
3923
3924clang_type_t
3925ClangASTContext::GetChildClangTypeAtIndex
3926(
3927    ExecutionContext *exe_ctx,
3928    const char *parent_name,
3929    clang_type_t parent_clang_type,
3930    size_t idx,
3931    bool transparent_pointers,
3932    bool omit_empty_base_classes,
3933    bool ignore_array_bounds,
3934    std::string& child_name,
3935    uint32_t &child_byte_size,
3936    int32_t &child_byte_offset,
3937    uint32_t &child_bitfield_bit_size,
3938    uint32_t &child_bitfield_bit_offset,
3939    bool &child_is_base_class,
3940    bool &child_is_deref_of_parent
3941)
3942{
3943    if (parent_clang_type)
3944
3945        return GetChildClangTypeAtIndex (exe_ctx,
3946                                         getASTContext(),
3947                                         parent_name,
3948                                         parent_clang_type,
3949                                         idx,
3950                                         transparent_pointers,
3951                                         omit_empty_base_classes,
3952                                         ignore_array_bounds,
3953                                         child_name,
3954                                         child_byte_size,
3955                                         child_byte_offset,
3956                                         child_bitfield_bit_size,
3957                                         child_bitfield_bit_offset,
3958                                         child_is_base_class,
3959                                         child_is_deref_of_parent);
3960    return NULL;
3961}
3962
3963clang_type_t
3964ClangASTContext::GetChildClangTypeAtIndex
3965(
3966    ExecutionContext *exe_ctx,
3967    ASTContext *ast,
3968    const char *parent_name,
3969    clang_type_t parent_clang_type,
3970    size_t idx,
3971    bool transparent_pointers,
3972    bool omit_empty_base_classes,
3973    bool ignore_array_bounds,
3974    std::string& child_name,
3975    uint32_t &child_byte_size,
3976    int32_t &child_byte_offset,
3977    uint32_t &child_bitfield_bit_size,
3978    uint32_t &child_bitfield_bit_offset,
3979    bool &child_is_base_class,
3980    bool &child_is_deref_of_parent
3981)
3982{
3983    if (parent_clang_type == NULL)
3984        return NULL;
3985
3986    QualType parent_qual_type(QualType::getFromOpaquePtr(parent_clang_type));
3987    const clang::Type::TypeClass parent_type_class = parent_qual_type->getTypeClass();
3988    child_bitfield_bit_size = 0;
3989    child_bitfield_bit_offset = 0;
3990    child_is_base_class = false;
3991
3992    const bool idx_is_valid = idx < ClangASTContext::GetNumChildren (ast, parent_clang_type, omit_empty_base_classes);
3993    uint32_t bit_offset;
3994    switch (parent_type_class)
3995    {
3996    case clang::Type::Builtin:
3997        if (idx_is_valid)
3998        {
3999            switch (cast<clang::BuiltinType>(parent_qual_type)->getKind())
4000            {
4001            case clang::BuiltinType::ObjCId:
4002            case clang::BuiltinType::ObjCClass:
4003                child_name = "isa";
4004                child_byte_size = ast->getTypeSize(ast->ObjCBuiltinClassTy) / CHAR_BIT;
4005                return ast->ObjCBuiltinClassTy.getAsOpaquePtr();
4006
4007            default:
4008                break;
4009            }
4010        }
4011        break;
4012
4013    case clang::Type::Record:
4014        if (idx_is_valid && GetCompleteQualType (ast, parent_qual_type))
4015        {
4016            const RecordType *record_type = cast<RecordType>(parent_qual_type.getTypePtr());
4017            const RecordDecl *record_decl = record_type->getDecl();
4018            assert(record_decl);
4019            const ASTRecordLayout &record_layout = ast->getASTRecordLayout(record_decl);
4020            uint32_t child_idx = 0;
4021
4022            const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
4023            if (cxx_record_decl)
4024            {
4025                // We might have base classes to print out first
4026                CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
4027                for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
4028                     base_class != base_class_end;
4029                     ++base_class)
4030                {
4031                    const CXXRecordDecl *base_class_decl = NULL;
4032
4033                    // Skip empty base classes
4034                    if (omit_empty_base_classes)
4035                    {
4036                        base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
4037                        if (RecordHasFields(base_class_decl) == false)
4038                            continue;
4039                    }
4040
4041                    if (idx == child_idx)
4042                    {
4043                        if (base_class_decl == NULL)
4044                            base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
4045
4046
4047                        if (base_class->isVirtual())
4048                            bit_offset = record_layout.getVBaseClassOffset(base_class_decl).getQuantity() * 8;
4049                        else
4050                            bit_offset = record_layout.getBaseClassOffset(base_class_decl).getQuantity() * 8;
4051
4052                        // Base classes should be a multiple of 8 bits in size
4053                        child_byte_offset = bit_offset/8;
4054
4055                        child_name = ClangASTType::GetTypeNameForQualType(ast, base_class->getType());
4056
4057                        uint64_t clang_type_info_bit_size = ast->getTypeSize(base_class->getType());
4058
4059                        // Base classes bit sizes should be a multiple of 8 bits in size
4060                        assert (clang_type_info_bit_size % 8 == 0);
4061                        child_byte_size = clang_type_info_bit_size / 8;
4062                        child_is_base_class = true;
4063                        return base_class->getType().getAsOpaquePtr();
4064                    }
4065                    // We don't increment the child index in the for loop since we might
4066                    // be skipping empty base classes
4067                    ++child_idx;
4068                }
4069            }
4070            // Make sure index is in range...
4071            uint32_t field_idx = 0;
4072            RecordDecl::field_iterator field, field_end;
4073            for (field = record_decl->field_begin(), field_end = record_decl->field_end(); field != field_end; ++field, ++field_idx, ++child_idx)
4074            {
4075                if (idx == child_idx)
4076                {
4077                    // Print the member type if requested
4078                    // Print the member name and equal sign
4079                    child_name.assign(field->getNameAsString().c_str());
4080
4081                    // Figure out the type byte size (field_type_info.first) and
4082                    // alignment (field_type_info.second) from the AST context.
4083                    std::pair<uint64_t, unsigned> field_type_info = ast->getTypeInfo(field->getType());
4084                    assert(field_idx < record_layout.getFieldCount());
4085
4086                    child_byte_size = field_type_info.first / 8;
4087
4088                    // Figure out the field offset within the current struct/union/class type
4089                    bit_offset = record_layout.getFieldOffset (field_idx);
4090                    child_byte_offset = bit_offset / 8;
4091                    if (ClangASTContext::FieldIsBitfield (ast, *field, child_bitfield_bit_size))
4092                        child_bitfield_bit_offset = bit_offset % 8;
4093
4094                    return field->getType().getAsOpaquePtr();
4095                }
4096            }
4097        }
4098        break;
4099
4100    case clang::Type::ObjCObject:
4101    case clang::Type::ObjCInterface:
4102        if (idx_is_valid && GetCompleteQualType (ast, parent_qual_type))
4103        {
4104            const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(parent_qual_type.getTypePtr());
4105            assert (objc_class_type);
4106            if (objc_class_type)
4107            {
4108                uint32_t child_idx = 0;
4109                ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
4110
4111                if (class_interface_decl)
4112                {
4113
4114                    const ASTRecordLayout &interface_layout = ast->getASTObjCInterfaceLayout(class_interface_decl);
4115                    ObjCInterfaceDecl *superclass_interface_decl = class_interface_decl->getSuperClass();
4116                    if (superclass_interface_decl)
4117                    {
4118                        if (omit_empty_base_classes)
4119                        {
4120                            if (ClangASTContext::GetNumChildren(ast, ast->getObjCInterfaceType(superclass_interface_decl).getAsOpaquePtr(), omit_empty_base_classes) > 0)
4121                            {
4122                                if (idx == 0)
4123                                {
4124                                    QualType ivar_qual_type(ast->getObjCInterfaceType(superclass_interface_decl));
4125
4126
4127                                    child_name.assign(superclass_interface_decl->getNameAsString().c_str());
4128
4129                                    std::pair<uint64_t, unsigned> ivar_type_info = ast->getTypeInfo(ivar_qual_type.getTypePtr());
4130
4131                                    child_byte_size = ivar_type_info.first / 8;
4132                                    child_byte_offset = 0;
4133                                    child_is_base_class = true;
4134
4135                                    return ivar_qual_type.getAsOpaquePtr();
4136                                }
4137
4138                                ++child_idx;
4139                            }
4140                        }
4141                        else
4142                            ++child_idx;
4143                    }
4144
4145                    const uint32_t superclass_idx = child_idx;
4146
4147                    if (idx < (child_idx + class_interface_decl->ivar_size()))
4148                    {
4149                        ObjCInterfaceDecl::ivar_iterator ivar_pos, ivar_end = class_interface_decl->ivar_end();
4150
4151                        for (ivar_pos = class_interface_decl->ivar_begin(); ivar_pos != ivar_end; ++ivar_pos)
4152                        {
4153                            if (child_idx == idx)
4154                            {
4155                                ObjCIvarDecl* ivar_decl = *ivar_pos;
4156
4157                                QualType ivar_qual_type(ivar_decl->getType());
4158
4159                                child_name.assign(ivar_decl->getNameAsString().c_str());
4160
4161                                std::pair<uint64_t, unsigned> ivar_type_info = ast->getTypeInfo(ivar_qual_type.getTypePtr());
4162
4163                                child_byte_size = ivar_type_info.first / 8;
4164
4165                                // Figure out the field offset within the current struct/union/class type
4166                                // For ObjC objects, we can't trust the bit offset we get from the Clang AST, since
4167                                // that doesn't account for the space taken up by unbacked properties, or from
4168                                // the changing size of base classes that are newer than this class.
4169                                // So if we have a process around that we can ask about this object, do so.
4170                                child_byte_offset = LLDB_INVALID_IVAR_OFFSET;
4171                                Process *process = NULL;
4172                                if (exe_ctx)
4173                                    process = exe_ctx->GetProcessPtr();
4174                                if (process)
4175                                {
4176                                    ObjCLanguageRuntime *objc_runtime = process->GetObjCLanguageRuntime();
4177                                    if (objc_runtime != NULL)
4178                                    {
4179                                        ClangASTType parent_ast_type (ast, parent_qual_type.getAsOpaquePtr());
4180                                        child_byte_offset = objc_runtime->GetByteOffsetForIvar (parent_ast_type, ivar_decl->getNameAsString().c_str());
4181                                    }
4182                                }
4183
4184                                // Setting this to UINT32_MAX to make sure we don't compute it twice...
4185                                bit_offset = UINT32_MAX;
4186
4187                                if (child_byte_offset == LLDB_INVALID_IVAR_OFFSET)
4188                                {
4189                                    bit_offset = interface_layout.getFieldOffset (child_idx - superclass_idx);
4190                                    child_byte_offset = bit_offset / 8;
4191                                }
4192
4193                                // Note, the ObjC Ivar Byte offset is just that, it doesn't account for the bit offset
4194                                // of a bitfield within its containing object.  So regardless of where we get the byte
4195                                // offset from, we still need to get the bit offset for bitfields from the layout.
4196
4197                                if (ClangASTContext::FieldIsBitfield (ast, ivar_decl, child_bitfield_bit_size))
4198                                {
4199                                    if (bit_offset == UINT32_MAX)
4200                                        bit_offset = interface_layout.getFieldOffset (child_idx - superclass_idx);
4201
4202                                    child_bitfield_bit_offset = bit_offset % 8;
4203                                }
4204                                return ivar_qual_type.getAsOpaquePtr();
4205                            }
4206                            ++child_idx;
4207                        }
4208                    }
4209                }
4210            }
4211        }
4212        break;
4213
4214    case clang::Type::ObjCObjectPointer:
4215        if (idx_is_valid)
4216        {
4217            const ObjCObjectPointerType *pointer_type = cast<ObjCObjectPointerType>(parent_qual_type.getTypePtr());
4218            QualType pointee_type = pointer_type->getPointeeType();
4219
4220            if (transparent_pointers && ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
4221            {
4222                child_is_deref_of_parent = false;
4223                bool tmp_child_is_deref_of_parent = false;
4224                return GetChildClangTypeAtIndex (exe_ctx,
4225                                                 ast,
4226                                                 parent_name,
4227                                                 pointer_type->getPointeeType().getAsOpaquePtr(),
4228                                                 idx,
4229                                                 transparent_pointers,
4230                                                 omit_empty_base_classes,
4231                                                 ignore_array_bounds,
4232                                                 child_name,
4233                                                 child_byte_size,
4234                                                 child_byte_offset,
4235                                                 child_bitfield_bit_size,
4236                                                 child_bitfield_bit_offset,
4237                                                 child_is_base_class,
4238                                                 tmp_child_is_deref_of_parent);
4239            }
4240            else
4241            {
4242                child_is_deref_of_parent = true;
4243                if (parent_name)
4244                {
4245                    child_name.assign(1, '*');
4246                    child_name += parent_name;
4247                }
4248
4249                // We have a pointer to an simple type
4250                if (idx == 0 && GetCompleteQualType(ast, pointee_type))
4251                {
4252                    std::pair<uint64_t, unsigned> clang_type_info = ast->getTypeInfo(pointee_type);
4253                    assert(clang_type_info.first % 8 == 0);
4254                    child_byte_size = clang_type_info.first / 8;
4255                    child_byte_offset = 0;
4256                    return pointee_type.getAsOpaquePtr();
4257                }
4258            }
4259        }
4260        break;
4261
4262        case clang::Type::Vector:
4263        case clang::Type::ExtVector:
4264            if (idx_is_valid)
4265            {
4266                const VectorType *array = cast<VectorType>(parent_qual_type.getTypePtr());
4267                if (array)
4268                {
4269                    if (GetCompleteQualType (ast, array->getElementType()))
4270                    {
4271                        std::pair<uint64_t, unsigned> field_type_info = ast->getTypeInfo(array->getElementType());
4272
4273                        char element_name[64];
4274                        ::snprintf (element_name, sizeof (element_name), "[%zu]", idx);
4275
4276                        child_name.assign(element_name);
4277                        assert(field_type_info.first % 8 == 0);
4278                        child_byte_size = field_type_info.first / 8;
4279                        child_byte_offset = (int32_t)idx * (int32_t)child_byte_size;
4280                        return array->getElementType().getAsOpaquePtr();
4281                    }
4282                }
4283            }
4284            break;
4285
4286        case clang::Type::ConstantArray:
4287        case clang::Type::IncompleteArray:
4288            if (ignore_array_bounds || idx_is_valid)
4289            {
4290                const ArrayType *array = cast<ArrayType>(parent_qual_type.getTypePtr());
4291                if (array)
4292                {
4293                    if (GetCompleteQualType (ast, array->getElementType()))
4294                    {
4295                        std::pair<uint64_t, unsigned> field_type_info = ast->getTypeInfo(array->getElementType());
4296
4297                        char element_name[64];
4298                        ::snprintf (element_name, sizeof (element_name), "[%zu]", idx);
4299
4300                        child_name.assign(element_name);
4301                        assert(field_type_info.first % 8 == 0);
4302                        child_byte_size = field_type_info.first / 8;
4303                        child_byte_offset = (int32_t)idx * (int32_t)child_byte_size;
4304                        return array->getElementType().getAsOpaquePtr();
4305                    }
4306                }
4307            }
4308            break;
4309
4310
4311    case clang::Type::Pointer:
4312        if (idx_is_valid)
4313        {
4314            const PointerType *pointer_type = cast<PointerType>(parent_qual_type.getTypePtr());
4315            QualType pointee_type = pointer_type->getPointeeType();
4316
4317            // Don't dereference "void *" pointers
4318            if (pointee_type->isVoidType())
4319                return NULL;
4320
4321            if (transparent_pointers && ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
4322            {
4323                child_is_deref_of_parent = false;
4324                bool tmp_child_is_deref_of_parent = false;
4325                return GetChildClangTypeAtIndex (exe_ctx,
4326                                                 ast,
4327                                                 parent_name,
4328                                                 pointer_type->getPointeeType().getAsOpaquePtr(),
4329                                                 idx,
4330                                                 transparent_pointers,
4331                                                 omit_empty_base_classes,
4332                                                 ignore_array_bounds,
4333                                                 child_name,
4334                                                 child_byte_size,
4335                                                 child_byte_offset,
4336                                                 child_bitfield_bit_size,
4337                                                 child_bitfield_bit_offset,
4338                                                 child_is_base_class,
4339                                                 tmp_child_is_deref_of_parent);
4340            }
4341            else
4342            {
4343                child_is_deref_of_parent = true;
4344
4345                if (parent_name)
4346                {
4347                    child_name.assign(1, '*');
4348                    child_name += parent_name;
4349                }
4350
4351                // We have a pointer to an simple type
4352                if (idx == 0)
4353                {
4354                    std::pair<uint64_t, unsigned> clang_type_info = ast->getTypeInfo(pointee_type);
4355                    assert(clang_type_info.first % 8 == 0);
4356                    child_byte_size = clang_type_info.first / 8;
4357                    child_byte_offset = 0;
4358                    return pointee_type.getAsOpaquePtr();
4359                }
4360            }
4361        }
4362        break;
4363
4364    case clang::Type::LValueReference:
4365    case clang::Type::RValueReference:
4366        if (idx_is_valid)
4367        {
4368            const ReferenceType *reference_type = cast<ReferenceType>(parent_qual_type.getTypePtr());
4369            QualType pointee_type(reference_type->getPointeeType());
4370            clang_type_t pointee_clang_type = pointee_type.getAsOpaquePtr();
4371            if (transparent_pointers && ClangASTContext::IsAggregateType (pointee_clang_type))
4372            {
4373                child_is_deref_of_parent = false;
4374                bool tmp_child_is_deref_of_parent = false;
4375                return GetChildClangTypeAtIndex (exe_ctx,
4376                                                 ast,
4377                                                 parent_name,
4378                                                 pointee_clang_type,
4379                                                 idx,
4380                                                 transparent_pointers,
4381                                                 omit_empty_base_classes,
4382                                                 ignore_array_bounds,
4383                                                 child_name,
4384                                                 child_byte_size,
4385                                                 child_byte_offset,
4386                                                 child_bitfield_bit_size,
4387                                                 child_bitfield_bit_offset,
4388                                                 child_is_base_class,
4389                                                 tmp_child_is_deref_of_parent);
4390            }
4391            else
4392            {
4393                if (parent_name)
4394                {
4395                    child_name.assign(1, '&');
4396                    child_name += parent_name;
4397                }
4398
4399                // We have a pointer to an simple type
4400                if (idx == 0)
4401                {
4402                    std::pair<uint64_t, unsigned> clang_type_info = ast->getTypeInfo(pointee_type);
4403                    assert(clang_type_info.first % 8 == 0);
4404                    child_byte_size = clang_type_info.first / 8;
4405                    child_byte_offset = 0;
4406                    return pointee_type.getAsOpaquePtr();
4407                }
4408            }
4409        }
4410        break;
4411
4412    case clang::Type::Typedef:
4413        return GetChildClangTypeAtIndex (exe_ctx,
4414                                         ast,
4415                                         parent_name,
4416                                         cast<TypedefType>(parent_qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(),
4417                                         idx,
4418                                         transparent_pointers,
4419                                         omit_empty_base_classes,
4420                                         ignore_array_bounds,
4421                                         child_name,
4422                                         child_byte_size,
4423                                         child_byte_offset,
4424                                         child_bitfield_bit_size,
4425                                         child_bitfield_bit_offset,
4426                                         child_is_base_class,
4427                                         child_is_deref_of_parent);
4428        break;
4429
4430    case clang::Type::Elaborated:
4431        return GetChildClangTypeAtIndex (exe_ctx,
4432                                         ast,
4433                                         parent_name,
4434                                         cast<ElaboratedType>(parent_qual_type)->getNamedType().getAsOpaquePtr(),
4435                                         idx,
4436                                         transparent_pointers,
4437                                         omit_empty_base_classes,
4438                                         ignore_array_bounds,
4439                                         child_name,
4440                                         child_byte_size,
4441                                         child_byte_offset,
4442                                         child_bitfield_bit_size,
4443                                         child_bitfield_bit_offset,
4444                                         child_is_base_class,
4445                                         child_is_deref_of_parent);
4446
4447    default:
4448        break;
4449    }
4450    return NULL;
4451}
4452
4453static inline bool
4454BaseSpecifierIsEmpty (const CXXBaseSpecifier *b)
4455{
4456    return ClangASTContext::RecordHasFields(b->getType()->getAsCXXRecordDecl()) == false;
4457}
4458
4459static uint32_t
4460GetNumBaseClasses (const CXXRecordDecl *cxx_record_decl, bool omit_empty_base_classes)
4461{
4462    uint32_t num_bases = 0;
4463    if (cxx_record_decl)
4464    {
4465        if (omit_empty_base_classes)
4466        {
4467            CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
4468            for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
4469                 base_class != base_class_end;
4470                 ++base_class)
4471            {
4472                // Skip empty base classes
4473                if (omit_empty_base_classes)
4474                {
4475                    if (BaseSpecifierIsEmpty (base_class))
4476                        continue;
4477                }
4478                ++num_bases;
4479            }
4480        }
4481        else
4482            num_bases = cxx_record_decl->getNumBases();
4483    }
4484    return num_bases;
4485}
4486
4487
4488static uint32_t
4489GetIndexForRecordBase
4490(
4491    const RecordDecl *record_decl,
4492    const CXXBaseSpecifier *base_spec,
4493    bool omit_empty_base_classes
4494)
4495{
4496    uint32_t child_idx = 0;
4497
4498    const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
4499
4500//    const char *super_name = record_decl->getNameAsCString();
4501//    const char *base_name = base_spec->getType()->getAs<RecordType>()->getDecl()->getNameAsCString();
4502//    printf ("GetIndexForRecordChild (%s, %s)\n", super_name, base_name);
4503//
4504    if (cxx_record_decl)
4505    {
4506        CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
4507        for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
4508             base_class != base_class_end;
4509             ++base_class)
4510        {
4511            if (omit_empty_base_classes)
4512            {
4513                if (BaseSpecifierIsEmpty (base_class))
4514                    continue;
4515            }
4516
4517//            printf ("GetIndexForRecordChild (%s, %s) base[%u] = %s\n", super_name, base_name,
4518//                    child_idx,
4519//                    base_class->getType()->getAs<RecordType>()->getDecl()->getNameAsCString());
4520//
4521//
4522            if (base_class == base_spec)
4523                return child_idx;
4524            ++child_idx;
4525        }
4526    }
4527
4528    return UINT32_MAX;
4529}
4530
4531
4532static uint32_t
4533GetIndexForRecordChild
4534(
4535    const RecordDecl *record_decl,
4536    NamedDecl *canonical_decl,
4537    bool omit_empty_base_classes
4538)
4539{
4540    uint32_t child_idx = GetNumBaseClasses (dyn_cast<CXXRecordDecl>(record_decl), omit_empty_base_classes);
4541
4542//    const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
4543//
4544////    printf ("GetIndexForRecordChild (%s, %s)\n", record_decl->getNameAsCString(), canonical_decl->getNameAsCString());
4545//    if (cxx_record_decl)
4546//    {
4547//        CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
4548//        for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
4549//             base_class != base_class_end;
4550//             ++base_class)
4551//        {
4552//            if (omit_empty_base_classes)
4553//            {
4554//                if (BaseSpecifierIsEmpty (base_class))
4555//                    continue;
4556//            }
4557//
4558////            printf ("GetIndexForRecordChild (%s, %s) base[%u] = %s\n",
4559////                    record_decl->getNameAsCString(),
4560////                    canonical_decl->getNameAsCString(),
4561////                    child_idx,
4562////                    base_class->getType()->getAs<RecordType>()->getDecl()->getNameAsCString());
4563//
4564//
4565//            CXXRecordDecl *curr_base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
4566//            if (curr_base_class_decl == canonical_decl)
4567//            {
4568//                return child_idx;
4569//            }
4570//            ++child_idx;
4571//        }
4572//    }
4573//
4574//    const uint32_t num_bases = child_idx;
4575    RecordDecl::field_iterator field, field_end;
4576    for (field = record_decl->field_begin(), field_end = record_decl->field_end();
4577         field != field_end;
4578         ++field, ++child_idx)
4579    {
4580//            printf ("GetIndexForRecordChild (%s, %s) field[%u] = %s\n",
4581//                    record_decl->getNameAsCString(),
4582//                    canonical_decl->getNameAsCString(),
4583//                    child_idx - num_bases,
4584//                    field->getNameAsCString());
4585
4586        if (field->getCanonicalDecl() == canonical_decl)
4587            return child_idx;
4588    }
4589
4590    return UINT32_MAX;
4591}
4592
4593// Look for a child member (doesn't include base classes, but it does include
4594// their members) in the type hierarchy. Returns an index path into "clang_type"
4595// on how to reach the appropriate member.
4596//
4597//    class A
4598//    {
4599//    public:
4600//        int m_a;
4601//        int m_b;
4602//    };
4603//
4604//    class B
4605//    {
4606//    };
4607//
4608//    class C :
4609//        public B,
4610//        public A
4611//    {
4612//    };
4613//
4614// If we have a clang type that describes "class C", and we wanted to looked
4615// "m_b" in it:
4616//
4617// With omit_empty_base_classes == false we would get an integer array back with:
4618// { 1,  1 }
4619// The first index 1 is the child index for "class A" within class C
4620// The second index 1 is the child index for "m_b" within class A
4621//
4622// With omit_empty_base_classes == true we would get an integer array back with:
4623// { 0,  1 }
4624// 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)
4625// The second index 1 is the child index for "m_b" within class A
4626
4627size_t
4628ClangASTContext::GetIndexOfChildMemberWithName
4629(
4630    ASTContext *ast,
4631    clang_type_t clang_type,
4632    const char *name,
4633    bool omit_empty_base_classes,
4634    std::vector<uint32_t>& child_indexes
4635)
4636{
4637    if (clang_type && name && name[0])
4638    {
4639        QualType qual_type(QualType::getFromOpaquePtr(clang_type));
4640        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
4641        switch (type_class)
4642        {
4643        case clang::Type::Record:
4644            if (GetCompleteQualType (ast, qual_type))
4645            {
4646                const RecordType *record_type = cast<RecordType>(qual_type.getTypePtr());
4647                const RecordDecl *record_decl = record_type->getDecl();
4648
4649                assert(record_decl);
4650                uint32_t child_idx = 0;
4651
4652                const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
4653
4654                // Try and find a field that matches NAME
4655                RecordDecl::field_iterator field, field_end;
4656                StringRef name_sref(name);
4657                for (field = record_decl->field_begin(), field_end = record_decl->field_end();
4658                     field != field_end;
4659                     ++field, ++child_idx)
4660                {
4661                    if (field->getName().equals (name_sref))
4662                    {
4663                        // We have to add on the number of base classes to this index!
4664                        child_indexes.push_back (child_idx + GetNumBaseClasses (cxx_record_decl, omit_empty_base_classes));
4665                        return child_indexes.size();
4666                    }
4667                }
4668
4669                if (cxx_record_decl)
4670                {
4671                    const RecordDecl *parent_record_decl = cxx_record_decl;
4672
4673                    //printf ("parent = %s\n", parent_record_decl->getNameAsCString());
4674
4675                    //const Decl *root_cdecl = cxx_record_decl->getCanonicalDecl();
4676                    // Didn't find things easily, lets let clang do its thang...
4677                    IdentifierInfo & ident_ref = ast->Idents.get(name_sref);
4678                    DeclarationName decl_name(&ident_ref);
4679
4680                    CXXBasePaths paths;
4681                    if (cxx_record_decl->lookupInBases(CXXRecordDecl::FindOrdinaryMember,
4682                                                       decl_name.getAsOpaquePtr(),
4683                                                       paths))
4684                    {
4685                        CXXBasePaths::const_paths_iterator path, path_end = paths.end();
4686                        for (path = paths.begin(); path != path_end; ++path)
4687                        {
4688                            const size_t num_path_elements = path->size();
4689                            for (size_t e=0; e<num_path_elements; ++e)
4690                            {
4691                                CXXBasePathElement elem = (*path)[e];
4692
4693                                child_idx = GetIndexForRecordBase (parent_record_decl, elem.Base, omit_empty_base_classes);
4694                                if (child_idx == UINT32_MAX)
4695                                {
4696                                    child_indexes.clear();
4697                                    return 0;
4698                                }
4699                                else
4700                                {
4701                                    child_indexes.push_back (child_idx);
4702                                    parent_record_decl = cast<RecordDecl>(elem.Base->getType()->getAs<RecordType>()->getDecl());
4703                                }
4704                            }
4705                            for (NamedDecl *path_decl : path->Decls)
4706                            {
4707                                child_idx = GetIndexForRecordChild (parent_record_decl, path_decl, omit_empty_base_classes);
4708                                if (child_idx == UINT32_MAX)
4709                                {
4710                                    child_indexes.clear();
4711                                    return 0;
4712                                }
4713                                else
4714                                {
4715                                    child_indexes.push_back (child_idx);
4716                                }
4717                            }
4718                        }
4719                        return child_indexes.size();
4720                    }
4721                }
4722
4723            }
4724            break;
4725
4726        case clang::Type::ObjCObject:
4727        case clang::Type::ObjCInterface:
4728            if (GetCompleteQualType (ast, qual_type))
4729            {
4730                StringRef name_sref(name);
4731                const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(qual_type.getTypePtr());
4732                assert (objc_class_type);
4733                if (objc_class_type)
4734                {
4735                    uint32_t child_idx = 0;
4736                    ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
4737
4738                    if (class_interface_decl)
4739                    {
4740                        ObjCInterfaceDecl::ivar_iterator ivar_pos, ivar_end = class_interface_decl->ivar_end();
4741                        ObjCInterfaceDecl *superclass_interface_decl = class_interface_decl->getSuperClass();
4742
4743                        for (ivar_pos = class_interface_decl->ivar_begin(); ivar_pos != ivar_end; ++ivar_pos, ++child_idx)
4744                        {
4745                            const ObjCIvarDecl* ivar_decl = *ivar_pos;
4746
4747                            if (ivar_decl->getName().equals (name_sref))
4748                            {
4749                                if ((!omit_empty_base_classes && superclass_interface_decl) ||
4750                                    ( omit_empty_base_classes && ObjCDeclHasIVars (superclass_interface_decl, true)))
4751                                    ++child_idx;
4752
4753                                child_indexes.push_back (child_idx);
4754                                return child_indexes.size();
4755                            }
4756                        }
4757
4758                        if (superclass_interface_decl)
4759                        {
4760                            // The super class index is always zero for ObjC classes,
4761                            // so we push it onto the child indexes in case we find
4762                            // an ivar in our superclass...
4763                            child_indexes.push_back (0);
4764
4765                            if (GetIndexOfChildMemberWithName (ast,
4766                                                               ast->getObjCInterfaceType(superclass_interface_decl).getAsOpaquePtr(),
4767                                                               name,
4768                                                               omit_empty_base_classes,
4769                                                               child_indexes))
4770                            {
4771                                // We did find an ivar in a superclass so just
4772                                // return the results!
4773                                return child_indexes.size();
4774                            }
4775
4776                            // We didn't find an ivar matching "name" in our
4777                            // superclass, pop the superclass zero index that
4778                            // we pushed on above.
4779                            child_indexes.pop_back();
4780                        }
4781                    }
4782                }
4783            }
4784            break;
4785
4786        case clang::Type::ObjCObjectPointer:
4787            {
4788                return GetIndexOfChildMemberWithName (ast,
4789                                                      cast<ObjCObjectPointerType>(qual_type.getTypePtr())->getPointeeType().getAsOpaquePtr(),
4790                                                      name,
4791                                                      omit_empty_base_classes,
4792                                                      child_indexes);
4793            }
4794            break;
4795
4796
4797        case clang::Type::ConstantArray:
4798            {
4799//                const ConstantArrayType *array = cast<ConstantArrayType>(parent_qual_type.getTypePtr());
4800//                const uint64_t element_count = array->getSize().getLimitedValue();
4801//
4802//                if (idx < element_count)
4803//                {
4804//                    std::pair<uint64_t, unsigned> field_type_info = ast->getTypeInfo(array->getElementType());
4805//
4806//                    char element_name[32];
4807//                    ::snprintf (element_name, sizeof (element_name), "%s[%u]", parent_name ? parent_name : "", idx);
4808//
4809//                    child_name.assign(element_name);
4810//                    assert(field_type_info.first % 8 == 0);
4811//                    child_byte_size = field_type_info.first / 8;
4812//                    child_byte_offset = idx * child_byte_size;
4813//                    return array->getElementType().getAsOpaquePtr();
4814//                }
4815            }
4816            break;
4817
4818//        case clang::Type::MemberPointerType:
4819//            {
4820//                MemberPointerType *mem_ptr_type = cast<MemberPointerType>(qual_type.getTypePtr());
4821//                QualType pointee_type = mem_ptr_type->getPointeeType();
4822//
4823//                if (ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
4824//                {
4825//                    return GetIndexOfChildWithName (ast,
4826//                                                    mem_ptr_type->getPointeeType().getAsOpaquePtr(),
4827//                                                    name);
4828//                }
4829//            }
4830//            break;
4831//
4832        case clang::Type::LValueReference:
4833        case clang::Type::RValueReference:
4834            {
4835                const ReferenceType *reference_type = cast<ReferenceType>(qual_type.getTypePtr());
4836                QualType pointee_type = reference_type->getPointeeType();
4837
4838                if (ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
4839                {
4840                    return GetIndexOfChildMemberWithName (ast,
4841                                                          reference_type->getPointeeType().getAsOpaquePtr(),
4842                                                          name,
4843                                                          omit_empty_base_classes,
4844                                                          child_indexes);
4845                }
4846            }
4847            break;
4848
4849        case clang::Type::Pointer:
4850            {
4851                const PointerType *pointer_type = cast<PointerType>(qual_type.getTypePtr());
4852                QualType pointee_type = pointer_type->getPointeeType();
4853
4854                if (ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
4855                {
4856                    return GetIndexOfChildMemberWithName (ast,
4857                                                          pointer_type->getPointeeType().getAsOpaquePtr(),
4858                                                          name,
4859                                                          omit_empty_base_classes,
4860                                                          child_indexes);
4861                }
4862                else
4863                {
4864//                    if (parent_name)
4865//                    {
4866//                        child_name.assign(1, '*');
4867//                        child_name += parent_name;
4868//                    }
4869//
4870//                    // We have a pointer to an simple type
4871//                    if (idx == 0)
4872//                    {
4873//                        std::pair<uint64_t, unsigned> clang_type_info = ast->getTypeInfo(pointee_type);
4874//                        assert(clang_type_info.first % 8 == 0);
4875//                        child_byte_size = clang_type_info.first / 8;
4876//                        child_byte_offset = 0;
4877//                        return pointee_type.getAsOpaquePtr();
4878//                    }
4879                }
4880            }
4881            break;
4882
4883        case clang::Type::Typedef:
4884            return GetIndexOfChildMemberWithName (ast,
4885                                                  cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(),
4886                                                  name,
4887                                                  omit_empty_base_classes,
4888                                                  child_indexes);
4889
4890        case clang::Type::Elaborated:
4891            return GetIndexOfChildMemberWithName (ast,
4892                                                  cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(),
4893                                                  name,
4894                                                  omit_empty_base_classes,
4895                                                  child_indexes);
4896
4897        default:
4898            break;
4899        }
4900    }
4901    return 0;
4902}
4903
4904
4905// Get the index of the child of "clang_type" whose name matches. This function
4906// doesn't descend into the children, but only looks one level deep and name
4907// matches can include base class names.
4908
4909uint32_t
4910ClangASTContext::GetIndexOfChildWithName
4911(
4912    ASTContext *ast,
4913    clang_type_t clang_type,
4914    const char *name,
4915    bool omit_empty_base_classes
4916)
4917{
4918    if (clang_type && name && name[0])
4919    {
4920        QualType qual_type(QualType::getFromOpaquePtr(clang_type));
4921
4922        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
4923
4924        switch (type_class)
4925        {
4926        case clang::Type::Record:
4927            if (GetCompleteQualType (ast, qual_type))
4928            {
4929                const RecordType *record_type = cast<RecordType>(qual_type.getTypePtr());
4930                const RecordDecl *record_decl = record_type->getDecl();
4931
4932                assert(record_decl);
4933                uint32_t child_idx = 0;
4934
4935                const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
4936
4937                if (cxx_record_decl)
4938                {
4939                    CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
4940                    for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
4941                         base_class != base_class_end;
4942                         ++base_class)
4943                    {
4944                        // Skip empty base classes
4945                        CXXRecordDecl *base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
4946                        if (omit_empty_base_classes && RecordHasFields(base_class_decl) == false)
4947                            continue;
4948
4949                        std::string base_class_type_name (ClangASTType::GetTypeNameForQualType(ast, base_class->getType()));
4950                        if (base_class_type_name.compare (name) == 0)
4951                            return child_idx;
4952                        ++child_idx;
4953                    }
4954                }
4955
4956                // Try and find a field that matches NAME
4957                RecordDecl::field_iterator field, field_end;
4958                StringRef name_sref(name);
4959                for (field = record_decl->field_begin(), field_end = record_decl->field_end();
4960                     field != field_end;
4961                     ++field, ++child_idx)
4962                {
4963                    if (field->getName().equals (name_sref))
4964                        return child_idx;
4965                }
4966
4967            }
4968            break;
4969
4970        case clang::Type::ObjCObject:
4971        case clang::Type::ObjCInterface:
4972            if (GetCompleteQualType (ast, qual_type))
4973            {
4974                StringRef name_sref(name);
4975                const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(qual_type.getTypePtr());
4976                assert (objc_class_type);
4977                if (objc_class_type)
4978                {
4979                    uint32_t child_idx = 0;
4980                    ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
4981
4982                    if (class_interface_decl)
4983                    {
4984                        ObjCInterfaceDecl::ivar_iterator ivar_pos, ivar_end = class_interface_decl->ivar_end();
4985                        ObjCInterfaceDecl *superclass_interface_decl = class_interface_decl->getSuperClass();
4986
4987                        for (ivar_pos = class_interface_decl->ivar_begin(); ivar_pos != ivar_end; ++ivar_pos, ++child_idx)
4988                        {
4989                            const ObjCIvarDecl* ivar_decl = *ivar_pos;
4990
4991                            if (ivar_decl->getName().equals (name_sref))
4992                            {
4993                                if ((!omit_empty_base_classes && superclass_interface_decl) ||
4994                                    ( omit_empty_base_classes && ObjCDeclHasIVars (superclass_interface_decl, true)))
4995                                    ++child_idx;
4996
4997                                return child_idx;
4998                            }
4999                        }
5000
5001                        if (superclass_interface_decl)
5002                        {
5003                            if (superclass_interface_decl->getName().equals (name_sref))
5004                                return 0;
5005                        }
5006                    }
5007                }
5008            }
5009            break;
5010
5011        case clang::Type::ObjCObjectPointer:
5012            {
5013                return GetIndexOfChildWithName (ast,
5014                                                cast<ObjCObjectPointerType>(qual_type.getTypePtr())->getPointeeType().getAsOpaquePtr(),
5015                                                name,
5016                                                omit_empty_base_classes);
5017            }
5018            break;
5019
5020        case clang::Type::ConstantArray:
5021            {
5022//                const ConstantArrayType *array = cast<ConstantArrayType>(parent_qual_type.getTypePtr());
5023//                const uint64_t element_count = array->getSize().getLimitedValue();
5024//
5025//                if (idx < element_count)
5026//                {
5027//                    std::pair<uint64_t, unsigned> field_type_info = ast->getTypeInfo(array->getElementType());
5028//
5029//                    char element_name[32];
5030//                    ::snprintf (element_name, sizeof (element_name), "%s[%u]", parent_name ? parent_name : "", idx);
5031//
5032//                    child_name.assign(element_name);
5033//                    assert(field_type_info.first % 8 == 0);
5034//                    child_byte_size = field_type_info.first / 8;
5035//                    child_byte_offset = idx * child_byte_size;
5036//                    return array->getElementType().getAsOpaquePtr();
5037//                }
5038            }
5039            break;
5040
5041//        case clang::Type::MemberPointerType:
5042//            {
5043//                MemberPointerType *mem_ptr_type = cast<MemberPointerType>(qual_type.getTypePtr());
5044//                QualType pointee_type = mem_ptr_type->getPointeeType();
5045//
5046//                if (ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
5047//                {
5048//                    return GetIndexOfChildWithName (ast,
5049//                                                    mem_ptr_type->getPointeeType().getAsOpaquePtr(),
5050//                                                    name);
5051//                }
5052//            }
5053//            break;
5054//
5055        case clang::Type::LValueReference:
5056        case clang::Type::RValueReference:
5057            {
5058                const ReferenceType *reference_type = cast<ReferenceType>(qual_type.getTypePtr());
5059                QualType pointee_type = reference_type->getPointeeType();
5060
5061                if (ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
5062                {
5063                    return GetIndexOfChildWithName (ast,
5064                                                    reference_type->getPointeeType().getAsOpaquePtr(),
5065                                                    name,
5066                                                    omit_empty_base_classes);
5067                }
5068            }
5069            break;
5070
5071        case clang::Type::Pointer:
5072            {
5073                const PointerType *pointer_type = cast<PointerType>(qual_type.getTypePtr());
5074                QualType pointee_type = pointer_type->getPointeeType();
5075
5076                if (ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
5077                {
5078                    return GetIndexOfChildWithName (ast,
5079                                                    pointer_type->getPointeeType().getAsOpaquePtr(),
5080                                                    name,
5081                                                    omit_empty_base_classes);
5082                }
5083                else
5084                {
5085//                    if (parent_name)
5086//                    {
5087//                        child_name.assign(1, '*');
5088//                        child_name += parent_name;
5089//                    }
5090//
5091//                    // We have a pointer to an simple type
5092//                    if (idx == 0)
5093//                    {
5094//                        std::pair<uint64_t, unsigned> clang_type_info = ast->getTypeInfo(pointee_type);
5095//                        assert(clang_type_info.first % 8 == 0);
5096//                        child_byte_size = clang_type_info.first / 8;
5097//                        child_byte_offset = 0;
5098//                        return pointee_type.getAsOpaquePtr();
5099//                    }
5100                }
5101            }
5102            break;
5103
5104        case clang::Type::Elaborated:
5105            return GetIndexOfChildWithName (ast,
5106                                            cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(),
5107                                            name,
5108                                            omit_empty_base_classes);
5109
5110        case clang::Type::Typedef:
5111            return GetIndexOfChildWithName (ast,
5112                                            cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(),
5113                                            name,
5114                                            omit_empty_base_classes);
5115
5116        default:
5117            break;
5118        }
5119    }
5120    return UINT32_MAX;
5121}
5122
5123#pragma mark TagType
5124
5125bool
5126ClangASTContext::SetTagTypeKind (clang_type_t tag_clang_type, int kind)
5127{
5128    if (tag_clang_type)
5129    {
5130        QualType tag_qual_type(QualType::getFromOpaquePtr(tag_clang_type));
5131        const clang::Type *clang_type = tag_qual_type.getTypePtr();
5132        if (clang_type)
5133        {
5134            const TagType *tag_type = dyn_cast<TagType>(clang_type);
5135            if (tag_type)
5136            {
5137                TagDecl *tag_decl = dyn_cast<TagDecl>(tag_type->getDecl());
5138                if (tag_decl)
5139                {
5140                    tag_decl->setTagKind ((TagDecl::TagKind)kind);
5141                    return true;
5142                }
5143            }
5144        }
5145    }
5146    return false;
5147}
5148
5149
5150#pragma mark DeclContext Functions
5151
5152DeclContext *
5153ClangASTContext::GetDeclContextForType (clang_type_t clang_type)
5154{
5155    if (clang_type == NULL)
5156        return NULL;
5157
5158    QualType qual_type(QualType::getFromOpaquePtr(clang_type));
5159    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5160    switch (type_class)
5161    {
5162    case clang::Type::UnaryTransform:           break;
5163    case clang::Type::FunctionNoProto:          break;
5164    case clang::Type::FunctionProto:            break;
5165    case clang::Type::IncompleteArray:          break;
5166    case clang::Type::VariableArray:            break;
5167    case clang::Type::ConstantArray:            break;
5168    case clang::Type::DependentSizedArray:      break;
5169    case clang::Type::ExtVector:                break;
5170    case clang::Type::DependentSizedExtVector:  break;
5171    case clang::Type::Vector:                   break;
5172    case clang::Type::Builtin:                  break;
5173    case clang::Type::BlockPointer:             break;
5174    case clang::Type::Pointer:                  break;
5175    case clang::Type::LValueReference:          break;
5176    case clang::Type::RValueReference:          break;
5177    case clang::Type::MemberPointer:            break;
5178    case clang::Type::Complex:                  break;
5179    case clang::Type::ObjCObject:               break;
5180    case clang::Type::ObjCInterface:            return cast<ObjCObjectType>(qual_type.getTypePtr())->getInterface();
5181    case clang::Type::ObjCObjectPointer:        return ClangASTContext::GetDeclContextForType (cast<ObjCObjectPointerType>(qual_type.getTypePtr())->getPointeeType().getAsOpaquePtr());
5182    case clang::Type::Record:                   return cast<RecordType>(qual_type)->getDecl();
5183    case clang::Type::Enum:                     return cast<EnumType>(qual_type)->getDecl();
5184    case clang::Type::Typedef:                  return ClangASTContext::GetDeclContextForType (cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
5185    case clang::Type::Elaborated:               return ClangASTContext::GetDeclContextForType (cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
5186    case clang::Type::TypeOfExpr:               break;
5187    case clang::Type::TypeOf:                   break;
5188    case clang::Type::Decltype:                 break;
5189    //case clang::Type::QualifiedName:          break;
5190    case clang::Type::TemplateSpecialization:   break;
5191    case clang::Type::DependentTemplateSpecialization:  break;
5192    case clang::Type::TemplateTypeParm:         break;
5193    case clang::Type::SubstTemplateTypeParm:    break;
5194    case clang::Type::SubstTemplateTypeParmPack:break;
5195    case clang::Type::PackExpansion:            break;
5196    case clang::Type::UnresolvedUsing:          break;
5197    case clang::Type::Paren:                    break;
5198    case clang::Type::Attributed:               break;
5199    case clang::Type::Auto:                     break;
5200    case clang::Type::InjectedClassName:        break;
5201    case clang::Type::DependentName:            break;
5202    case clang::Type::Atomic:                   break;
5203    }
5204    // No DeclContext in this type...
5205    return NULL;
5206}
5207
5208#pragma mark Namespace Declarations
5209
5210NamespaceDecl *
5211ClangASTContext::GetUniqueNamespaceDeclaration (const char *name, DeclContext *decl_ctx)
5212{
5213    NamespaceDecl *namespace_decl = NULL;
5214    ASTContext *ast = getASTContext();
5215    TranslationUnitDecl *translation_unit_decl = ast->getTranslationUnitDecl ();
5216    if (decl_ctx == NULL)
5217        decl_ctx = translation_unit_decl;
5218
5219    if (name)
5220    {
5221        IdentifierInfo &identifier_info = ast->Idents.get(name);
5222        DeclarationName decl_name (&identifier_info);
5223        clang::DeclContext::lookup_result result = decl_ctx->lookup(decl_name);
5224        for (NamedDecl *decl : result)
5225        {
5226            namespace_decl = dyn_cast<clang::NamespaceDecl>(decl);
5227            if (namespace_decl)
5228                return namespace_decl;
5229        }
5230
5231        namespace_decl = NamespaceDecl::Create(*ast,
5232                                               decl_ctx,
5233                                               false,
5234                                               SourceLocation(),
5235                                               SourceLocation(),
5236                                               &identifier_info,
5237                                               NULL);
5238
5239        decl_ctx->addDecl (namespace_decl);
5240    }
5241    else
5242    {
5243        if (decl_ctx == translation_unit_decl)
5244        {
5245            namespace_decl = translation_unit_decl->getAnonymousNamespace();
5246            if (namespace_decl)
5247                return namespace_decl;
5248
5249            namespace_decl = NamespaceDecl::Create(*ast,
5250                                                   decl_ctx,
5251                                                   false,
5252                                                   SourceLocation(),
5253                                                   SourceLocation(),
5254                                                   NULL,
5255                                                   NULL);
5256            translation_unit_decl->setAnonymousNamespace (namespace_decl);
5257            translation_unit_decl->addDecl (namespace_decl);
5258            assert (namespace_decl == translation_unit_decl->getAnonymousNamespace());
5259        }
5260        else
5261        {
5262            NamespaceDecl *parent_namespace_decl = cast<NamespaceDecl>(decl_ctx);
5263            if (parent_namespace_decl)
5264            {
5265                namespace_decl = parent_namespace_decl->getAnonymousNamespace();
5266                if (namespace_decl)
5267                    return namespace_decl;
5268                namespace_decl = NamespaceDecl::Create(*ast,
5269                                                       decl_ctx,
5270                                                       false,
5271                                                       SourceLocation(),
5272                                                       SourceLocation(),
5273                                                       NULL,
5274                                                       NULL);
5275                parent_namespace_decl->setAnonymousNamespace (namespace_decl);
5276                parent_namespace_decl->addDecl (namespace_decl);
5277                assert (namespace_decl == parent_namespace_decl->getAnonymousNamespace());
5278            }
5279            else
5280            {
5281                // BAD!!!
5282            }
5283        }
5284
5285
5286        if (namespace_decl)
5287        {
5288            // If we make it here, we are creating the anonymous namespace decl
5289            // for the first time, so we need to do the using directive magic
5290            // like SEMA does
5291            UsingDirectiveDecl* using_directive_decl = UsingDirectiveDecl::Create (*ast,
5292                                                                                   decl_ctx,
5293                                                                                   SourceLocation(),
5294                                                                                   SourceLocation(),
5295                                                                                   NestedNameSpecifierLoc(),
5296                                                                                   SourceLocation(),
5297                                                                                   namespace_decl,
5298                                                                                   decl_ctx);
5299            using_directive_decl->setImplicit();
5300            decl_ctx->addDecl(using_directive_decl);
5301        }
5302    }
5303#ifdef LLDB_CONFIGURATION_DEBUG
5304    VerifyDecl(namespace_decl);
5305#endif
5306    return namespace_decl;
5307}
5308
5309
5310#pragma mark Function Types
5311
5312FunctionDecl *
5313ClangASTContext::CreateFunctionDeclaration (DeclContext *decl_ctx, const char *name, clang_type_t function_clang_type, int storage, bool is_inline)
5314{
5315    FunctionDecl *func_decl = NULL;
5316    ASTContext *ast = getASTContext();
5317    if (decl_ctx == NULL)
5318        decl_ctx = ast->getTranslationUnitDecl();
5319
5320    if (name && name[0])
5321    {
5322        func_decl = FunctionDecl::Create (*ast,
5323                                          decl_ctx,
5324                                          SourceLocation(),
5325                                          SourceLocation(),
5326                                          DeclarationName (&ast->Idents.get(name)),
5327                                          QualType::getFromOpaquePtr(function_clang_type),
5328                                          NULL,
5329                                          (FunctionDecl::StorageClass)storage,
5330                                          (FunctionDecl::StorageClass)storage,
5331                                          is_inline);
5332    }
5333    else
5334    {
5335        func_decl = FunctionDecl::Create (*ast,
5336                                          decl_ctx,
5337                                          SourceLocation(),
5338                                          SourceLocation(),
5339                                          DeclarationName (),
5340                                          QualType::getFromOpaquePtr(function_clang_type),
5341                                          NULL,
5342                                          (FunctionDecl::StorageClass)storage,
5343                                          (FunctionDecl::StorageClass)storage,
5344                                          is_inline);
5345    }
5346    if (func_decl)
5347        decl_ctx->addDecl (func_decl);
5348
5349#ifdef LLDB_CONFIGURATION_DEBUG
5350    VerifyDecl(func_decl);
5351#endif
5352
5353    return func_decl;
5354}
5355
5356clang_type_t
5357ClangASTContext::CreateFunctionType (ASTContext *ast,
5358                                     clang_type_t result_type,
5359                                     clang_type_t *args,
5360                                     unsigned num_args,
5361                                     bool is_variadic,
5362                                     unsigned type_quals)
5363{
5364    assert (ast != NULL);
5365    std::vector<QualType> qual_type_args;
5366    for (unsigned i=0; i<num_args; ++i)
5367        qual_type_args.push_back (QualType::getFromOpaquePtr(args[i]));
5368
5369    // TODO: Detect calling convention in DWARF?
5370    FunctionProtoType::ExtProtoInfo proto_info;
5371    proto_info.Variadic = is_variadic;
5372    proto_info.ExceptionSpecType = EST_None;
5373    proto_info.TypeQuals = type_quals;
5374    proto_info.RefQualifier = RQ_None;
5375    proto_info.NumExceptions = 0;
5376    proto_info.Exceptions = NULL;
5377
5378    return ast->getFunctionType (QualType::getFromOpaquePtr(result_type),
5379                                 qual_type_args,
5380                                 proto_info).getAsOpaquePtr();
5381}
5382
5383ParmVarDecl *
5384ClangASTContext::CreateParameterDeclaration (const char *name, clang_type_t param_type, int storage)
5385{
5386    ASTContext *ast = getASTContext();
5387    assert (ast != NULL);
5388    return ParmVarDecl::Create(*ast,
5389                                ast->getTranslationUnitDecl(),
5390                                SourceLocation(),
5391                                SourceLocation(),
5392                                name && name[0] ? &ast->Idents.get(name) : NULL,
5393                                QualType::getFromOpaquePtr(param_type),
5394                                NULL,
5395                                (VarDecl::StorageClass)storage,
5396                                0);
5397}
5398
5399void
5400ClangASTContext::SetFunctionParameters (FunctionDecl *function_decl, ParmVarDecl **params, unsigned num_params)
5401{
5402    if (function_decl)
5403        function_decl->setParams (ArrayRef<ParmVarDecl*>(params, num_params));
5404}
5405
5406
5407#pragma mark Array Types
5408
5409clang_type_t
5410ClangASTContext::CreateArrayType (clang_type_t element_type,
5411                                  size_t element_count,
5412                                  bool is_vector)
5413{
5414    if (element_type)
5415    {
5416        ASTContext *ast = getASTContext();
5417        assert (ast != NULL);
5418
5419        QualType element_qual_type(QualType::getFromOpaquePtr(element_type));
5420
5421        if (is_vector)
5422        {
5423            return ast->getExtVectorType(element_qual_type, element_count).getAsOpaquePtr();
5424        }
5425        else
5426        {
5427
5428            llvm::APInt ap_element_count (64, element_count);
5429            if (element_count == 0)
5430            {
5431                return ast->getIncompleteArrayType(element_qual_type,
5432                                                   ArrayType::Normal,
5433                                                   0).getAsOpaquePtr();
5434
5435            }
5436            else
5437            {
5438                return ast->getConstantArrayType(element_qual_type,
5439                                                 ap_element_count,
5440                                                 ArrayType::Normal,
5441                                                 0).getAsOpaquePtr(); // ElemQuals
5442            }
5443        }
5444    }
5445    return NULL;
5446}
5447
5448
5449#pragma mark TagDecl
5450
5451bool
5452ClangASTContext::StartTagDeclarationDefinition (clang_type_t clang_type)
5453{
5454    if (clang_type)
5455    {
5456        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
5457        const clang::Type *t = qual_type.getTypePtr();
5458        if (t)
5459        {
5460            const TagType *tag_type = dyn_cast<TagType>(t);
5461            if (tag_type)
5462            {
5463                TagDecl *tag_decl = tag_type->getDecl();
5464                if (tag_decl)
5465                {
5466                    tag_decl->startDefinition();
5467                    return true;
5468                }
5469            }
5470
5471            const ObjCObjectType *object_type = dyn_cast<ObjCObjectType>(t);
5472            if (object_type)
5473            {
5474                ObjCInterfaceDecl *interface_decl = object_type->getInterface();
5475                if (interface_decl)
5476                {
5477                    interface_decl->startDefinition();
5478                    return true;
5479                }
5480            }
5481        }
5482    }
5483    return false;
5484}
5485
5486bool
5487ClangASTContext::CompleteTagDeclarationDefinition (clang_type_t clang_type)
5488{
5489    if (clang_type)
5490    {
5491        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
5492
5493        CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
5494
5495        if (cxx_record_decl)
5496        {
5497            cxx_record_decl->completeDefinition();
5498
5499            return true;
5500        }
5501
5502        const EnumType *enum_type = dyn_cast<EnumType>(qual_type.getTypePtr());
5503
5504        if (enum_type)
5505        {
5506            EnumDecl *enum_decl = enum_type->getDecl();
5507
5508            if (enum_decl)
5509            {
5510                /// TODO This really needs to be fixed.
5511
5512                unsigned NumPositiveBits = 1;
5513                unsigned NumNegativeBits = 0;
5514
5515                ASTContext *ast = getASTContext();
5516
5517                QualType promotion_qual_type;
5518                // If the enum integer type is less than an integer in bit width,
5519                // then we must promote it to an integer size.
5520                if (ast->getTypeSize(enum_decl->getIntegerType()) < ast->getTypeSize(ast->IntTy))
5521                {
5522                    if (enum_decl->getIntegerType()->isSignedIntegerType())
5523                        promotion_qual_type = ast->IntTy;
5524                    else
5525                        promotion_qual_type = ast->UnsignedIntTy;
5526                }
5527                else
5528                    promotion_qual_type = enum_decl->getIntegerType();
5529
5530                enum_decl->completeDefinition(enum_decl->getIntegerType(), promotion_qual_type, NumPositiveBits, NumNegativeBits);
5531                return true;
5532            }
5533        }
5534    }
5535    return false;
5536}
5537
5538
5539#pragma mark Enumeration Types
5540
5541clang_type_t
5542ClangASTContext::CreateEnumerationType
5543(
5544    const char *name,
5545    DeclContext *decl_ctx,
5546    const Declaration &decl,
5547    clang_type_t integer_qual_type
5548)
5549{
5550    // TODO: Do something intelligent with the Declaration object passed in
5551    // like maybe filling in the SourceLocation with it...
5552    ASTContext *ast = getASTContext();
5553    assert (ast != NULL);
5554
5555    // TODO: ask about these...
5556//    const bool IsScoped = false;
5557//    const bool IsFixed = false;
5558
5559    EnumDecl *enum_decl = EnumDecl::Create (*ast,
5560                                            decl_ctx,
5561                                            SourceLocation(),
5562                                            SourceLocation(),
5563                                            name && name[0] ? &ast->Idents.get(name) : NULL,
5564                                            NULL,
5565                                            false,  // IsScoped
5566                                            false,  // IsScopedUsingClassTag
5567                                            false); // IsFixed
5568
5569
5570    if (enum_decl)
5571    {
5572        // TODO: check if we should be setting the promotion type too?
5573        enum_decl->setIntegerType(QualType::getFromOpaquePtr (integer_qual_type));
5574
5575        enum_decl->setAccess(AS_public); // TODO respect what's in the debug info
5576
5577        return ast->getTagDeclType(enum_decl).getAsOpaquePtr();
5578    }
5579    return NULL;
5580}
5581
5582clang_type_t
5583ClangASTContext::GetEnumerationIntegerType (clang_type_t enum_clang_type)
5584{
5585    QualType enum_qual_type (QualType::getFromOpaquePtr(enum_clang_type));
5586
5587    const clang::Type *clang_type = enum_qual_type.getTypePtr();
5588    if (clang_type)
5589    {
5590        const EnumType *enum_type = dyn_cast<EnumType>(clang_type);
5591        if (enum_type)
5592        {
5593            EnumDecl *enum_decl = enum_type->getDecl();
5594            if (enum_decl)
5595                return enum_decl->getIntegerType().getAsOpaquePtr();
5596        }
5597    }
5598    return NULL;
5599}
5600bool
5601ClangASTContext::AddEnumerationValueToEnumerationType
5602(
5603    clang_type_t enum_clang_type,
5604    clang_type_t enumerator_clang_type,
5605    const Declaration &decl,
5606    const char *name,
5607    int64_t enum_value,
5608    uint32_t enum_value_bit_size
5609)
5610{
5611    if (enum_clang_type && enumerator_clang_type && name)
5612    {
5613        // TODO: Do something intelligent with the Declaration object passed in
5614        // like maybe filling in the SourceLocation with it...
5615        ASTContext *ast = getASTContext();
5616        IdentifierTable *identifier_table = getIdentifierTable();
5617
5618        assert (ast != NULL);
5619        assert (identifier_table != NULL);
5620        QualType enum_qual_type (QualType::getFromOpaquePtr(enum_clang_type));
5621
5622        bool is_signed = false;
5623        IsIntegerType (enumerator_clang_type, is_signed);
5624        const clang::Type *clang_type = enum_qual_type.getTypePtr();
5625        if (clang_type)
5626        {
5627            const EnumType *enum_type = dyn_cast<EnumType>(clang_type);
5628
5629            if (enum_type)
5630            {
5631                llvm::APSInt enum_llvm_apsint(enum_value_bit_size, is_signed);
5632                enum_llvm_apsint = enum_value;
5633                EnumConstantDecl *enumerator_decl =
5634                    EnumConstantDecl::Create (*ast,
5635                                              enum_type->getDecl(),
5636                                              SourceLocation(),
5637                                              name ? &identifier_table->get(name) : NULL,    // Identifier
5638                                              QualType::getFromOpaquePtr(enumerator_clang_type),
5639                                              NULL,
5640                                              enum_llvm_apsint);
5641
5642                if (enumerator_decl)
5643                {
5644                    enum_type->getDecl()->addDecl(enumerator_decl);
5645
5646#ifdef LLDB_CONFIGURATION_DEBUG
5647                    VerifyDecl(enumerator_decl);
5648#endif
5649
5650                    return true;
5651                }
5652            }
5653        }
5654    }
5655    return false;
5656}
5657
5658#pragma mark Pointers & References
5659
5660clang_type_t
5661ClangASTContext::CreatePointerType (clang_type_t clang_type)
5662{
5663    return CreatePointerType (getASTContext(), clang_type);
5664}
5665
5666clang_type_t
5667ClangASTContext::CreatePointerType (clang::ASTContext *ast, clang_type_t clang_type)
5668{
5669    if (ast && clang_type)
5670    {
5671        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
5672
5673        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5674        switch (type_class)
5675        {
5676        case clang::Type::ObjCObject:
5677        case clang::Type::ObjCInterface:
5678            return ast->getObjCObjectPointerType(qual_type).getAsOpaquePtr();
5679
5680        default:
5681            return ast->getPointerType(qual_type).getAsOpaquePtr();
5682        }
5683    }
5684    return NULL;
5685}
5686
5687clang_type_t
5688ClangASTContext::CreateLValueReferenceType (clang::ASTContext *ast,
5689                                            clang_type_t clang_type)
5690{
5691    if (clang_type)
5692        return ast->getLValueReferenceType (QualType::getFromOpaquePtr(clang_type)).getAsOpaquePtr();
5693    return NULL;
5694}
5695
5696clang_type_t
5697ClangASTContext::CreateRValueReferenceType (clang::ASTContext *ast,
5698                                            clang_type_t clang_type)
5699{
5700    if (clang_type)
5701        return ast->getRValueReferenceType (QualType::getFromOpaquePtr(clang_type)).getAsOpaquePtr();
5702    return NULL;
5703}
5704
5705clang_type_t
5706ClangASTContext::CreateMemberPointerType (clang_type_t clang_pointee_type, clang_type_t clang_class_type)
5707{
5708    if (clang_pointee_type && clang_pointee_type)
5709        return getASTContext()->getMemberPointerType(QualType::getFromOpaquePtr(clang_pointee_type),
5710                                                     QualType::getFromOpaquePtr(clang_class_type).getTypePtr()).getAsOpaquePtr();
5711    return NULL;
5712}
5713
5714uint64_t
5715ClangASTContext::GetPointerBitSize ()
5716{
5717    ASTContext *ast = getASTContext();
5718    return ast->getTypeSize(ast->VoidPtrTy);
5719}
5720
5721bool
5722ClangASTContext::IsPossibleDynamicType (clang::ASTContext *ast,
5723                                        clang_type_t clang_type,
5724                                        clang_type_t *dynamic_pointee_type,
5725                                        bool check_cplusplus,
5726                                        bool check_objc)
5727{
5728    QualType pointee_qual_type;
5729    if (clang_type)
5730    {
5731        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
5732        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5733        bool success = false;
5734        switch (type_class)
5735        {
5736            case clang::Type::Builtin:
5737                if (check_objc && cast<clang::BuiltinType>(qual_type)->getKind() == clang::BuiltinType::ObjCId)
5738                {
5739                    if (dynamic_pointee_type)
5740                        *dynamic_pointee_type = clang_type;
5741                    return true;
5742                }
5743                break;
5744
5745            case clang::Type::ObjCObjectPointer:
5746                if (check_objc)
5747                {
5748                    if (dynamic_pointee_type)
5749                        *dynamic_pointee_type = cast<ObjCObjectPointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
5750                    return true;
5751                }
5752                break;
5753
5754            case clang::Type::Pointer:
5755                pointee_qual_type = cast<PointerType>(qual_type)->getPointeeType();
5756                success = true;
5757                break;
5758
5759            case clang::Type::LValueReference:
5760            case clang::Type::RValueReference:
5761                pointee_qual_type = cast<ReferenceType>(qual_type)->getPointeeType();
5762                success = true;
5763                break;
5764
5765            case clang::Type::Typedef:
5766                return ClangASTContext::IsPossibleDynamicType (ast,
5767                                                               cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(),
5768                                                               dynamic_pointee_type,
5769                                                               check_cplusplus,
5770                                                               check_objc);
5771
5772            case clang::Type::Elaborated:
5773                return ClangASTContext::IsPossibleDynamicType (ast,
5774                                                               cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(),
5775                                                               dynamic_pointee_type,
5776                                                               check_cplusplus,
5777                                                               check_objc);
5778
5779            default:
5780                break;
5781        }
5782
5783        if (success)
5784        {
5785            // Check to make sure what we are pointing too is a possible dynamic C++ type
5786            // We currently accept any "void *" (in case we have a class that has been
5787            // watered down to an opaque pointer) and virtual C++ classes.
5788            const clang::Type::TypeClass pointee_type_class = pointee_qual_type->getTypeClass();
5789            switch (pointee_type_class)
5790            {
5791                case clang::Type::Builtin:
5792                    switch (cast<clang::BuiltinType>(pointee_qual_type)->getKind())
5793                    {
5794                        case clang::BuiltinType::UnknownAny:
5795                        case clang::BuiltinType::Void:
5796                            if (dynamic_pointee_type)
5797                                *dynamic_pointee_type = pointee_qual_type.getAsOpaquePtr();
5798                            return true;
5799
5800                        case clang::BuiltinType::NullPtr:
5801                        case clang::BuiltinType::Bool:
5802                        case clang::BuiltinType::Char_U:
5803                        case clang::BuiltinType::UChar:
5804                        case clang::BuiltinType::WChar_U:
5805                        case clang::BuiltinType::Char16:
5806                        case clang::BuiltinType::Char32:
5807                        case clang::BuiltinType::UShort:
5808                        case clang::BuiltinType::UInt:
5809                        case clang::BuiltinType::ULong:
5810                        case clang::BuiltinType::ULongLong:
5811                        case clang::BuiltinType::UInt128:
5812                        case clang::BuiltinType::Char_S:
5813                        case clang::BuiltinType::SChar:
5814                        case clang::BuiltinType::WChar_S:
5815                        case clang::BuiltinType::Short:
5816                        case clang::BuiltinType::Int:
5817                        case clang::BuiltinType::Long:
5818                        case clang::BuiltinType::LongLong:
5819                        case clang::BuiltinType::Int128:
5820                        case clang::BuiltinType::Float:
5821                        case clang::BuiltinType::Double:
5822                        case clang::BuiltinType::LongDouble:
5823                        case clang::BuiltinType::Dependent:
5824                        case clang::BuiltinType::Overload:
5825                        case clang::BuiltinType::ObjCId:
5826                        case clang::BuiltinType::ObjCClass:
5827                        case clang::BuiltinType::ObjCSel:
5828                        case clang::BuiltinType::BoundMember:
5829                        case clang::BuiltinType::Half:
5830                        case clang::BuiltinType::ARCUnbridgedCast:
5831                        case clang::BuiltinType::PseudoObject:
5832                        case clang::BuiltinType::BuiltinFn:
5833                        case clang::BuiltinType::OCLEvent:
5834                        case clang::BuiltinType::OCLImage1d:
5835                        case clang::BuiltinType::OCLImage1dArray:
5836                        case clang::BuiltinType::OCLImage1dBuffer:
5837                        case clang::BuiltinType::OCLImage2d:
5838                        case clang::BuiltinType::OCLImage2dArray:
5839                        case clang::BuiltinType::OCLImage3d:
5840                        case clang::BuiltinType::OCLSampler:
5841                            break;
5842                    }
5843                    break;
5844
5845                case clang::Type::Record:
5846                    if (check_cplusplus)
5847                    {
5848                        CXXRecordDecl *cxx_record_decl = pointee_qual_type->getAsCXXRecordDecl();
5849                        if (cxx_record_decl)
5850                        {
5851                            bool is_complete = cxx_record_decl->isCompleteDefinition();
5852
5853                            if (is_complete)
5854                                success = cxx_record_decl->isDynamicClass();
5855                            else
5856                            {
5857                                ClangASTMetadata *metadata = GetMetadata (ast, cxx_record_decl);
5858                                if (metadata)
5859                                    success = metadata->GetIsDynamicCXXType();
5860                                else
5861                                {
5862                                    is_complete = ClangASTContext::GetCompleteType (ast, pointee_qual_type.getAsOpaquePtr());
5863                                    if (is_complete)
5864                                        success = cxx_record_decl->isDynamicClass();
5865                                    else
5866                                        success = false;
5867                                }
5868                            }
5869
5870                            if (success)
5871                            {
5872                                if (dynamic_pointee_type)
5873                                    *dynamic_pointee_type = pointee_qual_type.getAsOpaquePtr();
5874                                return true;
5875                            }
5876                        }
5877                    }
5878                    break;
5879
5880                case clang::Type::ObjCObject:
5881                case clang::Type::ObjCInterface:
5882                    if (check_objc)
5883                    {
5884                        if (dynamic_pointee_type)
5885                            *dynamic_pointee_type = pointee_qual_type.getAsOpaquePtr();
5886                        return true;
5887                    }
5888                    break;
5889
5890                default:
5891                    break;
5892            }
5893        }
5894    }
5895    if (dynamic_pointee_type)
5896        *dynamic_pointee_type = NULL;
5897    return false;
5898}
5899
5900
5901bool
5902ClangASTContext::IsPossibleCPlusPlusDynamicType (clang::ASTContext *ast, clang_type_t clang_type, clang_type_t *dynamic_pointee_type)
5903{
5904    return IsPossibleDynamicType (ast,
5905                                  clang_type,
5906                                  dynamic_pointee_type,
5907                                  true,     // Check for dynamic C++ types
5908                                  false);   // Check for dynamic ObjC types
5909}
5910
5911bool
5912ClangASTContext::IsReferenceType (clang_type_t clang_type, clang_type_t *target_type)
5913{
5914    if (clang_type == NULL)
5915        return false;
5916
5917    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
5918    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5919
5920    switch (type_class)
5921    {
5922    case clang::Type::LValueReference:
5923        if (target_type)
5924            *target_type = cast<LValueReferenceType>(qual_type)->desugar().getAsOpaquePtr();
5925        return true;
5926    case clang::Type::RValueReference:
5927        if (target_type)
5928            *target_type = cast<LValueReferenceType>(qual_type)->desugar().getAsOpaquePtr();
5929        return true;
5930    case clang::Type::Typedef:
5931        return ClangASTContext::IsReferenceType (cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
5932    case clang::Type::Elaborated:
5933        return ClangASTContext::IsReferenceType (cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
5934    default:
5935        break;
5936    }
5937
5938    return false;
5939}
5940
5941bool
5942ClangASTContext::IsPointerOrReferenceType (clang_type_t clang_type, clang_type_t*target_type)
5943{
5944    if (clang_type == NULL)
5945        return false;
5946
5947    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
5948    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5949    switch (type_class)
5950    {
5951    case clang::Type::Builtin:
5952        switch (cast<clang::BuiltinType>(qual_type)->getKind())
5953        {
5954        default:
5955            break;
5956        case clang::BuiltinType::ObjCId:
5957        case clang::BuiltinType::ObjCClass:
5958            return true;
5959        }
5960        return false;
5961    case clang::Type::ObjCObjectPointer:
5962        if (target_type)
5963            *target_type = cast<ObjCObjectPointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
5964        return true;
5965    case clang::Type::BlockPointer:
5966        if (target_type)
5967            *target_type = cast<BlockPointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
5968        return true;
5969    case clang::Type::Pointer:
5970        if (target_type)
5971            *target_type = cast<PointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
5972        return true;
5973    case clang::Type::MemberPointer:
5974        if (target_type)
5975            *target_type = cast<MemberPointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
5976        return true;
5977    case clang::Type::LValueReference:
5978        if (target_type)
5979            *target_type = cast<LValueReferenceType>(qual_type)->desugar().getAsOpaquePtr();
5980        return true;
5981    case clang::Type::RValueReference:
5982        if (target_type)
5983            *target_type = cast<LValueReferenceType>(qual_type)->desugar().getAsOpaquePtr();
5984        return true;
5985    case clang::Type::Typedef:
5986        return ClangASTContext::IsPointerOrReferenceType (cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
5987    case clang::Type::Elaborated:
5988        return ClangASTContext::IsPointerOrReferenceType (cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
5989    default:
5990        break;
5991    }
5992    return false;
5993}
5994
5995bool
5996ClangASTContext::IsIntegerType (clang_type_t clang_type, bool &is_signed)
5997{
5998    if (!clang_type)
5999        return false;
6000
6001    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6002    const BuiltinType *builtin_type = dyn_cast<BuiltinType>(qual_type->getCanonicalTypeInternal());
6003
6004    if (builtin_type)
6005    {
6006        if (builtin_type->isInteger())
6007        {
6008            is_signed = builtin_type->isSignedInteger();
6009            return true;
6010        }
6011    }
6012
6013    return false;
6014}
6015
6016bool
6017ClangASTContext::IsPointerType (clang_type_t clang_type, clang_type_t *target_type)
6018{
6019    if (target_type)
6020        *target_type = NULL;
6021
6022    if (clang_type)
6023    {
6024        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6025        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
6026        switch (type_class)
6027        {
6028        case clang::Type::Builtin:
6029            switch (cast<clang::BuiltinType>(qual_type)->getKind())
6030            {
6031            default:
6032                break;
6033            case clang::BuiltinType::ObjCId:
6034            case clang::BuiltinType::ObjCClass:
6035                return true;
6036            }
6037            return false;
6038        case clang::Type::ObjCObjectPointer:
6039            if (target_type)
6040                *target_type = cast<ObjCObjectPointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
6041            return true;
6042        case clang::Type::BlockPointer:
6043            if (target_type)
6044                *target_type = cast<BlockPointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
6045            return true;
6046        case clang::Type::Pointer:
6047            if (target_type)
6048                *target_type = cast<PointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
6049            return true;
6050        case clang::Type::MemberPointer:
6051            if (target_type)
6052                *target_type = cast<MemberPointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
6053            return true;
6054        case clang::Type::Typedef:
6055            return ClangASTContext::IsPointerType (cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(), target_type);
6056        case clang::Type::Elaborated:
6057            return ClangASTContext::IsPointerType (cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(), target_type);
6058        default:
6059            break;
6060        }
6061    }
6062    return false;
6063}
6064
6065bool
6066ClangASTContext::IsFloatingPointType (clang_type_t clang_type, uint32_t &count, bool &is_complex)
6067{
6068    if (clang_type)
6069    {
6070        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6071
6072        if (const BuiltinType *BT = dyn_cast<BuiltinType>(qual_type->getCanonicalTypeInternal()))
6073        {
6074            clang::BuiltinType::Kind kind = BT->getKind();
6075            if (kind >= BuiltinType::Float && kind <= BuiltinType::LongDouble)
6076            {
6077                count = 1;
6078                is_complex = false;
6079                return true;
6080            }
6081        }
6082        else if (const ComplexType *CT = dyn_cast<ComplexType>(qual_type->getCanonicalTypeInternal()))
6083        {
6084            if (IsFloatingPointType(CT->getElementType().getAsOpaquePtr(), count, is_complex))
6085            {
6086                count = 2;
6087                is_complex = true;
6088                return true;
6089            }
6090        }
6091        else if (const VectorType *VT = dyn_cast<VectorType>(qual_type->getCanonicalTypeInternal()))
6092        {
6093            if (IsFloatingPointType(VT->getElementType().getAsOpaquePtr(), count, is_complex))
6094            {
6095                count = VT->getNumElements();
6096                is_complex = false;
6097                return true;
6098            }
6099        }
6100    }
6101    return false;
6102}
6103
6104bool
6105ClangASTContext::IsScalarType (lldb::clang_type_t clang_type)
6106{
6107    bool is_signed;
6108    if (ClangASTContext::IsIntegerType(clang_type, is_signed))
6109        return true;
6110
6111    uint32_t count;
6112    bool is_complex;
6113    return ClangASTContext::IsFloatingPointType(clang_type, count, is_complex) && !is_complex;
6114}
6115
6116bool
6117ClangASTContext::IsPointerToScalarType (lldb::clang_type_t clang_type)
6118{
6119    if (!IsPointerType(clang_type))
6120        return false;
6121
6122    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6123    lldb::clang_type_t pointee_type = qual_type.getTypePtr()->getPointeeType().getAsOpaquePtr();
6124    return IsScalarType(pointee_type);
6125}
6126
6127bool
6128ClangASTContext::IsArrayOfScalarType (lldb::clang_type_t clang_type)
6129{
6130    clang_type = GetAsArrayType(clang_type, NULL, NULL, NULL);
6131
6132    if (clang_type == 0)
6133        return false;
6134
6135    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6136    lldb::clang_type_t item_type = cast<ArrayType>(qual_type.getTypePtr())->getElementType().getAsOpaquePtr();
6137    return IsScalarType(item_type);
6138}
6139
6140
6141bool
6142ClangASTContext::GetCXXClassName (clang_type_t clang_type, std::string &class_name)
6143{
6144    if (clang_type)
6145    {
6146        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6147
6148        CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
6149        if (cxx_record_decl)
6150        {
6151            class_name.assign (cxx_record_decl->getIdentifier()->getNameStart());
6152            return true;
6153        }
6154    }
6155    class_name.clear();
6156    return false;
6157}
6158
6159
6160bool
6161ClangASTContext::IsCXXClassType (clang_type_t clang_type)
6162{
6163    if (clang_type)
6164    {
6165        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6166        if (qual_type->getAsCXXRecordDecl() != NULL)
6167            return true;
6168    }
6169    return false;
6170}
6171
6172bool
6173ClangASTContext::IsBeingDefined (lldb::clang_type_t clang_type)
6174{
6175    if (clang_type)
6176    {
6177        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6178        const clang::TagType *tag_type = dyn_cast<clang::TagType>(qual_type);
6179        if (tag_type)
6180            return tag_type->isBeingDefined();
6181    }
6182    return false;
6183}
6184
6185bool
6186ClangASTContext::IsObjCClassType (clang_type_t clang_type)
6187{
6188    if (clang_type)
6189    {
6190        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6191        if (qual_type->isObjCObjectOrInterfaceType())
6192            return true;
6193    }
6194    return false;
6195}
6196
6197bool
6198ClangASTContext::IsObjCObjectPointerType (lldb::clang_type_t clang_type, clang_type_t *class_type)
6199{
6200    if (clang_type)
6201    {
6202        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6203        if (qual_type->isObjCObjectPointerType())
6204        {
6205            if (class_type)
6206            {
6207                *class_type = NULL;
6208
6209                if (!qual_type->isObjCClassType() &&
6210                    !qual_type->isObjCIdType())
6211                {
6212                    const ObjCObjectPointerType *obj_pointer_type = dyn_cast<ObjCObjectPointerType>(qual_type);
6213                    if (!obj_pointer_type)
6214                        *class_type = NULL;
6215                    else
6216                        *class_type = QualType(obj_pointer_type->getInterfaceType(), 0).getAsOpaquePtr();
6217                }
6218            }
6219            return true;
6220        }
6221    }
6222    return false;
6223}
6224
6225bool
6226ClangASTContext::GetObjCClassName (lldb::clang_type_t clang_type,
6227                                   std::string &class_name)
6228{
6229    if (!clang_type)
6230        return false;
6231
6232    const ObjCObjectType *object_type = dyn_cast<ObjCObjectType>(QualType::getFromOpaquePtr(clang_type));
6233    if (!object_type)
6234        return false;
6235
6236    const ObjCInterfaceDecl *interface = object_type->getInterface();
6237    if (!interface)
6238        return false;
6239
6240    class_name = interface->getNameAsString();
6241    return true;
6242}
6243
6244bool
6245ClangASTContext::IsCharType (clang_type_t clang_type)
6246{
6247    if (clang_type)
6248        return QualType::getFromOpaquePtr(clang_type)->isCharType();
6249    return false;
6250}
6251
6252bool
6253ClangASTContext::IsCStringType (clang_type_t clang_type, uint32_t &length)
6254{
6255    clang_type_t pointee_or_element_clang_type = NULL;
6256    Flags type_flags (ClangASTContext::GetTypeInfo (clang_type, NULL, &pointee_or_element_clang_type));
6257
6258    if (pointee_or_element_clang_type == NULL)
6259        return false;
6260
6261    if (type_flags.AnySet (eTypeIsArray | eTypeIsPointer))
6262    {
6263        QualType pointee_or_element_qual_type (QualType::getFromOpaquePtr (pointee_or_element_clang_type));
6264
6265        if (pointee_or_element_qual_type.getUnqualifiedType()->isCharType())
6266        {
6267            QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6268            if (type_flags.Test (eTypeIsArray))
6269            {
6270                // We know the size of the array and it could be a C string
6271                // since it is an array of characters
6272                length = cast<ConstantArrayType>(qual_type.getTypePtr())->getSize().getLimitedValue();
6273                return true;
6274            }
6275            else
6276            {
6277                length = 0;
6278                return true;
6279            }
6280
6281        }
6282    }
6283    return false;
6284}
6285
6286bool
6287ClangASTContext::IsFunctionPointerType (clang_type_t clang_type)
6288{
6289    if (clang_type)
6290    {
6291        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6292
6293        if (qual_type->isFunctionPointerType())
6294            return true;
6295
6296        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
6297        switch (type_class)
6298        {
6299        default:
6300            break;
6301        case clang::Type::Typedef:
6302            return ClangASTContext::IsFunctionPointerType (cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
6303        case clang::Type::Elaborated:
6304            return ClangASTContext::IsFunctionPointerType (cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
6305
6306        case clang::Type::LValueReference:
6307        case clang::Type::RValueReference:
6308            {
6309                const ReferenceType *reference_type = cast<ReferenceType>(qual_type.getTypePtr());
6310                if (reference_type)
6311                    return ClangASTContext::IsFunctionPointerType (reference_type->getPointeeType().getAsOpaquePtr());
6312            }
6313            break;
6314        }
6315    }
6316    return false;
6317}
6318
6319size_t
6320ClangASTContext::GetArraySize (clang_type_t clang_type)
6321{
6322    if (clang_type)
6323    {
6324        QualType qual_type(QualType::getFromOpaquePtr(clang_type));
6325        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
6326        switch (type_class)
6327        {
6328        case clang::Type::ConstantArray:
6329            {
6330                const ConstantArrayType *array = cast<ConstantArrayType>(QualType::getFromOpaquePtr(clang_type).getTypePtr());
6331                if (array)
6332                    return array->getSize().getLimitedValue();
6333            }
6334            break;
6335
6336        case clang::Type::Typedef:
6337            return ClangASTContext::GetArraySize(cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
6338
6339        case clang::Type::Elaborated:
6340            return ClangASTContext::GetArraySize(cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
6341
6342        default:
6343            break;
6344        }
6345    }
6346    return 0;
6347}
6348
6349clang_type_t
6350ClangASTContext::GetAsArrayType (clang_type_t clang_type, clang_type_t*member_type, uint64_t *size, bool *is_incomplete)
6351{
6352    if (is_incomplete)
6353        *is_incomplete = false;
6354    if (!clang_type)
6355        return 0;
6356
6357    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6358
6359    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
6360    switch (type_class)
6361    {
6362    default:
6363        break;
6364
6365    case clang::Type::ConstantArray:
6366        if (member_type)
6367            *member_type = cast<ConstantArrayType>(qual_type)->getElementType().getAsOpaquePtr();
6368        if (size)
6369            *size = cast<ConstantArrayType>(qual_type)->getSize().getLimitedValue(ULLONG_MAX);
6370        return clang_type;
6371
6372    case clang::Type::IncompleteArray:
6373        if (member_type)
6374            *member_type = cast<IncompleteArrayType>(qual_type)->getElementType().getAsOpaquePtr();
6375        if (size)
6376            *size = 0;
6377        if (is_incomplete)
6378            *is_incomplete = true;
6379        return clang_type;
6380
6381    case clang::Type::VariableArray:
6382        if (member_type)
6383            *member_type = cast<VariableArrayType>(qual_type)->getElementType().getAsOpaquePtr();
6384        if (size)
6385            *size = 0;
6386        return clang_type;
6387
6388    case clang::Type::DependentSizedArray:
6389        if (member_type)
6390            *member_type = cast<DependentSizedArrayType>(qual_type)->getElementType().getAsOpaquePtr();
6391        if (size)
6392            *size = 0;
6393        return clang_type;
6394
6395    case clang::Type::Typedef:
6396        return ClangASTContext::GetAsArrayType (cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(),
6397                                                member_type,
6398                                                size,
6399                                                is_incomplete);
6400
6401    case clang::Type::Elaborated:
6402        return ClangASTContext::GetAsArrayType (cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(),
6403                                                member_type,
6404                                                size,
6405                                                is_incomplete);
6406    }
6407    return 0;
6408}
6409
6410
6411#pragma mark Typedefs
6412
6413clang_type_t
6414ClangASTContext::CreateTypedefType (const char *name, clang_type_t clang_type, DeclContext *decl_ctx)
6415{
6416    if (clang_type)
6417    {
6418        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6419        ASTContext *ast = getASTContext();
6420        IdentifierTable *identifier_table = getIdentifierTable();
6421        assert (ast != NULL);
6422        assert (identifier_table != NULL);
6423        if (decl_ctx == NULL)
6424            decl_ctx = ast->getTranslationUnitDecl();
6425        TypedefDecl *decl = TypedefDecl::Create (*ast,
6426                                                 decl_ctx,
6427                                                 SourceLocation(),
6428                                                 SourceLocation(),
6429                                                 name ? &identifier_table->get(name) : NULL, // Identifier
6430                                                 ast->getTrivialTypeSourceInfo(qual_type));
6431
6432        //decl_ctx->addDecl (decl);
6433
6434        decl->setAccess(AS_public); // TODO respect proper access specifier
6435
6436        // Get a uniqued QualType for the typedef decl type
6437        return ast->getTypedefType (decl).getAsOpaquePtr();
6438    }
6439    return NULL;
6440}
6441
6442// Disable this for now since I can't seem to get a nicely formatted float
6443// out of the APFloat class without just getting the float, double or quad
6444// and then using a formatted print on it which defeats the purpose. We ideally
6445// would like to get perfect string values for any kind of float semantics
6446// so we can support remote targets. The code below also requires a patch to
6447// llvm::APInt.
6448//bool
6449//ClangASTContext::ConvertFloatValueToString (ASTContext *ast, clang_type_t clang_type, const uint8_t* bytes, size_t byte_size, int apint_byte_order, std::string &float_str)
6450//{
6451//  uint32_t count = 0;
6452//  bool is_complex = false;
6453//  if (ClangASTContext::IsFloatingPointType (clang_type, count, is_complex))
6454//  {
6455//      unsigned num_bytes_per_float = byte_size / count;
6456//      unsigned num_bits_per_float = num_bytes_per_float * 8;
6457//
6458//      float_str.clear();
6459//      uint32_t i;
6460//      for (i=0; i<count; i++)
6461//      {
6462//          APInt ap_int(num_bits_per_float, bytes + i * num_bytes_per_float, (APInt::ByteOrder)apint_byte_order);
6463//          bool is_ieee = false;
6464//          APFloat ap_float(ap_int, is_ieee);
6465//          char s[1024];
6466//          unsigned int hex_digits = 0;
6467//          bool upper_case = false;
6468//
6469//          if (ap_float.convertToHexString(s, hex_digits, upper_case, APFloat::rmNearestTiesToEven) > 0)
6470//          {
6471//              if (i > 0)
6472//                  float_str.append(", ");
6473//              float_str.append(s);
6474//              if (i == 1 && is_complex)
6475//                  float_str.append(1, 'i');
6476//          }
6477//      }
6478//      return !float_str.empty();
6479//  }
6480//  return false;
6481//}
6482
6483size_t
6484ClangASTContext::ConvertStringToFloatValue (ASTContext *ast, clang_type_t clang_type, const char *s, uint8_t *dst, size_t dst_size)
6485{
6486    if (clang_type)
6487    {
6488        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6489        uint32_t count = 0;
6490        bool is_complex = false;
6491        if (ClangASTContext::IsFloatingPointType (clang_type, count, is_complex))
6492        {
6493            // TODO: handle complex and vector types
6494            if (count != 1)
6495                return false;
6496
6497            StringRef s_sref(s);
6498            APFloat ap_float(ast->getFloatTypeSemantics(qual_type), s_sref);
6499
6500            const uint64_t bit_size = ast->getTypeSize (qual_type);
6501            const uint64_t byte_size = bit_size / 8;
6502            if (dst_size >= byte_size)
6503            {
6504                if (bit_size == sizeof(float)*8)
6505                {
6506                    float float32 = ap_float.convertToFloat();
6507                    ::memcpy (dst, &float32, byte_size);
6508                    return byte_size;
6509                }
6510                else if (bit_size >= 64)
6511                {
6512                    llvm::APInt ap_int(ap_float.bitcastToAPInt());
6513                    ::memcpy (dst, ap_int.getRawData(), byte_size);
6514                    return byte_size;
6515                }
6516            }
6517        }
6518    }
6519    return 0;
6520}
6521
6522unsigned
6523ClangASTContext::GetTypeQualifiers(clang_type_t clang_type)
6524{
6525    assert (clang_type);
6526
6527    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6528
6529    return qual_type.getQualifiers().getCVRQualifiers();
6530}
6531
6532bool
6533ClangASTContext::GetCompleteType (clang::ASTContext *ast, lldb::clang_type_t clang_type)
6534{
6535    if (clang_type == NULL)
6536        return false;
6537
6538    return GetCompleteQualType (ast, clang::QualType::getFromOpaquePtr(clang_type));
6539}
6540
6541
6542bool
6543ClangASTContext::GetCompleteType (clang_type_t clang_type)
6544{
6545    return ClangASTContext::GetCompleteType (getASTContext(), clang_type);
6546}
6547
6548bool
6549ClangASTContext::IsCompleteType (clang::ASTContext *ast, lldb::clang_type_t clang_type)
6550{
6551    if (clang_type == NULL)
6552        return false;
6553
6554    return GetCompleteQualType (ast, clang::QualType::getFromOpaquePtr(clang_type), false); // just check but don't let it actually complete
6555}
6556
6557
6558bool
6559ClangASTContext::IsCompleteType (clang_type_t clang_type)
6560{
6561    return ClangASTContext::IsCompleteType (getASTContext(), clang_type);
6562}
6563
6564bool
6565ClangASTContext::GetCompleteDecl (clang::ASTContext *ast,
6566                                  clang::Decl *decl)
6567{
6568    if (!decl)
6569        return false;
6570
6571    ExternalASTSource *ast_source = ast->getExternalSource();
6572
6573    if (!ast_source)
6574        return false;
6575
6576    if (clang::TagDecl *tag_decl = llvm::dyn_cast<clang::TagDecl>(decl))
6577    {
6578        if (tag_decl->isCompleteDefinition())
6579            return true;
6580
6581        if (!tag_decl->hasExternalLexicalStorage())
6582            return false;
6583
6584        ast_source->CompleteType(tag_decl);
6585
6586        return !tag_decl->getTypeForDecl()->isIncompleteType();
6587    }
6588    else if (clang::ObjCInterfaceDecl *objc_interface_decl = llvm::dyn_cast<clang::ObjCInterfaceDecl>(decl))
6589    {
6590        if (objc_interface_decl->getDefinition())
6591            return true;
6592
6593        if (!objc_interface_decl->hasExternalLexicalStorage())
6594            return false;
6595
6596        ast_source->CompleteType(objc_interface_decl);
6597
6598        return !objc_interface_decl->getTypeForDecl()->isIncompleteType();
6599    }
6600    else
6601    {
6602        return false;
6603    }
6604}
6605
6606void
6607ClangASTContext::SetMetadataAsUserID (const void *object,
6608                                      user_id_t user_id)
6609{
6610    ClangASTMetadata meta_data;
6611    meta_data.SetUserID (user_id);
6612    SetMetadata (object, meta_data);
6613}
6614
6615void
6616ClangASTContext::SetMetadata (clang::ASTContext *ast,
6617                              const void *object,
6618                              ClangASTMetadata &metadata)
6619{
6620    ClangExternalASTSourceCommon *external_source =
6621        static_cast<ClangExternalASTSourceCommon*>(ast->getExternalSource());
6622
6623    if (external_source)
6624        external_source->SetMetadata(object, metadata);
6625}
6626
6627ClangASTMetadata *
6628ClangASTContext::GetMetadata (clang::ASTContext *ast,
6629                              const void *object)
6630{
6631    ClangExternalASTSourceCommon *external_source =
6632        static_cast<ClangExternalASTSourceCommon*>(ast->getExternalSource());
6633
6634    if (external_source && external_source->HasMetadata(object))
6635        return external_source->GetMetadata(object);
6636    else
6637        return NULL;
6638}
6639
6640clang::DeclContext *
6641ClangASTContext::GetAsDeclContext (clang::CXXMethodDecl *cxx_method_decl)
6642{
6643    return llvm::dyn_cast<clang::DeclContext>(cxx_method_decl);
6644}
6645
6646clang::DeclContext *
6647ClangASTContext::GetAsDeclContext (clang::ObjCMethodDecl *objc_method_decl)
6648{
6649    return llvm::dyn_cast<clang::DeclContext>(objc_method_decl);
6650}
6651
6652
6653bool
6654ClangASTContext::GetClassMethodInfoForDeclContext (clang::DeclContext *decl_ctx,
6655                                                   lldb::LanguageType &language,
6656                                                   bool &is_instance_method,
6657                                                   ConstString &language_object_name)
6658{
6659    language_object_name.Clear();
6660    language = eLanguageTypeUnknown;
6661    is_instance_method = false;
6662
6663    if (decl_ctx)
6664    {
6665        if (clang::CXXMethodDecl *method_decl = llvm::dyn_cast<clang::CXXMethodDecl>(decl_ctx))
6666        {
6667            if (method_decl->isStatic())
6668            {
6669                is_instance_method = false;
6670            }
6671            else
6672            {
6673                language_object_name.SetCString("this");
6674                is_instance_method = true;
6675            }
6676            language = eLanguageTypeC_plus_plus;
6677            return true;
6678        }
6679        else if (clang::ObjCMethodDecl *method_decl = llvm::dyn_cast<clang::ObjCMethodDecl>(decl_ctx))
6680        {
6681            // Both static and instance methods have a "self" object in objective C
6682            language_object_name.SetCString("self");
6683            if (method_decl->isInstanceMethod())
6684            {
6685                is_instance_method = true;
6686            }
6687            else
6688            {
6689                is_instance_method = false;
6690            }
6691            language = eLanguageTypeObjC;
6692            return true;
6693        }
6694        else if (clang::FunctionDecl *function_decl = llvm::dyn_cast<clang::FunctionDecl>(decl_ctx))
6695        {
6696            ClangASTMetadata *metadata = GetMetadata (&decl_ctx->getParentASTContext(), function_decl);
6697            if (metadata && metadata->HasObjectPtr())
6698            {
6699                language_object_name.SetCString (metadata->GetObjectPtrName());
6700                language = eLanguageTypeObjC;
6701                is_instance_method = true;
6702            }
6703            return true;
6704        }
6705    }
6706    return false;
6707}
6708
6709