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