ClangASTContext.cpp revision 3dc2a5b732ae161b8ae51d376a8f0060a7d9e2a8
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    LogSP 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, (uintptr_t)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       cxx_ctor_decl = CXXConstructorDecl::Create (*ast,
1781                                                   cxx_record_decl,
1782                                                   SourceLocation(),
1783                                                   DeclarationNameInfo (ast->DeclarationNames.getCXXConstructorName (ast->getCanonicalType (record_qual_type)), SourceLocation()),
1784                                                   method_qual_type,
1785                                                   NULL, // TypeSourceInfo *
1786                                                   is_explicit,
1787                                                   is_inline,
1788                                                   is_artificial,
1789                                                   false /*is_constexpr*/);
1790        cxx_method_decl = cxx_ctor_decl;
1791    }
1792    else
1793    {
1794
1795        OverloadedOperatorKind op_kind = NUM_OVERLOADED_OPERATORS;
1796        if (IsOperator (name, op_kind))
1797        {
1798            if (op_kind != NUM_OVERLOADED_OPERATORS)
1799            {
1800                // Check the number of operator parameters. Sometimes we have
1801                // seen bad DWARF that doesn't correctly describe operators and
1802                // if we try to create a methed and add it to the class, clang
1803                // will assert and crash, so we need to make sure things are
1804                // acceptable.
1805                if (!ClangASTContext::CheckOverloadedOperatorKindParameterCount (op_kind, num_params))
1806                    return NULL;
1807                cxx_method_decl = CXXMethodDecl::Create (*ast,
1808                                                         cxx_record_decl,
1809                                                         SourceLocation(),
1810                                                         DeclarationNameInfo (ast->DeclarationNames.getCXXOperatorName (op_kind), SourceLocation()),
1811                                                         method_qual_type,
1812                                                         NULL, // TypeSourceInfo *
1813                                                         is_static,
1814                                                         SC_None,
1815                                                         is_inline,
1816                                                         false /*is_constexpr*/,
1817                                                         SourceLocation());
1818            }
1819            else if (num_params == 0)
1820            {
1821                // Conversion operators don't take params...
1822                cxx_method_decl = CXXConversionDecl::Create (*ast,
1823                                                             cxx_record_decl,
1824                                                             SourceLocation(),
1825                                                             DeclarationNameInfo (ast->DeclarationNames.getCXXConversionFunctionName (ast->getCanonicalType (function_Type->getResultType())), SourceLocation()),
1826                                                             method_qual_type,
1827                                                             NULL, // TypeSourceInfo *
1828                                                             is_inline,
1829                                                             is_explicit,
1830                                                             false /*is_constexpr*/,
1831                                                             SourceLocation());
1832            }
1833        }
1834
1835        if (cxx_method_decl == NULL)
1836        {
1837            cxx_method_decl = CXXMethodDecl::Create (*ast,
1838                                                     cxx_record_decl,
1839                                                     SourceLocation(),
1840                                                     DeclarationNameInfo (decl_name, SourceLocation()),
1841                                                     method_qual_type,
1842                                                     NULL, // TypeSourceInfo *
1843                                                     is_static,
1844                                                     SC_None,
1845                                                     is_inline,
1846                                                     false /*is_constexpr*/,
1847                                                     SourceLocation());
1848        }
1849    }
1850
1851    AccessSpecifier access_specifier = ConvertAccessTypeToAccessSpecifier (access);
1852
1853    cxx_method_decl->setAccess (access_specifier);
1854    cxx_method_decl->setVirtualAsWritten (is_virtual);
1855
1856    if (is_attr_used)
1857        cxx_method_decl->addAttr(::new (*ast) UsedAttr(SourceRange(), *ast));
1858
1859    // Populate the method decl with parameter decls
1860
1861    llvm::SmallVector<ParmVarDecl *, 12> params;
1862
1863    for (int param_index = 0;
1864         param_index < num_params;
1865         ++param_index)
1866    {
1867        params.push_back (ParmVarDecl::Create (*ast,
1868                                               cxx_method_decl,
1869                                               SourceLocation(),
1870                                               SourceLocation(),
1871                                               NULL, // anonymous
1872                                               method_function_prototype->getArgType(param_index),
1873                                               NULL,
1874                                               SC_None,
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, (uintptr_t)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, (uintptr_t)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, (uintptr_t)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, (uintptr_t)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                                                               SC_Auto,
2605                                                               NULL));
2606
2607                        setter->setMethodParams(*ast, ArrayRef<ParmVarDecl*>(params), ArrayRef<SourceLocation>());
2608
2609                        class_interface_decl->addDecl(setter);
2610                    }
2611
2612                    return true;
2613                }
2614            }
2615        }
2616    }
2617    return false;
2618}
2619
2620bool
2621ClangASTContext::ObjCTypeHasIVars (clang_type_t class_opaque_type, bool check_superclass)
2622{
2623    QualType class_qual_type(QualType::getFromOpaquePtr(class_opaque_type));
2624
2625    const clang::Type *class_type = class_qual_type.getTypePtr();
2626    if (class_type)
2627    {
2628        const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(class_type);
2629
2630        if (objc_class_type)
2631            return ObjCDeclHasIVars (objc_class_type->getInterface(), check_superclass);
2632    }
2633    return false;
2634}
2635
2636bool
2637ClangASTContext::ObjCDeclHasIVars (ObjCInterfaceDecl *class_interface_decl, bool check_superclass)
2638{
2639    while (class_interface_decl)
2640    {
2641        if (class_interface_decl->ivar_size() > 0)
2642            return true;
2643
2644        if (check_superclass)
2645            class_interface_decl = class_interface_decl->getSuperClass();
2646        else
2647            break;
2648    }
2649    return false;
2650}
2651
2652ObjCMethodDecl *
2653ClangASTContext::AddMethodToObjCObjectType (ASTContext *ast,
2654                                            clang_type_t class_opaque_type,
2655                                            const char *name,  // the full symbol name as seen in the symbol table ("-[NString stringWithCString:]")
2656                                            clang_type_t method_opaque_type,
2657                                            lldb::AccessType access,
2658                                            bool is_artificial)
2659{
2660    if (class_opaque_type == NULL || method_opaque_type == NULL)
2661        return NULL;
2662
2663    IdentifierTable *identifier_table = &ast->Idents;
2664
2665    assert (ast != NULL);
2666    assert (identifier_table != NULL);
2667
2668    QualType class_qual_type(QualType::getFromOpaquePtr(class_opaque_type));
2669
2670    const clang::Type *class_type = class_qual_type.getTypePtr();
2671    if (class_type == NULL)
2672        return NULL;
2673
2674    const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(class_type);
2675
2676    if (objc_class_type == NULL)
2677        return NULL;
2678
2679    ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
2680
2681    if (class_interface_decl == NULL)
2682        return NULL;
2683
2684    const char *selector_start = ::strchr (name, ' ');
2685    if (selector_start == NULL)
2686        return NULL;
2687
2688    selector_start++;
2689    llvm::SmallVector<IdentifierInfo *, 12> selector_idents;
2690
2691    size_t len = 0;
2692    const char *start;
2693    //printf ("name = '%s'\n", name);
2694
2695    unsigned num_selectors_with_args = 0;
2696    for (start = selector_start;
2697         start && *start != '\0' && *start != ']';
2698         start += len)
2699    {
2700        len = ::strcspn(start, ":]");
2701        bool has_arg = (start[len] == ':');
2702        if (has_arg)
2703            ++num_selectors_with_args;
2704        selector_idents.push_back (&identifier_table->get (StringRef (start, len)));
2705        if (has_arg)
2706            len += 1;
2707    }
2708
2709
2710    if (selector_idents.size() == 0)
2711        return 0;
2712
2713    clang::Selector method_selector = ast->Selectors.getSelector (num_selectors_with_args ? selector_idents.size() : 0,
2714                                                                          selector_idents.data());
2715
2716    QualType method_qual_type (QualType::getFromOpaquePtr (method_opaque_type));
2717
2718    // Populate the method decl with parameter decls
2719    const clang::Type *method_type(method_qual_type.getTypePtr());
2720
2721    if (method_type == NULL)
2722        return NULL;
2723
2724    const FunctionProtoType *method_function_prototype (dyn_cast<FunctionProtoType>(method_type));
2725
2726    if (!method_function_prototype)
2727        return NULL;
2728
2729
2730    bool is_variadic = false;
2731    bool is_synthesized = false;
2732    bool is_defined = false;
2733    ObjCMethodDecl::ImplementationControl imp_control = ObjCMethodDecl::None;
2734
2735    const unsigned num_args = method_function_prototype->getNumArgs();
2736
2737    if (num_args != num_selectors_with_args)
2738        return NULL; // some debug information is corrupt.  We are not going to deal with it.
2739
2740    ObjCMethodDecl *objc_method_decl = ObjCMethodDecl::Create (*ast,
2741                                                               SourceLocation(), // beginLoc,
2742                                                               SourceLocation(), // endLoc,
2743                                                               method_selector,
2744                                                               method_function_prototype->getResultType(),
2745                                                               NULL, // TypeSourceInfo *ResultTInfo,
2746                                                               GetDeclContextForType (class_opaque_type),
2747                                                               name[0] == '-',
2748                                                               is_variadic,
2749                                                               is_synthesized,
2750                                                               true, // is_implicitly_declared; we force this to true because we don't have source locations
2751                                                               is_defined,
2752                                                               imp_control,
2753                                                               false /*has_related_result_type*/);
2754
2755
2756    if (objc_method_decl == NULL)
2757        return NULL;
2758
2759    if (num_args > 0)
2760    {
2761        llvm::SmallVector<ParmVarDecl *, 12> params;
2762
2763        for (int param_index = 0; param_index < num_args; ++param_index)
2764        {
2765            params.push_back (ParmVarDecl::Create (*ast,
2766                                                   objc_method_decl,
2767                                                   SourceLocation(),
2768                                                   SourceLocation(),
2769                                                   NULL, // anonymous
2770                                                   method_function_prototype->getArgType(param_index),
2771                                                   NULL,
2772                                                   SC_Auto,
2773                                                   SC_Auto,
2774                                                   NULL));
2775        }
2776
2777        objc_method_decl->setMethodParams(*ast, ArrayRef<ParmVarDecl*>(params), ArrayRef<SourceLocation>());
2778    }
2779
2780    class_interface_decl->addDecl (objc_method_decl);
2781
2782#ifdef LLDB_CONFIGURATION_DEBUG
2783    VerifyDecl(objc_method_decl);
2784#endif
2785
2786    return objc_method_decl;
2787}
2788
2789size_t
2790ClangASTContext::GetNumTemplateArguments (clang::ASTContext *ast, clang_type_t clang_type)
2791{
2792    if (clang_type)
2793    {
2794        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
2795
2796        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2797        switch (type_class)
2798        {
2799            case clang::Type::Record:
2800                if (GetCompleteQualType (ast, qual_type))
2801                {
2802                    const CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
2803                    if (cxx_record_decl)
2804                    {
2805                        const ClassTemplateSpecializationDecl *template_decl = dyn_cast<ClassTemplateSpecializationDecl>(cxx_record_decl);
2806                        if (template_decl)
2807                            return template_decl->getTemplateArgs().size();
2808                    }
2809                }
2810                break;
2811
2812            case clang::Type::Typedef:
2813                return ClangASTContext::GetNumTemplateArguments (ast, cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
2814
2815            case clang::Type::Elaborated:
2816                return ClangASTContext::GetNumTemplateArguments (ast, cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
2817
2818            default:
2819                break;
2820        }
2821    }
2822    return 0;
2823}
2824
2825clang_type_t
2826ClangASTContext::GetTemplateArgument (clang::ASTContext *ast, clang_type_t clang_type, size_t arg_idx, lldb::TemplateArgumentKind &kind)
2827{
2828    if (clang_type)
2829    {
2830        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
2831
2832        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2833        switch (type_class)
2834        {
2835            case clang::Type::Record:
2836                if (GetCompleteQualType (ast, qual_type))
2837                {
2838                    const CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
2839                    if (cxx_record_decl)
2840                    {
2841                        const ClassTemplateSpecializationDecl *template_decl = dyn_cast<ClassTemplateSpecializationDecl>(cxx_record_decl);
2842                        if (template_decl && arg_idx < template_decl->getTemplateArgs().size())
2843                        {
2844                            const TemplateArgument &template_arg = template_decl->getTemplateArgs()[arg_idx];
2845                            switch (template_arg.getKind())
2846                            {
2847                                case clang::TemplateArgument::Null:
2848                                    kind = eTemplateArgumentKindNull;
2849                                    return NULL;
2850
2851                                case clang::TemplateArgument::Type:
2852                                    kind = eTemplateArgumentKindType;
2853                                    return template_arg.getAsType().getAsOpaquePtr();
2854
2855                                case clang::TemplateArgument::Declaration:
2856                                    kind = eTemplateArgumentKindDeclaration;
2857                                    return NULL;
2858
2859                                case clang::TemplateArgument::Integral:
2860                                    kind = eTemplateArgumentKindIntegral;
2861                                    return template_arg.getIntegralType().getAsOpaquePtr();
2862
2863                                case clang::TemplateArgument::Template:
2864                                    kind = eTemplateArgumentKindTemplate;
2865                                    return NULL;
2866
2867                                case clang::TemplateArgument::TemplateExpansion:
2868                                    kind = eTemplateArgumentKindTemplateExpansion;
2869                                    return NULL;
2870
2871                                case clang::TemplateArgument::Expression:
2872                                    kind = eTemplateArgumentKindExpression;
2873                                    return NULL;
2874
2875                                case clang::TemplateArgument::Pack:
2876                                    kind = eTemplateArgumentKindPack;
2877                                    return NULL;
2878
2879                                default:
2880                                    assert (!"Unhandled TemplateArgument::ArgKind");
2881                                    kind = eTemplateArgumentKindNull;
2882                                    return NULL;
2883                            }
2884                        }
2885                    }
2886                }
2887                break;
2888
2889            case clang::Type::Typedef:
2890                return ClangASTContext::GetTemplateArgument (ast, cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(), arg_idx, kind);
2891
2892            case clang::Type::Elaborated:
2893                return ClangASTContext::GetTemplateArgument (ast, cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(), arg_idx, kind);
2894
2895            default:
2896                break;
2897        }
2898    }
2899    kind = eTemplateArgumentKindNull;
2900    return NULL;
2901}
2902
2903uint32_t
2904ClangASTContext::GetTypeInfo
2905(
2906    clang_type_t clang_type,
2907    clang::ASTContext *ast,
2908    clang_type_t *pointee_or_element_clang_type
2909)
2910{
2911    if (clang_type == NULL)
2912        return 0;
2913
2914    if (pointee_or_element_clang_type)
2915        *pointee_or_element_clang_type = NULL;
2916
2917    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
2918
2919    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2920    switch (type_class)
2921    {
2922    case clang::Type::Builtin:
2923        switch (cast<clang::BuiltinType>(qual_type)->getKind())
2924        {
2925        case clang::BuiltinType::ObjCId:
2926        case clang::BuiltinType::ObjCClass:
2927            if (ast && pointee_or_element_clang_type)
2928                *pointee_or_element_clang_type = ast->ObjCBuiltinClassTy.getAsOpaquePtr();
2929            return eTypeIsBuiltIn | eTypeIsPointer | eTypeHasValue | eTypeIsObjC;
2930                break;
2931        case clang::BuiltinType::Bool:
2932        case clang::BuiltinType::Char_U:
2933        case clang::BuiltinType::UChar:
2934        case clang::BuiltinType::WChar_U:
2935        case clang::BuiltinType::Char16:
2936        case clang::BuiltinType::Char32:
2937        case clang::BuiltinType::UShort:
2938        case clang::BuiltinType::UInt:
2939        case clang::BuiltinType::ULong:
2940        case clang::BuiltinType::ULongLong:
2941        case clang::BuiltinType::UInt128:
2942        case clang::BuiltinType::Char_S:
2943        case clang::BuiltinType::SChar:
2944        case clang::BuiltinType::WChar_S:
2945        case clang::BuiltinType::Short:
2946        case clang::BuiltinType::Int:
2947        case clang::BuiltinType::Long:
2948        case clang::BuiltinType::LongLong:
2949        case clang::BuiltinType::Int128:
2950        case clang::BuiltinType::Float:
2951        case clang::BuiltinType::Double:
2952        case clang::BuiltinType::LongDouble:
2953                return eTypeIsBuiltIn | eTypeHasValue | eTypeIsScalar;
2954        default:
2955            break;
2956        }
2957        return eTypeIsBuiltIn | eTypeHasValue;
2958
2959    case clang::Type::BlockPointer:
2960        if (pointee_or_element_clang_type)
2961            *pointee_or_element_clang_type = qual_type->getPointeeType().getAsOpaquePtr();
2962        return eTypeIsPointer | eTypeHasChildren | eTypeIsBlock;
2963
2964    case clang::Type::Complex:                          return eTypeIsBuiltIn | eTypeHasValue;
2965
2966    case clang::Type::ConstantArray:
2967    case clang::Type::DependentSizedArray:
2968    case clang::Type::IncompleteArray:
2969    case clang::Type::VariableArray:
2970        if (pointee_or_element_clang_type)
2971            *pointee_or_element_clang_type = cast<ArrayType>(qual_type.getTypePtr())->getElementType().getAsOpaquePtr();
2972        return eTypeHasChildren | eTypeIsArray;
2973
2974    case clang::Type::DependentName:                    return 0;
2975    case clang::Type::DependentSizedExtVector:          return eTypeHasChildren | eTypeIsVector;
2976    case clang::Type::DependentTemplateSpecialization:  return eTypeIsTemplate;
2977    case clang::Type::Decltype:                         return 0;
2978
2979    case clang::Type::Enum:
2980        if (pointee_or_element_clang_type)
2981            *pointee_or_element_clang_type = cast<EnumType>(qual_type)->getDecl()->getIntegerType().getAsOpaquePtr();
2982        return eTypeIsEnumeration | eTypeHasValue;
2983
2984    case clang::Type::Elaborated:
2985        return ClangASTContext::GetTypeInfo (cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(),
2986                                             ast,
2987                                             pointee_or_element_clang_type);
2988    case clang::Type::ExtVector:                        return eTypeHasChildren | eTypeIsVector;
2989    case clang::Type::FunctionProto:                    return eTypeIsFuncPrototype | eTypeHasValue;
2990    case clang::Type::FunctionNoProto:                  return eTypeIsFuncPrototype | eTypeHasValue;
2991    case clang::Type::InjectedClassName:                return 0;
2992
2993    case clang::Type::LValueReference:
2994    case clang::Type::RValueReference:
2995        if (pointee_or_element_clang_type)
2996            *pointee_or_element_clang_type = cast<ReferenceType>(qual_type.getTypePtr())->getPointeeType().getAsOpaquePtr();
2997        return eTypeHasChildren | eTypeIsReference | eTypeHasValue;
2998
2999    case clang::Type::MemberPointer:                    return eTypeIsPointer   | eTypeIsMember | eTypeHasValue;
3000
3001    case clang::Type::ObjCObjectPointer:
3002        if (pointee_or_element_clang_type)
3003            *pointee_or_element_clang_type = qual_type->getPointeeType().getAsOpaquePtr();
3004        return eTypeHasChildren | eTypeIsObjC | eTypeIsClass | eTypeIsPointer | eTypeHasValue;
3005
3006    case clang::Type::ObjCObject:                       return eTypeHasChildren | eTypeIsObjC | eTypeIsClass;
3007    case clang::Type::ObjCInterface:                    return eTypeHasChildren | eTypeIsObjC | eTypeIsClass;
3008
3009    case clang::Type::Pointer:
3010        if (pointee_or_element_clang_type)
3011            *pointee_or_element_clang_type = qual_type->getPointeeType().getAsOpaquePtr();
3012        return eTypeHasChildren | eTypeIsPointer | eTypeHasValue;
3013
3014    case clang::Type::Record:
3015        if (qual_type->getAsCXXRecordDecl())
3016            return eTypeHasChildren | eTypeIsClass | eTypeIsCPlusPlus;
3017        else
3018            return eTypeHasChildren | eTypeIsStructUnion;
3019        break;
3020    case clang::Type::SubstTemplateTypeParm:            return eTypeIsTemplate;
3021    case clang::Type::TemplateTypeParm:                 return eTypeIsTemplate;
3022    case clang::Type::TemplateSpecialization:           return eTypeIsTemplate;
3023
3024    case clang::Type::Typedef:
3025        return eTypeIsTypedef | ClangASTContext::GetTypeInfo (cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(),
3026                                                                  ast,
3027                                                                  pointee_or_element_clang_type);
3028
3029    case clang::Type::TypeOfExpr:                       return 0;
3030    case clang::Type::TypeOf:                           return 0;
3031    case clang::Type::UnresolvedUsing:                  return 0;
3032    case clang::Type::Vector:                           return eTypeHasChildren | eTypeIsVector;
3033    default:                                            return 0;
3034    }
3035    return 0;
3036}
3037
3038
3039#pragma mark Aggregate Types
3040
3041bool
3042ClangASTContext::IsAggregateType (clang_type_t clang_type)
3043{
3044    if (clang_type == NULL)
3045        return false;
3046
3047    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
3048
3049    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3050    switch (type_class)
3051    {
3052    case clang::Type::IncompleteArray:
3053    case clang::Type::VariableArray:
3054    case clang::Type::ConstantArray:
3055    case clang::Type::ExtVector:
3056    case clang::Type::Vector:
3057    case clang::Type::Record:
3058    case clang::Type::ObjCObject:
3059    case clang::Type::ObjCInterface:
3060        return true;
3061    case clang::Type::Elaborated:
3062        return ClangASTContext::IsAggregateType (cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
3063    case clang::Type::Typedef:
3064        return ClangASTContext::IsAggregateType (cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
3065
3066    default:
3067        break;
3068    }
3069    // The clang type does have a value
3070    return false;
3071}
3072
3073uint32_t
3074ClangASTContext::GetNumChildren (clang::ASTContext *ast, clang_type_t clang_type, bool omit_empty_base_classes)
3075{
3076    if (clang_type == NULL)
3077        return 0;
3078
3079    uint32_t num_children = 0;
3080    QualType qual_type(QualType::getFromOpaquePtr(clang_type));
3081    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3082    switch (type_class)
3083    {
3084    case clang::Type::Builtin:
3085        switch (cast<clang::BuiltinType>(qual_type)->getKind())
3086        {
3087        case clang::BuiltinType::ObjCId:    // child is Class
3088        case clang::BuiltinType::ObjCClass: // child is Class
3089            num_children = 1;
3090            break;
3091
3092        default:
3093            break;
3094        }
3095        break;
3096
3097    case clang::Type::Complex: return 0;
3098
3099    case clang::Type::Record:
3100        if (GetCompleteQualType (ast, qual_type))
3101        {
3102            const RecordType *record_type = cast<RecordType>(qual_type.getTypePtr());
3103            const RecordDecl *record_decl = record_type->getDecl();
3104            assert(record_decl);
3105            const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
3106            if (cxx_record_decl)
3107            {
3108                if (omit_empty_base_classes)
3109                {
3110                    // Check each base classes to see if it or any of its
3111                    // base classes contain any fields. This can help
3112                    // limit the noise in variable views by not having to
3113                    // show base classes that contain no members.
3114                    CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
3115                    for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
3116                         base_class != base_class_end;
3117                         ++base_class)
3118                    {
3119                        const CXXRecordDecl *base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
3120
3121                        // Skip empty base classes
3122                        if (RecordHasFields(base_class_decl) == false)
3123                            continue;
3124
3125                        num_children++;
3126                    }
3127                }
3128                else
3129                {
3130                    // Include all base classes
3131                    num_children += cxx_record_decl->getNumBases();
3132                }
3133
3134            }
3135            RecordDecl::field_iterator field, field_end;
3136            for (field = record_decl->field_begin(), field_end = record_decl->field_end(); field != field_end; ++field)
3137                ++num_children;
3138        }
3139        break;
3140
3141    case clang::Type::ObjCObject:
3142    case clang::Type::ObjCInterface:
3143        if (GetCompleteQualType (ast, qual_type))
3144        {
3145            const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(qual_type.getTypePtr());
3146            assert (objc_class_type);
3147            if (objc_class_type)
3148            {
3149                ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
3150
3151                if (class_interface_decl)
3152                {
3153
3154                    ObjCInterfaceDecl *superclass_interface_decl = class_interface_decl->getSuperClass();
3155                    if (superclass_interface_decl)
3156                    {
3157                        if (omit_empty_base_classes)
3158                        {
3159                            if (ClangASTContext::ObjCDeclHasIVars (superclass_interface_decl, true))
3160                                ++num_children;
3161                        }
3162                        else
3163                            ++num_children;
3164                    }
3165
3166                    num_children += class_interface_decl->ivar_size();
3167                }
3168            }
3169        }
3170        break;
3171
3172    case clang::Type::ObjCObjectPointer:
3173        {
3174            const ObjCObjectPointerType *pointer_type = cast<ObjCObjectPointerType>(qual_type.getTypePtr());
3175            QualType pointee_type = pointer_type->getPointeeType();
3176            uint32_t num_pointee_children = ClangASTContext::GetNumChildren (ast,
3177                                                                             pointee_type.getAsOpaquePtr(),
3178                                                                             omit_empty_base_classes);
3179            // If this type points to a simple type, then it has 1 child
3180            if (num_pointee_children == 0)
3181                num_children = 1;
3182            else
3183                num_children = num_pointee_children;
3184        }
3185        break;
3186
3187    case clang::Type::ConstantArray:
3188        num_children = cast<ConstantArrayType>(qual_type.getTypePtr())->getSize().getLimitedValue();
3189        break;
3190
3191    case clang::Type::Pointer:
3192        {
3193            const PointerType *pointer_type = cast<PointerType>(qual_type.getTypePtr());
3194            QualType pointee_type (pointer_type->getPointeeType());
3195            uint32_t num_pointee_children = ClangASTContext::GetNumChildren (ast,
3196                                                                             pointee_type.getAsOpaquePtr(),
3197                                                                             omit_empty_base_classes);
3198            if (num_pointee_children == 0)
3199            {
3200                // We have a pointer to a pointee type that claims it has no children.
3201                // We will want to look at
3202                num_children = ClangASTContext::GetNumPointeeChildren (pointee_type.getAsOpaquePtr());
3203            }
3204            else
3205                num_children = num_pointee_children;
3206        }
3207        break;
3208
3209    case clang::Type::LValueReference:
3210    case clang::Type::RValueReference:
3211        {
3212            const ReferenceType *reference_type = cast<ReferenceType>(qual_type.getTypePtr());
3213            QualType pointee_type = reference_type->getPointeeType();
3214            uint32_t num_pointee_children = ClangASTContext::GetNumChildren (ast,
3215                                                                             pointee_type.getAsOpaquePtr(),
3216                                                                             omit_empty_base_classes);
3217            // If this type points to a simple type, then it has 1 child
3218            if (num_pointee_children == 0)
3219                num_children = 1;
3220            else
3221                num_children = num_pointee_children;
3222        }
3223        break;
3224
3225
3226    case clang::Type::Typedef:
3227        num_children = ClangASTContext::GetNumChildren (ast,
3228                                                        cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(),
3229                                                        omit_empty_base_classes);
3230        break;
3231
3232    case clang::Type::Elaborated:
3233        num_children = ClangASTContext::GetNumChildren (ast,
3234                                                        cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(),
3235                                                        omit_empty_base_classes);
3236        break;
3237
3238    default:
3239        break;
3240    }
3241    return num_children;
3242}
3243
3244uint32_t
3245ClangASTContext::GetNumDirectBaseClasses (clang::ASTContext *ast, clang_type_t clang_type)
3246{
3247    if (clang_type == NULL)
3248        return 0;
3249
3250    uint32_t count = 0;
3251    QualType qual_type(QualType::getFromOpaquePtr(clang_type));
3252    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3253    switch (type_class)
3254    {
3255        case clang::Type::Record:
3256            if (GetCompleteQualType (ast, qual_type))
3257            {
3258                const CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
3259                if (cxx_record_decl)
3260                    count = cxx_record_decl->getNumBases();
3261            }
3262            break;
3263
3264        case clang::Type::ObjCObject:
3265        case clang::Type::ObjCInterface:
3266            if (GetCompleteQualType (ast, qual_type))
3267            {
3268                const ObjCObjectType *objc_class_type = qual_type->getAsObjCQualifiedInterfaceType();
3269                if (objc_class_type)
3270                {
3271                    ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
3272
3273                    if (class_interface_decl && class_interface_decl->getSuperClass())
3274                        count = 1;
3275                }
3276            }
3277            break;
3278
3279
3280        case clang::Type::Typedef:
3281            count = ClangASTContext::GetNumDirectBaseClasses (ast, cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
3282            break;
3283
3284        case clang::Type::Elaborated:
3285            count = ClangASTContext::GetNumDirectBaseClasses (ast, cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
3286            break;
3287
3288        default:
3289            break;
3290    }
3291    return count;
3292}
3293
3294uint32_t
3295ClangASTContext::GetNumVirtualBaseClasses (clang::ASTContext *ast,
3296                                           clang_type_t clang_type)
3297{
3298    if (clang_type == NULL)
3299        return 0;
3300
3301    uint32_t count = 0;
3302    QualType qual_type(QualType::getFromOpaquePtr(clang_type));
3303    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3304    switch (type_class)
3305    {
3306        case clang::Type::Record:
3307            if (GetCompleteQualType (ast, qual_type))
3308            {
3309                const CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
3310                if (cxx_record_decl)
3311                    count = cxx_record_decl->getNumVBases();
3312            }
3313            break;
3314
3315        case clang::Type::Typedef:
3316            count = ClangASTContext::GetNumVirtualBaseClasses (ast, cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
3317            break;
3318
3319        case clang::Type::Elaborated:
3320            count = ClangASTContext::GetNumVirtualBaseClasses (ast, cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
3321            break;
3322
3323        default:
3324            break;
3325    }
3326    return count;
3327}
3328
3329uint32_t
3330ClangASTContext::GetNumFields (clang::ASTContext *ast, clang_type_t clang_type)
3331{
3332    if (clang_type == NULL)
3333        return 0;
3334
3335    uint32_t count = 0;
3336    QualType qual_type(QualType::getFromOpaquePtr(clang_type));
3337    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3338    switch (type_class)
3339    {
3340        case clang::Type::Record:
3341            if (GetCompleteQualType (ast, qual_type))
3342            {
3343                const RecordType *record_type = dyn_cast<RecordType>(qual_type.getTypePtr());
3344                if (record_type)
3345                {
3346                    RecordDecl *record_decl = record_type->getDecl();
3347                    if (record_decl)
3348                    {
3349                        uint32_t field_idx = 0;
3350                        RecordDecl::field_iterator field, field_end;
3351                        for (field = record_decl->field_begin(), field_end = record_decl->field_end(); field != field_end; ++field)
3352                            ++field_idx;
3353                        count = field_idx;
3354                    }
3355                }
3356            }
3357            break;
3358
3359        case clang::Type::Typedef:
3360            count = ClangASTContext::GetNumFields (ast, cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
3361            break;
3362
3363        case clang::Type::Elaborated:
3364            count = ClangASTContext::GetNumFields (ast, cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
3365            break;
3366
3367        case clang::Type::ObjCObject:
3368        case clang::Type::ObjCInterface:
3369            if (GetCompleteQualType (ast, qual_type))
3370            {
3371                const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(qual_type.getTypePtr());
3372                if (objc_class_type)
3373                {
3374                    ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
3375
3376                    if (class_interface_decl)
3377                        count = class_interface_decl->ivar_size();
3378                }
3379            }
3380            break;
3381
3382        default:
3383            break;
3384    }
3385    return count;
3386}
3387
3388clang_type_t
3389ClangASTContext::GetDirectBaseClassAtIndex (clang::ASTContext *ast,
3390                                            clang_type_t clang_type,
3391                                            size_t idx,
3392                                            uint32_t *bit_offset_ptr)
3393{
3394    if (clang_type == NULL)
3395        return 0;
3396
3397    QualType qual_type(QualType::getFromOpaquePtr(clang_type));
3398    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3399    switch (type_class)
3400    {
3401        case clang::Type::Record:
3402            if (GetCompleteQualType (ast, qual_type))
3403            {
3404                const CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
3405                if (cxx_record_decl)
3406                {
3407                    uint32_t curr_idx = 0;
3408                    CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
3409                    for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
3410                         base_class != base_class_end;
3411                         ++base_class, ++curr_idx)
3412                    {
3413                        if (curr_idx == idx)
3414                        {
3415                            if (bit_offset_ptr)
3416                            {
3417                                const ASTRecordLayout &record_layout = ast->getASTRecordLayout(cxx_record_decl);
3418                                const CXXRecordDecl *base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
3419//                                if (base_class->isVirtual())
3420//                                    *bit_offset_ptr = record_layout.getVBaseClassOffset(base_class_decl).getQuantity() * 8;
3421//                                else
3422                                    *bit_offset_ptr = record_layout.getBaseClassOffset(base_class_decl).getQuantity() * 8;
3423                            }
3424                            return base_class->getType().getAsOpaquePtr();
3425                        }
3426                    }
3427                }
3428            }
3429            break;
3430
3431        case clang::Type::ObjCObject:
3432        case clang::Type::ObjCInterface:
3433            if (idx == 0 && GetCompleteQualType (ast, qual_type))
3434            {
3435                const ObjCObjectType *objc_class_type = qual_type->getAsObjCQualifiedInterfaceType();
3436                if (objc_class_type)
3437                {
3438                    ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
3439
3440                    if (class_interface_decl)
3441                    {
3442                        ObjCInterfaceDecl *superclass_interface_decl = class_interface_decl->getSuperClass();
3443                        if (superclass_interface_decl)
3444                        {
3445                            if (bit_offset_ptr)
3446                                *bit_offset_ptr = 0;
3447                            return ast->getObjCInterfaceType(superclass_interface_decl).getAsOpaquePtr();
3448                        }
3449                    }
3450                }
3451            }
3452            break;
3453
3454
3455        case clang::Type::Typedef:
3456            return ClangASTContext::GetDirectBaseClassAtIndex (ast,
3457                                                               cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(),
3458                                                               idx,
3459                                                               bit_offset_ptr);
3460
3461        case clang::Type::Elaborated:
3462            return  ClangASTContext::GetDirectBaseClassAtIndex (ast,
3463                                                                cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(),
3464                                                                idx,
3465                                                                bit_offset_ptr);
3466
3467        default:
3468            break;
3469    }
3470    return NULL;
3471}
3472
3473clang_type_t
3474ClangASTContext::GetVirtualBaseClassAtIndex (clang::ASTContext *ast,
3475                                             clang_type_t clang_type,
3476                                             size_t idx,
3477                                             uint32_t *bit_offset_ptr)
3478{
3479    if (clang_type == NULL)
3480        return 0;
3481
3482    QualType qual_type(QualType::getFromOpaquePtr(clang_type));
3483    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3484    switch (type_class)
3485    {
3486        case clang::Type::Record:
3487            if (GetCompleteQualType (ast, qual_type))
3488            {
3489                const CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
3490                if (cxx_record_decl)
3491                {
3492                    uint32_t curr_idx = 0;
3493                    CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
3494                    for (base_class = cxx_record_decl->vbases_begin(), base_class_end = cxx_record_decl->vbases_end();
3495                         base_class != base_class_end;
3496                         ++base_class, ++curr_idx)
3497                    {
3498                        if (curr_idx == idx)
3499                        {
3500                            if (bit_offset_ptr)
3501                            {
3502                                const ASTRecordLayout &record_layout = ast->getASTRecordLayout(cxx_record_decl);
3503                                const CXXRecordDecl *base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
3504                                *bit_offset_ptr = record_layout.getVBaseClassOffset(base_class_decl).getQuantity() * 8;
3505
3506                            }
3507                            return base_class->getType().getAsOpaquePtr();
3508                        }
3509                    }
3510                }
3511            }
3512            break;
3513
3514        case clang::Type::Typedef:
3515            return ClangASTContext::GetVirtualBaseClassAtIndex (ast,
3516                                                                cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(),
3517                                                                idx,
3518                                                                bit_offset_ptr);
3519
3520        case clang::Type::Elaborated:
3521            return  ClangASTContext::GetVirtualBaseClassAtIndex (ast,
3522                                                                 cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(),
3523                                                                 idx,
3524                                                                 bit_offset_ptr);
3525
3526        default:
3527            break;
3528    }
3529    return NULL;
3530}
3531
3532clang_type_t
3533ClangASTContext::GetFieldAtIndex (clang::ASTContext *ast,
3534                                  clang_type_t clang_type,
3535                                  size_t idx,
3536                                  std::string& name,
3537                                  uint64_t *bit_offset_ptr,
3538                                  uint32_t *bitfield_bit_size_ptr,
3539                                  bool *is_bitfield_ptr)
3540{
3541    if (clang_type == NULL)
3542        return 0;
3543
3544    QualType qual_type(QualType::getFromOpaquePtr(clang_type));
3545    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3546    switch (type_class)
3547    {
3548        case clang::Type::Record:
3549            if (GetCompleteQualType (ast, qual_type))
3550            {
3551                const RecordType *record_type = cast<RecordType>(qual_type.getTypePtr());
3552                const RecordDecl *record_decl = record_type->getDecl();
3553                uint32_t field_idx = 0;
3554                RecordDecl::field_iterator field, field_end;
3555                for (field = record_decl->field_begin(), field_end = record_decl->field_end(); field != field_end; ++field, ++field_idx)
3556                {
3557                    if (idx == field_idx)
3558                    {
3559                        // Print the member type if requested
3560                        // Print the member name and equal sign
3561                        name.assign(field->getNameAsString());
3562
3563                        // Figure out the type byte size (field_type_info.first) and
3564                        // alignment (field_type_info.second) from the AST context.
3565                        if (bit_offset_ptr)
3566                        {
3567                            const ASTRecordLayout &record_layout = ast->getASTRecordLayout(record_decl);
3568                            *bit_offset_ptr = record_layout.getFieldOffset (field_idx);
3569                        }
3570
3571                        const bool is_bitfield = field->isBitField();
3572
3573                        if (bitfield_bit_size_ptr)
3574                        {
3575                            *bitfield_bit_size_ptr = 0;
3576
3577                            if (is_bitfield && ast)
3578                            {
3579                                Expr *bitfield_bit_size_expr = field->getBitWidth();
3580                                llvm::APSInt bitfield_apsint;
3581                                if (bitfield_bit_size_expr && bitfield_bit_size_expr->EvaluateAsInt(bitfield_apsint, *ast))
3582                                {
3583                                    *bitfield_bit_size_ptr = bitfield_apsint.getLimitedValue();
3584                                }
3585                            }
3586                        }
3587                        if (is_bitfield_ptr)
3588                            *is_bitfield_ptr = is_bitfield;
3589
3590                        return field->getType().getAsOpaquePtr();
3591                    }
3592                }
3593            }
3594            break;
3595
3596        case clang::Type::ObjCObject:
3597        case clang::Type::ObjCInterface:
3598            if (GetCompleteQualType (ast, qual_type))
3599            {
3600                const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(qual_type.getTypePtr());
3601                assert (objc_class_type);
3602                if (objc_class_type)
3603                {
3604                    ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
3605
3606                    if (class_interface_decl)
3607                    {
3608                        if (idx < (class_interface_decl->ivar_size()))
3609                        {
3610                            ObjCInterfaceDecl::ivar_iterator ivar_pos, ivar_end = class_interface_decl->ivar_end();
3611                            uint32_t ivar_idx = 0;
3612
3613                            for (ivar_pos = class_interface_decl->ivar_begin(); ivar_pos != ivar_end; ++ivar_pos, ++ivar_idx)
3614                            {
3615                                if (ivar_idx == idx)
3616                                {
3617                                    const ObjCIvarDecl* ivar_decl = *ivar_pos;
3618
3619                                    QualType ivar_qual_type(ivar_decl->getType());
3620
3621                                    name.assign(ivar_decl->getNameAsString());
3622
3623                                    if (bit_offset_ptr)
3624                                    {
3625                                        const ASTRecordLayout &interface_layout = ast->getASTObjCInterfaceLayout(class_interface_decl);
3626                                        *bit_offset_ptr = interface_layout.getFieldOffset (ivar_idx);
3627                                    }
3628
3629                                    const bool is_bitfield = ivar_pos->isBitField();
3630
3631                                    if (bitfield_bit_size_ptr)
3632                                    {
3633                                        *bitfield_bit_size_ptr = 0;
3634
3635                                        if (is_bitfield && ast)
3636                                        {
3637                                            Expr *bitfield_bit_size_expr = ivar_pos->getBitWidth();
3638                                            llvm::APSInt bitfield_apsint;
3639                                            if (bitfield_bit_size_expr && bitfield_bit_size_expr->EvaluateAsInt(bitfield_apsint, *ast))
3640                                            {
3641                                                *bitfield_bit_size_ptr = bitfield_apsint.getLimitedValue();
3642                                            }
3643                                        }
3644                                    }
3645                                    if (is_bitfield_ptr)
3646                                        *is_bitfield_ptr = is_bitfield;
3647
3648                                    return ivar_qual_type.getAsOpaquePtr();
3649                                }
3650                            }
3651                        }
3652                    }
3653                }
3654            }
3655            break;
3656
3657
3658        case clang::Type::Typedef:
3659            return ClangASTContext::GetFieldAtIndex (ast,
3660                                                     cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(),
3661                                                     idx,
3662                                                     name,
3663                                                     bit_offset_ptr,
3664                                                     bitfield_bit_size_ptr,
3665                                                     is_bitfield_ptr);
3666
3667        case clang::Type::Elaborated:
3668            return  ClangASTContext::GetFieldAtIndex (ast,
3669                                                      cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(),
3670                                                      idx,
3671                                                      name,
3672                                                      bit_offset_ptr,
3673                                                      bitfield_bit_size_ptr,
3674                                                      is_bitfield_ptr);
3675
3676        default:
3677            break;
3678    }
3679    return NULL;
3680}
3681
3682size_t
3683ClangASTContext::GetIndexOfFieldWithName (clang::ASTContext *ast,
3684                                          lldb::clang_type_t clang_type,
3685                                          const char* name,
3686                                          lldb::clang_type_t* field_clang_type,
3687                                          uint64_t *bit_offset_ptr,
3688                                          uint32_t *bitfield_bit_size_ptr,
3689                                          bool *is_bitfield_ptr)
3690{
3691    auto count = ClangASTContext::GetNumFields(ast, clang_type);
3692    lldb::clang_type_t field_clang_type_internal;
3693    std::string field_name;
3694    for (auto index = 0; index < count; index++)
3695    {
3696        field_clang_type_internal = ClangASTContext::GetFieldAtIndex(ast, clang_type, index, field_name, bit_offset_ptr, bitfield_bit_size_ptr, is_bitfield_ptr);
3697        if ( strcmp(field_name.c_str(), name) == 0 )
3698        {
3699            if (field_clang_type)
3700                *field_clang_type = field_clang_type_internal;
3701            return index;
3702        }
3703    }
3704    return UINT32_MAX;
3705}
3706
3707lldb::BasicType
3708ClangASTContext::GetLLDBBasicTypeEnumeration (clang_type_t clang_type)
3709{
3710    if (clang_type)
3711    {
3712        QualType qual_type(QualType::getFromOpaquePtr(clang_type));
3713        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3714        if (type_class == clang::Type::Builtin)
3715        {
3716            switch (cast<clang::BuiltinType>(qual_type)->getKind())
3717            {
3718            case clang::BuiltinType::Void:      return eBasicTypeVoid;
3719            case clang::BuiltinType::Bool:      return eBasicTypeBool;
3720            case clang::BuiltinType::Char_S:    return eBasicTypeSignedChar;
3721            case clang::BuiltinType::Char_U:    return eBasicTypeUnsignedChar;
3722            case clang::BuiltinType::Char16:    return eBasicTypeChar16;
3723            case clang::BuiltinType::Char32:    return eBasicTypeChar32;
3724            case clang::BuiltinType::UChar:     return eBasicTypeUnsignedChar;
3725            case clang::BuiltinType::SChar:     return eBasicTypeSignedChar;
3726            case clang::BuiltinType::WChar_S:   return eBasicTypeSignedWChar;
3727            case clang::BuiltinType::WChar_U:   return eBasicTypeUnsignedWChar;
3728            case clang::BuiltinType::Short:     return eBasicTypeShort;
3729            case clang::BuiltinType::UShort:    return eBasicTypeUnsignedShort;
3730            case clang::BuiltinType::Int:       return eBasicTypeInt;
3731            case clang::BuiltinType::UInt:      return eBasicTypeUnsignedInt;
3732            case clang::BuiltinType::Long:      return eBasicTypeLong;
3733            case clang::BuiltinType::ULong:     return eBasicTypeUnsignedLong;
3734            case clang::BuiltinType::LongLong:  return eBasicTypeLongLong;
3735            case clang::BuiltinType::ULongLong: return eBasicTypeUnsignedLongLong;
3736            case clang::BuiltinType::Int128:    return eBasicTypeInt128;
3737            case clang::BuiltinType::UInt128:   return eBasicTypeUnsignedInt128;
3738
3739            case clang::BuiltinType::Half:      return eBasicTypeHalf;
3740            case clang::BuiltinType::Float:     return eBasicTypeFloat;
3741            case clang::BuiltinType::Double:    return eBasicTypeDouble;
3742            case clang::BuiltinType::LongDouble:return eBasicTypeLongDouble;
3743
3744            case clang::BuiltinType::NullPtr:   return eBasicTypeNullPtr;
3745            case clang::BuiltinType::ObjCId:    return eBasicTypeObjCID;
3746            case clang::BuiltinType::ObjCClass: return eBasicTypeObjCClass;
3747            case clang::BuiltinType::ObjCSel:   return eBasicTypeObjCSel;
3748            case clang::BuiltinType::Dependent:
3749            case clang::BuiltinType::Overload:
3750            case clang::BuiltinType::BoundMember:
3751            case clang::BuiltinType::PseudoObject:
3752            case clang::BuiltinType::UnknownAny:
3753            case clang::BuiltinType::BuiltinFn:
3754            case clang::BuiltinType::ARCUnbridgedCast:
3755            case clang::BuiltinType::OCLEvent:
3756            case clang::BuiltinType::OCLImage1d:
3757            case clang::BuiltinType::OCLImage1dArray:
3758            case clang::BuiltinType::OCLImage1dBuffer:
3759            case clang::BuiltinType::OCLImage2d:
3760            case clang::BuiltinType::OCLImage2dArray:
3761            case clang::BuiltinType::OCLImage3d:
3762            case clang::BuiltinType::OCLSampler:
3763                return eBasicTypeOther;
3764            }
3765        }
3766    }
3767
3768    return eBasicTypeInvalid;
3769}
3770
3771
3772
3773// If a pointer to a pointee type (the clang_type arg) says that it has no
3774// children, then we either need to trust it, or override it and return a
3775// different result. For example, an "int *" has one child that is an integer,
3776// but a function pointer doesn't have any children. Likewise if a Record type
3777// claims it has no children, then there really is nothing to show.
3778uint32_t
3779ClangASTContext::GetNumPointeeChildren (clang_type_t clang_type)
3780{
3781    if (clang_type == NULL)
3782        return 0;
3783
3784    QualType qual_type(QualType::getFromOpaquePtr(clang_type));
3785    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3786    switch (type_class)
3787    {
3788    case clang::Type::Builtin:
3789        switch (cast<clang::BuiltinType>(qual_type)->getKind())
3790        {
3791        case clang::BuiltinType::UnknownAny:
3792        case clang::BuiltinType::Void:
3793        case clang::BuiltinType::NullPtr:
3794        case clang::BuiltinType::OCLEvent:
3795        case clang::BuiltinType::OCLImage1d:
3796        case clang::BuiltinType::OCLImage1dArray:
3797        case clang::BuiltinType::OCLImage1dBuffer:
3798        case clang::BuiltinType::OCLImage2d:
3799        case clang::BuiltinType::OCLImage2dArray:
3800        case clang::BuiltinType::OCLImage3d:
3801        case clang::BuiltinType::OCLSampler:
3802            return 0;
3803        case clang::BuiltinType::Bool:
3804        case clang::BuiltinType::Char_U:
3805        case clang::BuiltinType::UChar:
3806        case clang::BuiltinType::WChar_U:
3807        case clang::BuiltinType::Char16:
3808        case clang::BuiltinType::Char32:
3809        case clang::BuiltinType::UShort:
3810        case clang::BuiltinType::UInt:
3811        case clang::BuiltinType::ULong:
3812        case clang::BuiltinType::ULongLong:
3813        case clang::BuiltinType::UInt128:
3814        case clang::BuiltinType::Char_S:
3815        case clang::BuiltinType::SChar:
3816        case clang::BuiltinType::WChar_S:
3817        case clang::BuiltinType::Short:
3818        case clang::BuiltinType::Int:
3819        case clang::BuiltinType::Long:
3820        case clang::BuiltinType::LongLong:
3821        case clang::BuiltinType::Int128:
3822        case clang::BuiltinType::Float:
3823        case clang::BuiltinType::Double:
3824        case clang::BuiltinType::LongDouble:
3825        case clang::BuiltinType::Dependent:
3826        case clang::BuiltinType::Overload:
3827        case clang::BuiltinType::ObjCId:
3828        case clang::BuiltinType::ObjCClass:
3829        case clang::BuiltinType::ObjCSel:
3830        case clang::BuiltinType::BoundMember:
3831        case clang::BuiltinType::Half:
3832        case clang::BuiltinType::ARCUnbridgedCast:
3833        case clang::BuiltinType::PseudoObject:
3834        case clang::BuiltinType::BuiltinFn:
3835            return 1;
3836        }
3837        break;
3838
3839    case clang::Type::Complex:                  return 1;
3840    case clang::Type::Pointer:                  return 1;
3841    case clang::Type::BlockPointer:             return 0;   // If block pointers don't have debug info, then no children for them
3842    case clang::Type::LValueReference:          return 1;
3843    case clang::Type::RValueReference:          return 1;
3844    case clang::Type::MemberPointer:            return 0;
3845    case clang::Type::ConstantArray:            return 0;
3846    case clang::Type::IncompleteArray:          return 0;
3847    case clang::Type::VariableArray:            return 0;
3848    case clang::Type::DependentSizedArray:      return 0;
3849    case clang::Type::DependentSizedExtVector:  return 0;
3850    case clang::Type::Vector:                   return 0;
3851    case clang::Type::ExtVector:                return 0;
3852    case clang::Type::FunctionProto:            return 0;   // When we function pointers, they have no children...
3853    case clang::Type::FunctionNoProto:          return 0;   // When we function pointers, they have no children...
3854    case clang::Type::UnresolvedUsing:          return 0;
3855    case clang::Type::Paren:                    return 0;
3856    case clang::Type::Typedef:                  return ClangASTContext::GetNumPointeeChildren (cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
3857    case clang::Type::Elaborated:               return ClangASTContext::GetNumPointeeChildren (cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
3858    case clang::Type::TypeOfExpr:               return 0;
3859    case clang::Type::TypeOf:                   return 0;
3860    case clang::Type::Decltype:                 return 0;
3861    case clang::Type::Record:                   return 0;
3862    case clang::Type::Enum:                     return 1;
3863    case clang::Type::TemplateTypeParm:         return 1;
3864    case clang::Type::SubstTemplateTypeParm:    return 1;
3865    case clang::Type::TemplateSpecialization:   return 1;
3866    case clang::Type::InjectedClassName:        return 0;
3867    case clang::Type::DependentName:            return 1;
3868    case clang::Type::DependentTemplateSpecialization:  return 1;
3869    case clang::Type::ObjCObject:               return 0;
3870    case clang::Type::ObjCInterface:            return 0;
3871    case clang::Type::ObjCObjectPointer:        return 1;
3872    default:
3873        break;
3874    }
3875    return 0;
3876}
3877
3878clang_type_t
3879ClangASTContext::GetChildClangTypeAtIndex
3880(
3881    ExecutionContext *exe_ctx,
3882    const char *parent_name,
3883    clang_type_t parent_clang_type,
3884    size_t idx,
3885    bool transparent_pointers,
3886    bool omit_empty_base_classes,
3887    bool ignore_array_bounds,
3888    std::string& child_name,
3889    uint32_t &child_byte_size,
3890    int32_t &child_byte_offset,
3891    uint32_t &child_bitfield_bit_size,
3892    uint32_t &child_bitfield_bit_offset,
3893    bool &child_is_base_class,
3894    bool &child_is_deref_of_parent
3895)
3896{
3897    if (parent_clang_type)
3898
3899        return GetChildClangTypeAtIndex (exe_ctx,
3900                                         getASTContext(),
3901                                         parent_name,
3902                                         parent_clang_type,
3903                                         idx,
3904                                         transparent_pointers,
3905                                         omit_empty_base_classes,
3906                                         ignore_array_bounds,
3907                                         child_name,
3908                                         child_byte_size,
3909                                         child_byte_offset,
3910                                         child_bitfield_bit_size,
3911                                         child_bitfield_bit_offset,
3912                                         child_is_base_class,
3913                                         child_is_deref_of_parent);
3914    return NULL;
3915}
3916
3917clang_type_t
3918ClangASTContext::GetChildClangTypeAtIndex
3919(
3920    ExecutionContext *exe_ctx,
3921    ASTContext *ast,
3922    const char *parent_name,
3923    clang_type_t parent_clang_type,
3924    size_t idx,
3925    bool transparent_pointers,
3926    bool omit_empty_base_classes,
3927    bool ignore_array_bounds,
3928    std::string& child_name,
3929    uint32_t &child_byte_size,
3930    int32_t &child_byte_offset,
3931    uint32_t &child_bitfield_bit_size,
3932    uint32_t &child_bitfield_bit_offset,
3933    bool &child_is_base_class,
3934    bool &child_is_deref_of_parent
3935)
3936{
3937    if (parent_clang_type == NULL)
3938        return NULL;
3939
3940    QualType parent_qual_type(QualType::getFromOpaquePtr(parent_clang_type));
3941    const clang::Type::TypeClass parent_type_class = parent_qual_type->getTypeClass();
3942    child_bitfield_bit_size = 0;
3943    child_bitfield_bit_offset = 0;
3944    child_is_base_class = false;
3945
3946    const bool idx_is_valid = idx < ClangASTContext::GetNumChildren (ast, parent_clang_type, omit_empty_base_classes);
3947    uint32_t bit_offset;
3948    switch (parent_type_class)
3949    {
3950    case clang::Type::Builtin:
3951        if (idx_is_valid)
3952        {
3953            switch (cast<clang::BuiltinType>(parent_qual_type)->getKind())
3954            {
3955            case clang::BuiltinType::ObjCId:
3956            case clang::BuiltinType::ObjCClass:
3957                child_name = "isa";
3958                child_byte_size = ast->getTypeSize(ast->ObjCBuiltinClassTy) / CHAR_BIT;
3959                return ast->ObjCBuiltinClassTy.getAsOpaquePtr();
3960
3961            default:
3962                break;
3963            }
3964        }
3965        break;
3966
3967    case clang::Type::Record:
3968        if (idx_is_valid && GetCompleteQualType (ast, parent_qual_type))
3969        {
3970            const RecordType *record_type = cast<RecordType>(parent_qual_type.getTypePtr());
3971            const RecordDecl *record_decl = record_type->getDecl();
3972            assert(record_decl);
3973            const ASTRecordLayout &record_layout = ast->getASTRecordLayout(record_decl);
3974            uint32_t child_idx = 0;
3975
3976            const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
3977            if (cxx_record_decl)
3978            {
3979                // We might have base classes to print out first
3980                CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
3981                for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
3982                     base_class != base_class_end;
3983                     ++base_class)
3984                {
3985                    const CXXRecordDecl *base_class_decl = NULL;
3986
3987                    // Skip empty base classes
3988                    if (omit_empty_base_classes)
3989                    {
3990                        base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
3991                        if (RecordHasFields(base_class_decl) == false)
3992                            continue;
3993                    }
3994
3995                    if (idx == child_idx)
3996                    {
3997                        if (base_class_decl == NULL)
3998                            base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
3999
4000
4001                        if (base_class->isVirtual())
4002                            bit_offset = record_layout.getVBaseClassOffset(base_class_decl).getQuantity() * 8;
4003                        else
4004                            bit_offset = record_layout.getBaseClassOffset(base_class_decl).getQuantity() * 8;
4005
4006                        // Base classes should be a multiple of 8 bits in size
4007                        child_byte_offset = bit_offset/8;
4008
4009                        child_name = ClangASTType::GetTypeNameForQualType(ast, base_class->getType());
4010
4011                        uint64_t clang_type_info_bit_size = ast->getTypeSize(base_class->getType());
4012
4013                        // Base classes bit sizes should be a multiple of 8 bits in size
4014                        assert (clang_type_info_bit_size % 8 == 0);
4015                        child_byte_size = clang_type_info_bit_size / 8;
4016                        child_is_base_class = true;
4017                        return base_class->getType().getAsOpaquePtr();
4018                    }
4019                    // We don't increment the child index in the for loop since we might
4020                    // be skipping empty base classes
4021                    ++child_idx;
4022                }
4023            }
4024            // Make sure index is in range...
4025            uint32_t field_idx = 0;
4026            RecordDecl::field_iterator field, field_end;
4027            for (field = record_decl->field_begin(), field_end = record_decl->field_end(); field != field_end; ++field, ++field_idx, ++child_idx)
4028            {
4029                if (idx == child_idx)
4030                {
4031                    // Print the member type if requested
4032                    // Print the member name and equal sign
4033                    child_name.assign(field->getNameAsString().c_str());
4034
4035                    // Figure out the type byte size (field_type_info.first) and
4036                    // alignment (field_type_info.second) from the AST context.
4037                    std::pair<uint64_t, unsigned> field_type_info = ast->getTypeInfo(field->getType());
4038                    assert(field_idx < record_layout.getFieldCount());
4039
4040                    child_byte_size = field_type_info.first / 8;
4041
4042                    // Figure out the field offset within the current struct/union/class type
4043                    bit_offset = record_layout.getFieldOffset (field_idx);
4044                    child_byte_offset = bit_offset / 8;
4045                    if (ClangASTContext::FieldIsBitfield (ast, *field, child_bitfield_bit_size))
4046                        child_bitfield_bit_offset = bit_offset % 8;
4047
4048                    return field->getType().getAsOpaquePtr();
4049                }
4050            }
4051        }
4052        break;
4053
4054    case clang::Type::ObjCObject:
4055    case clang::Type::ObjCInterface:
4056        if (idx_is_valid && GetCompleteQualType (ast, parent_qual_type))
4057        {
4058            const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(parent_qual_type.getTypePtr());
4059            assert (objc_class_type);
4060            if (objc_class_type)
4061            {
4062                uint32_t child_idx = 0;
4063                ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
4064
4065                if (class_interface_decl)
4066                {
4067
4068                    const ASTRecordLayout &interface_layout = ast->getASTObjCInterfaceLayout(class_interface_decl);
4069                    ObjCInterfaceDecl *superclass_interface_decl = class_interface_decl->getSuperClass();
4070                    if (superclass_interface_decl)
4071                    {
4072                        if (omit_empty_base_classes)
4073                        {
4074                            if (ClangASTContext::GetNumChildren(ast, ast->getObjCInterfaceType(superclass_interface_decl).getAsOpaquePtr(), omit_empty_base_classes) > 0)
4075                            {
4076                                if (idx == 0)
4077                                {
4078                                    QualType ivar_qual_type(ast->getObjCInterfaceType(superclass_interface_decl));
4079
4080
4081                                    child_name.assign(superclass_interface_decl->getNameAsString().c_str());
4082
4083                                    std::pair<uint64_t, unsigned> ivar_type_info = ast->getTypeInfo(ivar_qual_type.getTypePtr());
4084
4085                                    child_byte_size = ivar_type_info.first / 8;
4086                                    child_byte_offset = 0;
4087                                    child_is_base_class = true;
4088
4089                                    return ivar_qual_type.getAsOpaquePtr();
4090                                }
4091
4092                                ++child_idx;
4093                            }
4094                        }
4095                        else
4096                            ++child_idx;
4097                    }
4098
4099                    const uint32_t superclass_idx = child_idx;
4100
4101                    if (idx < (child_idx + class_interface_decl->ivar_size()))
4102                    {
4103                        ObjCInterfaceDecl::ivar_iterator ivar_pos, ivar_end = class_interface_decl->ivar_end();
4104
4105                        for (ivar_pos = class_interface_decl->ivar_begin(); ivar_pos != ivar_end; ++ivar_pos)
4106                        {
4107                            if (child_idx == idx)
4108                            {
4109                                ObjCIvarDecl* ivar_decl = *ivar_pos;
4110
4111                                QualType ivar_qual_type(ivar_decl->getType());
4112
4113                                child_name.assign(ivar_decl->getNameAsString().c_str());
4114
4115                                std::pair<uint64_t, unsigned> ivar_type_info = ast->getTypeInfo(ivar_qual_type.getTypePtr());
4116
4117                                child_byte_size = ivar_type_info.first / 8;
4118
4119                                // Figure out the field offset within the current struct/union/class type
4120                                // For ObjC objects, we can't trust the bit offset we get from the Clang AST, since
4121                                // that doesn't account for the space taken up by unbacked properties, or from
4122                                // the changing size of base classes that are newer than this class.
4123                                // So if we have a process around that we can ask about this object, do so.
4124                                child_byte_offset = LLDB_INVALID_IVAR_OFFSET;
4125                                Process *process = NULL;
4126                                if (exe_ctx)
4127                                    process = exe_ctx->GetProcessPtr();
4128                                if (process)
4129                                {
4130                                    ObjCLanguageRuntime *objc_runtime = process->GetObjCLanguageRuntime();
4131                                    if (objc_runtime != NULL)
4132                                    {
4133                                        ClangASTType parent_ast_type (ast, parent_qual_type.getAsOpaquePtr());
4134                                        child_byte_offset = objc_runtime->GetByteOffsetForIvar (parent_ast_type, ivar_decl->getNameAsString().c_str());
4135                                    }
4136                                }
4137
4138                                // Setting this to UINT32_MAX to make sure we don't compute it twice...
4139                                bit_offset = UINT32_MAX;
4140
4141                                if (child_byte_offset == LLDB_INVALID_IVAR_OFFSET)
4142                                {
4143                                    bit_offset = interface_layout.getFieldOffset (child_idx - superclass_idx);
4144                                    child_byte_offset = bit_offset / 8;
4145                                }
4146
4147                                // Note, the ObjC Ivar Byte offset is just that, it doesn't account for the bit offset
4148                                // of a bitfield within its containing object.  So regardless of where we get the byte
4149                                // offset from, we still need to get the bit offset for bitfields from the layout.
4150
4151                                if (ClangASTContext::FieldIsBitfield (ast, ivar_decl, child_bitfield_bit_size))
4152                                {
4153                                    if (bit_offset == UINT32_MAX)
4154                                        bit_offset = interface_layout.getFieldOffset (child_idx - superclass_idx);
4155
4156                                    child_bitfield_bit_offset = bit_offset % 8;
4157                                }
4158                                return ivar_qual_type.getAsOpaquePtr();
4159                            }
4160                            ++child_idx;
4161                        }
4162                    }
4163                }
4164            }
4165        }
4166        break;
4167
4168    case clang::Type::ObjCObjectPointer:
4169        if (idx_is_valid)
4170        {
4171            const ObjCObjectPointerType *pointer_type = cast<ObjCObjectPointerType>(parent_qual_type.getTypePtr());
4172            QualType pointee_type = pointer_type->getPointeeType();
4173
4174            if (transparent_pointers && ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
4175            {
4176                child_is_deref_of_parent = false;
4177                bool tmp_child_is_deref_of_parent = false;
4178                return GetChildClangTypeAtIndex (exe_ctx,
4179                                                 ast,
4180                                                 parent_name,
4181                                                 pointer_type->getPointeeType().getAsOpaquePtr(),
4182                                                 idx,
4183                                                 transparent_pointers,
4184                                                 omit_empty_base_classes,
4185                                                 ignore_array_bounds,
4186                                                 child_name,
4187                                                 child_byte_size,
4188                                                 child_byte_offset,
4189                                                 child_bitfield_bit_size,
4190                                                 child_bitfield_bit_offset,
4191                                                 child_is_base_class,
4192                                                 tmp_child_is_deref_of_parent);
4193            }
4194            else
4195            {
4196                child_is_deref_of_parent = true;
4197                if (parent_name)
4198                {
4199                    child_name.assign(1, '*');
4200                    child_name += parent_name;
4201                }
4202
4203                // We have a pointer to an simple type
4204                if (idx == 0 && GetCompleteQualType(ast, pointee_type))
4205                {
4206                    std::pair<uint64_t, unsigned> clang_type_info = ast->getTypeInfo(pointee_type);
4207                    assert(clang_type_info.first % 8 == 0);
4208                    child_byte_size = clang_type_info.first / 8;
4209                    child_byte_offset = 0;
4210                    return pointee_type.getAsOpaquePtr();
4211                }
4212            }
4213        }
4214        break;
4215
4216        case clang::Type::ConstantArray:
4217        case clang::Type::IncompleteArray:
4218            if (ignore_array_bounds || idx_is_valid)
4219            {
4220                const ArrayType *array = cast<ArrayType>(parent_qual_type.getTypePtr());
4221                if (array)
4222                {
4223                    if (GetCompleteQualType (ast, array->getElementType()))
4224                    {
4225                        std::pair<uint64_t, unsigned> field_type_info = ast->getTypeInfo(array->getElementType());
4226
4227                        char element_name[64];
4228                        ::snprintf (element_name, sizeof (element_name), "[%zu]", idx);
4229
4230                        child_name.assign(element_name);
4231                        assert(field_type_info.first % 8 == 0);
4232                        child_byte_size = field_type_info.first / 8;
4233                        child_byte_offset = (int32_t)idx * (int32_t)child_byte_size;
4234                        return array->getElementType().getAsOpaquePtr();
4235                    }
4236                }
4237            }
4238            break;
4239
4240
4241    case clang::Type::Pointer:
4242        if (idx_is_valid)
4243        {
4244            const PointerType *pointer_type = cast<PointerType>(parent_qual_type.getTypePtr());
4245            QualType pointee_type = pointer_type->getPointeeType();
4246
4247            // Don't dereference "void *" pointers
4248            if (pointee_type->isVoidType())
4249                return NULL;
4250
4251            if (transparent_pointers && ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
4252            {
4253                child_is_deref_of_parent = false;
4254                bool tmp_child_is_deref_of_parent = false;
4255                return GetChildClangTypeAtIndex (exe_ctx,
4256                                                 ast,
4257                                                 parent_name,
4258                                                 pointer_type->getPointeeType().getAsOpaquePtr(),
4259                                                 idx,
4260                                                 transparent_pointers,
4261                                                 omit_empty_base_classes,
4262                                                 ignore_array_bounds,
4263                                                 child_name,
4264                                                 child_byte_size,
4265                                                 child_byte_offset,
4266                                                 child_bitfield_bit_size,
4267                                                 child_bitfield_bit_offset,
4268                                                 child_is_base_class,
4269                                                 tmp_child_is_deref_of_parent);
4270            }
4271            else
4272            {
4273                child_is_deref_of_parent = true;
4274
4275                if (parent_name)
4276                {
4277                    child_name.assign(1, '*');
4278                    child_name += parent_name;
4279                }
4280
4281                // We have a pointer to an simple type
4282                if (idx == 0)
4283                {
4284                    std::pair<uint64_t, unsigned> clang_type_info = ast->getTypeInfo(pointee_type);
4285                    assert(clang_type_info.first % 8 == 0);
4286                    child_byte_size = clang_type_info.first / 8;
4287                    child_byte_offset = 0;
4288                    return pointee_type.getAsOpaquePtr();
4289                }
4290            }
4291        }
4292        break;
4293
4294    case clang::Type::LValueReference:
4295    case clang::Type::RValueReference:
4296        if (idx_is_valid)
4297        {
4298            const ReferenceType *reference_type = cast<ReferenceType>(parent_qual_type.getTypePtr());
4299            QualType pointee_type(reference_type->getPointeeType());
4300            clang_type_t pointee_clang_type = pointee_type.getAsOpaquePtr();
4301            if (transparent_pointers && ClangASTContext::IsAggregateType (pointee_clang_type))
4302            {
4303                child_is_deref_of_parent = false;
4304                bool tmp_child_is_deref_of_parent = false;
4305                return GetChildClangTypeAtIndex (exe_ctx,
4306                                                 ast,
4307                                                 parent_name,
4308                                                 pointee_clang_type,
4309                                                 idx,
4310                                                 transparent_pointers,
4311                                                 omit_empty_base_classes,
4312                                                 ignore_array_bounds,
4313                                                 child_name,
4314                                                 child_byte_size,
4315                                                 child_byte_offset,
4316                                                 child_bitfield_bit_size,
4317                                                 child_bitfield_bit_offset,
4318                                                 child_is_base_class,
4319                                                 tmp_child_is_deref_of_parent);
4320            }
4321            else
4322            {
4323                if (parent_name)
4324                {
4325                    child_name.assign(1, '&');
4326                    child_name += parent_name;
4327                }
4328
4329                // We have a pointer to an simple type
4330                if (idx == 0)
4331                {
4332                    std::pair<uint64_t, unsigned> clang_type_info = ast->getTypeInfo(pointee_type);
4333                    assert(clang_type_info.first % 8 == 0);
4334                    child_byte_size = clang_type_info.first / 8;
4335                    child_byte_offset = 0;
4336                    return pointee_type.getAsOpaquePtr();
4337                }
4338            }
4339        }
4340        break;
4341
4342    case clang::Type::Typedef:
4343        return GetChildClangTypeAtIndex (exe_ctx,
4344                                         ast,
4345                                         parent_name,
4346                                         cast<TypedefType>(parent_qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(),
4347                                         idx,
4348                                         transparent_pointers,
4349                                         omit_empty_base_classes,
4350                                         ignore_array_bounds,
4351                                         child_name,
4352                                         child_byte_size,
4353                                         child_byte_offset,
4354                                         child_bitfield_bit_size,
4355                                         child_bitfield_bit_offset,
4356                                         child_is_base_class,
4357                                         child_is_deref_of_parent);
4358        break;
4359
4360    case clang::Type::Elaborated:
4361        return GetChildClangTypeAtIndex (exe_ctx,
4362                                         ast,
4363                                         parent_name,
4364                                         cast<ElaboratedType>(parent_qual_type)->getNamedType().getAsOpaquePtr(),
4365                                         idx,
4366                                         transparent_pointers,
4367                                         omit_empty_base_classes,
4368                                         ignore_array_bounds,
4369                                         child_name,
4370                                         child_byte_size,
4371                                         child_byte_offset,
4372                                         child_bitfield_bit_size,
4373                                         child_bitfield_bit_offset,
4374                                         child_is_base_class,
4375                                         child_is_deref_of_parent);
4376
4377    default:
4378        break;
4379    }
4380    return NULL;
4381}
4382
4383static inline bool
4384BaseSpecifierIsEmpty (const CXXBaseSpecifier *b)
4385{
4386    return ClangASTContext::RecordHasFields(b->getType()->getAsCXXRecordDecl()) == false;
4387}
4388
4389static uint32_t
4390GetNumBaseClasses (const CXXRecordDecl *cxx_record_decl, bool omit_empty_base_classes)
4391{
4392    uint32_t num_bases = 0;
4393    if (cxx_record_decl)
4394    {
4395        if (omit_empty_base_classes)
4396        {
4397            CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
4398            for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
4399                 base_class != base_class_end;
4400                 ++base_class)
4401            {
4402                // Skip empty base classes
4403                if (omit_empty_base_classes)
4404                {
4405                    if (BaseSpecifierIsEmpty (base_class))
4406                        continue;
4407                }
4408                ++num_bases;
4409            }
4410        }
4411        else
4412            num_bases = cxx_record_decl->getNumBases();
4413    }
4414    return num_bases;
4415}
4416
4417
4418static uint32_t
4419GetIndexForRecordBase
4420(
4421    const RecordDecl *record_decl,
4422    const CXXBaseSpecifier *base_spec,
4423    bool omit_empty_base_classes
4424)
4425{
4426    uint32_t child_idx = 0;
4427
4428    const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
4429
4430//    const char *super_name = record_decl->getNameAsCString();
4431//    const char *base_name = base_spec->getType()->getAs<RecordType>()->getDecl()->getNameAsCString();
4432//    printf ("GetIndexForRecordChild (%s, %s)\n", super_name, base_name);
4433//
4434    if (cxx_record_decl)
4435    {
4436        CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
4437        for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
4438             base_class != base_class_end;
4439             ++base_class)
4440        {
4441            if (omit_empty_base_classes)
4442            {
4443                if (BaseSpecifierIsEmpty (base_class))
4444                    continue;
4445            }
4446
4447//            printf ("GetIndexForRecordChild (%s, %s) base[%u] = %s\n", super_name, base_name,
4448//                    child_idx,
4449//                    base_class->getType()->getAs<RecordType>()->getDecl()->getNameAsCString());
4450//
4451//
4452            if (base_class == base_spec)
4453                return child_idx;
4454            ++child_idx;
4455        }
4456    }
4457
4458    return UINT32_MAX;
4459}
4460
4461
4462static uint32_t
4463GetIndexForRecordChild
4464(
4465    const RecordDecl *record_decl,
4466    NamedDecl *canonical_decl,
4467    bool omit_empty_base_classes
4468)
4469{
4470    uint32_t child_idx = GetNumBaseClasses (dyn_cast<CXXRecordDecl>(record_decl), omit_empty_base_classes);
4471
4472//    const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
4473//
4474////    printf ("GetIndexForRecordChild (%s, %s)\n", record_decl->getNameAsCString(), canonical_decl->getNameAsCString());
4475//    if (cxx_record_decl)
4476//    {
4477//        CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
4478//        for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
4479//             base_class != base_class_end;
4480//             ++base_class)
4481//        {
4482//            if (omit_empty_base_classes)
4483//            {
4484//                if (BaseSpecifierIsEmpty (base_class))
4485//                    continue;
4486//            }
4487//
4488////            printf ("GetIndexForRecordChild (%s, %s) base[%u] = %s\n",
4489////                    record_decl->getNameAsCString(),
4490////                    canonical_decl->getNameAsCString(),
4491////                    child_idx,
4492////                    base_class->getType()->getAs<RecordType>()->getDecl()->getNameAsCString());
4493//
4494//
4495//            CXXRecordDecl *curr_base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
4496//            if (curr_base_class_decl == canonical_decl)
4497//            {
4498//                return child_idx;
4499//            }
4500//            ++child_idx;
4501//        }
4502//    }
4503//
4504//    const uint32_t num_bases = child_idx;
4505    RecordDecl::field_iterator field, field_end;
4506    for (field = record_decl->field_begin(), field_end = record_decl->field_end();
4507         field != field_end;
4508         ++field, ++child_idx)
4509    {
4510//            printf ("GetIndexForRecordChild (%s, %s) field[%u] = %s\n",
4511//                    record_decl->getNameAsCString(),
4512//                    canonical_decl->getNameAsCString(),
4513//                    child_idx - num_bases,
4514//                    field->getNameAsCString());
4515
4516        if (field->getCanonicalDecl() == canonical_decl)
4517            return child_idx;
4518    }
4519
4520    return UINT32_MAX;
4521}
4522
4523// Look for a child member (doesn't include base classes, but it does include
4524// their members) in the type hierarchy. Returns an index path into "clang_type"
4525// on how to reach the appropriate member.
4526//
4527//    class A
4528//    {
4529//    public:
4530//        int m_a;
4531//        int m_b;
4532//    };
4533//
4534//    class B
4535//    {
4536//    };
4537//
4538//    class C :
4539//        public B,
4540//        public A
4541//    {
4542//    };
4543//
4544// If we have a clang type that describes "class C", and we wanted to looked
4545// "m_b" in it:
4546//
4547// With omit_empty_base_classes == false we would get an integer array back with:
4548// { 1,  1 }
4549// The first index 1 is the child index for "class A" within class C
4550// The second index 1 is the child index for "m_b" within class A
4551//
4552// With omit_empty_base_classes == true we would get an integer array back with:
4553// { 0,  1 }
4554// 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)
4555// The second index 1 is the child index for "m_b" within class A
4556
4557size_t
4558ClangASTContext::GetIndexOfChildMemberWithName
4559(
4560    ASTContext *ast,
4561    clang_type_t clang_type,
4562    const char *name,
4563    bool omit_empty_base_classes,
4564    std::vector<uint32_t>& child_indexes
4565)
4566{
4567    if (clang_type && name && name[0])
4568    {
4569        QualType qual_type(QualType::getFromOpaquePtr(clang_type));
4570        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
4571        switch (type_class)
4572        {
4573        case clang::Type::Record:
4574            if (GetCompleteQualType (ast, qual_type))
4575            {
4576                const RecordType *record_type = cast<RecordType>(qual_type.getTypePtr());
4577                const RecordDecl *record_decl = record_type->getDecl();
4578
4579                assert(record_decl);
4580                uint32_t child_idx = 0;
4581
4582                const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
4583
4584                // Try and find a field that matches NAME
4585                RecordDecl::field_iterator field, field_end;
4586                StringRef name_sref(name);
4587                for (field = record_decl->field_begin(), field_end = record_decl->field_end();
4588                     field != field_end;
4589                     ++field, ++child_idx)
4590                {
4591                    if (field->getName().equals (name_sref))
4592                    {
4593                        // We have to add on the number of base classes to this index!
4594                        child_indexes.push_back (child_idx + GetNumBaseClasses (cxx_record_decl, omit_empty_base_classes));
4595                        return child_indexes.size();
4596                    }
4597                }
4598
4599                if (cxx_record_decl)
4600                {
4601                    const RecordDecl *parent_record_decl = cxx_record_decl;
4602
4603                    //printf ("parent = %s\n", parent_record_decl->getNameAsCString());
4604
4605                    //const Decl *root_cdecl = cxx_record_decl->getCanonicalDecl();
4606                    // Didn't find things easily, lets let clang do its thang...
4607                    IdentifierInfo & ident_ref = ast->Idents.get(name_sref);
4608                    DeclarationName decl_name(&ident_ref);
4609
4610                    CXXBasePaths paths;
4611                    if (cxx_record_decl->lookupInBases(CXXRecordDecl::FindOrdinaryMember,
4612                                                       decl_name.getAsOpaquePtr(),
4613                                                       paths))
4614                    {
4615                        CXXBasePaths::const_paths_iterator path, path_end = paths.end();
4616                        for (path = paths.begin(); path != path_end; ++path)
4617                        {
4618                            const size_t num_path_elements = path->size();
4619                            for (size_t e=0; e<num_path_elements; ++e)
4620                            {
4621                                CXXBasePathElement elem = (*path)[e];
4622
4623                                child_idx = GetIndexForRecordBase (parent_record_decl, elem.Base, omit_empty_base_classes);
4624                                if (child_idx == UINT32_MAX)
4625                                {
4626                                    child_indexes.clear();
4627                                    return 0;
4628                                }
4629                                else
4630                                {
4631                                    child_indexes.push_back (child_idx);
4632                                    parent_record_decl = cast<RecordDecl>(elem.Base->getType()->getAs<RecordType>()->getDecl());
4633                                }
4634                            }
4635                            for (NamedDecl *path_decl : path->Decls)
4636                            {
4637                                child_idx = GetIndexForRecordChild (parent_record_decl, path_decl, omit_empty_base_classes);
4638                                if (child_idx == UINT32_MAX)
4639                                {
4640                                    child_indexes.clear();
4641                                    return 0;
4642                                }
4643                                else
4644                                {
4645                                    child_indexes.push_back (child_idx);
4646                                }
4647                            }
4648                        }
4649                        return child_indexes.size();
4650                    }
4651                }
4652
4653            }
4654            break;
4655
4656        case clang::Type::ObjCObject:
4657        case clang::Type::ObjCInterface:
4658            if (GetCompleteQualType (ast, qual_type))
4659            {
4660                StringRef name_sref(name);
4661                const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(qual_type.getTypePtr());
4662                assert (objc_class_type);
4663                if (objc_class_type)
4664                {
4665                    uint32_t child_idx = 0;
4666                    ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
4667
4668                    if (class_interface_decl)
4669                    {
4670                        ObjCInterfaceDecl::ivar_iterator ivar_pos, ivar_end = class_interface_decl->ivar_end();
4671                        ObjCInterfaceDecl *superclass_interface_decl = class_interface_decl->getSuperClass();
4672
4673                        for (ivar_pos = class_interface_decl->ivar_begin(); ivar_pos != ivar_end; ++ivar_pos, ++child_idx)
4674                        {
4675                            const ObjCIvarDecl* ivar_decl = *ivar_pos;
4676
4677                            if (ivar_decl->getName().equals (name_sref))
4678                            {
4679                                if ((!omit_empty_base_classes && superclass_interface_decl) ||
4680                                    ( omit_empty_base_classes && ObjCDeclHasIVars (superclass_interface_decl, true)))
4681                                    ++child_idx;
4682
4683                                child_indexes.push_back (child_idx);
4684                                return child_indexes.size();
4685                            }
4686                        }
4687
4688                        if (superclass_interface_decl)
4689                        {
4690                            // The super class index is always zero for ObjC classes,
4691                            // so we push it onto the child indexes in case we find
4692                            // an ivar in our superclass...
4693                            child_indexes.push_back (0);
4694
4695                            if (GetIndexOfChildMemberWithName (ast,
4696                                                               ast->getObjCInterfaceType(superclass_interface_decl).getAsOpaquePtr(),
4697                                                               name,
4698                                                               omit_empty_base_classes,
4699                                                               child_indexes))
4700                            {
4701                                // We did find an ivar in a superclass so just
4702                                // return the results!
4703                                return child_indexes.size();
4704                            }
4705
4706                            // We didn't find an ivar matching "name" in our
4707                            // superclass, pop the superclass zero index that
4708                            // we pushed on above.
4709                            child_indexes.pop_back();
4710                        }
4711                    }
4712                }
4713            }
4714            break;
4715
4716        case clang::Type::ObjCObjectPointer:
4717            {
4718                return GetIndexOfChildMemberWithName (ast,
4719                                                      cast<ObjCObjectPointerType>(qual_type.getTypePtr())->getPointeeType().getAsOpaquePtr(),
4720                                                      name,
4721                                                      omit_empty_base_classes,
4722                                                      child_indexes);
4723            }
4724            break;
4725
4726
4727        case clang::Type::ConstantArray:
4728            {
4729//                const ConstantArrayType *array = cast<ConstantArrayType>(parent_qual_type.getTypePtr());
4730//                const uint64_t element_count = array->getSize().getLimitedValue();
4731//
4732//                if (idx < element_count)
4733//                {
4734//                    std::pair<uint64_t, unsigned> field_type_info = ast->getTypeInfo(array->getElementType());
4735//
4736//                    char element_name[32];
4737//                    ::snprintf (element_name, sizeof (element_name), "%s[%u]", parent_name ? parent_name : "", idx);
4738//
4739//                    child_name.assign(element_name);
4740//                    assert(field_type_info.first % 8 == 0);
4741//                    child_byte_size = field_type_info.first / 8;
4742//                    child_byte_offset = idx * child_byte_size;
4743//                    return array->getElementType().getAsOpaquePtr();
4744//                }
4745            }
4746            break;
4747
4748//        case clang::Type::MemberPointerType:
4749//            {
4750//                MemberPointerType *mem_ptr_type = cast<MemberPointerType>(qual_type.getTypePtr());
4751//                QualType pointee_type = mem_ptr_type->getPointeeType();
4752//
4753//                if (ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
4754//                {
4755//                    return GetIndexOfChildWithName (ast,
4756//                                                    mem_ptr_type->getPointeeType().getAsOpaquePtr(),
4757//                                                    name);
4758//                }
4759//            }
4760//            break;
4761//
4762        case clang::Type::LValueReference:
4763        case clang::Type::RValueReference:
4764            {
4765                const ReferenceType *reference_type = cast<ReferenceType>(qual_type.getTypePtr());
4766                QualType pointee_type = reference_type->getPointeeType();
4767
4768                if (ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
4769                {
4770                    return GetIndexOfChildMemberWithName (ast,
4771                                                          reference_type->getPointeeType().getAsOpaquePtr(),
4772                                                          name,
4773                                                          omit_empty_base_classes,
4774                                                          child_indexes);
4775                }
4776            }
4777            break;
4778
4779        case clang::Type::Pointer:
4780            {
4781                const PointerType *pointer_type = cast<PointerType>(qual_type.getTypePtr());
4782                QualType pointee_type = pointer_type->getPointeeType();
4783
4784                if (ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
4785                {
4786                    return GetIndexOfChildMemberWithName (ast,
4787                                                          pointer_type->getPointeeType().getAsOpaquePtr(),
4788                                                          name,
4789                                                          omit_empty_base_classes,
4790                                                          child_indexes);
4791                }
4792                else
4793                {
4794//                    if (parent_name)
4795//                    {
4796//                        child_name.assign(1, '*');
4797//                        child_name += parent_name;
4798//                    }
4799//
4800//                    // We have a pointer to an simple type
4801//                    if (idx == 0)
4802//                    {
4803//                        std::pair<uint64_t, unsigned> clang_type_info = ast->getTypeInfo(pointee_type);
4804//                        assert(clang_type_info.first % 8 == 0);
4805//                        child_byte_size = clang_type_info.first / 8;
4806//                        child_byte_offset = 0;
4807//                        return pointee_type.getAsOpaquePtr();
4808//                    }
4809                }
4810            }
4811            break;
4812
4813        case clang::Type::Typedef:
4814            return GetIndexOfChildMemberWithName (ast,
4815                                                  cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(),
4816                                                  name,
4817                                                  omit_empty_base_classes,
4818                                                  child_indexes);
4819
4820        case clang::Type::Elaborated:
4821            return GetIndexOfChildMemberWithName (ast,
4822                                                  cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(),
4823                                                  name,
4824                                                  omit_empty_base_classes,
4825                                                  child_indexes);
4826
4827        default:
4828            break;
4829        }
4830    }
4831    return 0;
4832}
4833
4834
4835// Get the index of the child of "clang_type" whose name matches. This function
4836// doesn't descend into the children, but only looks one level deep and name
4837// matches can include base class names.
4838
4839uint32_t
4840ClangASTContext::GetIndexOfChildWithName
4841(
4842    ASTContext *ast,
4843    clang_type_t clang_type,
4844    const char *name,
4845    bool omit_empty_base_classes
4846)
4847{
4848    if (clang_type && name && name[0])
4849    {
4850        QualType qual_type(QualType::getFromOpaquePtr(clang_type));
4851
4852        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
4853
4854        switch (type_class)
4855        {
4856        case clang::Type::Record:
4857            if (GetCompleteQualType (ast, qual_type))
4858            {
4859                const RecordType *record_type = cast<RecordType>(qual_type.getTypePtr());
4860                const RecordDecl *record_decl = record_type->getDecl();
4861
4862                assert(record_decl);
4863                uint32_t child_idx = 0;
4864
4865                const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
4866
4867                if (cxx_record_decl)
4868                {
4869                    CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
4870                    for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
4871                         base_class != base_class_end;
4872                         ++base_class)
4873                    {
4874                        // Skip empty base classes
4875                        CXXRecordDecl *base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
4876                        if (omit_empty_base_classes && RecordHasFields(base_class_decl) == false)
4877                            continue;
4878
4879                        std::string base_class_type_name (ClangASTType::GetTypeNameForQualType(ast, base_class->getType()));
4880                        if (base_class_type_name.compare (name) == 0)
4881                            return child_idx;
4882                        ++child_idx;
4883                    }
4884                }
4885
4886                // Try and find a field that matches NAME
4887                RecordDecl::field_iterator field, field_end;
4888                StringRef name_sref(name);
4889                for (field = record_decl->field_begin(), field_end = record_decl->field_end();
4890                     field != field_end;
4891                     ++field, ++child_idx)
4892                {
4893                    if (field->getName().equals (name_sref))
4894                        return child_idx;
4895                }
4896
4897            }
4898            break;
4899
4900        case clang::Type::ObjCObject:
4901        case clang::Type::ObjCInterface:
4902            if (GetCompleteQualType (ast, qual_type))
4903            {
4904                StringRef name_sref(name);
4905                const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(qual_type.getTypePtr());
4906                assert (objc_class_type);
4907                if (objc_class_type)
4908                {
4909                    uint32_t child_idx = 0;
4910                    ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
4911
4912                    if (class_interface_decl)
4913                    {
4914                        ObjCInterfaceDecl::ivar_iterator ivar_pos, ivar_end = class_interface_decl->ivar_end();
4915                        ObjCInterfaceDecl *superclass_interface_decl = class_interface_decl->getSuperClass();
4916
4917                        for (ivar_pos = class_interface_decl->ivar_begin(); ivar_pos != ivar_end; ++ivar_pos, ++child_idx)
4918                        {
4919                            const ObjCIvarDecl* ivar_decl = *ivar_pos;
4920
4921                            if (ivar_decl->getName().equals (name_sref))
4922                            {
4923                                if ((!omit_empty_base_classes && superclass_interface_decl) ||
4924                                    ( omit_empty_base_classes && ObjCDeclHasIVars (superclass_interface_decl, true)))
4925                                    ++child_idx;
4926
4927                                return child_idx;
4928                            }
4929                        }
4930
4931                        if (superclass_interface_decl)
4932                        {
4933                            if (superclass_interface_decl->getName().equals (name_sref))
4934                                return 0;
4935                        }
4936                    }
4937                }
4938            }
4939            break;
4940
4941        case clang::Type::ObjCObjectPointer:
4942            {
4943                return GetIndexOfChildWithName (ast,
4944                                                cast<ObjCObjectPointerType>(qual_type.getTypePtr())->getPointeeType().getAsOpaquePtr(),
4945                                                name,
4946                                                omit_empty_base_classes);
4947            }
4948            break;
4949
4950        case clang::Type::ConstantArray:
4951            {
4952//                const ConstantArrayType *array = cast<ConstantArrayType>(parent_qual_type.getTypePtr());
4953//                const uint64_t element_count = array->getSize().getLimitedValue();
4954//
4955//                if (idx < element_count)
4956//                {
4957//                    std::pair<uint64_t, unsigned> field_type_info = ast->getTypeInfo(array->getElementType());
4958//
4959//                    char element_name[32];
4960//                    ::snprintf (element_name, sizeof (element_name), "%s[%u]", parent_name ? parent_name : "", idx);
4961//
4962//                    child_name.assign(element_name);
4963//                    assert(field_type_info.first % 8 == 0);
4964//                    child_byte_size = field_type_info.first / 8;
4965//                    child_byte_offset = idx * child_byte_size;
4966//                    return array->getElementType().getAsOpaquePtr();
4967//                }
4968            }
4969            break;
4970
4971//        case clang::Type::MemberPointerType:
4972//            {
4973//                MemberPointerType *mem_ptr_type = cast<MemberPointerType>(qual_type.getTypePtr());
4974//                QualType pointee_type = mem_ptr_type->getPointeeType();
4975//
4976//                if (ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
4977//                {
4978//                    return GetIndexOfChildWithName (ast,
4979//                                                    mem_ptr_type->getPointeeType().getAsOpaquePtr(),
4980//                                                    name);
4981//                }
4982//            }
4983//            break;
4984//
4985        case clang::Type::LValueReference:
4986        case clang::Type::RValueReference:
4987            {
4988                const ReferenceType *reference_type = cast<ReferenceType>(qual_type.getTypePtr());
4989                QualType pointee_type = reference_type->getPointeeType();
4990
4991                if (ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
4992                {
4993                    return GetIndexOfChildWithName (ast,
4994                                                    reference_type->getPointeeType().getAsOpaquePtr(),
4995                                                    name,
4996                                                    omit_empty_base_classes);
4997                }
4998            }
4999            break;
5000
5001        case clang::Type::Pointer:
5002            {
5003                const PointerType *pointer_type = cast<PointerType>(qual_type.getTypePtr());
5004                QualType pointee_type = pointer_type->getPointeeType();
5005
5006                if (ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
5007                {
5008                    return GetIndexOfChildWithName (ast,
5009                                                    pointer_type->getPointeeType().getAsOpaquePtr(),
5010                                                    name,
5011                                                    omit_empty_base_classes);
5012                }
5013                else
5014                {
5015//                    if (parent_name)
5016//                    {
5017//                        child_name.assign(1, '*');
5018//                        child_name += parent_name;
5019//                    }
5020//
5021//                    // We have a pointer to an simple type
5022//                    if (idx == 0)
5023//                    {
5024//                        std::pair<uint64_t, unsigned> clang_type_info = ast->getTypeInfo(pointee_type);
5025//                        assert(clang_type_info.first % 8 == 0);
5026//                        child_byte_size = clang_type_info.first / 8;
5027//                        child_byte_offset = 0;
5028//                        return pointee_type.getAsOpaquePtr();
5029//                    }
5030                }
5031            }
5032            break;
5033
5034        case clang::Type::Elaborated:
5035            return GetIndexOfChildWithName (ast,
5036                                            cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(),
5037                                            name,
5038                                            omit_empty_base_classes);
5039
5040        case clang::Type::Typedef:
5041            return GetIndexOfChildWithName (ast,
5042                                            cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(),
5043                                            name,
5044                                            omit_empty_base_classes);
5045
5046        default:
5047            break;
5048        }
5049    }
5050    return UINT32_MAX;
5051}
5052
5053#pragma mark TagType
5054
5055bool
5056ClangASTContext::SetTagTypeKind (clang_type_t tag_clang_type, int kind)
5057{
5058    if (tag_clang_type)
5059    {
5060        QualType tag_qual_type(QualType::getFromOpaquePtr(tag_clang_type));
5061        const clang::Type *clang_type = tag_qual_type.getTypePtr();
5062        if (clang_type)
5063        {
5064            const TagType *tag_type = dyn_cast<TagType>(clang_type);
5065            if (tag_type)
5066            {
5067                TagDecl *tag_decl = dyn_cast<TagDecl>(tag_type->getDecl());
5068                if (tag_decl)
5069                {
5070                    tag_decl->setTagKind ((TagDecl::TagKind)kind);
5071                    return true;
5072                }
5073            }
5074        }
5075    }
5076    return false;
5077}
5078
5079
5080#pragma mark DeclContext Functions
5081
5082DeclContext *
5083ClangASTContext::GetDeclContextForType (clang_type_t clang_type)
5084{
5085    if (clang_type == NULL)
5086        return NULL;
5087
5088    QualType qual_type(QualType::getFromOpaquePtr(clang_type));
5089    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5090    switch (type_class)
5091    {
5092    case clang::Type::UnaryTransform:           break;
5093    case clang::Type::FunctionNoProto:          break;
5094    case clang::Type::FunctionProto:            break;
5095    case clang::Type::IncompleteArray:          break;
5096    case clang::Type::VariableArray:            break;
5097    case clang::Type::ConstantArray:            break;
5098    case clang::Type::DependentSizedArray:      break;
5099    case clang::Type::ExtVector:                break;
5100    case clang::Type::DependentSizedExtVector:  break;
5101    case clang::Type::Vector:                   break;
5102    case clang::Type::Builtin:                  break;
5103    case clang::Type::BlockPointer:             break;
5104    case clang::Type::Pointer:                  break;
5105    case clang::Type::LValueReference:          break;
5106    case clang::Type::RValueReference:          break;
5107    case clang::Type::MemberPointer:            break;
5108    case clang::Type::Complex:                  break;
5109    case clang::Type::ObjCObject:               break;
5110    case clang::Type::ObjCInterface:            return cast<ObjCObjectType>(qual_type.getTypePtr())->getInterface();
5111    case clang::Type::ObjCObjectPointer:        return ClangASTContext::GetDeclContextForType (cast<ObjCObjectPointerType>(qual_type.getTypePtr())->getPointeeType().getAsOpaquePtr());
5112    case clang::Type::Record:                   return cast<RecordType>(qual_type)->getDecl();
5113    case clang::Type::Enum:                     return cast<EnumType>(qual_type)->getDecl();
5114    case clang::Type::Typedef:                  return ClangASTContext::GetDeclContextForType (cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
5115    case clang::Type::Elaborated:               return ClangASTContext::GetDeclContextForType (cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
5116    case clang::Type::TypeOfExpr:               break;
5117    case clang::Type::TypeOf:                   break;
5118    case clang::Type::Decltype:                 break;
5119    //case clang::Type::QualifiedName:          break;
5120    case clang::Type::TemplateSpecialization:   break;
5121    case clang::Type::DependentTemplateSpecialization:  break;
5122    case clang::Type::TemplateTypeParm:         break;
5123    case clang::Type::SubstTemplateTypeParm:    break;
5124    case clang::Type::SubstTemplateTypeParmPack:break;
5125    case clang::Type::PackExpansion:            break;
5126    case clang::Type::UnresolvedUsing:          break;
5127    case clang::Type::Paren:                    break;
5128    case clang::Type::Attributed:               break;
5129    case clang::Type::Auto:                     break;
5130    case clang::Type::InjectedClassName:        break;
5131    case clang::Type::DependentName:            break;
5132    case clang::Type::Atomic:                   break;
5133    }
5134    // No DeclContext in this type...
5135    return NULL;
5136}
5137
5138#pragma mark Namespace Declarations
5139
5140NamespaceDecl *
5141ClangASTContext::GetUniqueNamespaceDeclaration (const char *name, DeclContext *decl_ctx)
5142{
5143    NamespaceDecl *namespace_decl = NULL;
5144    ASTContext *ast = getASTContext();
5145    TranslationUnitDecl *translation_unit_decl = ast->getTranslationUnitDecl ();
5146    if (decl_ctx == NULL)
5147        decl_ctx = translation_unit_decl;
5148
5149    if (name)
5150    {
5151        IdentifierInfo &identifier_info = ast->Idents.get(name);
5152        DeclarationName decl_name (&identifier_info);
5153        clang::DeclContext::lookup_result result = decl_ctx->lookup(decl_name);
5154        for (NamedDecl *decl : result)
5155        {
5156            namespace_decl = dyn_cast<clang::NamespaceDecl>(decl);
5157            if (namespace_decl)
5158                return namespace_decl;
5159        }
5160
5161        namespace_decl = NamespaceDecl::Create(*ast,
5162                                               decl_ctx,
5163                                               false,
5164                                               SourceLocation(),
5165                                               SourceLocation(),
5166                                               &identifier_info,
5167                                               NULL);
5168
5169        decl_ctx->addDecl (namespace_decl);
5170    }
5171    else
5172    {
5173        if (decl_ctx == translation_unit_decl)
5174        {
5175            namespace_decl = translation_unit_decl->getAnonymousNamespace();
5176            if (namespace_decl)
5177                return namespace_decl;
5178
5179            namespace_decl = NamespaceDecl::Create(*ast,
5180                                                   decl_ctx,
5181                                                   false,
5182                                                   SourceLocation(),
5183                                                   SourceLocation(),
5184                                                   NULL,
5185                                                   NULL);
5186            translation_unit_decl->setAnonymousNamespace (namespace_decl);
5187            translation_unit_decl->addDecl (namespace_decl);
5188            assert (namespace_decl == translation_unit_decl->getAnonymousNamespace());
5189        }
5190        else
5191        {
5192            NamespaceDecl *parent_namespace_decl = cast<NamespaceDecl>(decl_ctx);
5193            if (parent_namespace_decl)
5194            {
5195                namespace_decl = parent_namespace_decl->getAnonymousNamespace();
5196                if (namespace_decl)
5197                    return namespace_decl;
5198                namespace_decl = NamespaceDecl::Create(*ast,
5199                                                       decl_ctx,
5200                                                       false,
5201                                                       SourceLocation(),
5202                                                       SourceLocation(),
5203                                                       NULL,
5204                                                       NULL);
5205                parent_namespace_decl->setAnonymousNamespace (namespace_decl);
5206                parent_namespace_decl->addDecl (namespace_decl);
5207                assert (namespace_decl == parent_namespace_decl->getAnonymousNamespace());
5208            }
5209            else
5210            {
5211                // BAD!!!
5212            }
5213        }
5214
5215
5216        if (namespace_decl)
5217        {
5218            // If we make it here, we are creating the anonymous namespace decl
5219            // for the first time, so we need to do the using directive magic
5220            // like SEMA does
5221            UsingDirectiveDecl* using_directive_decl = UsingDirectiveDecl::Create (*ast,
5222                                                                                   decl_ctx,
5223                                                                                   SourceLocation(),
5224                                                                                   SourceLocation(),
5225                                                                                   NestedNameSpecifierLoc(),
5226                                                                                   SourceLocation(),
5227                                                                                   namespace_decl,
5228                                                                                   decl_ctx);
5229            using_directive_decl->setImplicit();
5230            decl_ctx->addDecl(using_directive_decl);
5231        }
5232    }
5233#ifdef LLDB_CONFIGURATION_DEBUG
5234    VerifyDecl(namespace_decl);
5235#endif
5236    return namespace_decl;
5237}
5238
5239
5240#pragma mark Function Types
5241
5242FunctionDecl *
5243ClangASTContext::CreateFunctionDeclaration (DeclContext *decl_ctx, const char *name, clang_type_t function_clang_type, int storage, bool is_inline)
5244{
5245    FunctionDecl *func_decl = NULL;
5246    ASTContext *ast = getASTContext();
5247    if (decl_ctx == NULL)
5248        decl_ctx = ast->getTranslationUnitDecl();
5249
5250    if (name && name[0])
5251    {
5252        func_decl = FunctionDecl::Create (*ast,
5253                                          decl_ctx,
5254                                          SourceLocation(),
5255                                          SourceLocation(),
5256                                          DeclarationName (&ast->Idents.get(name)),
5257                                          QualType::getFromOpaquePtr(function_clang_type),
5258                                          NULL,
5259                                          (FunctionDecl::StorageClass)storage,
5260                                          (FunctionDecl::StorageClass)storage,
5261                                          is_inline);
5262    }
5263    else
5264    {
5265        func_decl = FunctionDecl::Create (*ast,
5266                                          decl_ctx,
5267                                          SourceLocation(),
5268                                          SourceLocation(),
5269                                          DeclarationName (),
5270                                          QualType::getFromOpaquePtr(function_clang_type),
5271                                          NULL,
5272                                          (FunctionDecl::StorageClass)storage,
5273                                          (FunctionDecl::StorageClass)storage,
5274                                          is_inline);
5275    }
5276    if (func_decl)
5277        decl_ctx->addDecl (func_decl);
5278
5279#ifdef LLDB_CONFIGURATION_DEBUG
5280    VerifyDecl(func_decl);
5281#endif
5282
5283    return func_decl;
5284}
5285
5286clang_type_t
5287ClangASTContext::CreateFunctionType (ASTContext *ast,
5288                                     clang_type_t result_type,
5289                                     clang_type_t *args,
5290                                     unsigned num_args,
5291                                     bool is_variadic,
5292                                     unsigned type_quals)
5293{
5294    assert (ast != NULL);
5295    std::vector<QualType> qual_type_args;
5296    for (unsigned i=0; i<num_args; ++i)
5297        qual_type_args.push_back (QualType::getFromOpaquePtr(args[i]));
5298
5299    // TODO: Detect calling convention in DWARF?
5300    FunctionProtoType::ExtProtoInfo proto_info;
5301    proto_info.Variadic = is_variadic;
5302    proto_info.ExceptionSpecType = EST_None;
5303    proto_info.TypeQuals = type_quals;
5304    proto_info.RefQualifier = RQ_None;
5305    proto_info.NumExceptions = 0;
5306    proto_info.Exceptions = NULL;
5307
5308    return ast->getFunctionType (QualType::getFromOpaquePtr(result_type),
5309                                 qual_type_args,
5310                                 proto_info).getAsOpaquePtr();
5311}
5312
5313ParmVarDecl *
5314ClangASTContext::CreateParameterDeclaration (const char *name, clang_type_t param_type, int storage)
5315{
5316    ASTContext *ast = getASTContext();
5317    assert (ast != NULL);
5318    return ParmVarDecl::Create(*ast,
5319                                ast->getTranslationUnitDecl(),
5320                                SourceLocation(),
5321                                SourceLocation(),
5322                                name && name[0] ? &ast->Idents.get(name) : NULL,
5323                                QualType::getFromOpaquePtr(param_type),
5324                                NULL,
5325                                (VarDecl::StorageClass)storage,
5326                                (VarDecl::StorageClass)storage,
5327                                0);
5328}
5329
5330void
5331ClangASTContext::SetFunctionParameters (FunctionDecl *function_decl, ParmVarDecl **params, unsigned num_params)
5332{
5333    if (function_decl)
5334        function_decl->setParams (ArrayRef<ParmVarDecl*>(params, num_params));
5335}
5336
5337
5338#pragma mark Array Types
5339
5340clang_type_t
5341ClangASTContext::CreateArrayType (clang_type_t element_type, size_t element_count)
5342{
5343    if (element_type)
5344    {
5345        ASTContext *ast = getASTContext();
5346        assert (ast != NULL);
5347        llvm::APInt ap_element_count (64, element_count);
5348        if (element_count == 0)
5349        {
5350            return ast->getIncompleteArrayType(QualType::getFromOpaquePtr(element_type),
5351                                               ArrayType::Normal,
5352                                               0).getAsOpaquePtr();
5353
5354        }
5355        else
5356        {
5357            return ast->getConstantArrayType(QualType::getFromOpaquePtr(element_type),
5358                                                     ap_element_count,
5359                                                     ArrayType::Normal,
5360                                                     0).getAsOpaquePtr(); // ElemQuals
5361        }
5362    }
5363    return NULL;
5364}
5365
5366
5367#pragma mark TagDecl
5368
5369bool
5370ClangASTContext::StartTagDeclarationDefinition (clang_type_t clang_type)
5371{
5372    if (clang_type)
5373    {
5374        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
5375        const clang::Type *t = qual_type.getTypePtr();
5376        if (t)
5377        {
5378            const TagType *tag_type = dyn_cast<TagType>(t);
5379            if (tag_type)
5380            {
5381                TagDecl *tag_decl = tag_type->getDecl();
5382                if (tag_decl)
5383                {
5384                    tag_decl->startDefinition();
5385                    return true;
5386                }
5387            }
5388
5389            const ObjCObjectType *object_type = dyn_cast<ObjCObjectType>(t);
5390            if (object_type)
5391            {
5392                ObjCInterfaceDecl *interface_decl = object_type->getInterface();
5393                if (interface_decl)
5394                {
5395                    interface_decl->startDefinition();
5396                    return true;
5397                }
5398            }
5399        }
5400    }
5401    return false;
5402}
5403
5404bool
5405ClangASTContext::CompleteTagDeclarationDefinition (clang_type_t clang_type)
5406{
5407    if (clang_type)
5408    {
5409        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
5410
5411        CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
5412
5413        if (cxx_record_decl)
5414        {
5415            cxx_record_decl->completeDefinition();
5416
5417            return true;
5418        }
5419
5420        const EnumType *enum_type = dyn_cast<EnumType>(qual_type.getTypePtr());
5421
5422        if (enum_type)
5423        {
5424            EnumDecl *enum_decl = enum_type->getDecl();
5425
5426            if (enum_decl)
5427            {
5428                /// TODO This really needs to be fixed.
5429
5430                unsigned NumPositiveBits = 1;
5431                unsigned NumNegativeBits = 0;
5432
5433                ASTContext *ast = getASTContext();
5434
5435                QualType promotion_qual_type;
5436                // If the enum integer type is less than an integer in bit width,
5437                // then we must promote it to an integer size.
5438                if (ast->getTypeSize(enum_decl->getIntegerType()) < ast->getTypeSize(ast->IntTy))
5439                {
5440                    if (enum_decl->getIntegerType()->isSignedIntegerType())
5441                        promotion_qual_type = ast->IntTy;
5442                    else
5443                        promotion_qual_type = ast->UnsignedIntTy;
5444                }
5445                else
5446                    promotion_qual_type = enum_decl->getIntegerType();
5447
5448                enum_decl->completeDefinition(enum_decl->getIntegerType(), promotion_qual_type, NumPositiveBits, NumNegativeBits);
5449                return true;
5450            }
5451        }
5452    }
5453    return false;
5454}
5455
5456
5457#pragma mark Enumeration Types
5458
5459clang_type_t
5460ClangASTContext::CreateEnumerationType
5461(
5462    const char *name,
5463    DeclContext *decl_ctx,
5464    const Declaration &decl,
5465    clang_type_t integer_qual_type
5466)
5467{
5468    // TODO: Do something intelligent with the Declaration object passed in
5469    // like maybe filling in the SourceLocation with it...
5470    ASTContext *ast = getASTContext();
5471    assert (ast != NULL);
5472
5473    // TODO: ask about these...
5474//    const bool IsScoped = false;
5475//    const bool IsFixed = false;
5476
5477    EnumDecl *enum_decl = EnumDecl::Create (*ast,
5478                                            decl_ctx,
5479                                            SourceLocation(),
5480                                            SourceLocation(),
5481                                            name && name[0] ? &ast->Idents.get(name) : NULL,
5482                                            NULL,
5483                                            false,  // IsScoped
5484                                            false,  // IsScopedUsingClassTag
5485                                            false); // IsFixed
5486
5487
5488    if (enum_decl)
5489    {
5490        // TODO: check if we should be setting the promotion type too?
5491        enum_decl->setIntegerType(QualType::getFromOpaquePtr (integer_qual_type));
5492
5493        enum_decl->setAccess(AS_public); // TODO respect what's in the debug info
5494
5495        return ast->getTagDeclType(enum_decl).getAsOpaquePtr();
5496    }
5497    return NULL;
5498}
5499
5500clang_type_t
5501ClangASTContext::GetEnumerationIntegerType (clang_type_t enum_clang_type)
5502{
5503    QualType enum_qual_type (QualType::getFromOpaquePtr(enum_clang_type));
5504
5505    const clang::Type *clang_type = enum_qual_type.getTypePtr();
5506    if (clang_type)
5507    {
5508        const EnumType *enum_type = dyn_cast<EnumType>(clang_type);
5509        if (enum_type)
5510        {
5511            EnumDecl *enum_decl = enum_type->getDecl();
5512            if (enum_decl)
5513                return enum_decl->getIntegerType().getAsOpaquePtr();
5514        }
5515    }
5516    return NULL;
5517}
5518bool
5519ClangASTContext::AddEnumerationValueToEnumerationType
5520(
5521    clang_type_t enum_clang_type,
5522    clang_type_t enumerator_clang_type,
5523    const Declaration &decl,
5524    const char *name,
5525    int64_t enum_value,
5526    uint32_t enum_value_bit_size
5527)
5528{
5529    if (enum_clang_type && enumerator_clang_type && name)
5530    {
5531        // TODO: Do something intelligent with the Declaration object passed in
5532        // like maybe filling in the SourceLocation with it...
5533        ASTContext *ast = getASTContext();
5534        IdentifierTable *identifier_table = getIdentifierTable();
5535
5536        assert (ast != NULL);
5537        assert (identifier_table != NULL);
5538        QualType enum_qual_type (QualType::getFromOpaquePtr(enum_clang_type));
5539
5540        bool is_signed = false;
5541        IsIntegerType (enumerator_clang_type, is_signed);
5542        const clang::Type *clang_type = enum_qual_type.getTypePtr();
5543        if (clang_type)
5544        {
5545            const EnumType *enum_type = dyn_cast<EnumType>(clang_type);
5546
5547            if (enum_type)
5548            {
5549                llvm::APSInt enum_llvm_apsint(enum_value_bit_size, is_signed);
5550                enum_llvm_apsint = enum_value;
5551                EnumConstantDecl *enumerator_decl =
5552                    EnumConstantDecl::Create (*ast,
5553                                              enum_type->getDecl(),
5554                                              SourceLocation(),
5555                                              name ? &identifier_table->get(name) : NULL,    // Identifier
5556                                              QualType::getFromOpaquePtr(enumerator_clang_type),
5557                                              NULL,
5558                                              enum_llvm_apsint);
5559
5560                if (enumerator_decl)
5561                {
5562                    enum_type->getDecl()->addDecl(enumerator_decl);
5563
5564#ifdef LLDB_CONFIGURATION_DEBUG
5565                    VerifyDecl(enumerator_decl);
5566#endif
5567
5568                    return true;
5569                }
5570            }
5571        }
5572    }
5573    return false;
5574}
5575
5576#pragma mark Pointers & References
5577
5578clang_type_t
5579ClangASTContext::CreatePointerType (clang_type_t clang_type)
5580{
5581    return CreatePointerType (getASTContext(), clang_type);
5582}
5583
5584clang_type_t
5585ClangASTContext::CreatePointerType (clang::ASTContext *ast, clang_type_t clang_type)
5586{
5587    if (ast && clang_type)
5588    {
5589        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
5590
5591        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5592        switch (type_class)
5593        {
5594        case clang::Type::ObjCObject:
5595        case clang::Type::ObjCInterface:
5596            return ast->getObjCObjectPointerType(qual_type).getAsOpaquePtr();
5597
5598        default:
5599            return ast->getPointerType(qual_type).getAsOpaquePtr();
5600        }
5601    }
5602    return NULL;
5603}
5604
5605clang_type_t
5606ClangASTContext::CreateLValueReferenceType (clang::ASTContext *ast,
5607                                            clang_type_t clang_type)
5608{
5609    if (clang_type)
5610        return ast->getLValueReferenceType (QualType::getFromOpaquePtr(clang_type)).getAsOpaquePtr();
5611    return NULL;
5612}
5613
5614clang_type_t
5615ClangASTContext::CreateRValueReferenceType (clang::ASTContext *ast,
5616                                            clang_type_t clang_type)
5617{
5618    if (clang_type)
5619        return ast->getRValueReferenceType (QualType::getFromOpaquePtr(clang_type)).getAsOpaquePtr();
5620    return NULL;
5621}
5622
5623clang_type_t
5624ClangASTContext::CreateMemberPointerType (clang_type_t clang_pointee_type, clang_type_t clang_class_type)
5625{
5626    if (clang_pointee_type && clang_pointee_type)
5627        return getASTContext()->getMemberPointerType(QualType::getFromOpaquePtr(clang_pointee_type),
5628                                                     QualType::getFromOpaquePtr(clang_class_type).getTypePtr()).getAsOpaquePtr();
5629    return NULL;
5630}
5631
5632uint64_t
5633ClangASTContext::GetPointerBitSize ()
5634{
5635    ASTContext *ast = getASTContext();
5636    return ast->getTypeSize(ast->VoidPtrTy);
5637}
5638
5639bool
5640ClangASTContext::IsPossibleDynamicType (clang::ASTContext *ast,
5641                                        clang_type_t clang_type,
5642                                        clang_type_t *dynamic_pointee_type,
5643                                        bool check_cplusplus,
5644                                        bool check_objc)
5645{
5646    QualType pointee_qual_type;
5647    if (clang_type)
5648    {
5649        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
5650        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5651        bool success = false;
5652        switch (type_class)
5653        {
5654            case clang::Type::Builtin:
5655                if (check_objc && cast<clang::BuiltinType>(qual_type)->getKind() == clang::BuiltinType::ObjCId)
5656                {
5657                    if (dynamic_pointee_type)
5658                        *dynamic_pointee_type = clang_type;
5659                    return true;
5660                }
5661                break;
5662
5663            case clang::Type::ObjCObjectPointer:
5664                if (check_objc)
5665                {
5666                    if (dynamic_pointee_type)
5667                        *dynamic_pointee_type = cast<ObjCObjectPointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
5668                    return true;
5669                }
5670                break;
5671
5672            case clang::Type::Pointer:
5673                pointee_qual_type = cast<PointerType>(qual_type)->getPointeeType();
5674                success = true;
5675                break;
5676
5677            case clang::Type::LValueReference:
5678            case clang::Type::RValueReference:
5679                pointee_qual_type = cast<ReferenceType>(qual_type)->getPointeeType();
5680                success = true;
5681                break;
5682
5683            case clang::Type::Typedef:
5684                return ClangASTContext::IsPossibleDynamicType (ast,
5685                                                               cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(),
5686                                                               dynamic_pointee_type,
5687                                                               check_cplusplus,
5688                                                               check_objc);
5689
5690            case clang::Type::Elaborated:
5691                return ClangASTContext::IsPossibleDynamicType (ast,
5692                                                               cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(),
5693                                                               dynamic_pointee_type,
5694                                                               check_cplusplus,
5695                                                               check_objc);
5696
5697            default:
5698                break;
5699        }
5700
5701        if (success)
5702        {
5703            // Check to make sure what we are pointing too is a possible dynamic C++ type
5704            // We currently accept any "void *" (in case we have a class that has been
5705            // watered down to an opaque pointer) and virtual C++ classes.
5706            const clang::Type::TypeClass pointee_type_class = pointee_qual_type->getTypeClass();
5707            switch (pointee_type_class)
5708            {
5709                case clang::Type::Builtin:
5710                    switch (cast<clang::BuiltinType>(pointee_qual_type)->getKind())
5711                    {
5712                        case clang::BuiltinType::UnknownAny:
5713                        case clang::BuiltinType::Void:
5714                            if (dynamic_pointee_type)
5715                                *dynamic_pointee_type = pointee_qual_type.getAsOpaquePtr();
5716                            return true;
5717
5718                        case clang::BuiltinType::NullPtr:
5719                        case clang::BuiltinType::Bool:
5720                        case clang::BuiltinType::Char_U:
5721                        case clang::BuiltinType::UChar:
5722                        case clang::BuiltinType::WChar_U:
5723                        case clang::BuiltinType::Char16:
5724                        case clang::BuiltinType::Char32:
5725                        case clang::BuiltinType::UShort:
5726                        case clang::BuiltinType::UInt:
5727                        case clang::BuiltinType::ULong:
5728                        case clang::BuiltinType::ULongLong:
5729                        case clang::BuiltinType::UInt128:
5730                        case clang::BuiltinType::Char_S:
5731                        case clang::BuiltinType::SChar:
5732                        case clang::BuiltinType::WChar_S:
5733                        case clang::BuiltinType::Short:
5734                        case clang::BuiltinType::Int:
5735                        case clang::BuiltinType::Long:
5736                        case clang::BuiltinType::LongLong:
5737                        case clang::BuiltinType::Int128:
5738                        case clang::BuiltinType::Float:
5739                        case clang::BuiltinType::Double:
5740                        case clang::BuiltinType::LongDouble:
5741                        case clang::BuiltinType::Dependent:
5742                        case clang::BuiltinType::Overload:
5743                        case clang::BuiltinType::ObjCId:
5744                        case clang::BuiltinType::ObjCClass:
5745                        case clang::BuiltinType::ObjCSel:
5746                        case clang::BuiltinType::BoundMember:
5747                        case clang::BuiltinType::Half:
5748                        case clang::BuiltinType::ARCUnbridgedCast:
5749                        case clang::BuiltinType::PseudoObject:
5750                        case clang::BuiltinType::BuiltinFn:
5751                        case clang::BuiltinType::OCLEvent:
5752                        case clang::BuiltinType::OCLImage1d:
5753                        case clang::BuiltinType::OCLImage1dArray:
5754                        case clang::BuiltinType::OCLImage1dBuffer:
5755                        case clang::BuiltinType::OCLImage2d:
5756                        case clang::BuiltinType::OCLImage2dArray:
5757                        case clang::BuiltinType::OCLImage3d:
5758                        case clang::BuiltinType::OCLSampler:
5759                            break;
5760                    }
5761                    break;
5762
5763                case clang::Type::Record:
5764                    if (check_cplusplus)
5765                    {
5766                        CXXRecordDecl *cxx_record_decl = pointee_qual_type->getAsCXXRecordDecl();
5767                        if (cxx_record_decl)
5768                        {
5769                            bool is_complete = cxx_record_decl->isCompleteDefinition();
5770
5771                            if (is_complete)
5772                                success = cxx_record_decl->isDynamicClass();
5773                            else
5774                            {
5775                                ClangASTMetadata *metadata = GetMetadata (ast, (uintptr_t)cxx_record_decl);
5776                                if (metadata)
5777                                    success = metadata->GetIsDynamicCXXType();
5778                                else
5779                                {
5780                                    is_complete = ClangASTContext::GetCompleteType (ast, pointee_qual_type.getAsOpaquePtr());
5781                                    if (is_complete)
5782                                        success = cxx_record_decl->isDynamicClass();
5783                                    else
5784                                        success = false;
5785                                }
5786                            }
5787
5788                            if (success)
5789                            {
5790                                if (dynamic_pointee_type)
5791                                    *dynamic_pointee_type = pointee_qual_type.getAsOpaquePtr();
5792                                return true;
5793                            }
5794                        }
5795                    }
5796                    break;
5797
5798                case clang::Type::ObjCObject:
5799                case clang::Type::ObjCInterface:
5800                    if (check_objc)
5801                    {
5802                        if (dynamic_pointee_type)
5803                            *dynamic_pointee_type = pointee_qual_type.getAsOpaquePtr();
5804                        return true;
5805                    }
5806                    break;
5807
5808                default:
5809                    break;
5810            }
5811        }
5812    }
5813    if (dynamic_pointee_type)
5814        *dynamic_pointee_type = NULL;
5815    return false;
5816}
5817
5818
5819bool
5820ClangASTContext::IsPossibleCPlusPlusDynamicType (clang::ASTContext *ast, clang_type_t clang_type, clang_type_t *dynamic_pointee_type)
5821{
5822    return IsPossibleDynamicType (ast,
5823                                  clang_type,
5824                                  dynamic_pointee_type,
5825                                  true,     // Check for dynamic C++ types
5826                                  false);   // Check for dynamic ObjC types
5827}
5828
5829bool
5830ClangASTContext::IsReferenceType (clang_type_t clang_type, clang_type_t *target_type)
5831{
5832    if (clang_type == NULL)
5833        return false;
5834
5835    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
5836    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5837
5838    switch (type_class)
5839    {
5840    case clang::Type::LValueReference:
5841        if (target_type)
5842            *target_type = cast<LValueReferenceType>(qual_type)->desugar().getAsOpaquePtr();
5843        return true;
5844    case clang::Type::RValueReference:
5845        if (target_type)
5846            *target_type = cast<LValueReferenceType>(qual_type)->desugar().getAsOpaquePtr();
5847        return true;
5848    case clang::Type::Typedef:
5849        return ClangASTContext::IsReferenceType (cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
5850    case clang::Type::Elaborated:
5851        return ClangASTContext::IsReferenceType (cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
5852    default:
5853        break;
5854    }
5855
5856    return false;
5857}
5858
5859bool
5860ClangASTContext::IsPointerOrReferenceType (clang_type_t clang_type, clang_type_t*target_type)
5861{
5862    if (clang_type == NULL)
5863        return false;
5864
5865    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
5866    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5867    switch (type_class)
5868    {
5869    case clang::Type::Builtin:
5870        switch (cast<clang::BuiltinType>(qual_type)->getKind())
5871        {
5872        default:
5873            break;
5874        case clang::BuiltinType::ObjCId:
5875        case clang::BuiltinType::ObjCClass:
5876            return true;
5877        }
5878        return false;
5879    case clang::Type::ObjCObjectPointer:
5880        if (target_type)
5881            *target_type = cast<ObjCObjectPointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
5882        return true;
5883    case clang::Type::BlockPointer:
5884        if (target_type)
5885            *target_type = cast<BlockPointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
5886        return true;
5887    case clang::Type::Pointer:
5888        if (target_type)
5889            *target_type = cast<PointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
5890        return true;
5891    case clang::Type::MemberPointer:
5892        if (target_type)
5893            *target_type = cast<MemberPointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
5894        return true;
5895    case clang::Type::LValueReference:
5896        if (target_type)
5897            *target_type = cast<LValueReferenceType>(qual_type)->desugar().getAsOpaquePtr();
5898        return true;
5899    case clang::Type::RValueReference:
5900        if (target_type)
5901            *target_type = cast<LValueReferenceType>(qual_type)->desugar().getAsOpaquePtr();
5902        return true;
5903    case clang::Type::Typedef:
5904        return ClangASTContext::IsPointerOrReferenceType (cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
5905    case clang::Type::Elaborated:
5906        return ClangASTContext::IsPointerOrReferenceType (cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
5907    default:
5908        break;
5909    }
5910    return false;
5911}
5912
5913bool
5914ClangASTContext::IsIntegerType (clang_type_t clang_type, bool &is_signed)
5915{
5916    if (!clang_type)
5917        return false;
5918
5919    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
5920    const BuiltinType *builtin_type = dyn_cast<BuiltinType>(qual_type->getCanonicalTypeInternal());
5921
5922    if (builtin_type)
5923    {
5924        if (builtin_type->isInteger())
5925        {
5926            is_signed = builtin_type->isSignedInteger();
5927            return true;
5928        }
5929    }
5930
5931    return false;
5932}
5933
5934bool
5935ClangASTContext::IsPointerType (clang_type_t clang_type, clang_type_t *target_type)
5936{
5937    if (target_type)
5938        *target_type = NULL;
5939
5940    if (clang_type)
5941    {
5942        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
5943        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5944        switch (type_class)
5945        {
5946        case clang::Type::Builtin:
5947            switch (cast<clang::BuiltinType>(qual_type)->getKind())
5948            {
5949            default:
5950                break;
5951            case clang::BuiltinType::ObjCId:
5952            case clang::BuiltinType::ObjCClass:
5953                return true;
5954            }
5955            return false;
5956        case clang::Type::ObjCObjectPointer:
5957            if (target_type)
5958                *target_type = cast<ObjCObjectPointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
5959            return true;
5960        case clang::Type::BlockPointer:
5961            if (target_type)
5962                *target_type = cast<BlockPointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
5963            return true;
5964        case clang::Type::Pointer:
5965            if (target_type)
5966                *target_type = cast<PointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
5967            return true;
5968        case clang::Type::MemberPointer:
5969            if (target_type)
5970                *target_type = cast<MemberPointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
5971            return true;
5972        case clang::Type::Typedef:
5973            return ClangASTContext::IsPointerType (cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(), target_type);
5974        case clang::Type::Elaborated:
5975            return ClangASTContext::IsPointerType (cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(), target_type);
5976        default:
5977            break;
5978        }
5979    }
5980    return false;
5981}
5982
5983bool
5984ClangASTContext::IsFloatingPointType (clang_type_t clang_type, uint32_t &count, bool &is_complex)
5985{
5986    if (clang_type)
5987    {
5988        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
5989
5990        if (const BuiltinType *BT = dyn_cast<BuiltinType>(qual_type->getCanonicalTypeInternal()))
5991        {
5992            clang::BuiltinType::Kind kind = BT->getKind();
5993            if (kind >= BuiltinType::Float && kind <= BuiltinType::LongDouble)
5994            {
5995                count = 1;
5996                is_complex = false;
5997                return true;
5998            }
5999        }
6000        else if (const ComplexType *CT = dyn_cast<ComplexType>(qual_type->getCanonicalTypeInternal()))
6001        {
6002            if (IsFloatingPointType(CT->getElementType().getAsOpaquePtr(), count, is_complex))
6003            {
6004                count = 2;
6005                is_complex = true;
6006                return true;
6007            }
6008        }
6009        else if (const VectorType *VT = dyn_cast<VectorType>(qual_type->getCanonicalTypeInternal()))
6010        {
6011            if (IsFloatingPointType(VT->getElementType().getAsOpaquePtr(), count, is_complex))
6012            {
6013                count = VT->getNumElements();
6014                is_complex = false;
6015                return true;
6016            }
6017        }
6018    }
6019    return false;
6020}
6021
6022bool
6023ClangASTContext::IsScalarType (lldb::clang_type_t clang_type)
6024{
6025    bool is_signed;
6026    if (ClangASTContext::IsIntegerType(clang_type, is_signed))
6027        return true;
6028
6029    uint32_t count;
6030    bool is_complex;
6031    return ClangASTContext::IsFloatingPointType(clang_type, count, is_complex) && !is_complex;
6032}
6033
6034bool
6035ClangASTContext::IsPointerToScalarType (lldb::clang_type_t clang_type)
6036{
6037    if (!IsPointerType(clang_type))
6038        return false;
6039
6040    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6041    lldb::clang_type_t pointee_type = qual_type.getTypePtr()->getPointeeType().getAsOpaquePtr();
6042    return IsScalarType(pointee_type);
6043}
6044
6045bool
6046ClangASTContext::IsArrayOfScalarType (lldb::clang_type_t clang_type)
6047{
6048    clang_type = GetAsArrayType(clang_type, NULL, NULL, NULL);
6049
6050    if (clang_type == 0)
6051        return false;
6052
6053    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6054    lldb::clang_type_t item_type = cast<ArrayType>(qual_type.getTypePtr())->getElementType().getAsOpaquePtr();
6055    return IsScalarType(item_type);
6056}
6057
6058
6059bool
6060ClangASTContext::GetCXXClassName (clang_type_t clang_type, std::string &class_name)
6061{
6062    if (clang_type)
6063    {
6064        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6065
6066        CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
6067        if (cxx_record_decl)
6068        {
6069            class_name.assign (cxx_record_decl->getIdentifier()->getNameStart());
6070            return true;
6071        }
6072    }
6073    class_name.clear();
6074    return false;
6075}
6076
6077
6078bool
6079ClangASTContext::IsCXXClassType (clang_type_t clang_type)
6080{
6081    if (clang_type)
6082    {
6083        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6084        if (qual_type->getAsCXXRecordDecl() != NULL)
6085            return true;
6086    }
6087    return false;
6088}
6089
6090bool
6091ClangASTContext::IsBeingDefined (lldb::clang_type_t clang_type)
6092{
6093    if (clang_type)
6094    {
6095        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6096        const clang::TagType *tag_type = dyn_cast<clang::TagType>(qual_type);
6097        if (tag_type)
6098            return tag_type->isBeingDefined();
6099    }
6100    return false;
6101}
6102
6103bool
6104ClangASTContext::IsObjCClassType (clang_type_t clang_type)
6105{
6106    if (clang_type)
6107    {
6108        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6109        if (qual_type->isObjCObjectOrInterfaceType())
6110            return true;
6111    }
6112    return false;
6113}
6114
6115bool
6116ClangASTContext::IsObjCObjectPointerType (lldb::clang_type_t clang_type, clang_type_t *class_type)
6117{
6118    if (clang_type)
6119    {
6120        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6121        if (qual_type->isObjCObjectPointerType())
6122        {
6123            if (class_type)
6124            {
6125                *class_type = NULL;
6126
6127                if (!qual_type->isObjCClassType() &&
6128                    !qual_type->isObjCIdType())
6129                {
6130                    const ObjCObjectPointerType *obj_pointer_type = dyn_cast<ObjCObjectPointerType>(qual_type);
6131                    if (!obj_pointer_type)
6132                        *class_type = NULL;
6133                    else
6134                        *class_type = QualType(obj_pointer_type->getInterfaceType(), 0).getAsOpaquePtr();
6135                }
6136            }
6137            return true;
6138        }
6139    }
6140    return false;
6141}
6142
6143bool
6144ClangASTContext::GetObjCClassName (lldb::clang_type_t clang_type,
6145                                   std::string &class_name)
6146{
6147    if (!clang_type)
6148        return false;
6149
6150    const ObjCObjectType *object_type = dyn_cast<ObjCObjectType>(QualType::getFromOpaquePtr(clang_type));
6151    if (!object_type)
6152        return false;
6153
6154    const ObjCInterfaceDecl *interface = object_type->getInterface();
6155    if (!interface)
6156        return false;
6157
6158    class_name = interface->getNameAsString();
6159    return true;
6160}
6161
6162bool
6163ClangASTContext::IsCharType (clang_type_t clang_type)
6164{
6165    if (clang_type)
6166        return QualType::getFromOpaquePtr(clang_type)->isCharType();
6167    return false;
6168}
6169
6170bool
6171ClangASTContext::IsCStringType (clang_type_t clang_type, uint32_t &length)
6172{
6173    clang_type_t pointee_or_element_clang_type = NULL;
6174    Flags type_flags (ClangASTContext::GetTypeInfo (clang_type, NULL, &pointee_or_element_clang_type));
6175
6176    if (pointee_or_element_clang_type == NULL)
6177        return false;
6178
6179    if (type_flags.AnySet (eTypeIsArray | eTypeIsPointer))
6180    {
6181        QualType pointee_or_element_qual_type (QualType::getFromOpaquePtr (pointee_or_element_clang_type));
6182
6183        if (pointee_or_element_qual_type.getUnqualifiedType()->isCharType())
6184        {
6185            QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6186            if (type_flags.Test (eTypeIsArray))
6187            {
6188                // We know the size of the array and it could be a C string
6189                // since it is an array of characters
6190                length = cast<ConstantArrayType>(qual_type.getTypePtr())->getSize().getLimitedValue();
6191                return true;
6192            }
6193            else
6194            {
6195                length = 0;
6196                return true;
6197            }
6198
6199        }
6200    }
6201    return false;
6202}
6203
6204bool
6205ClangASTContext::IsFunctionPointerType (clang_type_t clang_type)
6206{
6207    if (clang_type)
6208    {
6209        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6210
6211        if (qual_type->isFunctionPointerType())
6212            return true;
6213
6214        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
6215        switch (type_class)
6216        {
6217        default:
6218            break;
6219        case clang::Type::Typedef:
6220            return ClangASTContext::IsFunctionPointerType (cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
6221        case clang::Type::Elaborated:
6222            return ClangASTContext::IsFunctionPointerType (cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
6223
6224        case clang::Type::LValueReference:
6225        case clang::Type::RValueReference:
6226            {
6227                const ReferenceType *reference_type = cast<ReferenceType>(qual_type.getTypePtr());
6228                if (reference_type)
6229                    return ClangASTContext::IsFunctionPointerType (reference_type->getPointeeType().getAsOpaquePtr());
6230            }
6231            break;
6232        }
6233    }
6234    return false;
6235}
6236
6237size_t
6238ClangASTContext::GetArraySize (clang_type_t clang_type)
6239{
6240    if (clang_type)
6241    {
6242        QualType qual_type(QualType::getFromOpaquePtr(clang_type));
6243        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
6244        switch (type_class)
6245        {
6246        case clang::Type::ConstantArray:
6247            {
6248                const ConstantArrayType *array = cast<ConstantArrayType>(QualType::getFromOpaquePtr(clang_type).getTypePtr());
6249                if (array)
6250                    return array->getSize().getLimitedValue();
6251            }
6252            break;
6253
6254        case clang::Type::Typedef:
6255            return ClangASTContext::GetArraySize(cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
6256
6257        case clang::Type::Elaborated:
6258            return ClangASTContext::GetArraySize(cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
6259
6260        default:
6261            break;
6262        }
6263    }
6264    return 0;
6265}
6266
6267clang_type_t
6268ClangASTContext::GetAsArrayType (clang_type_t clang_type, clang_type_t*member_type, uint64_t *size, bool *is_incomplete)
6269{
6270    if (is_incomplete)
6271        *is_incomplete = false;
6272    if (!clang_type)
6273        return 0;
6274
6275    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6276
6277    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
6278    switch (type_class)
6279    {
6280    default:
6281        break;
6282
6283    case clang::Type::ConstantArray:
6284        if (member_type)
6285            *member_type = cast<ConstantArrayType>(qual_type)->getElementType().getAsOpaquePtr();
6286        if (size)
6287            *size = cast<ConstantArrayType>(qual_type)->getSize().getLimitedValue(ULLONG_MAX);
6288        return clang_type;
6289
6290    case clang::Type::IncompleteArray:
6291        if (member_type)
6292            *member_type = cast<IncompleteArrayType>(qual_type)->getElementType().getAsOpaquePtr();
6293        if (size)
6294            *size = 0;
6295        if (is_incomplete)
6296            *is_incomplete = true;
6297        return clang_type;
6298
6299    case clang::Type::VariableArray:
6300        if (member_type)
6301            *member_type = cast<VariableArrayType>(qual_type)->getElementType().getAsOpaquePtr();
6302        if (size)
6303            *size = 0;
6304        return clang_type;
6305
6306    case clang::Type::DependentSizedArray:
6307        if (member_type)
6308            *member_type = cast<DependentSizedArrayType>(qual_type)->getElementType().getAsOpaquePtr();
6309        if (size)
6310            *size = 0;
6311        return clang_type;
6312
6313    case clang::Type::Typedef:
6314        return ClangASTContext::GetAsArrayType (cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(),
6315                                                member_type,
6316                                                size,
6317                                                is_incomplete);
6318
6319    case clang::Type::Elaborated:
6320        return ClangASTContext::GetAsArrayType (cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(),
6321                                                member_type,
6322                                                size,
6323                                                is_incomplete);
6324    }
6325    return 0;
6326}
6327
6328
6329#pragma mark Typedefs
6330
6331clang_type_t
6332ClangASTContext::CreateTypedefType (const char *name, clang_type_t clang_type, DeclContext *decl_ctx)
6333{
6334    if (clang_type)
6335    {
6336        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6337        ASTContext *ast = getASTContext();
6338        IdentifierTable *identifier_table = getIdentifierTable();
6339        assert (ast != NULL);
6340        assert (identifier_table != NULL);
6341        if (decl_ctx == NULL)
6342            decl_ctx = ast->getTranslationUnitDecl();
6343        TypedefDecl *decl = TypedefDecl::Create (*ast,
6344                                                 decl_ctx,
6345                                                 SourceLocation(),
6346                                                 SourceLocation(),
6347                                                 name ? &identifier_table->get(name) : NULL, // Identifier
6348                                                 ast->getTrivialTypeSourceInfo(qual_type));
6349
6350        //decl_ctx->addDecl (decl);
6351
6352        decl->setAccess(AS_public); // TODO respect proper access specifier
6353
6354        // Get a uniqued QualType for the typedef decl type
6355        return ast->getTypedefType (decl).getAsOpaquePtr();
6356    }
6357    return NULL;
6358}
6359
6360// Disable this for now since I can't seem to get a nicely formatted float
6361// out of the APFloat class without just getting the float, double or quad
6362// and then using a formatted print on it which defeats the purpose. We ideally
6363// would like to get perfect string values for any kind of float semantics
6364// so we can support remote targets. The code below also requires a patch to
6365// llvm::APInt.
6366//bool
6367//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)
6368//{
6369//  uint32_t count = 0;
6370//  bool is_complex = false;
6371//  if (ClangASTContext::IsFloatingPointType (clang_type, count, is_complex))
6372//  {
6373//      unsigned num_bytes_per_float = byte_size / count;
6374//      unsigned num_bits_per_float = num_bytes_per_float * 8;
6375//
6376//      float_str.clear();
6377//      uint32_t i;
6378//      for (i=0; i<count; i++)
6379//      {
6380//          APInt ap_int(num_bits_per_float, bytes + i * num_bytes_per_float, (APInt::ByteOrder)apint_byte_order);
6381//          bool is_ieee = false;
6382//          APFloat ap_float(ap_int, is_ieee);
6383//          char s[1024];
6384//          unsigned int hex_digits = 0;
6385//          bool upper_case = false;
6386//
6387//          if (ap_float.convertToHexString(s, hex_digits, upper_case, APFloat::rmNearestTiesToEven) > 0)
6388//          {
6389//              if (i > 0)
6390//                  float_str.append(", ");
6391//              float_str.append(s);
6392//              if (i == 1 && is_complex)
6393//                  float_str.append(1, 'i');
6394//          }
6395//      }
6396//      return !float_str.empty();
6397//  }
6398//  return false;
6399//}
6400
6401size_t
6402ClangASTContext::ConvertStringToFloatValue (ASTContext *ast, clang_type_t clang_type, const char *s, uint8_t *dst, size_t dst_size)
6403{
6404    if (clang_type)
6405    {
6406        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6407        uint32_t count = 0;
6408        bool is_complex = false;
6409        if (ClangASTContext::IsFloatingPointType (clang_type, count, is_complex))
6410        {
6411            // TODO: handle complex and vector types
6412            if (count != 1)
6413                return false;
6414
6415            StringRef s_sref(s);
6416            APFloat ap_float(ast->getFloatTypeSemantics(qual_type), s_sref);
6417
6418            const uint64_t bit_size = ast->getTypeSize (qual_type);
6419            const uint64_t byte_size = bit_size / 8;
6420            if (dst_size >= byte_size)
6421            {
6422                if (bit_size == sizeof(float)*8)
6423                {
6424                    float float32 = ap_float.convertToFloat();
6425                    ::memcpy (dst, &float32, byte_size);
6426                    return byte_size;
6427                }
6428                else if (bit_size >= 64)
6429                {
6430                    llvm::APInt ap_int(ap_float.bitcastToAPInt());
6431                    ::memcpy (dst, ap_int.getRawData(), byte_size);
6432                    return byte_size;
6433                }
6434            }
6435        }
6436    }
6437    return 0;
6438}
6439
6440unsigned
6441ClangASTContext::GetTypeQualifiers(clang_type_t clang_type)
6442{
6443    assert (clang_type);
6444
6445    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6446
6447    return qual_type.getQualifiers().getCVRQualifiers();
6448}
6449
6450bool
6451ClangASTContext::GetCompleteType (clang::ASTContext *ast, lldb::clang_type_t clang_type)
6452{
6453    if (clang_type == NULL)
6454        return false;
6455
6456    return GetCompleteQualType (ast, clang::QualType::getFromOpaquePtr(clang_type));
6457}
6458
6459
6460bool
6461ClangASTContext::GetCompleteType (clang_type_t clang_type)
6462{
6463    return ClangASTContext::GetCompleteType (getASTContext(), clang_type);
6464}
6465
6466bool
6467ClangASTContext::IsCompleteType (clang::ASTContext *ast, lldb::clang_type_t clang_type)
6468{
6469    if (clang_type == NULL)
6470        return false;
6471
6472    return GetCompleteQualType (ast, clang::QualType::getFromOpaquePtr(clang_type), false); // just check but don't let it actually complete
6473}
6474
6475
6476bool
6477ClangASTContext::IsCompleteType (clang_type_t clang_type)
6478{
6479    return ClangASTContext::IsCompleteType (getASTContext(), clang_type);
6480}
6481
6482bool
6483ClangASTContext::GetCompleteDecl (clang::ASTContext *ast,
6484                                  clang::Decl *decl)
6485{
6486    if (!decl)
6487        return false;
6488
6489    ExternalASTSource *ast_source = ast->getExternalSource();
6490
6491    if (!ast_source)
6492        return false;
6493
6494    if (clang::TagDecl *tag_decl = llvm::dyn_cast<clang::TagDecl>(decl))
6495    {
6496        if (tag_decl->isCompleteDefinition())
6497            return true;
6498
6499        if (!tag_decl->hasExternalLexicalStorage())
6500            return false;
6501
6502        ast_source->CompleteType(tag_decl);
6503
6504        return !tag_decl->getTypeForDecl()->isIncompleteType();
6505    }
6506    else if (clang::ObjCInterfaceDecl *objc_interface_decl = llvm::dyn_cast<clang::ObjCInterfaceDecl>(decl))
6507    {
6508        if (objc_interface_decl->getDefinition())
6509            return true;
6510
6511        if (!objc_interface_decl->hasExternalLexicalStorage())
6512            return false;
6513
6514        ast_source->CompleteType(objc_interface_decl);
6515
6516        return !objc_interface_decl->getTypeForDecl()->isIncompleteType();
6517    }
6518    else
6519    {
6520        return false;
6521    }
6522}
6523
6524void
6525ClangASTContext::SetMetadataAsUserID (uintptr_t object,
6526                                      user_id_t user_id)
6527{
6528    ClangASTMetadata meta_data;
6529    meta_data.SetUserID (user_id);
6530    SetMetadata (object, meta_data);
6531}
6532
6533void
6534ClangASTContext::SetMetadata (clang::ASTContext *ast,
6535                              uintptr_t object,
6536                              ClangASTMetadata &metadata)
6537{
6538    ClangExternalASTSourceCommon *external_source =
6539        static_cast<ClangExternalASTSourceCommon*>(ast->getExternalSource());
6540
6541    if (external_source)
6542        external_source->SetMetadata(object, metadata);
6543}
6544
6545ClangASTMetadata *
6546ClangASTContext::GetMetadata (clang::ASTContext *ast,
6547                              uintptr_t object)
6548{
6549    ClangExternalASTSourceCommon *external_source =
6550        static_cast<ClangExternalASTSourceCommon*>(ast->getExternalSource());
6551
6552    if (external_source && external_source->HasMetadata(object))
6553        return external_source->GetMetadata(object);
6554    else
6555        return NULL;
6556}
6557
6558clang::DeclContext *
6559ClangASTContext::GetAsDeclContext (clang::CXXMethodDecl *cxx_method_decl)
6560{
6561    return llvm::dyn_cast<clang::DeclContext>(cxx_method_decl);
6562}
6563
6564clang::DeclContext *
6565ClangASTContext::GetAsDeclContext (clang::ObjCMethodDecl *objc_method_decl)
6566{
6567    return llvm::dyn_cast<clang::DeclContext>(objc_method_decl);
6568}
6569
6570
6571bool
6572ClangASTContext::GetClassMethodInfoForDeclContext (clang::DeclContext *decl_ctx,
6573                                                   lldb::LanguageType &language,
6574                                                   bool &is_instance_method,
6575                                                   ConstString &language_object_name)
6576{
6577    language_object_name.Clear();
6578    language = eLanguageTypeUnknown;
6579    is_instance_method = false;
6580
6581    if (decl_ctx)
6582    {
6583        if (clang::CXXMethodDecl *method_decl = llvm::dyn_cast<clang::CXXMethodDecl>(decl_ctx))
6584        {
6585            if (method_decl->isStatic())
6586            {
6587                is_instance_method = false;
6588            }
6589            else
6590            {
6591                language_object_name.SetCString("this");
6592                is_instance_method = true;
6593            }
6594            language = eLanguageTypeC_plus_plus;
6595            return true;
6596        }
6597        else if (clang::ObjCMethodDecl *method_decl = llvm::dyn_cast<clang::ObjCMethodDecl>(decl_ctx))
6598        {
6599            // Both static and instance methods have a "self" object in objective C
6600            language_object_name.SetCString("self");
6601            if (method_decl->isInstanceMethod())
6602            {
6603                is_instance_method = true;
6604            }
6605            else
6606            {
6607                is_instance_method = false;
6608            }
6609            language = eLanguageTypeObjC;
6610            return true;
6611        }
6612        else if (clang::FunctionDecl *function_decl = llvm::dyn_cast<clang::FunctionDecl>(decl_ctx))
6613        {
6614            ClangASTMetadata *metadata = GetMetadata (&decl_ctx->getParentASTContext(), (uintptr_t) function_decl);
6615            if (metadata && metadata->HasObjectPtr())
6616            {
6617                language_object_name.SetCString (metadata->GetObjectPtrName());
6618                language = eLanguageTypeObjC;
6619                is_instance_method = true;
6620            }
6621            return true;
6622        }
6623    }
6624    return false;
6625}
6626
6627