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