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