ClangASTContext.cpp revision bef1583b89e73de77c8b0897fcf42b5b1fcabe4c
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/RecordLayout.h"
22#include "clang/AST/Type.h"
23#include "clang/Basic/Builtins.h"
24#include "clang/Basic/FileManager.h"
25#include "clang/Basic/SourceManager.h"
26#include "clang/Basic/TargetInfo.h"
27#include "clang/Basic/TargetOptions.h"
28#include "clang/Frontend/FrontendOptions.h"
29#include "clang/Frontend/LangStandard.h"
30#undef NDEBUG
31
32#include "lldb/Core/dwarf.h"
33
34#include <stdio.h>
35
36using namespace lldb_private;
37using namespace llvm;
38using namespace clang;
39
40static void
41ParseLangArgs
42(
43    LangOptions &Opts,
44    InputKind IK
45)
46{
47    // FIXME: Cleanup per-file based stuff.
48
49    // Set some properties which depend soley on the input kind; it would be nice
50    // to move these to the language standard, and have the driver resolve the
51    // input kind + language standard.
52    if (IK == IK_Asm) {
53        Opts.AsmPreprocessor = 1;
54    } else if (IK == IK_ObjC ||
55               IK == IK_ObjCXX ||
56               IK == IK_PreprocessedObjC ||
57               IK == IK_PreprocessedObjCXX) {
58        Opts.ObjC1 = Opts.ObjC2 = 1;
59    }
60
61    LangStandard::Kind LangStd = LangStandard::lang_unspecified;
62
63    if (LangStd == LangStandard::lang_unspecified) {
64        // Based on the base language, pick one.
65        switch (IK) {
66            case IK_None:
67            case IK_AST:
68                assert(0 && "Invalid input kind!");
69            case IK_OpenCL:
70                LangStd = LangStandard::lang_opencl;
71                break;
72            case IK_Asm:
73            case IK_C:
74            case IK_PreprocessedC:
75            case IK_ObjC:
76            case IK_PreprocessedObjC:
77                LangStd = LangStandard::lang_gnu99;
78                break;
79            case IK_CXX:
80            case IK_PreprocessedCXX:
81            case IK_ObjCXX:
82            case IK_PreprocessedObjCXX:
83                LangStd = LangStandard::lang_gnucxx98;
84                break;
85        }
86    }
87
88    const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd);
89    Opts.BCPLComment = Std.hasBCPLComments();
90    Opts.C99 = Std.isC99();
91    Opts.CPlusPlus = Std.isCPlusPlus();
92    Opts.CPlusPlus0x = Std.isCPlusPlus0x();
93    Opts.Digraphs = Std.hasDigraphs();
94    Opts.GNUMode = Std.isGNUMode();
95    Opts.GNUInline = !Std.isC99();
96    Opts.HexFloats = Std.hasHexFloats();
97    Opts.ImplicitInt = Std.hasImplicitInt();
98
99    // OpenCL has some additional defaults.
100    if (LangStd == LangStandard::lang_opencl) {
101        Opts.OpenCL = 1;
102        Opts.AltiVec = 1;
103        Opts.CXXOperatorNames = 1;
104        Opts.LaxVectorConversions = 1;
105    }
106
107    // OpenCL and C++ both have bool, true, false keywords.
108    Opts.Bool = Opts.OpenCL || Opts.CPlusPlus;
109
110//    if (Opts.CPlusPlus)
111//        Opts.CXXOperatorNames = !Args.hasArg(OPT_fno_operator_names);
112//
113//    if (Args.hasArg(OPT_fobjc_gc_only))
114//        Opts.setGCMode(LangOptions::GCOnly);
115//    else if (Args.hasArg(OPT_fobjc_gc))
116//        Opts.setGCMode(LangOptions::HybridGC);
117//
118//    if (Args.hasArg(OPT_print_ivar_layout))
119//        Opts.ObjCGCBitmapPrint = 1;
120//
121//    if (Args.hasArg(OPT_faltivec))
122//        Opts.AltiVec = 1;
123//
124//    if (Args.hasArg(OPT_pthread))
125//        Opts.POSIXThreads = 1;
126//
127//    llvm::StringRef Vis = getLastArgValue(Args, OPT_fvisibility,
128//                                          "default");
129//    if (Vis == "default")
130        Opts.setVisibilityMode(LangOptions::Default);
131//    else if (Vis == "hidden")
132//        Opts.setVisibilityMode(LangOptions::Hidden);
133//    else if (Vis == "protected")
134//        Opts.setVisibilityMode(LangOptions::Protected);
135//    else
136//        Diags.Report(diag::err_drv_invalid_value)
137//        << Args.getLastArg(OPT_fvisibility)->getAsString(Args) << Vis;
138
139//    Opts.OverflowChecking = Args.hasArg(OPT_ftrapv);
140
141    // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs
142    // is specified, or -std is set to a conforming mode.
143    Opts.Trigraphs = !Opts.GNUMode;
144//    if (Args.hasArg(OPT_trigraphs))
145//        Opts.Trigraphs = 1;
146//
147//    Opts.DollarIdents = Args.hasFlag(OPT_fdollars_in_identifiers,
148//                                     OPT_fno_dollars_in_identifiers,
149//                                     !Opts.AsmPreprocessor);
150//    Opts.PascalStrings = Args.hasArg(OPT_fpascal_strings);
151//    Opts.Microsoft = Args.hasArg(OPT_fms_extensions);
152//    Opts.WritableStrings = Args.hasArg(OPT_fwritable_strings);
153//    if (Args.hasArg(OPT_fno_lax_vector_conversions))
154//        Opts.LaxVectorConversions = 0;
155//    Opts.Exceptions = Args.hasArg(OPT_fexceptions);
156//    Opts.RTTI = !Args.hasArg(OPT_fno_rtti);
157//    Opts.Blocks = Args.hasArg(OPT_fblocks);
158//    Opts.CharIsSigned = !Args.hasArg(OPT_fno_signed_char);
159//    Opts.ShortWChar = Args.hasArg(OPT_fshort_wchar);
160//    Opts.Freestanding = Args.hasArg(OPT_ffreestanding);
161//    Opts.NoBuiltin = Args.hasArg(OPT_fno_builtin) || Opts.Freestanding;
162//    Opts.AssumeSaneOperatorNew = !Args.hasArg(OPT_fno_assume_sane_operator_new);
163//    Opts.HeinousExtensions = Args.hasArg(OPT_fheinous_gnu_extensions);
164//    Opts.AccessControl = Args.hasArg(OPT_faccess_control);
165//    Opts.ElideConstructors = !Args.hasArg(OPT_fno_elide_constructors);
166//    Opts.MathErrno = !Args.hasArg(OPT_fno_math_errno);
167//    Opts.InstantiationDepth = getLastArgIntValue(Args, OPT_ftemplate_depth, 99,
168//                                                 Diags);
169//    Opts.NeXTRuntime = !Args.hasArg(OPT_fgnu_runtime);
170//    Opts.ObjCConstantStringClass = getLastArgValue(Args,
171//                                                   OPT_fconstant_string_class);
172//    Opts.ObjCNonFragileABI = Args.hasArg(OPT_fobjc_nonfragile_abi);
173//    Opts.CatchUndefined = Args.hasArg(OPT_fcatch_undefined_behavior);
174//    Opts.EmitAllDecls = Args.hasArg(OPT_femit_all_decls);
175//    Opts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags);
176//    Opts.Static = Args.hasArg(OPT_static_define);
177    Opts.OptimizeSize = 0;
178
179    // FIXME: Eliminate this dependency.
180//    unsigned Opt =
181//    Args.hasArg(OPT_Os) ? 2 : getLastArgIntValue(Args, OPT_O, 0, Diags);
182//    Opts.Optimize = Opt != 0;
183    unsigned Opt = 0;
184
185    // This is the __NO_INLINE__ define, which just depends on things like the
186    // optimization level and -fno-inline, not actually whether the backend has
187    // inlining enabled.
188    //
189    // FIXME: This is affected by other options (-fno-inline).
190    Opts.NoInline = !Opt;
191
192//    unsigned SSP = getLastArgIntValue(Args, OPT_stack_protector, 0, Diags);
193//    switch (SSP) {
194//        default:
195//            Diags.Report(diag::err_drv_invalid_value)
196//            << Args.getLastArg(OPT_stack_protector)->getAsString(Args) << SSP;
197//            break;
198//        case 0: Opts.setStackProtectorMode(LangOptions::SSPOff); break;
199//        case 1: Opts.setStackProtectorMode(LangOptions::SSPOn);  break;
200//        case 2: Opts.setStackProtectorMode(LangOptions::SSPReq); break;
201//    }
202}
203
204
205ClangASTContext::ClangASTContext(const char *target_triple) :
206    m_target_triple(),
207    m_ast_context_ap(),
208    m_language_options_ap(),
209    m_source_manager_ap(),
210    m_diagnostic_ap(),
211    m_target_options_ap(),
212    m_target_info_ap(),
213    m_identifier_table_ap(),
214    m_selector_table_ap(),
215    m_builtins_ap()
216{
217    if (target_triple && target_triple[0])
218        m_target_triple.assign (target_triple);
219}
220
221//----------------------------------------------------------------------
222// Destructor
223//----------------------------------------------------------------------
224ClangASTContext::~ClangASTContext()
225{
226    m_builtins_ap.reset();
227    m_selector_table_ap.reset();
228    m_identifier_table_ap.reset();
229    m_target_info_ap.reset();
230    m_target_options_ap.reset();
231    m_diagnostic_ap.reset();
232    m_source_manager_ap.reset();
233    m_language_options_ap.reset();
234    m_ast_context_ap.reset();
235}
236
237
238void
239ClangASTContext::Clear()
240{
241    m_ast_context_ap.reset();
242    m_language_options_ap.reset();
243    m_source_manager_ap.reset();
244    m_diagnostic_ap.reset();
245    m_target_options_ap.reset();
246    m_target_info_ap.reset();
247    m_identifier_table_ap.reset();
248    m_selector_table_ap.reset();
249    m_builtins_ap.reset();
250}
251
252const char *
253ClangASTContext::GetTargetTriple ()
254{
255    return m_target_triple.c_str();
256}
257
258void
259ClangASTContext::SetTargetTriple (const char *target_triple)
260{
261    Clear();
262    m_target_triple.assign(target_triple);
263}
264
265
266ASTContext *
267ClangASTContext::getASTContext()
268{
269    if (m_ast_context_ap.get() == NULL)
270    {
271        m_ast_context_ap.reset(
272            new ASTContext(
273                *getLanguageOptions(),
274                *getSourceManager(),
275                *getTargetInfo(),
276                *getIdentifierTable(),
277                *getSelectorTable(),
278                *getBuiltinContext()));
279    }
280    return m_ast_context_ap.get();
281}
282
283Builtin::Context *
284ClangASTContext::getBuiltinContext()
285{
286    if (m_builtins_ap.get() == NULL)
287        m_builtins_ap.reset (new Builtin::Context(*getTargetInfo()));
288    return m_builtins_ap.get();
289}
290
291IdentifierTable *
292ClangASTContext::getIdentifierTable()
293{
294    if (m_identifier_table_ap.get() == NULL)
295        m_identifier_table_ap.reset(new IdentifierTable (*ClangASTContext::getLanguageOptions(), NULL));
296    return m_identifier_table_ap.get();
297}
298
299LangOptions *
300ClangASTContext::getLanguageOptions()
301{
302    if (m_language_options_ap.get() == NULL)
303    {
304        m_language_options_ap.reset(new LangOptions());
305        ParseLangArgs(*m_language_options_ap, IK_ObjCXX);
306//        InitializeLangOptions(*m_language_options_ap, IK_ObjCXX);
307    }
308    return m_language_options_ap.get();
309}
310
311SelectorTable *
312ClangASTContext::getSelectorTable()
313{
314    if (m_selector_table_ap.get() == NULL)
315        m_selector_table_ap.reset (new SelectorTable());
316    return m_selector_table_ap.get();
317}
318
319SourceManager *
320ClangASTContext::getSourceManager()
321{
322    if (m_source_manager_ap.get() == NULL)
323        m_source_manager_ap.reset(new SourceManager(*getDiagnostic()));
324    return m_source_manager_ap.get();
325}
326
327Diagnostic *
328ClangASTContext::getDiagnostic()
329{
330    if (m_diagnostic_ap.get() == NULL)
331        m_diagnostic_ap.reset(new Diagnostic());
332    return m_diagnostic_ap.get();
333}
334
335TargetOptions *
336ClangASTContext::getTargetOptions()
337{
338    if (m_target_options_ap.get() == NULL && !m_target_triple.empty())
339    {
340        m_target_options_ap.reset (new TargetOptions());
341        if (m_target_options_ap.get())
342            m_target_options_ap->Triple = m_target_triple;
343    }
344    return m_target_options_ap.get();
345}
346
347
348TargetInfo *
349ClangASTContext::getTargetInfo()
350{
351    // target_triple should be something like "x86_64-apple-darwin10"
352    if (m_target_info_ap.get() == NULL && !m_target_triple.empty())
353        m_target_info_ap.reset (TargetInfo::CreateTargetInfo(*getDiagnostic(), *getTargetOptions()));
354    return m_target_info_ap.get();
355}
356
357#pragma mark Basic Types
358
359static inline bool
360QualTypeMatchesBitSize(const uint64_t bit_size, ASTContext *ast_context, QualType qual_type)
361{
362    uint64_t qual_type_bit_size = ast_context->getTypeSize(qual_type);
363    if (qual_type_bit_size == bit_size)
364        return true;
365    return false;
366}
367
368void *
369ClangASTContext::GetBuiltinTypeForEncodingAndBitSize (lldb::Encoding encoding, uint32_t bit_size)
370{
371    ASTContext *ast_context = getASTContext();
372
373    assert (ast_context != NULL);
374
375    return GetBuiltinTypeForEncodingAndBitSize (ast_context, encoding, bit_size);
376}
377
378void *
379ClangASTContext::GetBuiltinTypeForEncodingAndBitSize (clang::ASTContext *ast_context, lldb::Encoding encoding, uint32_t bit_size)
380{
381    if (!ast_context)
382        return NULL;
383
384    switch (encoding)
385    {
386    case lldb::eEncodingInvalid:
387        if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->VoidPtrTy))
388            return ast_context->VoidPtrTy.getAsOpaquePtr();
389        break;
390
391    case lldb::eEncodingUint:
392        if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedCharTy))
393            return ast_context->UnsignedCharTy.getAsOpaquePtr();
394        if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedShortTy))
395            return ast_context->UnsignedShortTy.getAsOpaquePtr();
396        if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedIntTy))
397            return ast_context->UnsignedIntTy.getAsOpaquePtr();
398        if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedLongTy))
399            return ast_context->UnsignedLongTy.getAsOpaquePtr();
400        if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedLongLongTy))
401            return ast_context->UnsignedLongLongTy.getAsOpaquePtr();
402        if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedInt128Ty))
403            return ast_context->UnsignedInt128Ty.getAsOpaquePtr();
404        break;
405
406    case lldb::eEncodingSint:
407        if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->CharTy))
408            return ast_context->CharTy.getAsOpaquePtr();
409        if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->ShortTy))
410            return ast_context->ShortTy.getAsOpaquePtr();
411        if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->IntTy))
412            return ast_context->IntTy.getAsOpaquePtr();
413        if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->LongTy))
414            return ast_context->LongTy.getAsOpaquePtr();
415        if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->LongLongTy))
416            return ast_context->LongLongTy.getAsOpaquePtr();
417        if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->Int128Ty))
418            return ast_context->Int128Ty.getAsOpaquePtr();
419        break;
420
421    case lldb::eEncodingIEEE754:
422        if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->FloatTy))
423            return ast_context->FloatTy.getAsOpaquePtr();
424        if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->DoubleTy))
425            return ast_context->DoubleTy.getAsOpaquePtr();
426        if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->LongDoubleTy))
427            return ast_context->LongDoubleTy.getAsOpaquePtr();
428        break;
429
430    case lldb::eEncodingVector:
431    default:
432        break;
433    }
434
435    return NULL;
436}
437
438void *
439ClangASTContext::GetBuiltinTypeForDWARFEncodingAndBitSize (const char *type_name, uint32_t dw_ate, uint32_t bit_size)
440{
441    ASTContext *ast_context = getASTContext();
442
443    #define streq(a,b) strcmp(a,b) == 0
444    assert (ast_context != NULL);
445    if (ast_context)
446    {
447        switch (dw_ate)
448        {
449        default:
450            break;
451
452        case DW_ATE_address:
453            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->VoidPtrTy))
454                return ast_context->VoidPtrTy.getAsOpaquePtr();
455            break;
456
457        case DW_ATE_boolean:
458            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->BoolTy))
459                return ast_context->BoolTy.getAsOpaquePtr();
460            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedCharTy))
461                return ast_context->UnsignedCharTy.getAsOpaquePtr();
462            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedShortTy))
463                return ast_context->UnsignedShortTy.getAsOpaquePtr();
464            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedIntTy))
465                return ast_context->UnsignedIntTy.getAsOpaquePtr();
466            break;
467
468        case DW_ATE_complex_float:
469            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->FloatComplexTy))
470                return ast_context->FloatComplexTy.getAsOpaquePtr();
471            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->DoubleComplexTy))
472                return ast_context->DoubleComplexTy.getAsOpaquePtr();
473            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->LongDoubleComplexTy))
474                return ast_context->LongDoubleComplexTy.getAsOpaquePtr();
475            break;
476
477        case DW_ATE_float:
478            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->FloatTy))
479                return ast_context->FloatTy.getAsOpaquePtr();
480            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->DoubleTy))
481                return ast_context->DoubleTy.getAsOpaquePtr();
482            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->LongDoubleTy))
483                return ast_context->LongDoubleTy.getAsOpaquePtr();
484            break;
485
486        case DW_ATE_signed:
487            if (type_name)
488            {
489                if (streq(type_name, "int") ||
490                    streq(type_name, "signed int"))
491                {
492                    if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->IntTy))
493                        return ast_context->IntTy.getAsOpaquePtr();
494                    if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->Int128Ty))
495                        return ast_context->Int128Ty.getAsOpaquePtr();
496                }
497
498                if (streq(type_name, "long int") ||
499                    streq(type_name, "long long int") ||
500                    streq(type_name, "signed long long"))
501                {
502                    if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->LongTy))
503                        return ast_context->LongTy.getAsOpaquePtr();
504                    if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->LongLongTy))
505                        return ast_context->LongLongTy.getAsOpaquePtr();
506                }
507
508                if (streq(type_name, "short") ||
509                    streq(type_name, "short int") ||
510                    streq(type_name, "signed short") ||
511                    streq(type_name, "short signed int"))
512                {
513                    if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->ShortTy))
514                        return ast_context->ShortTy.getAsOpaquePtr();
515                }
516
517                if (streq(type_name, "char") ||
518                    streq(type_name, "signed char"))
519                {
520                    if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->CharTy))
521                        return ast_context->CharTy.getAsOpaquePtr();
522                    if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->SignedCharTy))
523                        return ast_context->SignedCharTy.getAsOpaquePtr();
524                }
525
526                if (streq(type_name, "wchar_t"))
527                {
528                    if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->WCharTy))
529                        return ast_context->WCharTy.getAsOpaquePtr();
530                }
531
532            }
533            // We weren't able to match up a type name, just search by size
534            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->CharTy))
535                return ast_context->CharTy.getAsOpaquePtr();
536            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->ShortTy))
537                return ast_context->ShortTy.getAsOpaquePtr();
538            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->IntTy))
539                return ast_context->IntTy.getAsOpaquePtr();
540            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->LongTy))
541                return ast_context->LongTy.getAsOpaquePtr();
542            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->LongLongTy))
543                return ast_context->LongLongTy.getAsOpaquePtr();
544            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->Int128Ty))
545                return ast_context->Int128Ty.getAsOpaquePtr();
546            break;
547
548        case DW_ATE_signed_char:
549            if (type_name)
550            {
551                if (streq(type_name, "signed char"))
552                {
553                    if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->SignedCharTy))
554                        return ast_context->SignedCharTy.getAsOpaquePtr();
555                }
556            }
557            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->CharTy))
558                return ast_context->CharTy.getAsOpaquePtr();
559            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->SignedCharTy))
560                return ast_context->SignedCharTy.getAsOpaquePtr();
561            break;
562
563        case DW_ATE_unsigned:
564            if (type_name)
565            {
566                if (streq(type_name, "unsigned int"))
567                {
568                    if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedIntTy))
569                        return ast_context->UnsignedIntTy.getAsOpaquePtr();
570                    if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedInt128Ty))
571                        return ast_context->UnsignedInt128Ty.getAsOpaquePtr();
572                }
573
574                if (streq(type_name, "unsigned int") ||
575                    streq(type_name, "long unsigned int") ||
576                    streq(type_name, "unsigned long long"))
577                {
578                    if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedLongTy))
579                        return ast_context->UnsignedLongTy.getAsOpaquePtr();
580                    if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedLongLongTy))
581                        return ast_context->UnsignedLongLongTy.getAsOpaquePtr();
582                }
583
584                if (streq(type_name, "unsigned short") ||
585                    streq(type_name, "short unsigned int"))
586                {
587                    if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedShortTy))
588                        return ast_context->UnsignedShortTy.getAsOpaquePtr();
589                }
590                if (streq(type_name, "unsigned char"))
591                {
592                    if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedCharTy))
593                        return ast_context->UnsignedCharTy.getAsOpaquePtr();
594                }
595
596            }
597            // We weren't able to match up a type name, just search by size
598            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedCharTy))
599                return ast_context->UnsignedCharTy.getAsOpaquePtr();
600            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedShortTy))
601                return ast_context->UnsignedShortTy.getAsOpaquePtr();
602            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedIntTy))
603                return ast_context->UnsignedIntTy.getAsOpaquePtr();
604            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedLongTy))
605                return ast_context->UnsignedLongTy.getAsOpaquePtr();
606            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedLongLongTy))
607                return ast_context->UnsignedLongLongTy.getAsOpaquePtr();
608            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedInt128Ty))
609                return ast_context->UnsignedInt128Ty.getAsOpaquePtr();
610            break;
611
612        case DW_ATE_unsigned_char:
613            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedCharTy))
614                return ast_context->UnsignedCharTy.getAsOpaquePtr();
615            break;
616
617        case DW_ATE_imaginary_float:
618            break;
619        }
620    }
621    // This assert should fire for anything that we don't catch above so we know
622    // to fix any issues we run into.
623    assert (!"error: ClangASTContext::GetClangTypeForDWARFEncodingAndSize() contains an unhandled encoding. Fix this ASAP!");
624    return NULL;
625}
626
627void *
628ClangASTContext::GetVoidBuiltInType()
629{
630    return getASTContext()->VoidTy.getAsOpaquePtr();
631}
632
633void *
634ClangASTContext::GetCStringType (bool is_const)
635{
636    QualType char_type(getASTContext()->CharTy);
637
638    if (is_const)
639        char_type.addConst();
640
641    return getASTContext()->getPointerType(char_type).getAsOpaquePtr();
642}
643
644void *
645ClangASTContext::GetVoidPtrType (bool is_const)
646{
647    return GetVoidPtrType(getASTContext(), is_const);
648}
649
650void *
651ClangASTContext::GetVoidPtrType (clang::ASTContext *ast_context, bool is_const)
652{
653    QualType void_ptr_type(ast_context->VoidPtrTy);
654
655    if (is_const)
656        void_ptr_type.addConst();
657
658    return void_ptr_type.getAsOpaquePtr();
659}
660
661void *
662ClangASTContext::CopyType(clang::ASTContext *dest_context,
663                          clang::ASTContext *source_context,
664                          void * clang_type)
665{
666    Diagnostic diagnostics;
667    FileManager file_manager;
668    ASTImporter importer(diagnostics,
669                         *dest_context, file_manager,
670                         *source_context, file_manager);
671    QualType ret = importer.Import(QualType::getFromOpaquePtr(clang_type));
672    return ret.getAsOpaquePtr();
673}
674
675#pragma mark CVR modifiers
676
677void *
678ClangASTContext::AddConstModifier (void *clang_type)
679{
680    if (clang_type)
681    {
682        QualType result(QualType::getFromOpaquePtr(clang_type));
683        result.addConst();
684        return result.getAsOpaquePtr();
685    }
686    return NULL;
687}
688
689void *
690ClangASTContext::AddRestrictModifier (void *clang_type)
691{
692    if (clang_type)
693    {
694        QualType result(QualType::getFromOpaquePtr(clang_type));
695        result.getQualifiers().setRestrict (true);
696        return result.getAsOpaquePtr();
697    }
698    return NULL;
699}
700
701void *
702ClangASTContext::AddVolatileModifier (void *clang_type)
703{
704    if (clang_type)
705    {
706        QualType result(QualType::getFromOpaquePtr(clang_type));
707        result.getQualifiers().setVolatile (true);
708        return result.getAsOpaquePtr();
709    }
710    return NULL;
711}
712
713#pragma mark Structure, Unions, Classes
714
715void *
716ClangASTContext::CreateRecordType (const char *name, int kind, DeclContext *decl_ctx)
717{
718    ASTContext *ast_context = getASTContext();
719    assert (ast_context != NULL);
720
721    if (decl_ctx == NULL)
722        decl_ctx = ast_context->getTranslationUnitDecl();
723
724    // NOTE: Eventually CXXRecordDecl will be merged back into RecordDecl and
725    // we will need to update this code. I was told to currently always use
726    // the CXXRecordDecl class since we often don't know from debug information
727    // if something is struct or a class, so we default to always use the more
728    // complete definition just in case.
729    CXXRecordDecl *decl = CXXRecordDecl::Create(*ast_context,
730                                                (TagDecl::TagKind)kind,
731                                                decl_ctx,
732                                                SourceLocation(),
733                                                name && name[0] ? &ast_context->Idents.get(name) : NULL);
734
735    return ast_context->getTagDeclType(decl).getAsOpaquePtr();
736}
737
738bool
739ClangASTContext::AddFieldToRecordType (void * record_clang_type, const char *name, void * field_type, int access, uint32_t bitfield_bit_size)
740{
741    if (record_clang_type == NULL || field_type == NULL)
742        return false;
743
744    ASTContext *ast_context = getASTContext();
745    IdentifierTable *identifier_table = getIdentifierTable();
746
747    assert (ast_context != NULL);
748    assert (identifier_table != NULL);
749
750    QualType record_qual_type(QualType::getFromOpaquePtr(record_clang_type));
751
752    Type *clang_type = record_qual_type.getTypePtr();
753    if (clang_type)
754    {
755        const RecordType *record_type = dyn_cast<RecordType>(clang_type);
756
757        if (record_type)
758        {
759            RecordDecl *record_decl = record_type->getDecl();
760
761            CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
762            if (cxx_record_decl)
763                cxx_record_decl->setEmpty (false);
764
765            clang::Expr *bit_width = NULL;
766            if (bitfield_bit_size != 0)
767            {
768                APInt bitfield_bit_size_apint(ast_context->getTypeSize(ast_context->IntTy), bitfield_bit_size);
769                bit_width = new (*ast_context)IntegerLiteral (bitfield_bit_size_apint, ast_context->IntTy, SourceLocation());
770            }
771            FieldDecl *field = FieldDecl::Create(*ast_context,
772                                                record_decl,
773                                                SourceLocation(),
774                                                name ? &identifier_table->get(name) : NULL, // Identifier
775                                                QualType::getFromOpaquePtr(field_type), // Field type
776                                                NULL,       // DeclaratorInfo *
777                                                bit_width,  // BitWidth
778                                                false);     // Mutable
779
780            field->setAccess((AccessSpecifier)access);
781
782            if (field)
783            {
784                record_decl->addDecl(field);
785                return true;
786            }
787        }
788    }
789    return false;
790}
791
792bool
793ClangASTContext::FieldIsBitfield (FieldDecl* field, uint32_t& bitfield_bit_size)
794{
795    return FieldIsBitfield(getASTContext(), field, bitfield_bit_size);
796}
797
798bool
799ClangASTContext::FieldIsBitfield
800(
801    ASTContext *ast_context,
802    FieldDecl* field,
803    uint32_t& bitfield_bit_size
804)
805{
806    if (ast_context == NULL || field == NULL)
807        return false;
808
809    if (field->isBitField())
810    {
811        Expr* bit_width_expr = field->getBitWidth();
812        if (bit_width_expr)
813        {
814            llvm::APSInt bit_width_apsint;
815            if (bit_width_expr->isIntegerConstantExpr(bit_width_apsint, *ast_context))
816            {
817                bitfield_bit_size = bit_width_apsint.getLimitedValue(UINT32_MAX);
818                return true;
819            }
820        }
821    }
822    return false;
823}
824
825bool
826ClangASTContext::RecordHasFields (const RecordDecl *record_decl)
827{
828    if (record_decl == NULL)
829        return false;
830
831    if (!record_decl->field_empty())
832        return true;
833
834    // No fields, lets check this is a CXX record and check the base classes
835    const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
836    if (cxx_record_decl)
837    {
838        CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
839        for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
840             base_class != base_class_end;
841             ++base_class)
842        {
843            const CXXRecordDecl *base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
844            if (RecordHasFields(base_class_decl))
845                return true;
846        }
847    }
848    return false;
849}
850
851void
852ClangASTContext::SetDefaultAccessForRecordFields (void *clang_qual_type, int default_accessibility, int *assigned_accessibilities, size_t num_assigned_accessibilities)
853{
854    if (clang_qual_type)
855    {
856        QualType qual_type(QualType::getFromOpaquePtr(clang_qual_type));
857        Type *clang_type = qual_type.getTypePtr();
858        if (clang_type)
859        {
860            RecordType *record_type = dyn_cast<RecordType>(clang_type);
861            if (record_type)
862            {
863                RecordDecl *record_decl = record_type->getDecl();
864                if (record_decl)
865                {
866                    uint32_t field_idx;
867                    RecordDecl::field_iterator field, field_end;
868                    for (field = record_decl->field_begin(), field_end = record_decl->field_end(), field_idx = 0;
869                         field != field_end;
870                         ++field, ++field_idx)
871                    {
872                        // If no accessibility was assigned, assign the correct one
873                        if (field_idx < num_assigned_accessibilities && assigned_accessibilities[field_idx] == clang::AS_none)
874                            field->setAccess ((AccessSpecifier)default_accessibility);
875                    }
876                }
877            }
878        }
879    }
880}
881
882#pragma mark C++ Base Classes
883
884CXXBaseSpecifier *
885ClangASTContext::CreateBaseClassSpecifier (void *base_class_type, int access, bool is_virtual, bool base_of_class)
886{
887    if (base_class_type)
888        return new CXXBaseSpecifier(SourceRange(), is_virtual, base_of_class, (AccessSpecifier)access, QualType::getFromOpaquePtr(base_class_type));
889    return NULL;
890}
891
892void
893ClangASTContext::DeleteBaseClassSpecifiers (CXXBaseSpecifier **base_classes, unsigned num_base_classes)
894{
895    for (unsigned i=0; i<num_base_classes; ++i)
896    {
897        delete base_classes[i];
898        base_classes[i] = NULL;
899    }
900}
901
902bool
903ClangASTContext::SetBaseClassesForClassType (void *class_clang_type, CXXBaseSpecifier const * const *base_classes, unsigned num_base_classes)
904{
905    if (class_clang_type)
906    {
907        Type *clang_type = QualType::getFromOpaquePtr(class_clang_type).getTypePtr();
908        if (clang_type)
909        {
910            RecordType *record_type = dyn_cast<RecordType>(clang_type);
911            if (record_type)
912            {
913                CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_type->getDecl());
914                if (cxx_record_decl)
915                {
916                    //cxx_record_decl->setEmpty (false);
917                    cxx_record_decl->setBases(base_classes, num_base_classes);
918                    return true;
919                }
920            }
921        }
922    }
923    return false;
924}
925
926
927#pragma mark Aggregate Types
928
929bool
930ClangASTContext::IsAggregateType (void *clang_type)
931{
932    if (clang_type == NULL)
933        return false;
934
935    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
936
937    if (qual_type->isAggregateType ())
938        return true;
939
940    switch (qual_type->getTypeClass())
941    {
942    case Type::IncompleteArray:
943    case Type::VariableArray:
944    case Type::ConstantArray:
945    case Type::ExtVector:
946    case Type::Vector:
947    case Type::Record:
948        return true;
949
950    case Type::Typedef:
951        return ClangASTContext::IsAggregateType (cast<TypedefType>(qual_type)->LookThroughTypedefs().getAsOpaquePtr());
952
953    default:
954        break;
955    }
956    // The clang type does have a value
957    return false;
958}
959
960uint32_t
961ClangASTContext::GetNumChildren (void *clang_qual_type, bool omit_empty_base_classes)
962{
963    if (clang_qual_type == NULL)
964        return 0;
965
966    uint32_t num_children = 0;
967    QualType qual_type(QualType::getFromOpaquePtr(clang_qual_type));
968    switch (qual_type->getTypeClass())
969    {
970    case Type::Record:
971        {
972            const RecordType *record_type = cast<RecordType>(qual_type.getTypePtr());
973            const RecordDecl *record_decl = record_type->getDecl();
974            assert(record_decl);
975            const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
976            if (cxx_record_decl)
977            {
978                if (omit_empty_base_classes)
979                {
980                    // Check each base classes to see if it or any of its
981                    // base classes contain any fields. This can help
982                    // limit the noise in variable views by not having to
983                    // show base classes that contain no members.
984                    CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
985                    for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
986                         base_class != base_class_end;
987                         ++base_class)
988                    {
989                        const CXXRecordDecl *base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
990
991                        // Skip empty base classes
992                        if (RecordHasFields(base_class_decl) == false)
993                            continue;
994
995                        num_children++;
996                    }
997                }
998                else
999                {
1000                    // Include all base classes
1001                    num_children += cxx_record_decl->getNumBases();
1002                }
1003
1004            }
1005            RecordDecl::field_iterator field, field_end;
1006            for (field = record_decl->field_begin(), field_end = record_decl->field_end(); field != field_end; ++field)
1007                ++num_children;
1008        }
1009        break;
1010
1011    case Type::ConstantArray:
1012        num_children = cast<ConstantArrayType>(qual_type.getTypePtr())->getSize().getLimitedValue();
1013        break;
1014
1015    case Type::Pointer:
1016        {
1017            PointerType *pointer_type = cast<PointerType>(qual_type.getTypePtr());
1018            QualType pointee_type = pointer_type->getPointeeType();
1019            uint32_t num_pointee_children = ClangASTContext::GetNumChildren (pointee_type.getAsOpaquePtr(), omit_empty_base_classes);
1020            // If this type points to a simple type, then it has 1 child
1021            if (num_pointee_children == 0)
1022                num_children = 1;
1023            else
1024                num_children = num_pointee_children;
1025        }
1026        break;
1027
1028    case Type::Typedef:
1029        num_children = ClangASTContext::GetNumChildren (cast<TypedefType>(qual_type)->LookThroughTypedefs().getAsOpaquePtr(), omit_empty_base_classes);
1030        break;
1031
1032    default:
1033        break;
1034    }
1035    return num_children;
1036}
1037
1038
1039void *
1040ClangASTContext::GetChildClangTypeAtIndex
1041(
1042    const char *parent_name,
1043    void *parent_clang_type,
1044    uint32_t idx,
1045    bool transparent_pointers,
1046    bool omit_empty_base_classes,
1047    std::string& child_name,
1048    uint32_t &child_byte_size,
1049    int32_t &child_byte_offset,
1050    uint32_t &child_bitfield_bit_size,
1051    uint32_t &child_bitfield_bit_offset
1052)
1053{
1054    if (parent_clang_type)
1055
1056        return GetChildClangTypeAtIndex (getASTContext(),
1057                                         parent_name,
1058                                         parent_clang_type,
1059                                         idx,
1060                                         transparent_pointers,
1061                                         omit_empty_base_classes,
1062                                         child_name,
1063                                         child_byte_size,
1064                                         child_byte_offset,
1065                                         child_bitfield_bit_size,
1066                                         child_bitfield_bit_offset);
1067    return NULL;
1068}
1069
1070void *
1071ClangASTContext::GetChildClangTypeAtIndex
1072(
1073    ASTContext *ast_context,
1074    const char *parent_name,
1075    void *parent_clang_type,
1076    uint32_t idx,
1077    bool transparent_pointers,
1078    bool omit_empty_base_classes,
1079    std::string& child_name,
1080    uint32_t &child_byte_size,
1081    int32_t &child_byte_offset,
1082    uint32_t &child_bitfield_bit_size,
1083    uint32_t &child_bitfield_bit_offset
1084)
1085{
1086    if (parent_clang_type == NULL)
1087        return NULL;
1088
1089    if (idx < ClangASTContext::GetNumChildren (parent_clang_type, omit_empty_base_classes))
1090    {
1091        uint32_t bit_offset;
1092        child_bitfield_bit_size = 0;
1093        child_bitfield_bit_offset = 0;
1094        QualType parent_qual_type(QualType::getFromOpaquePtr(parent_clang_type));
1095        switch (parent_qual_type->getTypeClass())
1096        {
1097        case Type::Record:
1098            {
1099                const RecordType *record_type = cast<RecordType>(parent_qual_type.getTypePtr());
1100                const RecordDecl *record_decl = record_type->getDecl();
1101                assert(record_decl);
1102                const ASTRecordLayout &record_layout = ast_context->getASTRecordLayout(record_decl);
1103                uint32_t child_idx = 0;
1104
1105                const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
1106                if (cxx_record_decl)
1107                {
1108                    // We might have base classes to print out first
1109                    CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
1110                    for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
1111                         base_class != base_class_end;
1112                         ++base_class)
1113                    {
1114                        const CXXRecordDecl *base_class_decl = NULL;
1115
1116                        // Skip empty base classes
1117                        if (omit_empty_base_classes)
1118                        {
1119                            base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
1120                            if (RecordHasFields(base_class_decl) == false)
1121                                continue;
1122                        }
1123
1124                        if (idx == child_idx)
1125                        {
1126                            if (base_class_decl == NULL)
1127                                base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
1128
1129
1130                            if (base_class->isVirtual())
1131                                bit_offset = record_layout.getVBaseClassOffset(base_class_decl);
1132                            else
1133                                bit_offset = record_layout.getBaseClassOffset(base_class_decl);
1134
1135                            // Base classes should be a multiple of 8 bits in size
1136                            assert (bit_offset % 8 == 0);
1137                            child_byte_offset = bit_offset/8;
1138                            std::string base_class_type_name(base_class->getType().getAsString());
1139
1140                            child_name.assign(base_class_type_name.c_str());
1141
1142                            uint64_t clang_type_info_bit_size = ast_context->getTypeSize(base_class->getType());
1143
1144                            // Base classes biut sizes should be a multiple of 8 bits in size
1145                            assert (clang_type_info_bit_size % 8 == 0);
1146                            child_byte_size = clang_type_info_bit_size / 8;
1147                            return base_class->getType().getAsOpaquePtr();
1148                        }
1149                        // We don't increment the child index in the for loop since we might
1150                        // be skipping empty base classes
1151                        ++child_idx;
1152                    }
1153                }
1154                // Make sure index is in range...
1155                uint32_t field_idx = 0;
1156                RecordDecl::field_iterator field, field_end;
1157                for (field = record_decl->field_begin(), field_end = record_decl->field_end(); field != field_end; ++field, ++field_idx, ++child_idx)
1158                {
1159                    if (idx == child_idx)
1160                    {
1161                        // Print the member type if requested
1162                        // Print the member name and equal sign
1163                        child_name.assign(field->getNameAsString().c_str());
1164
1165                        // Figure out the type byte size (field_type_info.first) and
1166                        // alignment (field_type_info.second) from the AST context.
1167                        std::pair<uint64_t, unsigned> field_type_info = ast_context->getTypeInfo(field->getType());
1168                        assert(field_idx < record_layout.getFieldCount());
1169
1170                        child_byte_size = field_type_info.first / 8;
1171
1172                        // Figure out the field offset within the current struct/union/class type
1173                        bit_offset = record_layout.getFieldOffset (field_idx);
1174                        child_byte_offset = bit_offset / 8;
1175                        if (ClangASTContext::FieldIsBitfield (ast_context, *field, child_bitfield_bit_size))
1176                            child_bitfield_bit_offset = bit_offset % 8;
1177
1178                        return field->getType().getAsOpaquePtr();
1179                    }
1180                }
1181            }
1182            break;
1183
1184        case Type::ConstantArray:
1185            {
1186                const ConstantArrayType *array = cast<ConstantArrayType>(parent_qual_type.getTypePtr());
1187                const uint64_t element_count = array->getSize().getLimitedValue();
1188
1189                if (idx < element_count)
1190                {
1191                    std::pair<uint64_t, unsigned> field_type_info = ast_context->getTypeInfo(array->getElementType());
1192
1193                    char element_name[32];
1194                    ::snprintf (element_name, sizeof (element_name), "%s[%u]", parent_name ? parent_name : "", idx);
1195
1196                    child_name.assign(element_name);
1197                    assert(field_type_info.first % 8 == 0);
1198                    child_byte_size = field_type_info.first / 8;
1199                    child_byte_offset = idx * child_byte_size;
1200                    return array->getElementType().getAsOpaquePtr();
1201                }
1202            }
1203            break;
1204
1205        case Type::Pointer:
1206            {
1207                PointerType *pointer_type = cast<PointerType>(parent_qual_type.getTypePtr());
1208                QualType pointee_type = pointer_type->getPointeeType();
1209
1210                if (transparent_pointers && ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
1211                {
1212                    return GetChildClangTypeAtIndex (ast_context,
1213                                                     parent_name,
1214                                                     pointer_type->getPointeeType().getAsOpaquePtr(),
1215                                                     idx,
1216                                                     transparent_pointers,
1217                                                     omit_empty_base_classes,
1218                                                     child_name,
1219                                                     child_byte_size,
1220                                                     child_byte_offset,
1221                                                     child_bitfield_bit_size,
1222                                                     child_bitfield_bit_offset);
1223                }
1224                else
1225                {
1226                    if (parent_name)
1227                    {
1228                        child_name.assign(1, '*');
1229                        child_name += parent_name;
1230                    }
1231
1232                    // We have a pointer to an simple type
1233                    if (idx == 0)
1234                    {
1235                        std::pair<uint64_t, unsigned> clang_type_info = ast_context->getTypeInfo(pointee_type);
1236                        assert(clang_type_info.first % 8 == 0);
1237                        child_byte_size = clang_type_info.first / 8;
1238                        child_byte_offset = 0;
1239                        return pointee_type.getAsOpaquePtr();
1240                    }
1241                }
1242            }
1243            break;
1244
1245        case Type::Typedef:
1246            return GetChildClangTypeAtIndex (ast_context,
1247                                             parent_name,
1248                                             cast<TypedefType>(parent_qual_type)->LookThroughTypedefs().getAsOpaquePtr(),
1249                                             idx,
1250                                             transparent_pointers,
1251                                             omit_empty_base_classes,
1252                                             child_name,
1253                                             child_byte_size,
1254                                             child_byte_offset,
1255                                             child_bitfield_bit_size,
1256                                             child_bitfield_bit_offset);
1257            break;
1258
1259        default:
1260            break;
1261        }
1262    }
1263    return false;
1264}
1265
1266static inline bool
1267BaseSpecifierIsEmpty (const CXXBaseSpecifier *b)
1268{
1269    return ClangASTContext::RecordHasFields(cast<CXXRecordDecl>(b->getType()->getAs<RecordType>()->getDecl())) == false;
1270}
1271
1272static uint32_t
1273GetNumBaseClasses (const CXXRecordDecl *cxx_record_decl, bool omit_empty_base_classes)
1274{
1275    uint32_t num_bases = 0;
1276    if (cxx_record_decl)
1277    {
1278        if (omit_empty_base_classes)
1279        {
1280            CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
1281            for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
1282                 base_class != base_class_end;
1283                 ++base_class)
1284            {
1285                // Skip empty base classes
1286                if (omit_empty_base_classes)
1287                {
1288                    if (BaseSpecifierIsEmpty (base_class))
1289                        continue;
1290                }
1291                ++num_bases;
1292            }
1293        }
1294        else
1295            num_bases = cxx_record_decl->getNumBases();
1296    }
1297    return num_bases;
1298}
1299
1300
1301static uint32_t
1302GetIndexForRecordBase
1303(
1304    const RecordDecl *record_decl,
1305    const CXXBaseSpecifier *base_spec,
1306    bool omit_empty_base_classes
1307)
1308{
1309    uint32_t child_idx = 0;
1310
1311    const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
1312
1313//    const char *super_name = record_decl->getNameAsCString();
1314//    const char *base_name = base_spec->getType()->getAs<RecordType>()->getDecl()->getNameAsCString();
1315//    printf ("GetIndexForRecordChild (%s, %s)\n", super_name, base_name);
1316//
1317    if (cxx_record_decl)
1318    {
1319        CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
1320        for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
1321             base_class != base_class_end;
1322             ++base_class)
1323        {
1324            if (omit_empty_base_classes)
1325            {
1326                if (BaseSpecifierIsEmpty (base_class))
1327                    continue;
1328            }
1329
1330//            printf ("GetIndexForRecordChild (%s, %s) base[%u] = %s\n", super_name, base_name,
1331//                    child_idx,
1332//                    base_class->getType()->getAs<RecordType>()->getDecl()->getNameAsCString());
1333//
1334//
1335            if (base_class == base_spec)
1336                return child_idx;
1337            ++child_idx;
1338        }
1339    }
1340
1341    return UINT32_MAX;
1342}
1343
1344
1345static uint32_t
1346GetIndexForRecordChild
1347(
1348    const RecordDecl *record_decl,
1349    NamedDecl *canonical_decl,
1350    bool omit_empty_base_classes
1351)
1352{
1353    uint32_t child_idx = GetNumBaseClasses (dyn_cast<CXXRecordDecl>(record_decl), omit_empty_base_classes);
1354
1355//    const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
1356//
1357////    printf ("GetIndexForRecordChild (%s, %s)\n", record_decl->getNameAsCString(), canonical_decl->getNameAsCString());
1358//    if (cxx_record_decl)
1359//    {
1360//        CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
1361//        for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
1362//             base_class != base_class_end;
1363//             ++base_class)
1364//        {
1365//            if (omit_empty_base_classes)
1366//            {
1367//                if (BaseSpecifierIsEmpty (base_class))
1368//                    continue;
1369//            }
1370//
1371////            printf ("GetIndexForRecordChild (%s, %s) base[%u] = %s\n",
1372////                    record_decl->getNameAsCString(),
1373////                    canonical_decl->getNameAsCString(),
1374////                    child_idx,
1375////                    base_class->getType()->getAs<RecordType>()->getDecl()->getNameAsCString());
1376//
1377//
1378//            CXXRecordDecl *curr_base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
1379//            if (curr_base_class_decl == canonical_decl)
1380//            {
1381//                return child_idx;
1382//            }
1383//            ++child_idx;
1384//        }
1385//    }
1386//
1387//    const uint32_t num_bases = child_idx;
1388    RecordDecl::field_iterator field, field_end;
1389    for (field = record_decl->field_begin(), field_end = record_decl->field_end();
1390         field != field_end;
1391         ++field, ++child_idx)
1392    {
1393//            printf ("GetIndexForRecordChild (%s, %s) field[%u] = %s\n",
1394//                    record_decl->getNameAsCString(),
1395//                    canonical_decl->getNameAsCString(),
1396//                    child_idx - num_bases,
1397//                    field->getNameAsCString());
1398
1399        if (field->getCanonicalDecl() == canonical_decl)
1400            return child_idx;
1401    }
1402
1403    return UINT32_MAX;
1404}
1405
1406// Look for a child member (doesn't include base classes, but it does include
1407// their members) in the type hierarchy. Returns an index path into "clang_type"
1408// on how to reach the appropriate member.
1409//
1410//    class A
1411//    {
1412//    public:
1413//        int m_a;
1414//        int m_b;
1415//    };
1416//
1417//    class B
1418//    {
1419//    };
1420//
1421//    class C :
1422//        public B,
1423//        public A
1424//    {
1425//    };
1426//
1427// If we have a clang type that describes "class C", and we wanted to looked
1428// "m_b" in it:
1429//
1430// With omit_empty_base_classes == false we would get an integer array back with:
1431// { 1,  1 }
1432// The first index 1 is the child index for "class A" within class C
1433// The second index 1 is the child index for "m_b" within class A
1434//
1435// With omit_empty_base_classes == true we would get an integer array back with:
1436// { 0,  1 }
1437// 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)
1438// The second index 1 is the child index for "m_b" within class A
1439
1440size_t
1441ClangASTContext::GetIndexOfChildMemberWithName
1442(
1443    ASTContext *ast_context,
1444    void *clang_type,
1445    const char *name,
1446    bool omit_empty_base_classes,
1447    std::vector<uint32_t>& child_indexes
1448)
1449{
1450    if (clang_type && name && name[0])
1451    {
1452        QualType qual_type(QualType::getFromOpaquePtr(clang_type));
1453        switch (qual_type->getTypeClass())
1454        {
1455        case Type::Record:
1456            {
1457                const RecordType *record_type = cast<RecordType>(qual_type.getTypePtr());
1458                const RecordDecl *record_decl = record_type->getDecl();
1459
1460                assert(record_decl);
1461                uint32_t child_idx = 0;
1462
1463                const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
1464
1465                // Try and find a field that matches NAME
1466                RecordDecl::field_iterator field, field_end;
1467                StringRef name_sref(name);
1468                for (field = record_decl->field_begin(), field_end = record_decl->field_end();
1469                     field != field_end;
1470                     ++field, ++child_idx)
1471                {
1472                    if (field->getName().equals (name_sref))
1473                    {
1474                        // We have to add on the number of base classes to this index!
1475                        child_indexes.push_back (child_idx + GetNumBaseClasses (cxx_record_decl, omit_empty_base_classes));
1476                        return child_indexes.size();
1477                    }
1478                }
1479
1480                if (cxx_record_decl)
1481                {
1482                    const RecordDecl *parent_record_decl = cxx_record_decl;
1483
1484                    //printf ("parent = %s\n", parent_record_decl->getNameAsCString());
1485
1486                    //const Decl *root_cdecl = cxx_record_decl->getCanonicalDecl();
1487                    // Didn't find things easily, lets let clang do its thang...
1488                    IdentifierInfo & ident_ref = ast_context->Idents.get(name, name + strlen (name));
1489                    DeclarationName decl_name(&ident_ref);
1490
1491                    CXXBasePaths paths;
1492                    if (cxx_record_decl->lookupInBases(CXXRecordDecl::FindOrdinaryMember,
1493                                                       decl_name.getAsOpaquePtr(),
1494                                                       paths))
1495                    {
1496                        CXXBasePaths::const_paths_iterator path, path_end = paths.end();
1497                        for (path = paths.begin(); path != path_end; ++path)
1498                        {
1499                            const size_t num_path_elements = path->size();
1500                            for (size_t e=0; e<num_path_elements; ++e)
1501                            {
1502                                CXXBasePathElement elem = (*path)[e];
1503
1504                                child_idx = GetIndexForRecordBase (parent_record_decl, elem.Base, omit_empty_base_classes);
1505                                if (child_idx == UINT32_MAX)
1506                                {
1507                                    child_indexes.clear();
1508                                    return 0;
1509                                }
1510                                else
1511                                {
1512                                    child_indexes.push_back (child_idx);
1513                                    parent_record_decl = cast<RecordDecl>(elem.Base->getType()->getAs<RecordType>()->getDecl());
1514                                }
1515                            }
1516                            DeclContext::lookup_iterator named_decl_pos;
1517                            for (named_decl_pos = path->Decls.first;
1518                                 named_decl_pos != path->Decls.second && parent_record_decl;
1519                                 ++named_decl_pos)
1520                            {
1521                                //printf ("path[%zu] = %s\n", child_indexes.size(), (*named_decl_pos)->getNameAsCString());
1522
1523                                child_idx = GetIndexForRecordChild (parent_record_decl, *named_decl_pos, omit_empty_base_classes);
1524                                if (child_idx == UINT32_MAX)
1525                                {
1526                                    child_indexes.clear();
1527                                    return 0;
1528                                }
1529                                else
1530                                {
1531                                    child_indexes.push_back (child_idx);
1532                                }
1533                            }
1534                        }
1535                        return child_indexes.size();
1536                    }
1537                }
1538
1539            }
1540            break;
1541
1542        case Type::ConstantArray:
1543            {
1544//                const ConstantArrayType *array = cast<ConstantArrayType>(parent_qual_type.getTypePtr());
1545//                const uint64_t element_count = array->getSize().getLimitedValue();
1546//
1547//                if (idx < element_count)
1548//                {
1549//                    std::pair<uint64_t, unsigned> field_type_info = ast_context->getTypeInfo(array->getElementType());
1550//
1551//                    char element_name[32];
1552//                    ::snprintf (element_name, sizeof (element_name), "%s[%u]", parent_name ? parent_name : "", idx);
1553//
1554//                    child_name.assign(element_name);
1555//                    assert(field_type_info.first % 8 == 0);
1556//                    child_byte_size = field_type_info.first / 8;
1557//                    child_byte_offset = idx * child_byte_size;
1558//                    return array->getElementType().getAsOpaquePtr();
1559//                }
1560            }
1561            break;
1562
1563//        case Type::MemberPointerType:
1564//            {
1565//                MemberPointerType *mem_ptr_type = cast<MemberPointerType>(qual_type.getTypePtr());
1566//                QualType pointee_type = mem_ptr_type->getPointeeType();
1567//
1568//                if (ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
1569//                {
1570//                    return GetIndexOfChildWithName (ast_context,
1571//                                                    mem_ptr_type->getPointeeType().getAsOpaquePtr(),
1572//                                                    name);
1573//                }
1574//            }
1575//            break;
1576//
1577        case Type::LValueReference:
1578        case Type::RValueReference:
1579            {
1580                ReferenceType *reference_type = cast<ReferenceType>(qual_type.getTypePtr());
1581                QualType pointee_type = reference_type->getPointeeType();
1582
1583                if (ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
1584                {
1585                    return GetIndexOfChildMemberWithName (ast_context,
1586                                                          reference_type->getPointeeType().getAsOpaquePtr(),
1587                                                          name,
1588                                                          omit_empty_base_classes,
1589                                                          child_indexes);
1590                }
1591            }
1592            break;
1593
1594        case Type::Pointer:
1595            {
1596                PointerType *pointer_type = cast<PointerType>(qual_type.getTypePtr());
1597                QualType pointee_type = pointer_type->getPointeeType();
1598
1599                if (ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
1600                {
1601                    return GetIndexOfChildMemberWithName (ast_context,
1602                                                          pointer_type->getPointeeType().getAsOpaquePtr(),
1603                                                          name,
1604                                                          omit_empty_base_classes,
1605                                                          child_indexes);
1606                }
1607                else
1608                {
1609//                    if (parent_name)
1610//                    {
1611//                        child_name.assign(1, '*');
1612//                        child_name += parent_name;
1613//                    }
1614//
1615//                    // We have a pointer to an simple type
1616//                    if (idx == 0)
1617//                    {
1618//                        std::pair<uint64_t, unsigned> clang_type_info = ast_context->getTypeInfo(pointee_type);
1619//                        assert(clang_type_info.first % 8 == 0);
1620//                        child_byte_size = clang_type_info.first / 8;
1621//                        child_byte_offset = 0;
1622//                        return pointee_type.getAsOpaquePtr();
1623//                    }
1624                }
1625            }
1626            break;
1627
1628        case Type::Typedef:
1629            return GetIndexOfChildMemberWithName (ast_context,
1630                                                  cast<TypedefType>(qual_type)->LookThroughTypedefs().getAsOpaquePtr(),
1631                                                  name,
1632                                                  omit_empty_base_classes,
1633                                                  child_indexes);
1634
1635        default:
1636            break;
1637        }
1638    }
1639    return 0;
1640}
1641
1642
1643// Get the index of the child of "clang_type" whose name matches. This function
1644// doesn't descend into the children, but only looks one level deep and name
1645// matches can include base class names.
1646
1647uint32_t
1648ClangASTContext::GetIndexOfChildWithName
1649(
1650    ASTContext *ast_context,
1651    void *clang_type,
1652    const char *name,
1653    bool omit_empty_base_classes
1654)
1655{
1656    if (clang_type && name && name[0])
1657    {
1658        QualType qual_type(QualType::getFromOpaquePtr(clang_type));
1659        switch (qual_type->getTypeClass())
1660        {
1661        case Type::Record:
1662            {
1663                const RecordType *record_type = cast<RecordType>(qual_type.getTypePtr());
1664                const RecordDecl *record_decl = record_type->getDecl();
1665
1666                assert(record_decl);
1667                uint32_t child_idx = 0;
1668
1669                const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
1670
1671                if (cxx_record_decl)
1672                {
1673                    CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
1674                    for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
1675                         base_class != base_class_end;
1676                         ++base_class)
1677                    {
1678                        // Skip empty base classes
1679                        CXXRecordDecl *base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
1680                        if (omit_empty_base_classes && RecordHasFields(base_class_decl) == false)
1681                            continue;
1682
1683                        if (base_class->getType().getAsString().compare (name) == 0)
1684                            return child_idx;
1685                        ++child_idx;
1686                    }
1687                }
1688
1689                // Try and find a field that matches NAME
1690                RecordDecl::field_iterator field, field_end;
1691                StringRef name_sref(name);
1692                for (field = record_decl->field_begin(), field_end = record_decl->field_end();
1693                     field != field_end;
1694                     ++field, ++child_idx)
1695                {
1696                    if (field->getName().equals (name_sref))
1697                        return child_idx;
1698                }
1699
1700            }
1701            break;
1702
1703        case Type::ConstantArray:
1704            {
1705//                const ConstantArrayType *array = cast<ConstantArrayType>(parent_qual_type.getTypePtr());
1706//                const uint64_t element_count = array->getSize().getLimitedValue();
1707//
1708//                if (idx < element_count)
1709//                {
1710//                    std::pair<uint64_t, unsigned> field_type_info = ast_context->getTypeInfo(array->getElementType());
1711//
1712//                    char element_name[32];
1713//                    ::snprintf (element_name, sizeof (element_name), "%s[%u]", parent_name ? parent_name : "", idx);
1714//
1715//                    child_name.assign(element_name);
1716//                    assert(field_type_info.first % 8 == 0);
1717//                    child_byte_size = field_type_info.first / 8;
1718//                    child_byte_offset = idx * child_byte_size;
1719//                    return array->getElementType().getAsOpaquePtr();
1720//                }
1721            }
1722            break;
1723
1724//        case Type::MemberPointerType:
1725//            {
1726//                MemberPointerType *mem_ptr_type = cast<MemberPointerType>(qual_type.getTypePtr());
1727//                QualType pointee_type = mem_ptr_type->getPointeeType();
1728//
1729//                if (ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
1730//                {
1731//                    return GetIndexOfChildWithName (ast_context,
1732//                                                    mem_ptr_type->getPointeeType().getAsOpaquePtr(),
1733//                                                    name);
1734//                }
1735//            }
1736//            break;
1737//
1738        case Type::LValueReference:
1739        case Type::RValueReference:
1740            {
1741                ReferenceType *reference_type = cast<ReferenceType>(qual_type.getTypePtr());
1742                QualType pointee_type = reference_type->getPointeeType();
1743
1744                if (ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
1745                {
1746                    return GetIndexOfChildWithName (ast_context,
1747                                                    reference_type->getPointeeType().getAsOpaquePtr(),
1748                                                    name,
1749                                                    omit_empty_base_classes);
1750                }
1751            }
1752            break;
1753
1754        case Type::Pointer:
1755            {
1756                PointerType *pointer_type = cast<PointerType>(qual_type.getTypePtr());
1757                QualType pointee_type = pointer_type->getPointeeType();
1758
1759                if (ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
1760                {
1761                    return GetIndexOfChildWithName (ast_context,
1762                                                    pointer_type->getPointeeType().getAsOpaquePtr(),
1763                                                    name,
1764                                                    omit_empty_base_classes);
1765                }
1766                else
1767                {
1768//                    if (parent_name)
1769//                    {
1770//                        child_name.assign(1, '*');
1771//                        child_name += parent_name;
1772//                    }
1773//
1774//                    // We have a pointer to an simple type
1775//                    if (idx == 0)
1776//                    {
1777//                        std::pair<uint64_t, unsigned> clang_type_info = ast_context->getTypeInfo(pointee_type);
1778//                        assert(clang_type_info.first % 8 == 0);
1779//                        child_byte_size = clang_type_info.first / 8;
1780//                        child_byte_offset = 0;
1781//                        return pointee_type.getAsOpaquePtr();
1782//                    }
1783                }
1784            }
1785            break;
1786
1787        case Type::Typedef:
1788            return GetIndexOfChildWithName (ast_context,
1789                                            cast<TypedefType>(qual_type)->LookThroughTypedefs().getAsOpaquePtr(),
1790                                            name,
1791                                            omit_empty_base_classes);
1792
1793        default:
1794            break;
1795        }
1796    }
1797    return UINT32_MAX;
1798}
1799
1800#pragma mark TagType
1801
1802bool
1803ClangASTContext::SetTagTypeKind (void *tag_clang_type, int kind)
1804{
1805    if (tag_clang_type)
1806    {
1807        QualType tag_qual_type(QualType::getFromOpaquePtr(tag_clang_type));
1808        Type *clang_type = tag_qual_type.getTypePtr();
1809        if (clang_type)
1810        {
1811            TagType *tag_type = dyn_cast<TagType>(clang_type);
1812            if (tag_type)
1813            {
1814                TagDecl *tag_decl = dyn_cast<TagDecl>(tag_type->getDecl());
1815                if (tag_decl)
1816                {
1817                    tag_decl->setTagKind ((TagDecl::TagKind)kind);
1818                    return true;
1819                }
1820            }
1821        }
1822    }
1823    return false;
1824}
1825
1826
1827#pragma mark DeclContext Functions
1828
1829DeclContext *
1830ClangASTContext::GetDeclContextForType (void *clang_type)
1831{
1832    if (clang_type == NULL)
1833        return NULL;
1834
1835    QualType qual_type(QualType::getFromOpaquePtr(clang_type));
1836    switch (qual_type->getTypeClass())
1837    {
1838    case Type::FunctionNoProto:         break;
1839    case Type::FunctionProto:           break;
1840    case Type::IncompleteArray:         break;
1841    case Type::VariableArray:           break;
1842    case Type::ConstantArray:           break;
1843    case Type::ExtVector:               break;
1844    case Type::Vector:                  break;
1845    case Type::Builtin:                 break;
1846    case Type::ObjCObjectPointer:       break;
1847    case Type::BlockPointer:            break;
1848    case Type::Pointer:                 break;
1849    case Type::LValueReference:         break;
1850    case Type::RValueReference:         break;
1851    case Type::MemberPointer:           break;
1852    case Type::Complex:                 break;
1853    case Type::ObjCInterface:           break;
1854    case Type::Record:
1855        return cast<RecordType>(qual_type)->getDecl();
1856    case Type::Enum:
1857        return cast<EnumType>(qual_type)->getDecl();
1858    case Type::Typedef:
1859        return ClangASTContext::GetDeclContextForType (cast<TypedefType>(qual_type)->LookThroughTypedefs().getAsOpaquePtr());
1860
1861    case Type::TypeOfExpr:              break;
1862    case Type::TypeOf:                  break;
1863    case Type::Decltype:                break;
1864    //case Type::QualifiedName:           break;
1865    case Type::TemplateSpecialization:  break;
1866    }
1867    // No DeclContext in this type...
1868    return NULL;
1869}
1870
1871#pragma mark Namespace Declarations
1872
1873NamespaceDecl *
1874ClangASTContext::GetUniqueNamespaceDeclaration (const char *name, const Declaration &decl, DeclContext *decl_ctx)
1875{
1876    // TODO: Do something intelligent with the Declaration object passed in
1877    // like maybe filling in the SourceLocation with it...
1878    if (name)
1879    {
1880        ASTContext *ast_context = getASTContext();
1881        if (decl_ctx == NULL)
1882            decl_ctx = ast_context->getTranslationUnitDecl();
1883        return NamespaceDecl::Create(*ast_context, decl_ctx, SourceLocation(), &ast_context->Idents.get(name));
1884    }
1885    return NULL;
1886}
1887
1888
1889#pragma mark Function Types
1890
1891FunctionDecl *
1892ClangASTContext::CreateFunctionDeclaration (const char *name, void *function_clang_type, int storage, bool is_inline)
1893{
1894    if (name)
1895    {
1896        ASTContext *ast_context = getASTContext();
1897        assert (ast_context != NULL);
1898
1899        if (name && name[0])
1900        {
1901            return FunctionDecl::Create(*ast_context,
1902                                        ast_context->getTranslationUnitDecl(),
1903                                        SourceLocation(),
1904                                        DeclarationName (&ast_context->Idents.get(name)),
1905                                        QualType::getFromOpaquePtr(function_clang_type),
1906                                        NULL,
1907                                        (FunctionDecl::StorageClass)storage,
1908                                        (FunctionDecl::StorageClass)storage,
1909                                        is_inline);
1910        }
1911        else
1912        {
1913            return FunctionDecl::Create(*ast_context,
1914                                        ast_context->getTranslationUnitDecl(),
1915                                        SourceLocation(),
1916                                        DeclarationName (),
1917                                        QualType::getFromOpaquePtr(function_clang_type),
1918                                        NULL,
1919                                        (FunctionDecl::StorageClass)storage,
1920                                        (FunctionDecl::StorageClass)storage,
1921                                        is_inline);
1922        }
1923    }
1924    return NULL;
1925}
1926
1927void *
1928ClangASTContext::CreateFunctionType (void *result_type, void **args, unsigned num_args, bool isVariadic, unsigned TypeQuals)
1929{
1930    ASTContext *ast_context = getASTContext();
1931    assert (ast_context != NULL);
1932    std::vector<QualType> qual_type_args;
1933    for (unsigned i=0; i<num_args; ++i)
1934        qual_type_args.push_back (QualType::getFromOpaquePtr(args[i]));
1935
1936    // TODO: Detect calling convention in DWARF?
1937    return ast_context->getFunctionType(QualType::getFromOpaquePtr(result_type),
1938                                        qual_type_args.data(),
1939                                        qual_type_args.size(),
1940                                        isVariadic,
1941                                        TypeQuals,
1942                                        false,  // hasExceptionSpec
1943                                        false,  // hasAnyExceptionSpec,
1944                                        0,      // NumExs
1945                                        0,      // const QualType *ExArray
1946                                        FunctionType::ExtInfo ()).getAsOpaquePtr();    // NoReturn);
1947}
1948
1949ParmVarDecl *
1950ClangASTContext::CreateParmeterDeclaration (const char *name, void * return_type, int storage)
1951{
1952    ASTContext *ast_context = getASTContext();
1953    assert (ast_context != NULL);
1954    return ParmVarDecl::Create(*ast_context,
1955                                ast_context->getTranslationUnitDecl(),
1956                                SourceLocation(),
1957                                name && name[0] ? &ast_context->Idents.get(name) : NULL,
1958                                QualType::getFromOpaquePtr(return_type),
1959                                NULL,
1960                                (VarDecl::StorageClass)storage,
1961                                (VarDecl::StorageClass)storage,
1962                                0);
1963}
1964
1965void
1966ClangASTContext::SetFunctionParameters (FunctionDecl *function_decl, ParmVarDecl **params, unsigned num_params)
1967{
1968    if (function_decl)
1969        function_decl->setParams (params, num_params);
1970}
1971
1972
1973#pragma mark Array Types
1974
1975void *
1976ClangASTContext::CreateArrayType (void *element_type, size_t element_count, uint32_t bit_stride)
1977{
1978    if (element_type)
1979    {
1980        ASTContext *ast_context = getASTContext();
1981        assert (ast_context != NULL);
1982        llvm::APInt ap_element_count (64, element_count);
1983        return ast_context->getConstantArrayType(QualType::getFromOpaquePtr(element_type),
1984                                                 ap_element_count,
1985                                                 ArrayType::Normal,
1986                                                 0).getAsOpaquePtr(); // ElemQuals
1987    }
1988    return NULL;
1989}
1990
1991
1992#pragma mark TagDecl
1993
1994bool
1995ClangASTContext::StartTagDeclarationDefinition (void *clang_type)
1996{
1997    if (clang_type)
1998    {
1999        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
2000        Type *t = qual_type.getTypePtr();
2001        if (t)
2002        {
2003            TagType *tag_type = dyn_cast<TagType>(t);
2004            if (tag_type)
2005            {
2006                TagDecl *tag_decl = tag_type->getDecl();
2007                if (tag_decl)
2008                {
2009                    tag_decl->startDefinition();
2010                    return true;
2011                }
2012            }
2013        }
2014    }
2015    return false;
2016}
2017
2018bool
2019ClangASTContext::CompleteTagDeclarationDefinition (void *clang_type)
2020{
2021    if (clang_type)
2022    {
2023        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
2024        Type *t = qual_type.getTypePtr();
2025        if (t)
2026        {
2027            TagType *tag_type = dyn_cast<TagType>(t);
2028            if (tag_type)
2029            {
2030                TagDecl *tag_decl = tag_type->getDecl();
2031                if (tag_decl)
2032                {
2033                    tag_decl->completeDefinition();
2034                    return true;
2035                }
2036            }
2037        }
2038    }
2039    return false;
2040}
2041
2042
2043#pragma mark Enumeration Types
2044
2045void *
2046ClangASTContext::CreateEnumerationType (const Declaration &decl, const char *name)
2047{
2048    // TODO: Do something intelligent with the Declaration object passed in
2049    // like maybe filling in the SourceLocation with it...
2050    ASTContext *ast_context = getASTContext();
2051    assert (ast_context != NULL);
2052    EnumDecl *enum_decl = EnumDecl::Create(*ast_context,
2053                                           ast_context->getTranslationUnitDecl(),
2054                                           SourceLocation(),
2055                                           name && name[0] ? &ast_context->Idents.get(name) : NULL,
2056                                           SourceLocation(),
2057                                           NULL);
2058    if (enum_decl)
2059        return ast_context->getTagDeclType(enum_decl).getAsOpaquePtr();
2060    return NULL;
2061}
2062
2063bool
2064ClangASTContext::AddEnumerationValueToEnumerationType
2065(
2066    void *enum_clang_type,
2067    void *enumerator_clang_type,
2068    const Declaration &decl,
2069    const char *name,
2070    int64_t enum_value,
2071    uint32_t enum_value_bit_size
2072)
2073{
2074    if (enum_clang_type && enumerator_clang_type && name)
2075    {
2076        // TODO: Do something intelligent with the Declaration object passed in
2077        // like maybe filling in the SourceLocation with it...
2078        ASTContext *ast_context = getASTContext();
2079        IdentifierTable *identifier_table = getIdentifierTable();
2080
2081        assert (ast_context != NULL);
2082        assert (identifier_table != NULL);
2083        QualType enum_qual_type (QualType::getFromOpaquePtr(enum_clang_type));
2084
2085        Type *clang_type = enum_qual_type.getTypePtr();
2086        if (clang_type)
2087        {
2088            const EnumType *enum_type = dyn_cast<EnumType>(clang_type);
2089
2090            if (enum_type)
2091            {
2092                llvm::APSInt enum_llvm_apsint(enum_value_bit_size, false);
2093                enum_llvm_apsint = enum_value;
2094                EnumConstantDecl *enumerator_decl =
2095                    EnumConstantDecl::Create(*ast_context,
2096                                             enum_type->getDecl(),
2097                                             SourceLocation(),
2098                                             name ? &identifier_table->get(name) : NULL,    // Identifier
2099                                             QualType::getFromOpaquePtr(enumerator_clang_type),
2100                                             NULL,
2101                                             enum_llvm_apsint);
2102
2103                if (enumerator_decl)
2104                {
2105                    enum_type->getDecl()->addDecl(enumerator_decl);
2106                    return true;
2107                }
2108            }
2109        }
2110    }
2111    return false;
2112}
2113
2114#pragma mark Pointers & References
2115
2116void *
2117ClangASTContext::CreatePointerType (void *clang_type)
2118{
2119    if (clang_type)
2120        return getASTContext()->getPointerType(QualType::getFromOpaquePtr(clang_type)).getAsOpaquePtr();
2121    return NULL;
2122}
2123
2124void *
2125ClangASTContext::CreateLValueReferenceType (void *clang_type)
2126{
2127    if (clang_type)
2128        return getASTContext()->getLValueReferenceType (QualType::getFromOpaquePtr(clang_type)).getAsOpaquePtr();
2129    return NULL;
2130}
2131
2132void *
2133ClangASTContext::CreateRValueReferenceType (void *clang_type)
2134{
2135    if (clang_type)
2136        return getASTContext()->getRValueReferenceType (QualType::getFromOpaquePtr(clang_type)).getAsOpaquePtr();
2137    return NULL;
2138}
2139
2140void *
2141ClangASTContext::CreateMemberPointerType (void * clang_pointee_type, void * clang_class_type)
2142{
2143    if (clang_pointee_type && clang_pointee_type)
2144        return getASTContext()->getMemberPointerType(QualType::getFromOpaquePtr(clang_pointee_type),
2145                                                     QualType::getFromOpaquePtr(clang_class_type).getTypePtr()).getAsOpaquePtr();
2146    return NULL;
2147}
2148
2149size_t
2150ClangASTContext::GetPointerBitSize ()
2151{
2152    ASTContext *ast_context = getASTContext();
2153    return ast_context->getTypeSize(ast_context->VoidPtrTy);
2154}
2155
2156bool
2157ClangASTContext::IsPointerOrReferenceType (void *clang_type, void **target_type)
2158{
2159    if (clang_type == NULL)
2160        return false;
2161
2162    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
2163    switch (qual_type->getTypeClass())
2164    {
2165    case Type::ObjCObjectPointer:
2166        if (target_type)
2167            *target_type = cast<ObjCObjectPointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
2168        return true;
2169    case Type::BlockPointer:
2170        if (target_type)
2171            *target_type = cast<BlockPointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
2172        return true;
2173    case Type::Pointer:
2174        if (target_type)
2175            *target_type = cast<PointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
2176        return true;
2177    case Type::MemberPointer:
2178        if (target_type)
2179            *target_type = cast<MemberPointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
2180        return true;
2181    case Type::LValueReference:
2182        if (target_type)
2183            *target_type = cast<LValueReferenceType>(qual_type)->desugar().getAsOpaquePtr();
2184        return true;
2185    case Type::RValueReference:
2186        if (target_type)
2187            *target_type = cast<LValueReferenceType>(qual_type)->desugar().getAsOpaquePtr();
2188        return true;
2189    case Type::Typedef:
2190        return ClangASTContext::IsPointerOrReferenceType (cast<TypedefType>(qual_type)->LookThroughTypedefs().getAsOpaquePtr());
2191    default:
2192        break;
2193    }
2194    return false;
2195}
2196
2197size_t
2198ClangASTContext::GetTypeBitSize (clang::ASTContext *ast_context, void *clang_type)
2199{
2200    if (clang_type)
2201        return ast_context->getTypeSize(QualType::getFromOpaquePtr(clang_type));
2202    return 0;
2203}
2204
2205size_t
2206ClangASTContext::GetTypeBitAlign (clang::ASTContext *ast_context, void *clang_type)
2207{
2208    if (clang_type)
2209        return ast_context->getTypeAlign(QualType::getFromOpaquePtr(clang_type));
2210    return 0;
2211}
2212
2213bool
2214ClangASTContext::IsIntegerType (void * clang_type, bool &is_signed)
2215{
2216    if (!clang_type)
2217        return false;
2218
2219    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
2220    const BuiltinType *builtin_type = dyn_cast<BuiltinType>(qual_type->getCanonicalTypeInternal());
2221
2222    if (builtin_type)
2223    {
2224        if (builtin_type->isInteger())
2225            is_signed = builtin_type->isSignedInteger();
2226
2227        return true;
2228    }
2229
2230    return false;
2231}
2232
2233bool
2234ClangASTContext::IsPointerType (void *clang_type, void **target_type)
2235{
2236    if (clang_type)
2237    {
2238        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
2239        switch (qual_type->getTypeClass())
2240        {
2241        case Type::ObjCObjectPointer:
2242            if (target_type)
2243                *target_type = cast<ObjCObjectPointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
2244            return true;
2245        case Type::BlockPointer:
2246            if (target_type)
2247                *target_type = cast<BlockPointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
2248            return true;
2249        case Type::Pointer:
2250            if (target_type)
2251                *target_type = cast<PointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
2252            return true;
2253        case Type::MemberPointer:
2254            if (target_type)
2255                *target_type = cast<MemberPointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
2256            return true;
2257        case Type::Typedef:
2258            return ClangASTContext::IsPointerOrReferenceType (cast<TypedefType>(qual_type)->LookThroughTypedefs().getAsOpaquePtr(), target_type);
2259        default:
2260            break;
2261        }
2262    }
2263    return false;
2264}
2265
2266bool
2267ClangASTContext::IsFloatingPointType (void *clang_type, uint32_t &count, bool &is_complex)
2268{
2269    if (clang_type)
2270    {
2271        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
2272
2273        if (const BuiltinType *BT = dyn_cast<BuiltinType>(qual_type->getCanonicalTypeInternal()))
2274        {
2275            clang::BuiltinType::Kind kind = BT->getKind();
2276            if (kind >= BuiltinType::Float && kind <= BuiltinType::LongDouble)
2277            {
2278                count = 1;
2279                is_complex = false;
2280                return true;
2281            }
2282        }
2283        else if (const ComplexType *CT = dyn_cast<ComplexType>(qual_type->getCanonicalTypeInternal()))
2284        {
2285            if (IsFloatingPointType(CT->getElementType().getAsOpaquePtr(), count, is_complex))
2286            {
2287                count = 2;
2288                is_complex = true;
2289                return true;
2290            }
2291        }
2292        else if (const VectorType *VT = dyn_cast<VectorType>(qual_type->getCanonicalTypeInternal()))
2293        {
2294            if (IsFloatingPointType(VT->getElementType().getAsOpaquePtr(), count, is_complex))
2295            {
2296                count = VT->getNumElements();
2297                is_complex = false;
2298                return true;
2299            }
2300        }
2301    }
2302    return false;
2303}
2304
2305
2306bool
2307ClangASTContext::IsCStringType (void *clang_type, uint32_t &length)
2308{
2309    if (clang_type)
2310    {
2311        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
2312        switch (qual_type->getTypeClass())
2313        {
2314        case Type::ConstantArray:
2315            {
2316                ConstantArrayType *array = cast<ConstantArrayType>(qual_type.getTypePtr());
2317                QualType element_qual_type = array->getElementType();
2318                Type *canonical_type = element_qual_type->getCanonicalTypeInternal().getTypePtr();
2319                if (canonical_type && canonical_type->isCharType())
2320                {
2321                    // We know the size of the array and it could be a C string
2322                    // since it is an array of characters
2323                    length = array->getSize().getLimitedValue();
2324                    return true;
2325                }
2326            }
2327            break;
2328
2329        case Type::Pointer:
2330            {
2331                PointerType *pointer_type = cast<PointerType>(qual_type.getTypePtr());
2332                Type *pointee_type_ptr = pointer_type->getPointeeType().getTypePtr();
2333                if (pointee_type_ptr)
2334                {
2335                    Type *canonical_type_ptr = pointee_type_ptr->getCanonicalTypeInternal().getTypePtr();
2336                    length = 0; // No length info, read until a NULL terminator is received
2337                    if (canonical_type_ptr)
2338                        return canonical_type_ptr->isCharType();
2339                    else
2340                        return pointee_type_ptr->isCharType();
2341                }
2342            }
2343            break;
2344
2345        case Type::Typedef:
2346            return ClangASTContext::IsCStringType (cast<TypedefType>(qual_type)->LookThroughTypedefs().getAsOpaquePtr(), length);
2347
2348        case Type::LValueReference:
2349        case Type::RValueReference:
2350            {
2351                ReferenceType *reference_type = cast<ReferenceType>(qual_type.getTypePtr());
2352                Type *pointee_type_ptr = reference_type->getPointeeType().getTypePtr();
2353                if (pointee_type_ptr)
2354                {
2355                    Type *canonical_type_ptr = pointee_type_ptr->getCanonicalTypeInternal().getTypePtr();
2356                    length = 0; // No length info, read until a NULL terminator is received
2357                    if (canonical_type_ptr)
2358                        return canonical_type_ptr->isCharType();
2359                    else
2360                        return pointee_type_ptr->isCharType();
2361                }
2362            }
2363            break;
2364        }
2365    }
2366    return false;
2367}
2368
2369bool
2370ClangASTContext::IsArrayType (void * clang_type, void **member_type, uint64_t *size)
2371{
2372    if (!clang_type)
2373        return false;
2374
2375    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
2376
2377    switch (qual_type->getTypeClass())
2378    {
2379    case Type::ConstantArray:
2380        if (member_type)
2381            *member_type = cast<ConstantArrayType>(qual_type)->getElementType().getAsOpaquePtr();
2382        if (size)
2383            *size = cast<ConstantArrayType>(qual_type)->getSize().getLimitedValue(ULONG_LONG_MAX);
2384        return true;
2385    case Type::IncompleteArray:
2386        if (member_type)
2387            *member_type = cast<IncompleteArrayType>(qual_type)->getElementType().getAsOpaquePtr();
2388        if (size)
2389            *size = 0;
2390        return true;
2391    case Type::VariableArray:
2392        if (member_type)
2393            *member_type = cast<VariableArrayType>(qual_type)->getElementType().getAsOpaquePtr();
2394        if (size)
2395            *size = 0;
2396    case Type::DependentSizedArray:
2397        if (member_type)
2398            *member_type = cast<DependentSizedArrayType>(qual_type)->getElementType().getAsOpaquePtr();
2399        if (size)
2400            *size = 0;
2401        return true;
2402    }
2403    return false;
2404}
2405
2406
2407#pragma mark Typedefs
2408
2409void *
2410ClangASTContext::CreateTypedefType (const char *name, void *clang_type, DeclContext *decl_ctx)
2411{
2412    if (clang_type)
2413    {
2414        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
2415        ASTContext *ast_context = getASTContext();
2416        IdentifierTable *identifier_table = getIdentifierTable();
2417        assert (ast_context != NULL);
2418        assert (identifier_table != NULL);
2419        if (decl_ctx == NULL)
2420            decl_ctx = ast_context->getTranslationUnitDecl();
2421        TypedefDecl *decl = TypedefDecl::Create(*ast_context,
2422                                                decl_ctx,
2423                                                SourceLocation(),
2424                                                name ? &identifier_table->get(name) : NULL, // Identifier
2425                                                ast_context->CreateTypeSourceInfo(qual_type));
2426
2427        // Get a uniqued QualType for the typedef decl type
2428        return ast_context->getTypedefType (decl).getAsOpaquePtr();
2429    }
2430    return NULL;
2431}
2432
2433
2434std::string
2435ClangASTContext::GetTypeName (void *opaque_qual_type)
2436{
2437    std::string return_name;
2438
2439    clang::QualType qual_type(clang::QualType::getFromOpaquePtr(opaque_qual_type));
2440
2441    const clang::TypedefType *typedef_type = qual_type->getAs<clang::TypedefType>();
2442    if (typedef_type)
2443    {
2444        const clang::TypedefDecl *typedef_decl = typedef_type->getDecl();
2445        return_name = typedef_decl->getQualifiedNameAsString();
2446    }
2447    else
2448    {
2449        return_name = qual_type.getAsString();
2450    }
2451
2452    return return_name;
2453}
2454
2455// Disable this for now since I can't seem to get a nicely formatted float
2456// out of the APFloat class without just getting the float, double or quad
2457// and then using a formatted print on it which defeats the purpose. We ideally
2458// would like to get perfect string values for any kind of float semantics
2459// so we can support remote targets. The code below also requires a patch to
2460// llvm::APInt.
2461//bool
2462//ClangASTContext::ConvertFloatValueToString (ASTContext *ast_context, void *clang_type, const uint8_t* bytes, size_t byte_size, int apint_byte_order, std::string &float_str)
2463//{
2464//  uint32_t count = 0;
2465//  bool is_complex = false;
2466//  if (ClangASTContext::IsFloatingPointType (clang_type, count, is_complex))
2467//  {
2468//      unsigned num_bytes_per_float = byte_size / count;
2469//      unsigned num_bits_per_float = num_bytes_per_float * 8;
2470//
2471//      float_str.clear();
2472//      uint32_t i;
2473//      for (i=0; i<count; i++)
2474//      {
2475//          APInt ap_int(num_bits_per_float, bytes + i * num_bytes_per_float, (APInt::ByteOrder)apint_byte_order);
2476//          bool is_ieee = false;
2477//          APFloat ap_float(ap_int, is_ieee);
2478//          char s[1024];
2479//          unsigned int hex_digits = 0;
2480//          bool upper_case = false;
2481//
2482//          if (ap_float.convertToHexString(s, hex_digits, upper_case, APFloat::rmNearestTiesToEven) > 0)
2483//          {
2484//              if (i > 0)
2485//                  float_str.append(", ");
2486//              float_str.append(s);
2487//              if (i == 1 && is_complex)
2488//                  float_str.append(1, 'i');
2489//          }
2490//      }
2491//      return !float_str.empty();
2492//  }
2493//  return false;
2494//}
2495
2496size_t
2497ClangASTContext::ConvertStringToFloatValue (ASTContext *ast_context, void *clang_type, const char *s, uint8_t *dst, size_t dst_size)
2498{
2499    if (clang_type)
2500    {
2501        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
2502        uint32_t count = 0;
2503        bool is_complex = false;
2504        if (ClangASTContext::IsFloatingPointType (clang_type, count, is_complex))
2505        {
2506            // TODO: handle complex and vector types
2507            if (count != 1)
2508                return false;
2509
2510            StringRef s_sref(s);
2511            APFloat ap_float(ast_context->getFloatTypeSemantics(qual_type), s_sref);
2512
2513            const uint64_t bit_size = ast_context->getTypeSize (qual_type);
2514            const uint64_t byte_size = bit_size / 8;
2515            if (dst_size >= byte_size)
2516            {
2517                if (bit_size == sizeof(float)*8)
2518                {
2519                    float float32 = ap_float.convertToFloat();
2520                    ::memcpy (dst, &float32, byte_size);
2521                    return byte_size;
2522                }
2523                else if (bit_size >= 64)
2524                {
2525                    llvm::APInt ap_int(ap_float.bitcastToAPInt());
2526                    ::memcpy (dst, ap_int.getRawData(), byte_size);
2527                    return byte_size;
2528                }
2529            }
2530        }
2531    }
2532    return 0;
2533}
2534