ClangASTContext.cpp revision bf8e42b9da0e1c6349a727d644ad37610b00d556
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#define NDEBUG
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/ASTImporter.h"
20#include "clang/AST/CXXInheritance.h"
21#include "clang/AST/DeclObjC.h"
22#include "clang/AST/RecordLayout.h"
23#include "clang/AST/Type.h"
24#include "clang/Basic/Builtins.h"
25#include "clang/Basic/FileManager.h"
26#include "clang/Basic/SourceManager.h"
27#include "clang/Basic/TargetInfo.h"
28#include "clang/Basic/TargetOptions.h"
29#include "clang/Frontend/FrontendOptions.h"
30#include "clang/Frontend/LangStandard.h"
31#undef NDEBUG
32
33#include "lldb/Core/dwarf.h"
34
35#include <stdio.h>
36
37using namespace lldb;
38using namespace lldb_private;
39using namespace llvm;
40using namespace clang;
41
42static AccessSpecifier
43ConvertAccessTypeToAccessSpecifier (AccessType access)
44{
45    switch (access)
46    {
47    default:               break;
48    case eAccessNone:      return AS_none;
49    case eAccessPublic:    return AS_public;
50    case eAccessPrivate:   return AS_private;
51    case eAccessProtected: return AS_protected;
52    }
53    return AS_none;
54}
55
56static ObjCIvarDecl::AccessControl
57ConvertAccessTypeToObjCIvarAccessControl (AccessType access)
58{
59    switch (access)
60    {
61    default:               break;
62    case eAccessNone:      return ObjCIvarDecl::None;
63    case eAccessPublic:    return ObjCIvarDecl::Public;
64    case eAccessPrivate:   return ObjCIvarDecl::Private;
65    case eAccessProtected: return ObjCIvarDecl::Protected;
66    case eAccessPackage:   return ObjCIvarDecl::Package;
67    }
68    return ObjCIvarDecl::None;
69}
70
71
72static void
73ParseLangArgs
74(
75    LangOptions &Opts,
76    InputKind IK
77)
78{
79    // FIXME: Cleanup per-file based stuff.
80
81    // Set some properties which depend soley on the input kind; it would be nice
82    // to move these to the language standard, and have the driver resolve the
83    // input kind + language standard.
84    if (IK == IK_Asm) {
85        Opts.AsmPreprocessor = 1;
86    } else if (IK == IK_ObjC ||
87               IK == IK_ObjCXX ||
88               IK == IK_PreprocessedObjC ||
89               IK == IK_PreprocessedObjCXX) {
90        Opts.ObjC1 = Opts.ObjC2 = 1;
91    }
92
93    LangStandard::Kind LangStd = LangStandard::lang_unspecified;
94
95    if (LangStd == LangStandard::lang_unspecified) {
96        // Based on the base language, pick one.
97        switch (IK) {
98            case IK_None:
99            case IK_AST:
100                assert(0 && "Invalid input kind!");
101            case IK_OpenCL:
102                LangStd = LangStandard::lang_opencl;
103                break;
104            case IK_Asm:
105            case IK_C:
106            case IK_PreprocessedC:
107            case IK_ObjC:
108            case IK_PreprocessedObjC:
109                LangStd = LangStandard::lang_gnu99;
110                break;
111            case IK_CXX:
112            case IK_PreprocessedCXX:
113            case IK_ObjCXX:
114            case IK_PreprocessedObjCXX:
115                LangStd = LangStandard::lang_gnucxx98;
116                break;
117        }
118    }
119
120    const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd);
121    Opts.BCPLComment = Std.hasBCPLComments();
122    Opts.C99 = Std.isC99();
123    Opts.CPlusPlus = Std.isCPlusPlus();
124    Opts.CPlusPlus0x = Std.isCPlusPlus0x();
125    Opts.Digraphs = Std.hasDigraphs();
126    Opts.GNUMode = Std.isGNUMode();
127    Opts.GNUInline = !Std.isC99();
128    Opts.HexFloats = Std.hasHexFloats();
129    Opts.ImplicitInt = Std.hasImplicitInt();
130
131    // OpenCL has some additional defaults.
132    if (LangStd == LangStandard::lang_opencl) {
133        Opts.OpenCL = 1;
134        Opts.AltiVec = 1;
135        Opts.CXXOperatorNames = 1;
136        Opts.LaxVectorConversions = 1;
137    }
138
139    // OpenCL and C++ both have bool, true, false keywords.
140    Opts.Bool = Opts.OpenCL || Opts.CPlusPlus;
141
142//    if (Opts.CPlusPlus)
143//        Opts.CXXOperatorNames = !Args.hasArg(OPT_fno_operator_names);
144//
145//    if (Args.hasArg(OPT_fobjc_gc_only))
146//        Opts.setGCMode(LangOptions::GCOnly);
147//    else if (Args.hasArg(OPT_fobjc_gc))
148//        Opts.setGCMode(LangOptions::HybridGC);
149//
150//    if (Args.hasArg(OPT_print_ivar_layout))
151//        Opts.ObjCGCBitmapPrint = 1;
152//
153//    if (Args.hasArg(OPT_faltivec))
154//        Opts.AltiVec = 1;
155//
156//    if (Args.hasArg(OPT_pthread))
157//        Opts.POSIXThreads = 1;
158//
159//    llvm::StringRef Vis = getLastArgValue(Args, OPT_fvisibility,
160//                                          "default");
161//    if (Vis == "default")
162        Opts.setVisibilityMode(LangOptions::Default);
163//    else if (Vis == "hidden")
164//        Opts.setVisibilityMode(LangOptions::Hidden);
165//    else if (Vis == "protected")
166//        Opts.setVisibilityMode(LangOptions::Protected);
167//    else
168//        Diags.Report(diag::err_drv_invalid_value)
169//        << Args.getLastArg(OPT_fvisibility)->getAsString(Args) << Vis;
170
171//    Opts.OverflowChecking = Args.hasArg(OPT_ftrapv);
172
173    // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs
174    // is specified, or -std is set to a conforming mode.
175    Opts.Trigraphs = !Opts.GNUMode;
176//    if (Args.hasArg(OPT_trigraphs))
177//        Opts.Trigraphs = 1;
178//
179//    Opts.DollarIdents = Args.hasFlag(OPT_fdollars_in_identifiers,
180//                                     OPT_fno_dollars_in_identifiers,
181//                                     !Opts.AsmPreprocessor);
182//    Opts.PascalStrings = Args.hasArg(OPT_fpascal_strings);
183//    Opts.Microsoft = Args.hasArg(OPT_fms_extensions);
184//    Opts.WritableStrings = Args.hasArg(OPT_fwritable_strings);
185//    if (Args.hasArg(OPT_fno_lax_vector_conversions))
186//        Opts.LaxVectorConversions = 0;
187//    Opts.Exceptions = Args.hasArg(OPT_fexceptions);
188//    Opts.RTTI = !Args.hasArg(OPT_fno_rtti);
189//    Opts.Blocks = Args.hasArg(OPT_fblocks);
190//    Opts.CharIsSigned = !Args.hasArg(OPT_fno_signed_char);
191//    Opts.ShortWChar = Args.hasArg(OPT_fshort_wchar);
192//    Opts.Freestanding = Args.hasArg(OPT_ffreestanding);
193//    Opts.NoBuiltin = Args.hasArg(OPT_fno_builtin) || Opts.Freestanding;
194//    Opts.AssumeSaneOperatorNew = !Args.hasArg(OPT_fno_assume_sane_operator_new);
195//    Opts.HeinousExtensions = Args.hasArg(OPT_fheinous_gnu_extensions);
196//    Opts.AccessControl = Args.hasArg(OPT_faccess_control);
197//    Opts.ElideConstructors = !Args.hasArg(OPT_fno_elide_constructors);
198//    Opts.MathErrno = !Args.hasArg(OPT_fno_math_errno);
199//    Opts.InstantiationDepth = getLastArgIntValue(Args, OPT_ftemplate_depth, 99,
200//                                                 Diags);
201//    Opts.NeXTRuntime = !Args.hasArg(OPT_fgnu_runtime);
202//    Opts.ObjCConstantStringClass = getLastArgValue(Args,
203//                                                   OPT_fconstant_string_class);
204//    Opts.ObjCNonFragileABI = Args.hasArg(OPT_fobjc_nonfragile_abi);
205//    Opts.CatchUndefined = Args.hasArg(OPT_fcatch_undefined_behavior);
206//    Opts.EmitAllDecls = Args.hasArg(OPT_femit_all_decls);
207//    Opts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags);
208//    Opts.Static = Args.hasArg(OPT_static_define);
209    Opts.OptimizeSize = 0;
210
211    // FIXME: Eliminate this dependency.
212//    unsigned Opt =
213//    Args.hasArg(OPT_Os) ? 2 : getLastArgIntValue(Args, OPT_O, 0, Diags);
214//    Opts.Optimize = Opt != 0;
215    unsigned Opt = 0;
216
217    // This is the __NO_INLINE__ define, which just depends on things like the
218    // optimization level and -fno-inline, not actually whether the backend has
219    // inlining enabled.
220    //
221    // FIXME: This is affected by other options (-fno-inline).
222    Opts.NoInline = !Opt;
223
224//    unsigned SSP = getLastArgIntValue(Args, OPT_stack_protector, 0, Diags);
225//    switch (SSP) {
226//        default:
227//            Diags.Report(diag::err_drv_invalid_value)
228//            << Args.getLastArg(OPT_stack_protector)->getAsString(Args) << SSP;
229//            break;
230//        case 0: Opts.setStackProtectorMode(LangOptions::SSPOff); break;
231//        case 1: Opts.setStackProtectorMode(LangOptions::SSPOn);  break;
232//        case 2: Opts.setStackProtectorMode(LangOptions::SSPReq); break;
233//    }
234}
235
236
237ClangASTContext::ClangASTContext(const char *target_triple) :
238    m_target_triple(),
239    m_ast_context_ap(),
240    m_language_options_ap(),
241    m_source_manager_ap(),
242    m_diagnostic_ap(),
243    m_target_options_ap(),
244    m_target_info_ap(),
245    m_identifier_table_ap(),
246    m_selector_table_ap(),
247    m_builtins_ap()
248{
249    if (target_triple && target_triple[0])
250        m_target_triple.assign (target_triple);
251}
252
253//----------------------------------------------------------------------
254// Destructor
255//----------------------------------------------------------------------
256ClangASTContext::~ClangASTContext()
257{
258    m_builtins_ap.reset();
259    m_selector_table_ap.reset();
260    m_identifier_table_ap.reset();
261    m_target_info_ap.reset();
262    m_target_options_ap.reset();
263    m_diagnostic_ap.reset();
264    m_source_manager_ap.reset();
265    m_language_options_ap.reset();
266    m_ast_context_ap.reset();
267}
268
269
270void
271ClangASTContext::Clear()
272{
273    m_ast_context_ap.reset();
274    m_language_options_ap.reset();
275    m_source_manager_ap.reset();
276    m_diagnostic_ap.reset();
277    m_target_options_ap.reset();
278    m_target_info_ap.reset();
279    m_identifier_table_ap.reset();
280    m_selector_table_ap.reset();
281    m_builtins_ap.reset();
282}
283
284const char *
285ClangASTContext::GetTargetTriple ()
286{
287    return m_target_triple.c_str();
288}
289
290void
291ClangASTContext::SetTargetTriple (const char *target_triple)
292{
293    Clear();
294    m_target_triple.assign(target_triple);
295}
296
297
298ASTContext *
299ClangASTContext::getASTContext()
300{
301    if (m_ast_context_ap.get() == NULL)
302    {
303        m_ast_context_ap.reset(
304            new ASTContext(
305                *getLanguageOptions(),
306                *getSourceManager(),
307                *getTargetInfo(),
308                *getIdentifierTable(),
309                *getSelectorTable(),
310                *getBuiltinContext(),
311                0));
312    }
313    return m_ast_context_ap.get();
314}
315
316Builtin::Context *
317ClangASTContext::getBuiltinContext()
318{
319    if (m_builtins_ap.get() == NULL)
320        m_builtins_ap.reset (new Builtin::Context(*getTargetInfo()));
321    return m_builtins_ap.get();
322}
323
324IdentifierTable *
325ClangASTContext::getIdentifierTable()
326{
327    if (m_identifier_table_ap.get() == NULL)
328        m_identifier_table_ap.reset(new IdentifierTable (*ClangASTContext::getLanguageOptions(), NULL));
329    return m_identifier_table_ap.get();
330}
331
332LangOptions *
333ClangASTContext::getLanguageOptions()
334{
335    if (m_language_options_ap.get() == NULL)
336    {
337        m_language_options_ap.reset(new LangOptions());
338        ParseLangArgs(*m_language_options_ap, IK_ObjCXX);
339//        InitializeLangOptions(*m_language_options_ap, IK_ObjCXX);
340    }
341    return m_language_options_ap.get();
342}
343
344SelectorTable *
345ClangASTContext::getSelectorTable()
346{
347    if (m_selector_table_ap.get() == NULL)
348        m_selector_table_ap.reset (new SelectorTable());
349    return m_selector_table_ap.get();
350}
351
352clang::SourceManager *
353ClangASTContext::getSourceManager()
354{
355    if (m_source_manager_ap.get() == NULL)
356        m_source_manager_ap.reset(new clang::SourceManager(*getDiagnostic()));
357    return m_source_manager_ap.get();
358}
359
360Diagnostic *
361ClangASTContext::getDiagnostic()
362{
363    if (m_diagnostic_ap.get() == NULL)
364        m_diagnostic_ap.reset(new Diagnostic());
365    return m_diagnostic_ap.get();
366}
367
368TargetOptions *
369ClangASTContext::getTargetOptions()
370{
371    if (m_target_options_ap.get() == NULL && !m_target_triple.empty())
372    {
373        m_target_options_ap.reset (new TargetOptions());
374        if (m_target_options_ap.get())
375            m_target_options_ap->Triple = m_target_triple;
376    }
377    return m_target_options_ap.get();
378}
379
380
381TargetInfo *
382ClangASTContext::getTargetInfo()
383{
384    // target_triple should be something like "x86_64-apple-darwin10"
385    if (m_target_info_ap.get() == NULL && !m_target_triple.empty())
386        m_target_info_ap.reset (TargetInfo::CreateTargetInfo(*getDiagnostic(), *getTargetOptions()));
387    return m_target_info_ap.get();
388}
389
390#pragma mark Basic Types
391
392static inline bool
393QualTypeMatchesBitSize(const uint64_t bit_size, ASTContext *ast_context, QualType qual_type)
394{
395    uint64_t qual_type_bit_size = ast_context->getTypeSize(qual_type);
396    if (qual_type_bit_size == bit_size)
397        return true;
398    return false;
399}
400
401clang_type_t
402ClangASTContext::GetBuiltinTypeForEncodingAndBitSize (Encoding encoding, uint32_t bit_size)
403{
404    ASTContext *ast_context = getASTContext();
405
406    assert (ast_context != NULL);
407
408    return GetBuiltinTypeForEncodingAndBitSize (ast_context, encoding, bit_size);
409}
410
411clang_type_t
412ClangASTContext::GetBuiltinTypeForEncodingAndBitSize (ASTContext *ast_context, Encoding encoding, uint32_t bit_size)
413{
414    if (!ast_context)
415        return NULL;
416
417    switch (encoding)
418    {
419    case eEncodingInvalid:
420        if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->VoidPtrTy))
421            return ast_context->VoidPtrTy.getAsOpaquePtr();
422        break;
423
424    case eEncodingUint:
425        if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedCharTy))
426            return ast_context->UnsignedCharTy.getAsOpaquePtr();
427        if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedShortTy))
428            return ast_context->UnsignedShortTy.getAsOpaquePtr();
429        if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedIntTy))
430            return ast_context->UnsignedIntTy.getAsOpaquePtr();
431        if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedLongTy))
432            return ast_context->UnsignedLongTy.getAsOpaquePtr();
433        if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedLongLongTy))
434            return ast_context->UnsignedLongLongTy.getAsOpaquePtr();
435        if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedInt128Ty))
436            return ast_context->UnsignedInt128Ty.getAsOpaquePtr();
437        break;
438
439    case eEncodingSint:
440        if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->CharTy))
441            return ast_context->CharTy.getAsOpaquePtr();
442        if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->ShortTy))
443            return ast_context->ShortTy.getAsOpaquePtr();
444        if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->IntTy))
445            return ast_context->IntTy.getAsOpaquePtr();
446        if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->LongTy))
447            return ast_context->LongTy.getAsOpaquePtr();
448        if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->LongLongTy))
449            return ast_context->LongLongTy.getAsOpaquePtr();
450        if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->Int128Ty))
451            return ast_context->Int128Ty.getAsOpaquePtr();
452        break;
453
454    case eEncodingIEEE754:
455        if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->FloatTy))
456            return ast_context->FloatTy.getAsOpaquePtr();
457        if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->DoubleTy))
458            return ast_context->DoubleTy.getAsOpaquePtr();
459        if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->LongDoubleTy))
460            return ast_context->LongDoubleTy.getAsOpaquePtr();
461        break;
462
463    case eEncodingVector:
464    default:
465        break;
466    }
467
468    return NULL;
469}
470
471clang_type_t
472ClangASTContext::GetBuiltinTypeForDWARFEncodingAndBitSize (const char *type_name, uint32_t dw_ate, uint32_t bit_size)
473{
474    ASTContext *ast_context = getASTContext();
475
476    #define streq(a,b) strcmp(a,b) == 0
477    assert (ast_context != NULL);
478    if (ast_context)
479    {
480        switch (dw_ate)
481        {
482        default:
483            break;
484
485        case DW_ATE_address:
486            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->VoidPtrTy))
487                return ast_context->VoidPtrTy.getAsOpaquePtr();
488            break;
489
490        case DW_ATE_boolean:
491            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->BoolTy))
492                return ast_context->BoolTy.getAsOpaquePtr();
493            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedCharTy))
494                return ast_context->UnsignedCharTy.getAsOpaquePtr();
495            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedShortTy))
496                return ast_context->UnsignedShortTy.getAsOpaquePtr();
497            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedIntTy))
498                return ast_context->UnsignedIntTy.getAsOpaquePtr();
499            break;
500
501        case DW_ATE_complex_float:
502            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->FloatComplexTy))
503                return ast_context->FloatComplexTy.getAsOpaquePtr();
504            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->DoubleComplexTy))
505                return ast_context->DoubleComplexTy.getAsOpaquePtr();
506            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->LongDoubleComplexTy))
507                return ast_context->LongDoubleComplexTy.getAsOpaquePtr();
508            break;
509
510        case DW_ATE_float:
511            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->FloatTy))
512                return ast_context->FloatTy.getAsOpaquePtr();
513            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->DoubleTy))
514                return ast_context->DoubleTy.getAsOpaquePtr();
515            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->LongDoubleTy))
516                return ast_context->LongDoubleTy.getAsOpaquePtr();
517            break;
518
519        case DW_ATE_signed:
520            if (type_name)
521            {
522                if (streq(type_name, "int") ||
523                    streq(type_name, "signed int"))
524                {
525                    if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->IntTy))
526                        return ast_context->IntTy.getAsOpaquePtr();
527                    if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->Int128Ty))
528                        return ast_context->Int128Ty.getAsOpaquePtr();
529                }
530
531                if (streq(type_name, "long int") ||
532                    streq(type_name, "long long int") ||
533                    streq(type_name, "signed long long"))
534                {
535                    if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->LongTy))
536                        return ast_context->LongTy.getAsOpaquePtr();
537                    if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->LongLongTy))
538                        return ast_context->LongLongTy.getAsOpaquePtr();
539                }
540
541                if (streq(type_name, "short") ||
542                    streq(type_name, "short int") ||
543                    streq(type_name, "signed short") ||
544                    streq(type_name, "short signed int"))
545                {
546                    if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->ShortTy))
547                        return ast_context->ShortTy.getAsOpaquePtr();
548                }
549
550                if (streq(type_name, "char") ||
551                    streq(type_name, "signed char"))
552                {
553                    if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->CharTy))
554                        return ast_context->CharTy.getAsOpaquePtr();
555                    if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->SignedCharTy))
556                        return ast_context->SignedCharTy.getAsOpaquePtr();
557                }
558
559                if (streq(type_name, "wchar_t"))
560                {
561                    if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->WCharTy))
562                        return ast_context->WCharTy.getAsOpaquePtr();
563                }
564
565            }
566            // We weren't able to match up a type name, just search by size
567            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->CharTy))
568                return ast_context->CharTy.getAsOpaquePtr();
569            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->ShortTy))
570                return ast_context->ShortTy.getAsOpaquePtr();
571            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->IntTy))
572                return ast_context->IntTy.getAsOpaquePtr();
573            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->LongTy))
574                return ast_context->LongTy.getAsOpaquePtr();
575            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->LongLongTy))
576                return ast_context->LongLongTy.getAsOpaquePtr();
577            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->Int128Ty))
578                return ast_context->Int128Ty.getAsOpaquePtr();
579            break;
580
581        case DW_ATE_signed_char:
582            if (type_name)
583            {
584                if (streq(type_name, "signed char"))
585                {
586                    if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->SignedCharTy))
587                        return ast_context->SignedCharTy.getAsOpaquePtr();
588                }
589            }
590            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->CharTy))
591                return ast_context->CharTy.getAsOpaquePtr();
592            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->SignedCharTy))
593                return ast_context->SignedCharTy.getAsOpaquePtr();
594            break;
595
596        case DW_ATE_unsigned:
597            if (type_name)
598            {
599                if (streq(type_name, "unsigned int"))
600                {
601                    if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedIntTy))
602                        return ast_context->UnsignedIntTy.getAsOpaquePtr();
603                    if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedInt128Ty))
604                        return ast_context->UnsignedInt128Ty.getAsOpaquePtr();
605                }
606
607                if (streq(type_name, "unsigned int") ||
608                    streq(type_name, "long unsigned int") ||
609                    streq(type_name, "unsigned long long"))
610                {
611                    if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedLongTy))
612                        return ast_context->UnsignedLongTy.getAsOpaquePtr();
613                    if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedLongLongTy))
614                        return ast_context->UnsignedLongLongTy.getAsOpaquePtr();
615                }
616
617                if (streq(type_name, "unsigned short") ||
618                    streq(type_name, "short unsigned int"))
619                {
620                    if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedShortTy))
621                        return ast_context->UnsignedShortTy.getAsOpaquePtr();
622                }
623                if (streq(type_name, "unsigned char"))
624                {
625                    if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedCharTy))
626                        return ast_context->UnsignedCharTy.getAsOpaquePtr();
627                }
628
629            }
630            // We weren't able to match up a type name, just search by size
631            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedCharTy))
632                return ast_context->UnsignedCharTy.getAsOpaquePtr();
633            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedShortTy))
634                return ast_context->UnsignedShortTy.getAsOpaquePtr();
635            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedIntTy))
636                return ast_context->UnsignedIntTy.getAsOpaquePtr();
637            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedLongTy))
638                return ast_context->UnsignedLongTy.getAsOpaquePtr();
639            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedLongLongTy))
640                return ast_context->UnsignedLongLongTy.getAsOpaquePtr();
641            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedInt128Ty))
642                return ast_context->UnsignedInt128Ty.getAsOpaquePtr();
643            break;
644
645        case DW_ATE_unsigned_char:
646            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedCharTy))
647                return ast_context->UnsignedCharTy.getAsOpaquePtr();
648            break;
649
650        case DW_ATE_imaginary_float:
651            break;
652        }
653    }
654    // This assert should fire for anything that we don't catch above so we know
655    // to fix any issues we run into.
656    assert (!"error: ClangASTContext::GetClangTypeForDWARFEncodingAndSize() contains an unhandled encoding. Fix this ASAP!");
657    return NULL;
658}
659
660clang_type_t
661ClangASTContext::GetBuiltInType_void(ASTContext *ast_context)
662{
663    return ast_context->VoidTy.getAsOpaquePtr();
664}
665
666clang_type_t
667ClangASTContext::GetBuiltInType_objc_id()
668{
669    return getASTContext()->getObjCIdType().getAsOpaquePtr();
670}
671
672clang_type_t
673ClangASTContext::GetBuiltInType_objc_Class()
674{
675    return getASTContext()->getObjCClassType().getAsOpaquePtr();
676}
677
678clang_type_t
679ClangASTContext::GetBuiltInType_objc_selector()
680{
681    return getASTContext()->getObjCSelType().getAsOpaquePtr();
682}
683
684clang_type_t
685ClangASTContext::GetCStringType (bool is_const)
686{
687    QualType char_type(getASTContext()->CharTy);
688
689    if (is_const)
690        char_type.addConst();
691
692    return getASTContext()->getPointerType(char_type).getAsOpaquePtr();
693}
694
695clang_type_t
696ClangASTContext::GetVoidPtrType (bool is_const)
697{
698    return GetVoidPtrType(getASTContext(), is_const);
699}
700
701clang_type_t
702ClangASTContext::GetVoidPtrType (ASTContext *ast_context, bool is_const)
703{
704    QualType void_ptr_type(ast_context->VoidPtrTy);
705
706    if (is_const)
707        void_ptr_type.addConst();
708
709    return void_ptr_type.getAsOpaquePtr();
710}
711
712clang_type_t
713ClangASTContext::CopyType (ASTContext *dest_context,
714                           ASTContext *source_context,
715                           clang_type_t clang_type)
716{
717    Diagnostic diagnostics;
718    FileManager file_manager;
719    ASTImporter importer(diagnostics,
720                         *dest_context, file_manager,
721                         *source_context, file_manager);
722    QualType ret = importer.Import(QualType::getFromOpaquePtr(clang_type));
723    return ret.getAsOpaquePtr();
724}
725
726bool
727ClangASTContext::AreTypesSame(ASTContext *ast_context,
728             clang_type_t type1,
729             clang_type_t type2)
730{
731    return ast_context->hasSameType(QualType::getFromOpaquePtr(type1),
732                                    QualType::getFromOpaquePtr(type2));
733}
734
735#pragma mark CVR modifiers
736
737clang_type_t
738ClangASTContext::AddConstModifier (clang_type_t clang_type)
739{
740    if (clang_type)
741    {
742        QualType result(QualType::getFromOpaquePtr(clang_type));
743        result.addConst();
744        return result.getAsOpaquePtr();
745    }
746    return NULL;
747}
748
749clang_type_t
750ClangASTContext::AddRestrictModifier (clang_type_t clang_type)
751{
752    if (clang_type)
753    {
754        QualType result(QualType::getFromOpaquePtr(clang_type));
755        result.getQualifiers().setRestrict (true);
756        return result.getAsOpaquePtr();
757    }
758    return NULL;
759}
760
761clang_type_t
762ClangASTContext::AddVolatileModifier (clang_type_t clang_type)
763{
764    if (clang_type)
765    {
766        QualType result(QualType::getFromOpaquePtr(clang_type));
767        result.getQualifiers().setVolatile (true);
768        return result.getAsOpaquePtr();
769    }
770    return NULL;
771}
772
773#pragma mark Structure, Unions, Classes
774
775clang_type_t
776ClangASTContext::CreateRecordType (const char *name, int kind, DeclContext *decl_ctx, LanguageType language)
777{
778    ASTContext *ast_context = getASTContext();
779    assert (ast_context != NULL);
780
781    if (decl_ctx == NULL)
782        decl_ctx = ast_context->getTranslationUnitDecl();
783
784
785    if (language == eLanguageTypeObjC)
786    {
787        bool isForwardDecl = true;
788        bool isInternal = false;
789        return CreateObjCClass (name, decl_ctx, isForwardDecl, isInternal);
790    }
791
792    // NOTE: Eventually CXXRecordDecl will be merged back into RecordDecl and
793    // we will need to update this code. I was told to currently always use
794    // the CXXRecordDecl class since we often don't know from debug information
795    // if something is struct or a class, so we default to always use the more
796    // complete definition just in case.
797    CXXRecordDecl *decl = CXXRecordDecl::Create(*ast_context,
798                                                (TagDecl::TagKind)kind,
799                                                decl_ctx,
800                                                SourceLocation(),
801                                                name && name[0] ? &ast_context->Idents.get(name) : NULL);
802
803    return ast_context->getTagDeclType(decl).getAsOpaquePtr();
804}
805
806static bool
807IsOperator (const char *name, OverloadedOperatorKind &op_kind)
808{
809    if (name == NULL || name[0] == '\0')
810        return false;
811
812    if (::strstr(name, "operator ") != name)
813        return false;
814
815    const char *post_op_name = name + 9;
816
817    // This is an operator, set the overloaded operator kind to invalid
818    // in case this is a conversion operator...
819    op_kind = NUM_OVERLOADED_OPERATORS;
820
821    switch (post_op_name[0])
822    {
823    case 'n':
824        if  (strcmp (post_op_name, "new") == 0)
825            op_kind = OO_New;
826        else if (strcmp (post_op_name, "new[]") == 0)
827            op_kind = OO_Array_New;
828        break;
829
830    case 'd':
831        if (strcmp (post_op_name, "delete") == 0)
832            op_kind = OO_Delete;
833        else if (strcmp (post_op_name, "delete[]") == 0)
834            op_kind = OO_Array_Delete;
835        break;
836
837    case '+':
838        if (post_op_name[1] == '\0')
839            op_kind = OO_Plus;
840        else if (post_op_name[2] == '\0')
841        {
842            if (post_op_name[1] == '=')
843                op_kind = OO_PlusEqual;
844            else if (post_op_name[1] == '+')
845                op_kind = OO_PlusPlus;
846        }
847        break;
848
849    case '-':
850        if (post_op_name[1] == '\0')
851            op_kind = OO_Minus;
852        else if (post_op_name[2] == '\0')
853        {
854            switch (post_op_name[1])
855            {
856            case '=': op_kind = OO_MinusEqual; break;
857            case '-': op_kind = OO_MinusMinus; break;
858            case '>': op_kind = OO_Arrow; break;
859            }
860        }
861        else if (post_op_name[3] == '\0')
862        {
863            if (post_op_name[2] == '*')
864                op_kind = OO_ArrowStar; break;
865        }
866        break;
867
868    case '*':
869        if (post_op_name[1] == '\0')
870            op_kind = OO_Star;
871        else if (post_op_name[1] == '=' && post_op_name[2] == '\0')
872            op_kind = OO_StarEqual;
873        break;
874
875    case '/':
876        if (post_op_name[1] == '\0')
877            op_kind = OO_Slash;
878        else if (post_op_name[1] == '=' && post_op_name[2] == '\0')
879            op_kind = OO_SlashEqual;
880        break;
881
882    case '%':
883        if (post_op_name[1] == '\0')
884            op_kind = OO_Percent;
885        else if (post_op_name[1] == '=' && post_op_name[2] == '\0')
886            op_kind = OO_PercentEqual;
887        break;
888
889
890    case '^':
891        if (post_op_name[1] == '\0')
892            op_kind = OO_Caret;
893        else if (post_op_name[1] == '=' && post_op_name[2] == '\0')
894            op_kind = OO_CaretEqual;
895        break;
896
897    case '&':
898        if (post_op_name[1] == '\0')
899            op_kind = OO_Amp;
900        else if (post_op_name[2] == '\0')
901        {
902            switch (post_op_name[1])
903            {
904            case '=': op_kind = OO_AmpEqual; break;
905            case '&': op_kind = OO_AmpAmp; break;
906            }
907        }
908        break;
909
910    case '|':
911        if (post_op_name[1] == '\0')
912            op_kind = OO_Pipe;
913        else if (post_op_name[2] == '\0')
914        {
915            switch (post_op_name[1])
916            {
917            case '=': op_kind = OO_PipeEqual; break;
918            case '|': op_kind = OO_PipePipe; break;
919            }
920        }
921        break;
922
923    case '~':
924        if (post_op_name[1] == '\0')
925            op_kind = OO_Tilde;
926        break;
927
928    case '!':
929        if (post_op_name[1] == '\0')
930            op_kind = OO_Exclaim;
931        else if (post_op_name[1] == '=' && post_op_name[2] == '\0')
932            op_kind = OO_ExclaimEqual;
933        break;
934
935    case '=':
936        if (post_op_name[1] == '\0')
937            op_kind = OO_Equal;
938        else if (post_op_name[1] == '=' && post_op_name[2] == '\0')
939            op_kind = OO_EqualEqual;
940        break;
941
942    case '<':
943        if (post_op_name[1] == '\0')
944            op_kind = OO_Less;
945        else if (post_op_name[2] == '\0')
946        {
947            switch (post_op_name[1])
948            {
949            case '<': op_kind = OO_LessLess; break;
950            case '=': op_kind = OO_LessEqual; break;
951            }
952        }
953        else if (post_op_name[3] == '\0')
954        {
955            if (post_op_name[2] == '=')
956                op_kind = OO_LessLessEqual;
957        }
958        break;
959
960    case '>':
961        if (post_op_name[1] == '\0')
962            op_kind = OO_Greater;
963        else if (post_op_name[2] == '\0')
964        {
965            switch (post_op_name[1])
966            {
967            case '>': op_kind = OO_GreaterGreater; break;
968            case '=': op_kind = OO_GreaterEqual; break;
969            }
970        }
971        else if (post_op_name[1] == '>' &&
972                 post_op_name[2] == '=' &&
973                 post_op_name[3] == '\0')
974        {
975                op_kind = OO_GreaterGreaterEqual;
976        }
977        break;
978
979    case ',':
980        if (post_op_name[1] == '\0')
981            op_kind = OO_Comma;
982        break;
983
984    case '(':
985        if (post_op_name[1] == ')' && post_op_name[2] == '\0')
986            op_kind = OO_Call;
987        break;
988
989    case '[':
990        if (post_op_name[1] == ']' && post_op_name[2] == '\0')
991            op_kind = OO_Subscript;
992        break;
993    }
994
995    return true;
996}
997CXXMethodDecl *
998ClangASTContext::AddMethodToCXXRecordType
999(
1000    ASTContext *ast_context,
1001    clang_type_t record_opaque_type,
1002    const char *name,
1003    clang_type_t method_opaque_type,
1004    lldb::AccessType access,
1005    bool is_virtual,
1006    bool is_static,
1007    bool is_inline,
1008    bool is_explicit
1009)
1010{
1011    if (!record_opaque_type || !method_opaque_type || !name)
1012        return NULL;
1013
1014    assert(ast_context);
1015
1016    IdentifierTable *identifier_table = &ast_context->Idents;
1017
1018    assert(identifier_table);
1019
1020    QualType record_qual_type(QualType::getFromOpaquePtr(record_opaque_type));
1021
1022    clang::Type *clang_type(record_qual_type.getTypePtr());
1023
1024    if (clang_type == NULL)
1025        return NULL;
1026
1027    RecordType *record_clang_type(dyn_cast<RecordType>(clang_type));
1028
1029    if (record_clang_type == NULL)
1030        return NULL;
1031
1032    RecordDecl *record_decl = record_clang_type->getDecl();
1033
1034    if (record_decl == NULL)
1035        return NULL;
1036
1037    CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
1038
1039    if (cxx_record_decl == NULL)
1040        return NULL;
1041
1042    QualType method_qual_type (QualType::getFromOpaquePtr (method_opaque_type));
1043
1044    CXXMethodDecl *cxx_method_decl = NULL;
1045
1046    DeclarationName decl_name (&identifier_table->get(name));
1047
1048    const bool is_implicitly_declared = false;
1049
1050    clang::FunctionType *function_Type = dyn_cast<FunctionType>(method_qual_type.getTypePtr());
1051
1052    if (function_Type == NULL)
1053        return NULL;
1054
1055    FunctionProtoType *method_function_prototype (dyn_cast<FunctionProtoType>(function_Type));
1056
1057    if (!method_function_prototype)
1058        return NULL;
1059
1060    unsigned int num_params = method_function_prototype->getNumArgs();
1061
1062    if (name[0] == '~')
1063    {
1064        cxx_method_decl = CXXDestructorDecl::Create (*ast_context,
1065                                                     cxx_record_decl,
1066                                                     DeclarationNameInfo (ast_context->DeclarationNames.getCXXDestructorName (ast_context->getCanonicalType (record_qual_type)), SourceLocation()),
1067                                                     method_qual_type,
1068                                                     is_inline,
1069                                                     is_implicitly_declared);
1070    }
1071    else if (decl_name == record_decl->getDeclName())
1072    {
1073        cxx_method_decl = CXXConstructorDecl::Create (*ast_context,
1074                                                      cxx_record_decl,
1075                                                      DeclarationNameInfo (ast_context->DeclarationNames.getCXXConstructorName (ast_context->getCanonicalType (record_qual_type)), SourceLocation()),
1076                                                      method_qual_type,
1077                                                      NULL, // TypeSourceInfo *
1078                                                      is_explicit,
1079                                                      is_inline,
1080                                                      is_implicitly_declared);
1081    }
1082    else
1083    {
1084
1085        OverloadedOperatorKind op_kind = NUM_OVERLOADED_OPERATORS;
1086        if (IsOperator (name, op_kind))
1087        {
1088            if (op_kind != NUM_OVERLOADED_OPERATORS)
1089            {
1090                cxx_method_decl = CXXMethodDecl::Create (*ast_context,
1091                                                         cxx_record_decl,
1092                                                         DeclarationNameInfo (ast_context->DeclarationNames.getCXXOperatorName (op_kind), SourceLocation()),
1093                                                         method_qual_type,
1094                                                         NULL, // TypeSourceInfo *
1095                                                         is_static,
1096                                                         SC_None,
1097                                                         is_inline);
1098            }
1099            else if (num_params == 0)
1100            {
1101                // Conversion operators don't take params...
1102                cxx_method_decl = CXXConversionDecl::Create (*ast_context,
1103                                                             cxx_record_decl,
1104                                                             DeclarationNameInfo (ast_context->DeclarationNames.getCXXConversionFunctionName (ast_context->getCanonicalType (function_Type->getResultType())), SourceLocation()),
1105                                                             method_qual_type,
1106                                                             NULL, // TypeSourceInfo *
1107                                                             is_inline,
1108                                                             is_explicit);
1109            }
1110        }
1111
1112        if (cxx_method_decl == NULL)
1113        {
1114            cxx_method_decl = CXXMethodDecl::Create (*ast_context,
1115                                                     cxx_record_decl,
1116                                                     DeclarationNameInfo (decl_name, SourceLocation()),
1117                                                     method_qual_type,
1118                                                     NULL, // TypeSourceInfo *
1119                                                     is_static,
1120                                                     SC_None,
1121                                                     is_inline);
1122        }
1123    }
1124
1125    AccessSpecifier access_specifier = ConvertAccessTypeToAccessSpecifier (access);
1126
1127    cxx_method_decl->setAccess (access_specifier);
1128    cxx_method_decl->setVirtualAsWritten (is_virtual);
1129
1130    // Populate the method decl with parameter decls
1131
1132    ParmVarDecl *params[num_params];
1133
1134    for (int param_index = 0;
1135         param_index < num_params;
1136         ++param_index)
1137    {
1138        params[param_index] = ParmVarDecl::Create (*ast_context,
1139                                                   cxx_method_decl,
1140                                                   SourceLocation(),
1141                                                   NULL, // anonymous
1142                                                   method_function_prototype->getArgType(param_index),
1143                                                   NULL,
1144                                                   SC_None,
1145                                                   SC_None,
1146                                                   NULL);
1147    }
1148
1149    cxx_method_decl->setParams (params, num_params);
1150
1151    cxx_record_decl->addDecl (cxx_method_decl);
1152
1153    return cxx_method_decl;
1154}
1155
1156bool
1157ClangASTContext::AddFieldToRecordType
1158(
1159    ASTContext *ast_context,
1160    clang_type_t record_clang_type,
1161    const char *name,
1162    clang_type_t field_type,
1163    AccessType access,
1164    uint32_t bitfield_bit_size
1165)
1166{
1167    if (record_clang_type == NULL || field_type == NULL)
1168        return false;
1169
1170    IdentifierTable *identifier_table = &ast_context->Idents;
1171
1172    assert (ast_context != NULL);
1173    assert (identifier_table != NULL);
1174
1175    QualType record_qual_type(QualType::getFromOpaquePtr(record_clang_type));
1176
1177    clang::Type *clang_type = record_qual_type.getTypePtr();
1178    if (clang_type)
1179    {
1180        const RecordType *record_type = dyn_cast<RecordType>(clang_type);
1181
1182        if (record_type)
1183        {
1184            RecordDecl *record_decl = record_type->getDecl();
1185
1186            clang::Expr *bit_width = NULL;
1187            if (bitfield_bit_size != 0)
1188            {
1189                APInt bitfield_bit_size_apint(ast_context->getTypeSize(ast_context->IntTy), bitfield_bit_size);
1190                bit_width = new (*ast_context)IntegerLiteral (*ast_context, bitfield_bit_size_apint, ast_context->IntTy, SourceLocation());
1191            }
1192            FieldDecl *field = FieldDecl::Create (*ast_context,
1193                                                  record_decl,
1194                                                  SourceLocation(),
1195                                                  name ? &identifier_table->get(name) : NULL, // Identifier
1196                                                  QualType::getFromOpaquePtr(field_type), // Field type
1197                                                  NULL,       // DeclaratorInfo *
1198                                                  bit_width,  // BitWidth
1199                                                  false);     // Mutable
1200
1201            field->setAccess (ConvertAccessTypeToAccessSpecifier (access));
1202
1203            if (field)
1204            {
1205                record_decl->addDecl(field);
1206            }
1207        }
1208        else
1209        {
1210            ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(clang_type);
1211            if (objc_class_type)
1212            {
1213                bool is_synthesized = false;
1214                ClangASTContext::AddObjCClassIVar (ast_context,
1215                                                   record_clang_type,
1216                                                   name,
1217                                                   field_type,
1218                                                   access,
1219                                                   bitfield_bit_size,
1220                                                   is_synthesized);
1221            }
1222        }
1223    }
1224    return false;
1225}
1226
1227bool
1228ClangASTContext::FieldIsBitfield (FieldDecl* field, uint32_t& bitfield_bit_size)
1229{
1230    return FieldIsBitfield(getASTContext(), field, bitfield_bit_size);
1231}
1232
1233bool
1234ClangASTContext::FieldIsBitfield
1235(
1236    ASTContext *ast_context,
1237    FieldDecl* field,
1238    uint32_t& bitfield_bit_size
1239)
1240{
1241    if (ast_context == NULL || field == NULL)
1242        return false;
1243
1244    if (field->isBitField())
1245    {
1246        Expr* bit_width_expr = field->getBitWidth();
1247        if (bit_width_expr)
1248        {
1249            llvm::APSInt bit_width_apsint;
1250            if (bit_width_expr->isIntegerConstantExpr(bit_width_apsint, *ast_context))
1251            {
1252                bitfield_bit_size = bit_width_apsint.getLimitedValue(UINT32_MAX);
1253                return true;
1254            }
1255        }
1256    }
1257    return false;
1258}
1259
1260bool
1261ClangASTContext::RecordHasFields (const RecordDecl *record_decl)
1262{
1263    if (record_decl == NULL)
1264        return false;
1265
1266    if (!record_decl->field_empty())
1267        return true;
1268
1269    // No fields, lets check this is a CXX record and check the base classes
1270    const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
1271    if (cxx_record_decl)
1272    {
1273        CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
1274        for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
1275             base_class != base_class_end;
1276             ++base_class)
1277        {
1278            const CXXRecordDecl *base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
1279            if (RecordHasFields(base_class_decl))
1280                return true;
1281        }
1282    }
1283    return false;
1284}
1285
1286void
1287ClangASTContext::SetDefaultAccessForRecordFields (clang_type_t clang_qual_type, int default_accessibility, int *assigned_accessibilities, size_t num_assigned_accessibilities)
1288{
1289    if (clang_qual_type)
1290    {
1291        QualType qual_type(QualType::getFromOpaquePtr(clang_qual_type));
1292        clang::Type *clang_type = qual_type.getTypePtr();
1293        if (clang_type)
1294        {
1295            RecordType *record_type = dyn_cast<RecordType>(clang_type);
1296            if (record_type)
1297            {
1298                RecordDecl *record_decl = record_type->getDecl();
1299                if (record_decl)
1300                {
1301                    uint32_t field_idx;
1302                    RecordDecl::field_iterator field, field_end;
1303                    for (field = record_decl->field_begin(), field_end = record_decl->field_end(), field_idx = 0;
1304                         field != field_end;
1305                         ++field, ++field_idx)
1306                    {
1307                        // If no accessibility was assigned, assign the correct one
1308                        if (field_idx < num_assigned_accessibilities && assigned_accessibilities[field_idx] == clang::AS_none)
1309                            field->setAccess ((AccessSpecifier)default_accessibility);
1310                    }
1311                }
1312            }
1313        }
1314    }
1315}
1316
1317#pragma mark C++ Base Classes
1318
1319CXXBaseSpecifier *
1320ClangASTContext::CreateBaseClassSpecifier (clang_type_t base_class_type, AccessType access, bool is_virtual, bool base_of_class)
1321{
1322    if (base_class_type)
1323        return new CXXBaseSpecifier (SourceRange(),
1324                                     is_virtual,
1325                                     base_of_class,
1326                                     ConvertAccessTypeToAccessSpecifier (access),
1327                                     getASTContext()->CreateTypeSourceInfo (QualType::getFromOpaquePtr(base_class_type)));
1328    return NULL;
1329}
1330
1331void
1332ClangASTContext::DeleteBaseClassSpecifiers (CXXBaseSpecifier **base_classes, unsigned num_base_classes)
1333{
1334    for (unsigned i=0; i<num_base_classes; ++i)
1335    {
1336        delete base_classes[i];
1337        base_classes[i] = NULL;
1338    }
1339}
1340
1341bool
1342ClangASTContext::SetBaseClassesForClassType (clang_type_t class_clang_type, CXXBaseSpecifier const * const *base_classes, unsigned num_base_classes)
1343{
1344    if (class_clang_type)
1345    {
1346        clang::Type *clang_type = QualType::getFromOpaquePtr(class_clang_type).getTypePtr();
1347        if (clang_type)
1348        {
1349            RecordType *record_type = dyn_cast<RecordType>(clang_type);
1350            if (record_type)
1351            {
1352                CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_type->getDecl());
1353                if (cxx_record_decl)
1354                {
1355                    cxx_record_decl->setBases(base_classes, num_base_classes);
1356                    return true;
1357                }
1358            }
1359        }
1360    }
1361    return false;
1362}
1363#pragma mark Objective C Classes
1364
1365clang_type_t
1366ClangASTContext::CreateObjCClass
1367(
1368    const char *name,
1369    DeclContext *decl_ctx,
1370    bool isForwardDecl,
1371    bool isInternal
1372)
1373{
1374    ASTContext *ast_context = getASTContext();
1375    assert (ast_context != NULL);
1376    assert (name && name[0]);
1377    if (decl_ctx == NULL)
1378        decl_ctx = ast_context->getTranslationUnitDecl();
1379
1380    // NOTE: Eventually CXXRecordDecl will be merged back into RecordDecl and
1381    // we will need to update this code. I was told to currently always use
1382    // the CXXRecordDecl class since we often don't know from debug information
1383    // if something is struct or a class, so we default to always use the more
1384    // complete definition just in case.
1385    ObjCInterfaceDecl *decl = ObjCInterfaceDecl::Create (*ast_context,
1386                                                         decl_ctx,
1387                                                         SourceLocation(),
1388                                                         &ast_context->Idents.get(name),
1389                                                         SourceLocation(),
1390                                                         isForwardDecl,
1391                                                         isInternal);
1392
1393    return ast_context->getObjCInterfaceType(decl).getAsOpaquePtr();
1394}
1395
1396bool
1397ClangASTContext::SetObjCSuperClass (clang_type_t class_opaque_type, clang_type_t super_opaque_type)
1398{
1399    if (class_opaque_type && super_opaque_type)
1400    {
1401        QualType class_qual_type(QualType::getFromOpaquePtr(class_opaque_type));
1402        QualType super_qual_type(QualType::getFromOpaquePtr(super_opaque_type));
1403        clang::Type *class_type = class_qual_type.getTypePtr();
1404        clang::Type *super_type = super_qual_type.getTypePtr();
1405        if (class_type && super_type)
1406        {
1407            ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(class_type);
1408            ObjCObjectType *objc_super_type = dyn_cast<ObjCObjectType>(super_type);
1409            if (objc_class_type && objc_super_type)
1410            {
1411                ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
1412                ObjCInterfaceDecl *super_interface_decl = objc_super_type->getInterface();
1413                if (class_interface_decl && super_interface_decl)
1414                {
1415                    class_interface_decl->setSuperClass(super_interface_decl);
1416                    return true;
1417                }
1418            }
1419        }
1420    }
1421    return false;
1422}
1423
1424
1425bool
1426ClangASTContext::AddObjCClassIVar
1427(
1428    ASTContext *ast_context,
1429    clang_type_t class_opaque_type,
1430    const char *name,
1431    clang_type_t ivar_opaque_type,
1432    AccessType access,
1433    uint32_t bitfield_bit_size,
1434    bool is_synthesized
1435)
1436{
1437    if (class_opaque_type == NULL || ivar_opaque_type == NULL)
1438        return false;
1439
1440    IdentifierTable *identifier_table = &ast_context->Idents;
1441
1442    assert (ast_context != NULL);
1443    assert (identifier_table != NULL);
1444
1445    QualType class_qual_type(QualType::getFromOpaquePtr(class_opaque_type));
1446
1447    clang::Type *class_type = class_qual_type.getTypePtr();
1448    if (class_type)
1449    {
1450        ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(class_type);
1451
1452        if (objc_class_type)
1453        {
1454            ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
1455
1456            if (class_interface_decl)
1457            {
1458                clang::Expr *bit_width = NULL;
1459                if (bitfield_bit_size != 0)
1460                {
1461                    APInt bitfield_bit_size_apint(ast_context->getTypeSize(ast_context->IntTy), bitfield_bit_size);
1462                    bit_width = new (*ast_context)IntegerLiteral (*ast_context, bitfield_bit_size_apint, ast_context->IntTy, SourceLocation());
1463                }
1464
1465                ObjCIvarDecl *field = ObjCIvarDecl::Create (*ast_context,
1466                                                            class_interface_decl,
1467                                                            SourceLocation(),
1468                                                            &identifier_table->get(name), // Identifier
1469                                                            QualType::getFromOpaquePtr(ivar_opaque_type), // Field type
1470                                                            NULL, // TypeSourceInfo *
1471                                                            ConvertAccessTypeToObjCIvarAccessControl (access),
1472                                                            bit_width,
1473                                                            is_synthesized);
1474
1475                if (field)
1476                {
1477                    class_interface_decl->addDecl(field);
1478                    return true;
1479                }
1480            }
1481        }
1482    }
1483    return false;
1484}
1485
1486
1487bool
1488ClangASTContext::ObjCTypeHasIVars (clang_type_t class_opaque_type, bool check_superclass)
1489{
1490    QualType class_qual_type(QualType::getFromOpaquePtr(class_opaque_type));
1491
1492    clang::Type *class_type = class_qual_type.getTypePtr();
1493    if (class_type)
1494    {
1495        ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(class_type);
1496
1497        if (objc_class_type)
1498            return ObjCDeclHasIVars (objc_class_type->getInterface(), check_superclass);
1499    }
1500    return false;
1501}
1502
1503bool
1504ClangASTContext::ObjCDeclHasIVars (ObjCInterfaceDecl *class_interface_decl, bool check_superclass)
1505{
1506    while (class_interface_decl)
1507    {
1508        if (class_interface_decl->ivar_size() > 0)
1509            return true;
1510
1511        if (check_superclass)
1512            class_interface_decl = class_interface_decl->getSuperClass();
1513        else
1514            break;
1515    }
1516    return false;
1517}
1518
1519ObjCMethodDecl *
1520ClangASTContext::AddMethodToObjCObjectType
1521(
1522    ASTContext *ast_context,
1523    clang_type_t class_opaque_type,
1524    const char *name,  // the full symbol name as seen in the symbol table ("-[NString stringWithCString:]")
1525    clang_type_t method_opaque_type,
1526    lldb::AccessType access
1527)
1528{
1529    if (class_opaque_type == NULL || method_opaque_type == NULL)
1530        return NULL;
1531
1532    IdentifierTable *identifier_table = &ast_context->Idents;
1533
1534    assert (ast_context != NULL);
1535    assert (identifier_table != NULL);
1536
1537    QualType class_qual_type(QualType::getFromOpaquePtr(class_opaque_type));
1538
1539    clang::Type *class_type = class_qual_type.getTypePtr();
1540    if (class_type == NULL)
1541        return NULL;
1542
1543    ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(class_type);
1544
1545    if (objc_class_type == NULL)
1546        return NULL;
1547
1548    ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
1549
1550    if (class_interface_decl == NULL)
1551        return NULL;
1552
1553    const char *selector_start = ::strchr (name, ' ');
1554    if (selector_start == NULL)
1555        return NULL;
1556
1557    selector_start++;
1558    if (!(::isalpha (selector_start[0]) || selector_start[0] == '_'))
1559        return NULL;
1560    llvm::SmallVector<IdentifierInfo *, 12> selector_idents;
1561
1562    size_t len = 0;
1563    const char *start;
1564    //printf ("name = '%s'\n", name);
1565
1566    unsigned num_selectors_with_args = 0;
1567    for (start = selector_start;
1568         start && *start != '\0' && *start != ']';
1569         start += len)
1570    {
1571        len = ::strcspn(start, ":]");
1572        if (start[len] == ':')
1573        {
1574            ++num_selectors_with_args;
1575            len += 1;
1576        }
1577        //printf ("@selector[%zu] = '%.*s'\n", selector_idents.size(), (int)len, start);
1578        selector_idents.push_back (&identifier_table->get (StringRef (start, len)));
1579    }
1580
1581
1582    if (selector_idents.size() == 0)
1583        return 0;
1584
1585    clang::Selector method_selector = ast_context->Selectors.getSelector (num_selectors_with_args ? selector_idents.size() : 0,
1586                                                                          selector_idents.data());
1587
1588    QualType method_qual_type (QualType::getFromOpaquePtr (method_opaque_type));
1589
1590    // Populate the method decl with parameter decls
1591    clang::Type *method_type(method_qual_type.getTypePtr());
1592
1593    if (method_type == NULL)
1594        return NULL;
1595
1596    FunctionProtoType *method_function_prototype (dyn_cast<FunctionProtoType>(method_type));
1597
1598    if (!method_function_prototype)
1599        return NULL;
1600
1601
1602    bool is_variadic = false;
1603    bool is_synthesized = false;
1604    bool is_defined = false;
1605    ObjCMethodDecl::ImplementationControl imp_control = ObjCMethodDecl::None;
1606
1607    const unsigned num_args = method_function_prototype->getNumArgs();
1608
1609    ObjCMethodDecl *objc_method_decl = ObjCMethodDecl::Create (*ast_context,
1610                                                               SourceLocation(), // beginLoc,
1611                                                               SourceLocation(), // endLoc,
1612                                                               method_selector,
1613                                                               method_function_prototype->getResultType(),
1614                                                               NULL, // TypeSourceInfo *ResultTInfo,
1615                                                               GetDeclContextForType (class_opaque_type),
1616                                                               name[0] == '-',
1617                                                               is_variadic,
1618                                                               is_synthesized,
1619                                                               is_defined,
1620                                                               imp_control,
1621                                                               num_args);
1622
1623
1624    if (objc_method_decl == NULL)
1625        return NULL;
1626
1627    if (num_args > 0)
1628    {
1629        llvm::SmallVector<ParmVarDecl *, 12> params;
1630
1631        for (int param_index = 0; param_index < num_args; ++param_index)
1632        {
1633            params.push_back (ParmVarDecl::Create (*ast_context,
1634                                                   objc_method_decl,
1635                                                   SourceLocation(),
1636                                                   NULL, // anonymous
1637                                                   method_function_prototype->getArgType(param_index),
1638                                                   NULL,
1639                                                   SC_Auto,
1640                                                   SC_Auto,
1641                                                   NULL));
1642        }
1643
1644        objc_method_decl->setMethodParams(*ast_context, params.data(), params.size(), num_args);
1645    }
1646
1647    class_interface_decl->addDecl (objc_method_decl);
1648
1649
1650    return objc_method_decl;
1651}
1652
1653
1654uint32_t
1655ClangASTContext::GetTypeInfoMask (clang_type_t clang_type)
1656{
1657    if (clang_type == NULL)
1658        return false;
1659
1660    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
1661
1662    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
1663    switch (type_class)
1664    {
1665    case clang::Type::BlockPointer:                     return eTypeIsPointer | eTypeHasChildren | eTypeIsBlock;
1666    case clang::Type::Builtin:                          return eTypeIsBuiltIn | eTypeHasValue;
1667    case clang::Type::Complex:                          return eTypeHasChildren | eTypeIsBuiltIn | eTypeHasValue;
1668    case clang::Type::ConstantArray:                    return eTypeHasChildren | eTypeIsArray;
1669    case clang::Type::DependentName:                    return 0;
1670    case clang::Type::DependentSizedArray:              return eTypeHasChildren | eTypeIsArray;
1671    case clang::Type::DependentSizedExtVector:          return eTypeHasChildren | eTypeIsVector;
1672    case clang::Type::DependentTemplateSpecialization:  return eTypeIsTemplate;
1673    case clang::Type::Decltype:                         return 0;
1674    case clang::Type::Enum:                             return eTypeIsEnumeration | eTypeHasValue;
1675    case clang::Type::Elaborated:                       return 0;
1676    case clang::Type::ExtVector:                        return eTypeHasChildren | eTypeIsVector;
1677    case clang::Type::FunctionProto:                    return eTypeIsFuncPrototype | eTypeHasValue;
1678    case clang::Type::FunctionNoProto:                  return eTypeIsFuncPrototype | eTypeHasValue;
1679    case clang::Type::IncompleteArray:                  return eTypeHasChildren | eTypeIsArray;
1680    case clang::Type::InjectedClassName:                return 0;
1681    case clang::Type::LValueReference:                  return eTypeHasChildren | eTypeIsReference | eTypeHasValue;
1682    case clang::Type::MemberPointer:                    return eTypeIsPointer   | eTypeIsMember | eTypeHasValue;
1683    case clang::Type::ObjCObjectPointer:                return eTypeHasChildren | eTypeIsObjC | eTypeIsClass | eTypeIsPointer | eTypeHasValue;
1684    case clang::Type::ObjCObject:                       return eTypeHasChildren | eTypeIsObjC | eTypeIsClass;
1685    case clang::Type::ObjCInterface:                    return eTypeHasChildren | eTypeIsObjC | eTypeIsClass;
1686    case clang::Type::Pointer:                      	return eTypeHasChildren | eTypeIsPointer | eTypeHasValue;
1687    case clang::Type::Record:
1688        if (qual_type->getAsCXXRecordDecl())
1689            return eTypeHasChildren | eTypeIsClass | eTypeIsCPlusPlus;
1690        else
1691            return eTypeHasChildren | eTypeIsStructUnion;
1692        break;
1693    case clang::Type::RValueReference:                  return eTypeHasChildren | eTypeIsReference | eTypeHasValue;
1694    case clang::Type::SubstTemplateTypeParm:            return eTypeIsTemplate;
1695    case clang::Type::TemplateTypeParm:                 return eTypeIsTemplate;
1696    case clang::Type::TemplateSpecialization:           return eTypeIsTemplate;
1697    case clang::Type::Typedef:                          return eTypeIsTypedef |
1698                                                               ClangASTContext::GetTypeInfoMask (cast<TypedefType>(qual_type)->LookThroughTypedefs().getAsOpaquePtr());
1699    case clang::Type::TypeOfExpr:                       return 0;
1700    case clang::Type::TypeOf:                           return 0;
1701    case clang::Type::UnresolvedUsing:                  return 0;
1702    case clang::Type::VariableArray:                    return eTypeHasChildren | eTypeIsArray;
1703    case clang::Type::Vector:                           return eTypeHasChildren | eTypeIsVector;
1704    default:                                            return 0;
1705    }
1706    return 0;
1707}
1708
1709
1710#pragma mark Aggregate Types
1711
1712bool
1713ClangASTContext::IsAggregateType (clang_type_t clang_type)
1714{
1715    if (clang_type == NULL)
1716        return false;
1717
1718    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
1719
1720    if (qual_type->isAggregateType ())
1721        return true;
1722
1723    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
1724    switch (type_class)
1725    {
1726    case clang::Type::IncompleteArray:
1727    case clang::Type::VariableArray:
1728    case clang::Type::ConstantArray:
1729    case clang::Type::ExtVector:
1730    case clang::Type::Vector:
1731    case clang::Type::Record:
1732    case clang::Type::ObjCObject:
1733    case clang::Type::ObjCInterface:
1734        return true;
1735
1736    case clang::Type::Typedef:
1737        return ClangASTContext::IsAggregateType (cast<TypedefType>(qual_type)->LookThroughTypedefs().getAsOpaquePtr());
1738
1739    default:
1740        break;
1741    }
1742    // The clang type does have a value
1743    return false;
1744}
1745
1746uint32_t
1747ClangASTContext::GetNumChildren (clang_type_t clang_qual_type, bool omit_empty_base_classes)
1748{
1749    if (clang_qual_type == NULL)
1750        return 0;
1751
1752    uint32_t num_children = 0;
1753    QualType qual_type(QualType::getFromOpaquePtr(clang_qual_type));
1754    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
1755    switch (type_class)
1756    {
1757    case clang::Type::Builtin:
1758        switch (cast<clang::BuiltinType>(qual_type)->getKind())
1759        {
1760        case clang::BuiltinType::ObjCId:    // Child is Class
1761        case clang::BuiltinType::ObjCClass: // child is Class
1762        case clang::BuiltinType::ObjCSel:   // child is const char *
1763            num_children = 1;
1764
1765        default:
1766            break;
1767        }
1768        break;
1769
1770    case clang::Type::Record:
1771        {
1772            const RecordType *record_type = cast<RecordType>(qual_type.getTypePtr());
1773            const RecordDecl *record_decl = record_type->getDecl();
1774            assert(record_decl);
1775            const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
1776            if (cxx_record_decl)
1777            {
1778                if (omit_empty_base_classes)
1779                {
1780                    // Check each base classes to see if it or any of its
1781                    // base classes contain any fields. This can help
1782                    // limit the noise in variable views by not having to
1783                    // show base classes that contain no members.
1784                    CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
1785                    for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
1786                         base_class != base_class_end;
1787                         ++base_class)
1788                    {
1789                        const CXXRecordDecl *base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
1790
1791                        // Skip empty base classes
1792                        if (RecordHasFields(base_class_decl) == false)
1793                            continue;
1794
1795                        num_children++;
1796                    }
1797                }
1798                else
1799                {
1800                    // Include all base classes
1801                    num_children += cxx_record_decl->getNumBases();
1802                }
1803
1804            }
1805            RecordDecl::field_iterator field, field_end;
1806            for (field = record_decl->field_begin(), field_end = record_decl->field_end(); field != field_end; ++field)
1807                ++num_children;
1808        }
1809        break;
1810
1811    case clang::Type::ObjCObject:
1812    case clang::Type::ObjCInterface:
1813        {
1814            ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(qual_type.getTypePtr());
1815            assert (objc_class_type);
1816            if (objc_class_type)
1817            {
1818                ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
1819
1820                if (class_interface_decl)
1821                {
1822
1823                    ObjCInterfaceDecl *superclass_interface_decl = class_interface_decl->getSuperClass();
1824                    if (superclass_interface_decl)
1825                    {
1826                        if (omit_empty_base_classes)
1827                        {
1828                            if (ClangASTContext::ObjCDeclHasIVars (superclass_interface_decl, true))
1829                                ++num_children;
1830                        }
1831                        else
1832                            ++num_children;
1833                    }
1834
1835                    num_children += class_interface_decl->ivar_size();
1836                }
1837            }
1838        }
1839        break;
1840
1841    case clang::Type::ObjCObjectPointer:
1842        {
1843            ObjCObjectPointerType *pointer_type = cast<ObjCObjectPointerType>(qual_type.getTypePtr());
1844            QualType pointee_type = pointer_type->getPointeeType();
1845            uint32_t num_pointee_children = ClangASTContext::GetNumChildren (pointee_type.getAsOpaquePtr(),
1846                                                                             omit_empty_base_classes);
1847            // If this type points to a simple type, then it has 1 child
1848            if (num_pointee_children == 0)
1849                num_children = 1;
1850            else
1851                num_children = num_pointee_children;
1852        }
1853        break;
1854
1855    case clang::Type::ConstantArray:
1856        num_children = cast<ConstantArrayType>(qual_type.getTypePtr())->getSize().getLimitedValue();
1857        break;
1858
1859    case clang::Type::Pointer:
1860        {
1861            PointerType *pointer_type = cast<PointerType>(qual_type.getTypePtr());
1862            QualType pointee_type = pointer_type->getPointeeType();
1863            uint32_t num_pointee_children = ClangASTContext::GetNumChildren (pointee_type.getAsOpaquePtr(),
1864                                                                             omit_empty_base_classes);
1865            // If this type points to a simple type, then it has 1 child
1866            if (num_pointee_children == 0)
1867                num_children = 1;
1868            else
1869                num_children = num_pointee_children;
1870        }
1871        break;
1872
1873    case clang::Type::Typedef:
1874        num_children = ClangASTContext::GetNumChildren (cast<TypedefType>(qual_type)->LookThroughTypedefs().getAsOpaquePtr(), omit_empty_base_classes);
1875        break;
1876
1877    default:
1878        break;
1879    }
1880    return num_children;
1881}
1882
1883
1884clang_type_t
1885ClangASTContext::GetChildClangTypeAtIndex
1886(
1887    const char *parent_name,
1888    clang_type_t parent_clang_type,
1889    uint32_t idx,
1890    bool transparent_pointers,
1891    bool omit_empty_base_classes,
1892    std::string& child_name,
1893    uint32_t &child_byte_size,
1894    int32_t &child_byte_offset,
1895    uint32_t &child_bitfield_bit_size,
1896    uint32_t &child_bitfield_bit_offset,
1897    bool &child_is_base_class
1898)
1899{
1900    if (parent_clang_type)
1901
1902        return GetChildClangTypeAtIndex (getASTContext(),
1903                                         parent_name,
1904                                         parent_clang_type,
1905                                         idx,
1906                                         transparent_pointers,
1907                                         omit_empty_base_classes,
1908                                         child_name,
1909                                         child_byte_size,
1910                                         child_byte_offset,
1911                                         child_bitfield_bit_size,
1912                                         child_bitfield_bit_offset,
1913                                         child_is_base_class);
1914    return NULL;
1915}
1916
1917clang_type_t
1918ClangASTContext::GetChildClangTypeAtIndex
1919(
1920    ASTContext *ast_context,
1921    const char *parent_name,
1922    clang_type_t parent_clang_type,
1923    uint32_t idx,
1924    bool transparent_pointers,
1925    bool omit_empty_base_classes,
1926    std::string& child_name,
1927    uint32_t &child_byte_size,
1928    int32_t &child_byte_offset,
1929    uint32_t &child_bitfield_bit_size,
1930    uint32_t &child_bitfield_bit_offset,
1931    bool &child_is_base_class
1932)
1933{
1934    if (parent_clang_type == NULL)
1935        return NULL;
1936
1937    if (idx < ClangASTContext::GetNumChildren (parent_clang_type, omit_empty_base_classes))
1938    {
1939        uint32_t bit_offset;
1940        child_bitfield_bit_size = 0;
1941        child_bitfield_bit_offset = 0;
1942        child_is_base_class = false;
1943        QualType parent_qual_type(QualType::getFromOpaquePtr(parent_clang_type));
1944        const clang::Type::TypeClass parent_type_class = parent_qual_type->getTypeClass();
1945        switch (parent_type_class)
1946        {
1947        case clang::Type::Builtin:
1948            switch (cast<clang::BuiltinType>(parent_qual_type)->getKind())
1949            {
1950            case clang::BuiltinType::ObjCId:
1951            case clang::BuiltinType::ObjCClass:
1952                return ast_context->ObjCBuiltinClassTy.getAsOpaquePtr();
1953
1954            case clang::BuiltinType::ObjCSel:
1955                {
1956                    QualType char_type(ast_context->CharTy);
1957                    char_type.addConst();
1958                    return ast_context->getPointerType(char_type).getAsOpaquePtr();
1959                }
1960                break;
1961
1962            default:
1963                break;
1964            }
1965            break;
1966
1967
1968        case clang::Type::Record:
1969            {
1970                const RecordType *record_type = cast<RecordType>(parent_qual_type.getTypePtr());
1971                const RecordDecl *record_decl = record_type->getDecl();
1972                assert(record_decl);
1973                const ASTRecordLayout &record_layout = ast_context->getASTRecordLayout(record_decl);
1974                uint32_t child_idx = 0;
1975
1976                const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
1977                if (cxx_record_decl)
1978                {
1979                    // We might have base classes to print out first
1980                    CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
1981                    for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
1982                         base_class != base_class_end;
1983                         ++base_class)
1984                    {
1985                        const CXXRecordDecl *base_class_decl = NULL;
1986
1987                        // Skip empty base classes
1988                        if (omit_empty_base_classes)
1989                        {
1990                            base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
1991                            if (RecordHasFields(base_class_decl) == false)
1992                                continue;
1993                        }
1994
1995                        if (idx == child_idx)
1996                        {
1997                            if (base_class_decl == NULL)
1998                                base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
1999
2000
2001                            if (base_class->isVirtual())
2002                                bit_offset = record_layout.getVBaseClassOffset(base_class_decl);
2003                            else
2004                                bit_offset = record_layout.getBaseClassOffset(base_class_decl);
2005
2006                            // Base classes should be a multiple of 8 bits in size
2007                            assert (bit_offset % 8 == 0);
2008                            child_byte_offset = bit_offset/8;
2009                            std::string base_class_type_name(base_class->getType().getAsString());
2010
2011                            child_name.assign(base_class_type_name.c_str());
2012
2013                            uint64_t clang_type_info_bit_size = ast_context->getTypeSize(base_class->getType());
2014
2015                            // Base classes biut sizes should be a multiple of 8 bits in size
2016                            assert (clang_type_info_bit_size % 8 == 0);
2017                            child_byte_size = clang_type_info_bit_size / 8;
2018                            child_is_base_class = true;
2019                            return base_class->getType().getAsOpaquePtr();
2020                        }
2021                        // We don't increment the child index in the for loop since we might
2022                        // be skipping empty base classes
2023                        ++child_idx;
2024                    }
2025                }
2026                // Make sure index is in range...
2027                uint32_t field_idx = 0;
2028                RecordDecl::field_iterator field, field_end;
2029                for (field = record_decl->field_begin(), field_end = record_decl->field_end(); field != field_end; ++field, ++field_idx, ++child_idx)
2030                {
2031                    if (idx == child_idx)
2032                    {
2033                        // Print the member type if requested
2034                        // Print the member name and equal sign
2035                        child_name.assign(field->getNameAsString().c_str());
2036
2037                        // Figure out the type byte size (field_type_info.first) and
2038                        // alignment (field_type_info.second) from the AST context.
2039                        std::pair<uint64_t, unsigned> field_type_info = ast_context->getTypeInfo(field->getType());
2040                        assert(field_idx < record_layout.getFieldCount());
2041
2042                        child_byte_size = field_type_info.first / 8;
2043
2044                        // Figure out the field offset within the current struct/union/class type
2045                        bit_offset = record_layout.getFieldOffset (field_idx);
2046                        child_byte_offset = bit_offset / 8;
2047                        if (ClangASTContext::FieldIsBitfield (ast_context, *field, child_bitfield_bit_size))
2048                            child_bitfield_bit_offset = bit_offset % 8;
2049
2050                        return field->getType().getAsOpaquePtr();
2051                    }
2052                }
2053            }
2054            break;
2055
2056        case clang::Type::ObjCObject:
2057        case clang::Type::ObjCInterface:
2058            {
2059                ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(parent_qual_type.getTypePtr());
2060                assert (objc_class_type);
2061                if (objc_class_type)
2062                {
2063                    uint32_t child_idx = 0;
2064                    ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
2065
2066                    if (class_interface_decl)
2067                    {
2068
2069                        const ASTRecordLayout &interface_layout = ast_context->getASTObjCInterfaceLayout(class_interface_decl);
2070                        ObjCInterfaceDecl *superclass_interface_decl = class_interface_decl->getSuperClass();
2071                        if (superclass_interface_decl)
2072                        {
2073                            if (omit_empty_base_classes)
2074                            {
2075                                if (ClangASTContext::GetNumChildren(ast_context->getObjCInterfaceType(superclass_interface_decl).getAsOpaquePtr(), omit_empty_base_classes) > 0)
2076                                {
2077                                    if (idx == 0)
2078                                    {
2079                                        QualType ivar_qual_type(ast_context->getObjCInterfaceType(superclass_interface_decl));
2080
2081
2082                                        child_name.assign(superclass_interface_decl->getNameAsString().c_str());
2083
2084                                        std::pair<uint64_t, unsigned> ivar_type_info = ast_context->getTypeInfo(ivar_qual_type.getTypePtr());
2085
2086                                        child_byte_size = ivar_type_info.first / 8;
2087                                        child_byte_offset = 0;
2088                                        child_is_base_class = true;
2089
2090                                        return ivar_qual_type.getAsOpaquePtr();
2091                                    }
2092
2093                                    ++child_idx;
2094                                }
2095                            }
2096                            else
2097                                ++child_idx;
2098                        }
2099
2100                        const uint32_t superclass_idx = child_idx;
2101
2102                        if (idx < (child_idx + class_interface_decl->ivar_size()))
2103                        {
2104                            ObjCInterfaceDecl::ivar_iterator ivar_pos, ivar_end = class_interface_decl->ivar_end();
2105
2106                            for (ivar_pos = class_interface_decl->ivar_begin(); ivar_pos != ivar_end; ++ivar_pos)
2107                            {
2108                                if (child_idx == idx)
2109                                {
2110                                    const ObjCIvarDecl* ivar_decl = *ivar_pos;
2111
2112                                    QualType ivar_qual_type(ivar_decl->getType());
2113
2114                                    child_name.assign(ivar_decl->getNameAsString().c_str());
2115
2116                                    std::pair<uint64_t, unsigned> ivar_type_info = ast_context->getTypeInfo(ivar_qual_type.getTypePtr());
2117
2118                                    child_byte_size = ivar_type_info.first / 8;
2119
2120                                    // Figure out the field offset within the current struct/union/class type
2121                                    bit_offset = interface_layout.getFieldOffset (child_idx - superclass_idx);
2122                                    child_byte_offset = bit_offset / 8;
2123
2124                                    return ivar_qual_type.getAsOpaquePtr();
2125                                }
2126                                ++child_idx;
2127                            }
2128                        }
2129                    }
2130                }
2131            }
2132            break;
2133
2134        case clang::Type::ObjCObjectPointer:
2135            {
2136                ObjCObjectPointerType *pointer_type = cast<ObjCObjectPointerType>(parent_qual_type.getTypePtr());
2137                QualType pointee_type = pointer_type->getPointeeType();
2138
2139                if (transparent_pointers && ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
2140                {
2141                    return GetChildClangTypeAtIndex (ast_context,
2142                                                     parent_name,
2143                                                     pointer_type->getPointeeType().getAsOpaquePtr(),
2144                                                     idx,
2145                                                     transparent_pointers,
2146                                                     omit_empty_base_classes,
2147                                                     child_name,
2148                                                     child_byte_size,
2149                                                     child_byte_offset,
2150                                                     child_bitfield_bit_size,
2151                                                     child_bitfield_bit_offset,
2152                                                     child_is_base_class);
2153                }
2154                else
2155                {
2156                    if (parent_name)
2157                    {
2158                        child_name.assign(1, '*');
2159                        child_name += parent_name;
2160                    }
2161
2162                    // We have a pointer to an simple type
2163                    if (idx == 0)
2164                    {
2165                        std::pair<uint64_t, unsigned> clang_type_info = ast_context->getTypeInfo(pointee_type);
2166                        assert(clang_type_info.first % 8 == 0);
2167                        child_byte_size = clang_type_info.first / 8;
2168                        child_byte_offset = 0;
2169                        return pointee_type.getAsOpaquePtr();
2170                    }
2171                }
2172            }
2173            break;
2174
2175        case clang::Type::ConstantArray:
2176            {
2177                const ConstantArrayType *array = cast<ConstantArrayType>(parent_qual_type.getTypePtr());
2178                const uint64_t element_count = array->getSize().getLimitedValue();
2179
2180                if (idx < element_count)
2181                {
2182                    std::pair<uint64_t, unsigned> field_type_info = ast_context->getTypeInfo(array->getElementType());
2183
2184                    char element_name[64];
2185                    ::snprintf (element_name, sizeof (element_name), "[%u]", idx);
2186
2187                    child_name.assign(element_name);
2188                    assert(field_type_info.first % 8 == 0);
2189                    child_byte_size = field_type_info.first / 8;
2190                    child_byte_offset = idx * child_byte_size;
2191                    return array->getElementType().getAsOpaquePtr();
2192                }
2193            }
2194            break;
2195
2196        case clang::Type::Pointer:
2197            {
2198                PointerType *pointer_type = cast<PointerType>(parent_qual_type.getTypePtr());
2199                QualType pointee_type = pointer_type->getPointeeType();
2200
2201                if (transparent_pointers && ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
2202                {
2203                    return GetChildClangTypeAtIndex (ast_context,
2204                                                     parent_name,
2205                                                     pointer_type->getPointeeType().getAsOpaquePtr(),
2206                                                     idx,
2207                                                     transparent_pointers,
2208                                                     omit_empty_base_classes,
2209                                                     child_name,
2210                                                     child_byte_size,
2211                                                     child_byte_offset,
2212                                                     child_bitfield_bit_size,
2213                                                     child_bitfield_bit_offset,
2214                                                     child_is_base_class);
2215                }
2216                else
2217                {
2218                    if (parent_name)
2219                    {
2220                        child_name.assign(1, '*');
2221                        child_name += parent_name;
2222                    }
2223
2224                    // We have a pointer to an simple type
2225                    if (idx == 0)
2226                    {
2227                        std::pair<uint64_t, unsigned> clang_type_info = ast_context->getTypeInfo(pointee_type);
2228                        assert(clang_type_info.first % 8 == 0);
2229                        child_byte_size = clang_type_info.first / 8;
2230                        child_byte_offset = 0;
2231                        return pointee_type.getAsOpaquePtr();
2232                    }
2233                }
2234            }
2235            break;
2236
2237        case clang::Type::Typedef:
2238            return GetChildClangTypeAtIndex (ast_context,
2239                                             parent_name,
2240                                             cast<TypedefType>(parent_qual_type)->LookThroughTypedefs().getAsOpaquePtr(),
2241                                             idx,
2242                                             transparent_pointers,
2243                                             omit_empty_base_classes,
2244                                             child_name,
2245                                             child_byte_size,
2246                                             child_byte_offset,
2247                                             child_bitfield_bit_size,
2248                                             child_bitfield_bit_offset,
2249                                             child_is_base_class);
2250            break;
2251
2252        default:
2253            break;
2254        }
2255    }
2256    return NULL;
2257}
2258
2259static inline bool
2260BaseSpecifierIsEmpty (const CXXBaseSpecifier *b)
2261{
2262    return ClangASTContext::RecordHasFields(cast<CXXRecordDecl>(b->getType()->getAs<RecordType>()->getDecl())) == false;
2263}
2264
2265static uint32_t
2266GetNumBaseClasses (const CXXRecordDecl *cxx_record_decl, bool omit_empty_base_classes)
2267{
2268    uint32_t num_bases = 0;
2269    if (cxx_record_decl)
2270    {
2271        if (omit_empty_base_classes)
2272        {
2273            CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
2274            for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
2275                 base_class != base_class_end;
2276                 ++base_class)
2277            {
2278                // Skip empty base classes
2279                if (omit_empty_base_classes)
2280                {
2281                    if (BaseSpecifierIsEmpty (base_class))
2282                        continue;
2283                }
2284                ++num_bases;
2285            }
2286        }
2287        else
2288            num_bases = cxx_record_decl->getNumBases();
2289    }
2290    return num_bases;
2291}
2292
2293
2294static uint32_t
2295GetIndexForRecordBase
2296(
2297    const RecordDecl *record_decl,
2298    const CXXBaseSpecifier *base_spec,
2299    bool omit_empty_base_classes
2300)
2301{
2302    uint32_t child_idx = 0;
2303
2304    const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
2305
2306//    const char *super_name = record_decl->getNameAsCString();
2307//    const char *base_name = base_spec->getType()->getAs<RecordType>()->getDecl()->getNameAsCString();
2308//    printf ("GetIndexForRecordChild (%s, %s)\n", super_name, base_name);
2309//
2310    if (cxx_record_decl)
2311    {
2312        CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
2313        for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
2314             base_class != base_class_end;
2315             ++base_class)
2316        {
2317            if (omit_empty_base_classes)
2318            {
2319                if (BaseSpecifierIsEmpty (base_class))
2320                    continue;
2321            }
2322
2323//            printf ("GetIndexForRecordChild (%s, %s) base[%u] = %s\n", super_name, base_name,
2324//                    child_idx,
2325//                    base_class->getType()->getAs<RecordType>()->getDecl()->getNameAsCString());
2326//
2327//
2328            if (base_class == base_spec)
2329                return child_idx;
2330            ++child_idx;
2331        }
2332    }
2333
2334    return UINT32_MAX;
2335}
2336
2337
2338static uint32_t
2339GetIndexForRecordChild
2340(
2341    const RecordDecl *record_decl,
2342    NamedDecl *canonical_decl,
2343    bool omit_empty_base_classes
2344)
2345{
2346    uint32_t child_idx = GetNumBaseClasses (dyn_cast<CXXRecordDecl>(record_decl), omit_empty_base_classes);
2347
2348//    const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
2349//
2350////    printf ("GetIndexForRecordChild (%s, %s)\n", record_decl->getNameAsCString(), canonical_decl->getNameAsCString());
2351//    if (cxx_record_decl)
2352//    {
2353//        CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
2354//        for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
2355//             base_class != base_class_end;
2356//             ++base_class)
2357//        {
2358//            if (omit_empty_base_classes)
2359//            {
2360//                if (BaseSpecifierIsEmpty (base_class))
2361//                    continue;
2362//            }
2363//
2364////            printf ("GetIndexForRecordChild (%s, %s) base[%u] = %s\n",
2365////                    record_decl->getNameAsCString(),
2366////                    canonical_decl->getNameAsCString(),
2367////                    child_idx,
2368////                    base_class->getType()->getAs<RecordType>()->getDecl()->getNameAsCString());
2369//
2370//
2371//            CXXRecordDecl *curr_base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
2372//            if (curr_base_class_decl == canonical_decl)
2373//            {
2374//                return child_idx;
2375//            }
2376//            ++child_idx;
2377//        }
2378//    }
2379//
2380//    const uint32_t num_bases = child_idx;
2381    RecordDecl::field_iterator field, field_end;
2382    for (field = record_decl->field_begin(), field_end = record_decl->field_end();
2383         field != field_end;
2384         ++field, ++child_idx)
2385    {
2386//            printf ("GetIndexForRecordChild (%s, %s) field[%u] = %s\n",
2387//                    record_decl->getNameAsCString(),
2388//                    canonical_decl->getNameAsCString(),
2389//                    child_idx - num_bases,
2390//                    field->getNameAsCString());
2391
2392        if (field->getCanonicalDecl() == canonical_decl)
2393            return child_idx;
2394    }
2395
2396    return UINT32_MAX;
2397}
2398
2399// Look for a child member (doesn't include base classes, but it does include
2400// their members) in the type hierarchy. Returns an index path into "clang_type"
2401// on how to reach the appropriate member.
2402//
2403//    class A
2404//    {
2405//    public:
2406//        int m_a;
2407//        int m_b;
2408//    };
2409//
2410//    class B
2411//    {
2412//    };
2413//
2414//    class C :
2415//        public B,
2416//        public A
2417//    {
2418//    };
2419//
2420// If we have a clang type that describes "class C", and we wanted to looked
2421// "m_b" in it:
2422//
2423// With omit_empty_base_classes == false we would get an integer array back with:
2424// { 1,  1 }
2425// The first index 1 is the child index for "class A" within class C
2426// The second index 1 is the child index for "m_b" within class A
2427//
2428// With omit_empty_base_classes == true we would get an integer array back with:
2429// { 0,  1 }
2430// 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)
2431// The second index 1 is the child index for "m_b" within class A
2432
2433size_t
2434ClangASTContext::GetIndexOfChildMemberWithName
2435(
2436    ASTContext *ast_context,
2437    clang_type_t clang_type,
2438    const char *name,
2439    bool omit_empty_base_classes,
2440    std::vector<uint32_t>& child_indexes
2441)
2442{
2443    if (clang_type && name && name[0])
2444    {
2445        QualType qual_type(QualType::getFromOpaquePtr(clang_type));
2446        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2447        switch (type_class)
2448        {
2449        case clang::Type::Record:
2450            {
2451                const RecordType *record_type = cast<RecordType>(qual_type.getTypePtr());
2452                const RecordDecl *record_decl = record_type->getDecl();
2453
2454                assert(record_decl);
2455                uint32_t child_idx = 0;
2456
2457                const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
2458
2459                // Try and find a field that matches NAME
2460                RecordDecl::field_iterator field, field_end;
2461                StringRef name_sref(name);
2462                for (field = record_decl->field_begin(), field_end = record_decl->field_end();
2463                     field != field_end;
2464                     ++field, ++child_idx)
2465                {
2466                    if (field->getName().equals (name_sref))
2467                    {
2468                        // We have to add on the number of base classes to this index!
2469                        child_indexes.push_back (child_idx + GetNumBaseClasses (cxx_record_decl, omit_empty_base_classes));
2470                        return child_indexes.size();
2471                    }
2472                }
2473
2474                if (cxx_record_decl)
2475                {
2476                    const RecordDecl *parent_record_decl = cxx_record_decl;
2477
2478                    //printf ("parent = %s\n", parent_record_decl->getNameAsCString());
2479
2480                    //const Decl *root_cdecl = cxx_record_decl->getCanonicalDecl();
2481                    // Didn't find things easily, lets let clang do its thang...
2482                    IdentifierInfo & ident_ref = ast_context->Idents.get(name, name + strlen (name));
2483                    DeclarationName decl_name(&ident_ref);
2484
2485                    CXXBasePaths paths;
2486                    if (cxx_record_decl->lookupInBases(CXXRecordDecl::FindOrdinaryMember,
2487                                                       decl_name.getAsOpaquePtr(),
2488                                                       paths))
2489                    {
2490                        CXXBasePaths::const_paths_iterator path, path_end = paths.end();
2491                        for (path = paths.begin(); path != path_end; ++path)
2492                        {
2493                            const size_t num_path_elements = path->size();
2494                            for (size_t e=0; e<num_path_elements; ++e)
2495                            {
2496                                CXXBasePathElement elem = (*path)[e];
2497
2498                                child_idx = GetIndexForRecordBase (parent_record_decl, elem.Base, omit_empty_base_classes);
2499                                if (child_idx == UINT32_MAX)
2500                                {
2501                                    child_indexes.clear();
2502                                    return 0;
2503                                }
2504                                else
2505                                {
2506                                    child_indexes.push_back (child_idx);
2507                                    parent_record_decl = cast<RecordDecl>(elem.Base->getType()->getAs<RecordType>()->getDecl());
2508                                }
2509                            }
2510                            DeclContext::lookup_iterator named_decl_pos;
2511                            for (named_decl_pos = path->Decls.first;
2512                                 named_decl_pos != path->Decls.second && parent_record_decl;
2513                                 ++named_decl_pos)
2514                            {
2515                                //printf ("path[%zu] = %s\n", child_indexes.size(), (*named_decl_pos)->getNameAsCString());
2516
2517                                child_idx = GetIndexForRecordChild (parent_record_decl, *named_decl_pos, omit_empty_base_classes);
2518                                if (child_idx == UINT32_MAX)
2519                                {
2520                                    child_indexes.clear();
2521                                    return 0;
2522                                }
2523                                else
2524                                {
2525                                    child_indexes.push_back (child_idx);
2526                                }
2527                            }
2528                        }
2529                        return child_indexes.size();
2530                    }
2531                }
2532
2533            }
2534            break;
2535
2536        case clang::Type::ObjCObject:
2537        case clang::Type::ObjCInterface:
2538            {
2539                StringRef name_sref(name);
2540                ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(qual_type.getTypePtr());
2541                assert (objc_class_type);
2542                if (objc_class_type)
2543                {
2544                    uint32_t child_idx = 0;
2545                    ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
2546
2547                    if (class_interface_decl)
2548                    {
2549                        ObjCInterfaceDecl::ivar_iterator ivar_pos, ivar_end = class_interface_decl->ivar_end();
2550                        ObjCInterfaceDecl *superclass_interface_decl = class_interface_decl->getSuperClass();
2551
2552                        for (ivar_pos = class_interface_decl->ivar_begin(); ivar_pos != ivar_end; ++ivar_pos, ++child_idx)
2553                        {
2554                            const ObjCIvarDecl* ivar_decl = *ivar_pos;
2555
2556                            if (ivar_decl->getName().equals (name_sref))
2557                            {
2558                                if ((!omit_empty_base_classes && superclass_interface_decl) ||
2559                                    ( omit_empty_base_classes && ObjCDeclHasIVars (superclass_interface_decl, true)))
2560                                    ++child_idx;
2561
2562                                child_indexes.push_back (child_idx);
2563                                return child_indexes.size();
2564                            }
2565                        }
2566
2567                        if (superclass_interface_decl)
2568                        {
2569                            // The super class index is always zero for ObjC classes,
2570                            // so we push it onto the child indexes in case we find
2571                            // an ivar in our superclass...
2572                            child_indexes.push_back (0);
2573
2574                            if (GetIndexOfChildMemberWithName (ast_context,
2575                                                               ast_context->getObjCInterfaceType(superclass_interface_decl).getAsOpaquePtr(),
2576                                                               name,
2577                                                               omit_empty_base_classes,
2578                                                               child_indexes))
2579                            {
2580                                // We did find an ivar in a superclass so just
2581                                // return the results!
2582                                return child_indexes.size();
2583                            }
2584
2585                            // We didn't find an ivar matching "name" in our
2586                            // superclass, pop the superclass zero index that
2587                            // we pushed on above.
2588                            child_indexes.pop_back();
2589                        }
2590                    }
2591                }
2592            }
2593            break;
2594
2595        case clang::Type::ObjCObjectPointer:
2596            {
2597                return GetIndexOfChildMemberWithName (ast_context,
2598                                                      cast<ObjCObjectPointerType>(qual_type.getTypePtr())->getPointeeType().getAsOpaquePtr(),
2599                                                      name,
2600                                                      omit_empty_base_classes,
2601                                                      child_indexes);
2602            }
2603            break;
2604
2605
2606        case clang::Type::ConstantArray:
2607            {
2608//                const ConstantArrayType *array = cast<ConstantArrayType>(parent_qual_type.getTypePtr());
2609//                const uint64_t element_count = array->getSize().getLimitedValue();
2610//
2611//                if (idx < element_count)
2612//                {
2613//                    std::pair<uint64_t, unsigned> field_type_info = ast_context->getTypeInfo(array->getElementType());
2614//
2615//                    char element_name[32];
2616//                    ::snprintf (element_name, sizeof (element_name), "%s[%u]", parent_name ? parent_name : "", idx);
2617//
2618//                    child_name.assign(element_name);
2619//                    assert(field_type_info.first % 8 == 0);
2620//                    child_byte_size = field_type_info.first / 8;
2621//                    child_byte_offset = idx * child_byte_size;
2622//                    return array->getElementType().getAsOpaquePtr();
2623//                }
2624            }
2625            break;
2626
2627//        case clang::Type::MemberPointerType:
2628//            {
2629//                MemberPointerType *mem_ptr_type = cast<MemberPointerType>(qual_type.getTypePtr());
2630//                QualType pointee_type = mem_ptr_type->getPointeeType();
2631//
2632//                if (ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
2633//                {
2634//                    return GetIndexOfChildWithName (ast_context,
2635//                                                    mem_ptr_type->getPointeeType().getAsOpaquePtr(),
2636//                                                    name);
2637//                }
2638//            }
2639//            break;
2640//
2641        case clang::Type::LValueReference:
2642        case clang::Type::RValueReference:
2643            {
2644                ReferenceType *reference_type = cast<ReferenceType>(qual_type.getTypePtr());
2645                QualType pointee_type = reference_type->getPointeeType();
2646
2647                if (ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
2648                {
2649                    return GetIndexOfChildMemberWithName (ast_context,
2650                                                          reference_type->getPointeeType().getAsOpaquePtr(),
2651                                                          name,
2652                                                          omit_empty_base_classes,
2653                                                          child_indexes);
2654                }
2655            }
2656            break;
2657
2658        case clang::Type::Pointer:
2659            {
2660                PointerType *pointer_type = cast<PointerType>(qual_type.getTypePtr());
2661                QualType pointee_type = pointer_type->getPointeeType();
2662
2663                if (ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
2664                {
2665                    return GetIndexOfChildMemberWithName (ast_context,
2666                                                          pointer_type->getPointeeType().getAsOpaquePtr(),
2667                                                          name,
2668                                                          omit_empty_base_classes,
2669                                                          child_indexes);
2670                }
2671                else
2672                {
2673//                    if (parent_name)
2674//                    {
2675//                        child_name.assign(1, '*');
2676//                        child_name += parent_name;
2677//                    }
2678//
2679//                    // We have a pointer to an simple type
2680//                    if (idx == 0)
2681//                    {
2682//                        std::pair<uint64_t, unsigned> clang_type_info = ast_context->getTypeInfo(pointee_type);
2683//                        assert(clang_type_info.first % 8 == 0);
2684//                        child_byte_size = clang_type_info.first / 8;
2685//                        child_byte_offset = 0;
2686//                        return pointee_type.getAsOpaquePtr();
2687//                    }
2688                }
2689            }
2690            break;
2691
2692        case clang::Type::Typedef:
2693            return GetIndexOfChildMemberWithName (ast_context,
2694                                                  cast<TypedefType>(qual_type)->LookThroughTypedefs().getAsOpaquePtr(),
2695                                                  name,
2696                                                  omit_empty_base_classes,
2697                                                  child_indexes);
2698
2699        default:
2700            break;
2701        }
2702    }
2703    return 0;
2704}
2705
2706
2707// Get the index of the child of "clang_type" whose name matches. This function
2708// doesn't descend into the children, but only looks one level deep and name
2709// matches can include base class names.
2710
2711uint32_t
2712ClangASTContext::GetIndexOfChildWithName
2713(
2714    ASTContext *ast_context,
2715    clang_type_t clang_type,
2716    const char *name,
2717    bool omit_empty_base_classes
2718)
2719{
2720    if (clang_type && name && name[0])
2721    {
2722        QualType qual_type(QualType::getFromOpaquePtr(clang_type));
2723
2724        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2725
2726        switch (type_class)
2727        {
2728        case clang::Type::Record:
2729            {
2730                const RecordType *record_type = cast<RecordType>(qual_type.getTypePtr());
2731                const RecordDecl *record_decl = record_type->getDecl();
2732
2733                assert(record_decl);
2734                uint32_t child_idx = 0;
2735
2736                const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
2737
2738                if (cxx_record_decl)
2739                {
2740                    CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
2741                    for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
2742                         base_class != base_class_end;
2743                         ++base_class)
2744                    {
2745                        // Skip empty base classes
2746                        CXXRecordDecl *base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
2747                        if (omit_empty_base_classes && RecordHasFields(base_class_decl) == false)
2748                            continue;
2749
2750                        if (base_class->getType().getAsString().compare (name) == 0)
2751                            return child_idx;
2752                        ++child_idx;
2753                    }
2754                }
2755
2756                // Try and find a field that matches NAME
2757                RecordDecl::field_iterator field, field_end;
2758                StringRef name_sref(name);
2759                for (field = record_decl->field_begin(), field_end = record_decl->field_end();
2760                     field != field_end;
2761                     ++field, ++child_idx)
2762                {
2763                    if (field->getName().equals (name_sref))
2764                        return child_idx;
2765                }
2766
2767            }
2768            break;
2769
2770        case clang::Type::ObjCObject:
2771        case clang::Type::ObjCInterface:
2772            {
2773                StringRef name_sref(name);
2774                ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(qual_type.getTypePtr());
2775                assert (objc_class_type);
2776                if (objc_class_type)
2777                {
2778                    uint32_t child_idx = 0;
2779                    ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
2780
2781                    if (class_interface_decl)
2782                    {
2783                        ObjCInterfaceDecl::ivar_iterator ivar_pos, ivar_end = class_interface_decl->ivar_end();
2784                        ObjCInterfaceDecl *superclass_interface_decl = class_interface_decl->getSuperClass();
2785
2786                        for (ivar_pos = class_interface_decl->ivar_begin(); ivar_pos != ivar_end; ++ivar_pos)
2787                        {
2788                            const ObjCIvarDecl* ivar_decl = *ivar_pos;
2789
2790                            if (ivar_decl->getName().equals (name_sref))
2791                            {
2792                                if ((!omit_empty_base_classes && superclass_interface_decl) ||
2793                                    ( omit_empty_base_classes && ObjCDeclHasIVars (superclass_interface_decl, true)))
2794                                    ++child_idx;
2795
2796                                return child_idx;
2797                            }
2798                        }
2799
2800                        if (superclass_interface_decl)
2801                        {
2802                            if (superclass_interface_decl->getName().equals (name_sref))
2803                                return 0;
2804                        }
2805                    }
2806                }
2807            }
2808            break;
2809
2810        case clang::Type::ObjCObjectPointer:
2811            {
2812                return GetIndexOfChildWithName (ast_context,
2813                                                cast<ObjCObjectPointerType>(qual_type.getTypePtr())->getPointeeType().getAsOpaquePtr(),
2814                                                name,
2815                                                omit_empty_base_classes);
2816            }
2817            break;
2818
2819        case clang::Type::ConstantArray:
2820            {
2821//                const ConstantArrayType *array = cast<ConstantArrayType>(parent_qual_type.getTypePtr());
2822//                const uint64_t element_count = array->getSize().getLimitedValue();
2823//
2824//                if (idx < element_count)
2825//                {
2826//                    std::pair<uint64_t, unsigned> field_type_info = ast_context->getTypeInfo(array->getElementType());
2827//
2828//                    char element_name[32];
2829//                    ::snprintf (element_name, sizeof (element_name), "%s[%u]", parent_name ? parent_name : "", idx);
2830//
2831//                    child_name.assign(element_name);
2832//                    assert(field_type_info.first % 8 == 0);
2833//                    child_byte_size = field_type_info.first / 8;
2834//                    child_byte_offset = idx * child_byte_size;
2835//                    return array->getElementType().getAsOpaquePtr();
2836//                }
2837            }
2838            break;
2839
2840//        case clang::Type::MemberPointerType:
2841//            {
2842//                MemberPointerType *mem_ptr_type = cast<MemberPointerType>(qual_type.getTypePtr());
2843//                QualType pointee_type = mem_ptr_type->getPointeeType();
2844//
2845//                if (ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
2846//                {
2847//                    return GetIndexOfChildWithName (ast_context,
2848//                                                    mem_ptr_type->getPointeeType().getAsOpaquePtr(),
2849//                                                    name);
2850//                }
2851//            }
2852//            break;
2853//
2854        case clang::Type::LValueReference:
2855        case clang::Type::RValueReference:
2856            {
2857                ReferenceType *reference_type = cast<ReferenceType>(qual_type.getTypePtr());
2858                QualType pointee_type = reference_type->getPointeeType();
2859
2860                if (ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
2861                {
2862                    return GetIndexOfChildWithName (ast_context,
2863                                                    reference_type->getPointeeType().getAsOpaquePtr(),
2864                                                    name,
2865                                                    omit_empty_base_classes);
2866                }
2867            }
2868            break;
2869
2870        case clang::Type::Pointer:
2871            {
2872                PointerType *pointer_type = cast<PointerType>(qual_type.getTypePtr());
2873                QualType pointee_type = pointer_type->getPointeeType();
2874
2875                if (ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
2876                {
2877                    return GetIndexOfChildWithName (ast_context,
2878                                                    pointer_type->getPointeeType().getAsOpaquePtr(),
2879                                                    name,
2880                                                    omit_empty_base_classes);
2881                }
2882                else
2883                {
2884//                    if (parent_name)
2885//                    {
2886//                        child_name.assign(1, '*');
2887//                        child_name += parent_name;
2888//                    }
2889//
2890//                    // We have a pointer to an simple type
2891//                    if (idx == 0)
2892//                    {
2893//                        std::pair<uint64_t, unsigned> clang_type_info = ast_context->getTypeInfo(pointee_type);
2894//                        assert(clang_type_info.first % 8 == 0);
2895//                        child_byte_size = clang_type_info.first / 8;
2896//                        child_byte_offset = 0;
2897//                        return pointee_type.getAsOpaquePtr();
2898//                    }
2899                }
2900            }
2901            break;
2902
2903        case clang::Type::Typedef:
2904            return GetIndexOfChildWithName (ast_context,
2905                                            cast<TypedefType>(qual_type)->LookThroughTypedefs().getAsOpaquePtr(),
2906                                            name,
2907                                            omit_empty_base_classes);
2908
2909        default:
2910            break;
2911        }
2912    }
2913    return UINT32_MAX;
2914}
2915
2916#pragma mark TagType
2917
2918bool
2919ClangASTContext::SetTagTypeKind (clang_type_t tag_clang_type, int kind)
2920{
2921    if (tag_clang_type)
2922    {
2923        QualType tag_qual_type(QualType::getFromOpaquePtr(tag_clang_type));
2924        clang::Type *clang_type = tag_qual_type.getTypePtr();
2925        if (clang_type)
2926        {
2927            TagType *tag_type = dyn_cast<TagType>(clang_type);
2928            if (tag_type)
2929            {
2930                TagDecl *tag_decl = dyn_cast<TagDecl>(tag_type->getDecl());
2931                if (tag_decl)
2932                {
2933                    tag_decl->setTagKind ((TagDecl::TagKind)kind);
2934                    return true;
2935                }
2936            }
2937        }
2938    }
2939    return false;
2940}
2941
2942
2943#pragma mark DeclContext Functions
2944
2945DeclContext *
2946ClangASTContext::GetDeclContextForType (clang_type_t clang_type)
2947{
2948    if (clang_type == NULL)
2949        return NULL;
2950
2951    QualType qual_type(QualType::getFromOpaquePtr(clang_type));
2952    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2953    switch (type_class)
2954    {
2955    case clang::Type::FunctionNoProto:          break;
2956    case clang::Type::FunctionProto:            break;
2957    case clang::Type::IncompleteArray:          break;
2958    case clang::Type::VariableArray:            break;
2959    case clang::Type::ConstantArray:            break;
2960    case clang::Type::ExtVector:                break;
2961    case clang::Type::Vector:                   break;
2962    case clang::Type::Builtin:                  break;
2963    case clang::Type::BlockPointer:             break;
2964    case clang::Type::Pointer:                  break;
2965    case clang::Type::LValueReference:          break;
2966    case clang::Type::RValueReference:          break;
2967    case clang::Type::MemberPointer:            break;
2968    case clang::Type::Complex:                  break;
2969    case clang::Type::ObjCObject:               break;
2970    case clang::Type::ObjCInterface:            return cast<ObjCObjectType>(qual_type.getTypePtr())->getInterface();
2971    case clang::Type::ObjCObjectPointer:        return ClangASTContext::GetDeclContextForType (cast<ObjCObjectPointerType>(qual_type.getTypePtr())->getPointeeType().getAsOpaquePtr());
2972    case clang::Type::Record:                   return cast<RecordType>(qual_type)->getDecl();
2973    case clang::Type::Enum:                     return cast<EnumType>(qual_type)->getDecl();
2974    case clang::Type::Typedef:                  return ClangASTContext::GetDeclContextForType (cast<TypedefType>(qual_type)->LookThroughTypedefs().getAsOpaquePtr());
2975
2976    case clang::Type::TypeOfExpr:               break;
2977    case clang::Type::TypeOf:                   break;
2978    case clang::Type::Decltype:                 break;
2979    //case clang::Type::QualifiedName:          break;
2980    case clang::Type::TemplateSpecialization:   break;
2981    }
2982    // No DeclContext in this type...
2983    return NULL;
2984}
2985
2986#pragma mark Namespace Declarations
2987
2988NamespaceDecl *
2989ClangASTContext::GetUniqueNamespaceDeclaration (const char *name, const Declaration &decl, DeclContext *decl_ctx)
2990{
2991    // TODO: Do something intelligent with the Declaration object passed in
2992    // like maybe filling in the SourceLocation with it...
2993    if (name)
2994    {
2995        ASTContext *ast_context = getASTContext();
2996        if (decl_ctx == NULL)
2997            decl_ctx = ast_context->getTranslationUnitDecl();
2998        return NamespaceDecl::Create(*ast_context, decl_ctx, SourceLocation(), &ast_context->Idents.get(name));
2999    }
3000    return NULL;
3001}
3002
3003
3004#pragma mark Function Types
3005
3006FunctionDecl *
3007ClangASTContext::CreateFunctionDeclaration (const char *name, clang_type_t function_clang_type, int storage, bool is_inline)
3008{
3009    if (name)
3010    {
3011        ASTContext *ast_context = getASTContext();
3012        assert (ast_context != NULL);
3013
3014        if (name && name[0])
3015        {
3016            return FunctionDecl::Create(*ast_context,
3017                                        ast_context->getTranslationUnitDecl(),
3018                                        SourceLocation(),
3019                                        DeclarationName (&ast_context->Idents.get(name)),
3020                                        QualType::getFromOpaquePtr(function_clang_type),
3021                                        NULL,
3022                                        (FunctionDecl::StorageClass)storage,
3023                                        (FunctionDecl::StorageClass)storage,
3024                                        is_inline);
3025        }
3026        else
3027        {
3028            return FunctionDecl::Create(*ast_context,
3029                                        ast_context->getTranslationUnitDecl(),
3030                                        SourceLocation(),
3031                                        DeclarationName (),
3032                                        QualType::getFromOpaquePtr(function_clang_type),
3033                                        NULL,
3034                                        (FunctionDecl::StorageClass)storage,
3035                                        (FunctionDecl::StorageClass)storage,
3036                                        is_inline);
3037        }
3038    }
3039    return NULL;
3040}
3041
3042clang_type_t
3043ClangASTContext::CreateFunctionType (ASTContext *ast_context,
3044                                     clang_type_t result_type,
3045                                     clang_type_t *args,
3046                                     unsigned num_args,
3047                                     bool is_variadic,
3048                                     unsigned type_quals)
3049{
3050    assert (ast_context != NULL);
3051    std::vector<QualType> qual_type_args;
3052    for (unsigned i=0; i<num_args; ++i)
3053        qual_type_args.push_back (QualType::getFromOpaquePtr(args[i]));
3054
3055    // TODO: Detect calling convention in DWARF?
3056    return ast_context->getFunctionType(QualType::getFromOpaquePtr(result_type),
3057                                        qual_type_args.empty() ? NULL : &qual_type_args.front(),
3058                                        qual_type_args.size(),
3059                                        is_variadic,
3060                                        type_quals,
3061                                        false,  // hasExceptionSpec
3062                                        false,  // hasAnyExceptionSpec,
3063                                        0,      // NumExs
3064                                        0,      // const QualType *ExArray
3065                                        FunctionType::ExtInfo ()).getAsOpaquePtr();    // NoReturn);
3066}
3067
3068ParmVarDecl *
3069ClangASTContext::CreateParameterDeclaration (const char *name, clang_type_t param_type, int storage)
3070{
3071    ASTContext *ast_context = getASTContext();
3072    assert (ast_context != NULL);
3073    return ParmVarDecl::Create(*ast_context,
3074                                ast_context->getTranslationUnitDecl(),
3075                                SourceLocation(),
3076                                name && name[0] ? &ast_context->Idents.get(name) : NULL,
3077                                QualType::getFromOpaquePtr(param_type),
3078                                NULL,
3079                                (VarDecl::StorageClass)storage,
3080                                (VarDecl::StorageClass)storage,
3081                                0);
3082}
3083
3084void
3085ClangASTContext::SetFunctionParameters (FunctionDecl *function_decl, ParmVarDecl **params, unsigned num_params)
3086{
3087    if (function_decl)
3088        function_decl->setParams (params, num_params);
3089}
3090
3091
3092#pragma mark Array Types
3093
3094clang_type_t
3095ClangASTContext::CreateArrayType (clang_type_t element_type, size_t element_count, uint32_t bit_stride)
3096{
3097    if (element_type)
3098    {
3099        ASTContext *ast_context = getASTContext();
3100        assert (ast_context != NULL);
3101        llvm::APInt ap_element_count (64, element_count);
3102        return ast_context->getConstantArrayType(QualType::getFromOpaquePtr(element_type),
3103                                                 ap_element_count,
3104                                                 ArrayType::Normal,
3105                                                 0).getAsOpaquePtr(); // ElemQuals
3106    }
3107    return NULL;
3108}
3109
3110
3111#pragma mark TagDecl
3112
3113bool
3114ClangASTContext::StartTagDeclarationDefinition (clang_type_t clang_type)
3115{
3116    if (clang_type)
3117    {
3118        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
3119        clang::Type *t = qual_type.getTypePtr();
3120        if (t)
3121        {
3122            TagType *tag_type = dyn_cast<TagType>(t);
3123            if (tag_type)
3124            {
3125                TagDecl *tag_decl = tag_type->getDecl();
3126                if (tag_decl)
3127                {
3128                    tag_decl->startDefinition();
3129                    return true;
3130                }
3131            }
3132        }
3133    }
3134    return false;
3135}
3136
3137bool
3138ClangASTContext::CompleteTagDeclarationDefinition (clang_type_t clang_type)
3139{
3140    if (clang_type)
3141    {
3142        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
3143
3144        CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
3145
3146        if (cxx_record_decl)
3147        {
3148            cxx_record_decl->completeDefinition();
3149
3150            return true;
3151        }
3152
3153        const EnumType *enum_type = dyn_cast<EnumType>(qual_type.getTypePtr());
3154
3155        if (enum_type)
3156        {
3157            EnumDecl *enum_decl = enum_type->getDecl();
3158
3159            if (enum_decl)
3160            {
3161                /// TODO This really needs to be fixed.
3162
3163                unsigned NumPositiveBits = 1;
3164                unsigned NumNegativeBits = 0;
3165
3166                ASTContext *ast_context = getASTContext();
3167
3168                QualType promotion_qual_type;
3169                // If the enum integer type is less than an integer in bit width,
3170                // then we must promote it to an integer size.
3171                if (ast_context->getTypeSize(enum_decl->getIntegerType()) < ast_context->getTypeSize(ast_context->IntTy))
3172                {
3173                    if (enum_decl->getIntegerType()->isSignedIntegerType())
3174                        promotion_qual_type = ast_context->IntTy;
3175                    else
3176                        promotion_qual_type = ast_context->UnsignedIntTy;
3177                }
3178                else
3179                    promotion_qual_type = enum_decl->getIntegerType();
3180
3181                enum_decl->completeDefinition(enum_decl->getIntegerType(), promotion_qual_type, NumPositiveBits, NumNegativeBits);
3182                return true;
3183            }
3184        }
3185    }
3186    return false;
3187}
3188
3189
3190#pragma mark Enumeration Types
3191
3192clang_type_t
3193ClangASTContext::CreateEnumerationType (const Declaration &decl, const char *name, clang_type_t integer_qual_type)
3194{
3195    // TODO: Do something intelligent with the Declaration object passed in
3196    // like maybe filling in the SourceLocation with it...
3197    ASTContext *ast_context = getASTContext();
3198    assert (ast_context != NULL);
3199
3200    // TODO: ask about these...
3201//    const bool IsScoped = false;
3202//    const bool IsFixed = false;
3203
3204    EnumDecl *enum_decl = EnumDecl::Create (*ast_context,
3205                                            ast_context->getTranslationUnitDecl(),
3206                                            SourceLocation(),
3207                                            name && name[0] ? &ast_context->Idents.get(name) : NULL,
3208                                            SourceLocation(),
3209                                            NULL); //IsScoped, IsFixed);
3210    if (enum_decl)
3211    {
3212        // TODO: check if we should be setting the promotion type too?
3213        enum_decl->setIntegerType(QualType::getFromOpaquePtr (integer_qual_type));
3214        return ast_context->getTagDeclType(enum_decl).getAsOpaquePtr();
3215    }
3216    return NULL;
3217}
3218
3219clang_type_t
3220ClangASTContext::GetEnumerationIntegerType (clang_type_t enum_clang_type)
3221{
3222    QualType enum_qual_type (QualType::getFromOpaquePtr(enum_clang_type));
3223
3224    clang::Type *clang_type = enum_qual_type.getTypePtr();
3225    if (clang_type)
3226    {
3227        const EnumType *enum_type = dyn_cast<EnumType>(clang_type);
3228        if (enum_type)
3229        {
3230            EnumDecl *enum_decl = enum_type->getDecl();
3231            if (enum_decl)
3232                return enum_decl->getIntegerType().getAsOpaquePtr();
3233        }
3234    }
3235    return NULL;
3236}
3237bool
3238ClangASTContext::AddEnumerationValueToEnumerationType
3239(
3240    clang_type_t enum_clang_type,
3241    clang_type_t enumerator_clang_type,
3242    const Declaration &decl,
3243    const char *name,
3244    int64_t enum_value,
3245    uint32_t enum_value_bit_size
3246)
3247{
3248    if (enum_clang_type && enumerator_clang_type && name)
3249    {
3250        // TODO: Do something intelligent with the Declaration object passed in
3251        // like maybe filling in the SourceLocation with it...
3252        ASTContext *ast_context = getASTContext();
3253        IdentifierTable *identifier_table = getIdentifierTable();
3254
3255        assert (ast_context != NULL);
3256        assert (identifier_table != NULL);
3257        QualType enum_qual_type (QualType::getFromOpaquePtr(enum_clang_type));
3258
3259        clang::Type *clang_type = enum_qual_type.getTypePtr();
3260        if (clang_type)
3261        {
3262            const EnumType *enum_type = dyn_cast<EnumType>(clang_type);
3263
3264            if (enum_type)
3265            {
3266                llvm::APSInt enum_llvm_apsint(enum_value_bit_size, false);
3267                enum_llvm_apsint = enum_value;
3268                EnumConstantDecl *enumerator_decl =
3269                    EnumConstantDecl::Create(*ast_context,
3270                                             enum_type->getDecl(),
3271                                             SourceLocation(),
3272                                             name ? &identifier_table->get(name) : NULL,    // Identifier
3273                                             QualType::getFromOpaquePtr(enumerator_clang_type),
3274                                             NULL,
3275                                             enum_llvm_apsint);
3276
3277                if (enumerator_decl)
3278                {
3279                    enum_type->getDecl()->addDecl(enumerator_decl);
3280                    return true;
3281                }
3282            }
3283        }
3284    }
3285    return false;
3286}
3287
3288#pragma mark Pointers & References
3289
3290clang_type_t
3291ClangASTContext::CreatePointerType (clang_type_t clang_type)
3292{
3293    if (clang_type)
3294    {
3295        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
3296
3297        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3298        switch (type_class)
3299        {
3300        case clang::Type::ObjCObject:
3301        case clang::Type::ObjCInterface:
3302            return getASTContext()->getObjCObjectPointerType(qual_type).getAsOpaquePtr();
3303
3304        default:
3305            return getASTContext()->getPointerType(qual_type).getAsOpaquePtr();
3306        }
3307    }
3308    return NULL;
3309}
3310
3311clang_type_t
3312ClangASTContext::CreateLValueReferenceType (clang_type_t clang_type)
3313{
3314    if (clang_type)
3315        return getASTContext()->getLValueReferenceType (QualType::getFromOpaquePtr(clang_type)).getAsOpaquePtr();
3316    return NULL;
3317}
3318
3319clang_type_t
3320ClangASTContext::CreateRValueReferenceType (clang_type_t clang_type)
3321{
3322    if (clang_type)
3323        return getASTContext()->getRValueReferenceType (QualType::getFromOpaquePtr(clang_type)).getAsOpaquePtr();
3324    return NULL;
3325}
3326
3327clang_type_t
3328ClangASTContext::CreateMemberPointerType (clang_type_t clang_pointee_type, clang_type_t clang_class_type)
3329{
3330    if (clang_pointee_type && clang_pointee_type)
3331        return getASTContext()->getMemberPointerType(QualType::getFromOpaquePtr(clang_pointee_type),
3332                                                     QualType::getFromOpaquePtr(clang_class_type).getTypePtr()).getAsOpaquePtr();
3333    return NULL;
3334}
3335
3336size_t
3337ClangASTContext::GetPointerBitSize ()
3338{
3339    ASTContext *ast_context = getASTContext();
3340    return ast_context->getTypeSize(ast_context->VoidPtrTy);
3341}
3342
3343bool
3344ClangASTContext::IsPointerOrReferenceType (clang_type_t clang_type, clang_type_t*target_type)
3345{
3346    if (clang_type == NULL)
3347        return false;
3348
3349    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
3350    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3351    switch (type_class)
3352    {
3353    case clang::Type::ObjCObjectPointer:
3354        if (target_type)
3355            *target_type = cast<ObjCObjectPointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
3356        return true;
3357    case clang::Type::BlockPointer:
3358        if (target_type)
3359            *target_type = cast<BlockPointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
3360        return true;
3361    case clang::Type::Pointer:
3362        if (target_type)
3363            *target_type = cast<PointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
3364        return true;
3365    case clang::Type::MemberPointer:
3366        if (target_type)
3367            *target_type = cast<MemberPointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
3368        return true;
3369    case clang::Type::LValueReference:
3370        if (target_type)
3371            *target_type = cast<LValueReferenceType>(qual_type)->desugar().getAsOpaquePtr();
3372        return true;
3373    case clang::Type::RValueReference:
3374        if (target_type)
3375            *target_type = cast<LValueReferenceType>(qual_type)->desugar().getAsOpaquePtr();
3376        return true;
3377    case clang::Type::Typedef:
3378        return ClangASTContext::IsPointerOrReferenceType (cast<TypedefType>(qual_type)->LookThroughTypedefs().getAsOpaquePtr());
3379    default:
3380        break;
3381    }
3382    return false;
3383}
3384
3385bool
3386ClangASTContext::IsIntegerType (clang_type_t clang_type, bool &is_signed)
3387{
3388    if (!clang_type)
3389        return false;
3390
3391    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
3392    const BuiltinType *builtin_type = dyn_cast<BuiltinType>(qual_type->getCanonicalTypeInternal());
3393
3394    if (builtin_type)
3395    {
3396        if (builtin_type->isInteger())
3397            is_signed = builtin_type->isSignedInteger();
3398
3399        return true;
3400    }
3401
3402    return false;
3403}
3404
3405bool
3406ClangASTContext::IsPointerType (clang_type_t clang_type, clang_type_t*target_type)
3407{
3408    if (clang_type)
3409    {
3410        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
3411        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3412        switch (type_class)
3413        {
3414        case clang::Type::ObjCObjectPointer:
3415            if (target_type)
3416                *target_type = cast<ObjCObjectPointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
3417            return true;
3418        case clang::Type::BlockPointer:
3419            if (target_type)
3420                *target_type = cast<BlockPointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
3421            return true;
3422        case clang::Type::Pointer:
3423            if (target_type)
3424                *target_type = cast<PointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
3425            return true;
3426        case clang::Type::MemberPointer:
3427            if (target_type)
3428                *target_type = cast<MemberPointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
3429            return true;
3430        case clang::Type::Typedef:
3431            return ClangASTContext::IsPointerOrReferenceType (cast<TypedefType>(qual_type)->LookThroughTypedefs().getAsOpaquePtr(), target_type);
3432        default:
3433            break;
3434        }
3435    }
3436    return false;
3437}
3438
3439bool
3440ClangASTContext::IsFloatingPointType (clang_type_t clang_type, uint32_t &count, bool &is_complex)
3441{
3442    if (clang_type)
3443    {
3444        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
3445
3446        if (const BuiltinType *BT = dyn_cast<BuiltinType>(qual_type->getCanonicalTypeInternal()))
3447        {
3448            clang::BuiltinType::Kind kind = BT->getKind();
3449            if (kind >= BuiltinType::Float && kind <= BuiltinType::LongDouble)
3450            {
3451                count = 1;
3452                is_complex = false;
3453                return true;
3454            }
3455        }
3456        else if (const ComplexType *CT = dyn_cast<ComplexType>(qual_type->getCanonicalTypeInternal()))
3457        {
3458            if (IsFloatingPointType(CT->getElementType().getAsOpaquePtr(), count, is_complex))
3459            {
3460                count = 2;
3461                is_complex = true;
3462                return true;
3463            }
3464        }
3465        else if (const VectorType *VT = dyn_cast<VectorType>(qual_type->getCanonicalTypeInternal()))
3466        {
3467            if (IsFloatingPointType(VT->getElementType().getAsOpaquePtr(), count, is_complex))
3468            {
3469                count = VT->getNumElements();
3470                is_complex = false;
3471                return true;
3472            }
3473        }
3474    }
3475    return false;
3476}
3477
3478
3479bool
3480ClangASTContext::GetCXXClassName (clang_type_t clang_type, std::string &class_name)
3481{
3482    if (clang_type)
3483    {
3484        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
3485
3486        CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
3487        if (cxx_record_decl)
3488        {
3489            class_name.assign (cxx_record_decl->getIdentifier()->getNameStart());
3490            return true;
3491        }
3492    }
3493    class_name.clear();
3494    return false;
3495}
3496
3497
3498bool
3499ClangASTContext::IsCXXClassType (clang_type_t clang_type)
3500{
3501    if (clang_type)
3502    {
3503        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
3504        if (qual_type->getAsCXXRecordDecl() != NULL)
3505            return true;
3506    }
3507    return false;
3508}
3509
3510bool
3511ClangASTContext::IsObjCClassType (clang_type_t clang_type)
3512{
3513    if (clang_type)
3514    {
3515        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
3516        if (qual_type->isObjCObjectOrInterfaceType())
3517            return true;
3518    }
3519    return false;
3520}
3521
3522
3523
3524
3525bool
3526ClangASTContext::IsCStringType (clang_type_t clang_type, uint32_t &length)
3527{
3528    if (clang_type)
3529    {
3530        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
3531        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3532        switch (type_class)
3533        {
3534        case clang::Type::ConstantArray:
3535            {
3536                ConstantArrayType *array = cast<ConstantArrayType>(qual_type.getTypePtr());
3537                QualType element_qual_type = array->getElementType();
3538                clang::Type *canonical_type = element_qual_type->getCanonicalTypeInternal().getTypePtr();
3539                if (canonical_type && canonical_type->isCharType())
3540                {
3541                    // We know the size of the array and it could be a C string
3542                    // since it is an array of characters
3543                    length = array->getSize().getLimitedValue();
3544                    return true;
3545                }
3546            }
3547            break;
3548
3549        case clang::Type::Pointer:
3550            {
3551                PointerType *pointer_type = cast<PointerType>(qual_type.getTypePtr());
3552                clang::Type *pointee_type_ptr = pointer_type->getPointeeType().getTypePtr();
3553                if (pointee_type_ptr)
3554                {
3555                    clang::Type *canonical_type_ptr = pointee_type_ptr->getCanonicalTypeInternal().getTypePtr();
3556                    length = 0; // No length info, read until a NULL terminator is received
3557                    if (canonical_type_ptr)
3558                        return canonical_type_ptr->isCharType();
3559                    else
3560                        return pointee_type_ptr->isCharType();
3561                }
3562            }
3563            break;
3564
3565        case clang::Type::Typedef:
3566            return ClangASTContext::IsCStringType (cast<TypedefType>(qual_type)->LookThroughTypedefs().getAsOpaquePtr(), length);
3567
3568        case clang::Type::LValueReference:
3569        case clang::Type::RValueReference:
3570            {
3571                ReferenceType *reference_type = cast<ReferenceType>(qual_type.getTypePtr());
3572                clang::Type *pointee_type_ptr = reference_type->getPointeeType().getTypePtr();
3573                if (pointee_type_ptr)
3574                {
3575                    clang::Type *canonical_type_ptr = pointee_type_ptr->getCanonicalTypeInternal().getTypePtr();
3576                    length = 0; // No length info, read until a NULL terminator is received
3577                    if (canonical_type_ptr)
3578                        return canonical_type_ptr->isCharType();
3579                    else
3580                        return pointee_type_ptr->isCharType();
3581                }
3582            }
3583            break;
3584        }
3585    }
3586    return false;
3587}
3588
3589bool
3590ClangASTContext::IsFunctionPointerType (clang_type_t clang_type)
3591{
3592    if (clang_type)
3593    {
3594        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
3595
3596        if (qual_type->isFunctionPointerType())
3597            return true;
3598
3599        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3600        switch (type_class)
3601        {
3602        case clang::Type::Typedef:
3603            return ClangASTContext::IsFunctionPointerType (cast<TypedefType>(qual_type)->LookThroughTypedefs().getAsOpaquePtr());
3604
3605        case clang::Type::LValueReference:
3606        case clang::Type::RValueReference:
3607            {
3608                ReferenceType *reference_type = cast<ReferenceType>(qual_type.getTypePtr());
3609                if (reference_type)
3610                    return ClangASTContext::IsFunctionPointerType (reference_type->getPointeeType().getAsOpaquePtr());
3611            }
3612            break;
3613        }
3614    }
3615    return false;
3616}
3617
3618
3619
3620
3621bool
3622ClangASTContext::IsArrayType (clang_type_t clang_type, clang_type_t*member_type, uint64_t *size)
3623{
3624    if (!clang_type)
3625        return false;
3626
3627    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
3628
3629    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3630    switch (type_class)
3631    {
3632    case clang::Type::ConstantArray:
3633        if (member_type)
3634            *member_type = cast<ConstantArrayType>(qual_type)->getElementType().getAsOpaquePtr();
3635        if (size)
3636            *size = cast<ConstantArrayType>(qual_type)->getSize().getLimitedValue(ULONG_LONG_MAX);
3637        return true;
3638    case clang::Type::IncompleteArray:
3639        if (member_type)
3640            *member_type = cast<IncompleteArrayType>(qual_type)->getElementType().getAsOpaquePtr();
3641        if (size)
3642            *size = 0;
3643        return true;
3644    case clang::Type::VariableArray:
3645        if (member_type)
3646            *member_type = cast<VariableArrayType>(qual_type)->getElementType().getAsOpaquePtr();
3647        if (size)
3648            *size = 0;
3649    case clang::Type::DependentSizedArray:
3650        if (member_type)
3651            *member_type = cast<DependentSizedArrayType>(qual_type)->getElementType().getAsOpaquePtr();
3652        if (size)
3653            *size = 0;
3654        return true;
3655    }
3656    return false;
3657}
3658
3659
3660#pragma mark Typedefs
3661
3662clang_type_t
3663ClangASTContext::CreateTypedefType (const char *name, clang_type_t clang_type, DeclContext *decl_ctx)
3664{
3665    if (clang_type)
3666    {
3667        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
3668        ASTContext *ast_context = getASTContext();
3669        IdentifierTable *identifier_table = getIdentifierTable();
3670        assert (ast_context != NULL);
3671        assert (identifier_table != NULL);
3672        if (decl_ctx == NULL)
3673            decl_ctx = ast_context->getTranslationUnitDecl();
3674        TypedefDecl *decl = TypedefDecl::Create(*ast_context,
3675                                                decl_ctx,
3676                                                SourceLocation(),
3677                                                name ? &identifier_table->get(name) : NULL, // Identifier
3678                                                ast_context->CreateTypeSourceInfo(qual_type));
3679
3680        // Get a uniqued QualType for the typedef decl type
3681        return ast_context->getTypedefType (decl).getAsOpaquePtr();
3682    }
3683    return NULL;
3684}
3685
3686
3687std::string
3688ClangASTContext::GetTypeName (clang_type_t opaque_qual_type)
3689{
3690    std::string return_name;
3691
3692    QualType qual_type(QualType::getFromOpaquePtr(opaque_qual_type));
3693
3694    const TypedefType *typedef_type = qual_type->getAs<TypedefType>();
3695    if (typedef_type)
3696    {
3697        const TypedefDecl *typedef_decl = typedef_type->getDecl();
3698        return_name = typedef_decl->getQualifiedNameAsString();
3699    }
3700    else
3701    {
3702        return_name = qual_type.getAsString();
3703    }
3704
3705    return return_name;
3706}
3707
3708// Disable this for now since I can't seem to get a nicely formatted float
3709// out of the APFloat class without just getting the float, double or quad
3710// and then using a formatted print on it which defeats the purpose. We ideally
3711// would like to get perfect string values for any kind of float semantics
3712// so we can support remote targets. The code below also requires a patch to
3713// llvm::APInt.
3714//bool
3715//ClangASTContext::ConvertFloatValueToString (ASTContext *ast_context, clang_type_t clang_type, const uint8_t* bytes, size_t byte_size, int apint_byte_order, std::string &float_str)
3716//{
3717//  uint32_t count = 0;
3718//  bool is_complex = false;
3719//  if (ClangASTContext::IsFloatingPointType (clang_type, count, is_complex))
3720//  {
3721//      unsigned num_bytes_per_float = byte_size / count;
3722//      unsigned num_bits_per_float = num_bytes_per_float * 8;
3723//
3724//      float_str.clear();
3725//      uint32_t i;
3726//      for (i=0; i<count; i++)
3727//      {
3728//          APInt ap_int(num_bits_per_float, bytes + i * num_bytes_per_float, (APInt::ByteOrder)apint_byte_order);
3729//          bool is_ieee = false;
3730//          APFloat ap_float(ap_int, is_ieee);
3731//          char s[1024];
3732//          unsigned int hex_digits = 0;
3733//          bool upper_case = false;
3734//
3735//          if (ap_float.convertToHexString(s, hex_digits, upper_case, APFloat::rmNearestTiesToEven) > 0)
3736//          {
3737//              if (i > 0)
3738//                  float_str.append(", ");
3739//              float_str.append(s);
3740//              if (i == 1 && is_complex)
3741//                  float_str.append(1, 'i');
3742//          }
3743//      }
3744//      return !float_str.empty();
3745//  }
3746//  return false;
3747//}
3748
3749size_t
3750ClangASTContext::ConvertStringToFloatValue (ASTContext *ast_context, clang_type_t clang_type, const char *s, uint8_t *dst, size_t dst_size)
3751{
3752    if (clang_type)
3753    {
3754        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
3755        uint32_t count = 0;
3756        bool is_complex = false;
3757        if (ClangASTContext::IsFloatingPointType (clang_type, count, is_complex))
3758        {
3759            // TODO: handle complex and vector types
3760            if (count != 1)
3761                return false;
3762
3763            StringRef s_sref(s);
3764            APFloat ap_float(ast_context->getFloatTypeSemantics(qual_type), s_sref);
3765
3766            const uint64_t bit_size = ast_context->getTypeSize (qual_type);
3767            const uint64_t byte_size = bit_size / 8;
3768            if (dst_size >= byte_size)
3769            {
3770                if (bit_size == sizeof(float)*8)
3771                {
3772                    float float32 = ap_float.convertToFloat();
3773                    ::memcpy (dst, &float32, byte_size);
3774                    return byte_size;
3775                }
3776                else if (bit_size >= 64)
3777                {
3778                    llvm::APInt ap_int(ap_float.bitcastToAPInt());
3779                    ::memcpy (dst, ap_int.getRawData(), byte_size);
3780                    return byte_size;
3781                }
3782            }
3783        }
3784    }
3785    return 0;
3786}
3787
3788unsigned
3789ClangASTContext::GetTypeQualifiers(clang_type_t clang_type)
3790{
3791    assert (clang_type);
3792
3793    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
3794
3795    return qual_type.getQualifiers().getCVRQualifiers();
3796}
3797