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