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