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