ClangASTContext.cpp revision d0250856d5e33dcb5c60f8dcd3a5b88860608b50
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    return class_template_specialization_decl;
1360}
1361
1362lldb::clang_type_t
1363ClangASTContext::CreateClassTemplateSpecializationType (ClassTemplateSpecializationDecl *class_template_specialization_decl)
1364{
1365    if (class_template_specialization_decl)
1366    {
1367        ASTContext *ast = getASTContext();
1368        if (ast)
1369            return ast->getTagDeclType(class_template_specialization_decl).getAsOpaquePtr();
1370    }
1371    return NULL;
1372}
1373
1374bool
1375ClangASTContext::SetHasExternalStorage (clang_type_t clang_type, bool has_extern)
1376{
1377    if (clang_type == NULL)
1378        return false;
1379
1380    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
1381
1382    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
1383    switch (type_class)
1384    {
1385    case clang::Type::Record:
1386        {
1387            CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
1388            if (cxx_record_decl)
1389            {
1390                cxx_record_decl->setHasExternalLexicalStorage (has_extern);
1391                cxx_record_decl->setHasExternalVisibleStorage (has_extern);
1392                return true;
1393            }
1394        }
1395        break;
1396
1397    case clang::Type::Enum:
1398        {
1399            EnumDecl *enum_decl = cast<EnumType>(qual_type)->getDecl();
1400            if (enum_decl)
1401            {
1402                enum_decl->setHasExternalLexicalStorage (has_extern);
1403                enum_decl->setHasExternalVisibleStorage (has_extern);
1404                return true;
1405            }
1406        }
1407        break;
1408
1409    case clang::Type::ObjCObject:
1410    case clang::Type::ObjCInterface:
1411        {
1412            const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(qual_type.getTypePtr());
1413            assert (objc_class_type);
1414            if (objc_class_type)
1415            {
1416                ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
1417
1418                if (class_interface_decl)
1419                {
1420                    class_interface_decl->setHasExternalLexicalStorage (has_extern);
1421                    class_interface_decl->setHasExternalVisibleStorage (has_extern);
1422                    return true;
1423                }
1424            }
1425        }
1426        break;
1427
1428    case clang::Type::Typedef:
1429        return ClangASTContext::SetHasExternalStorage (cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(), has_extern);
1430
1431    case clang::Type::Elaborated:
1432        return ClangASTContext::SetHasExternalStorage (cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(), has_extern);
1433
1434    default:
1435        break;
1436    }
1437    return false;
1438}
1439
1440static bool
1441IsOperator (const char *name, OverloadedOperatorKind &op_kind)
1442{
1443    if (name == NULL || name[0] == '\0')
1444        return false;
1445
1446#define OPERATOR_PREFIX "operator"
1447#define OPERATOR_PREFIX_LENGTH (sizeof (OPERATOR_PREFIX) - 1)
1448
1449    const char *post_op_name = NULL;
1450
1451    bool no_space = true;
1452
1453    if (::strncmp(name, OPERATOR_PREFIX, OPERATOR_PREFIX_LENGTH))
1454        return false;
1455
1456    post_op_name = name + OPERATOR_PREFIX_LENGTH;
1457
1458    if (post_op_name[0] == ' ')
1459    {
1460        post_op_name++;
1461        no_space = false;
1462    }
1463
1464#undef OPERATOR_PREFIX
1465#undef OPERATOR_PREFIX_LENGTH
1466
1467    // This is an operator, set the overloaded operator kind to invalid
1468    // in case this is a conversion operator...
1469    op_kind = NUM_OVERLOADED_OPERATORS;
1470
1471    switch (post_op_name[0])
1472    {
1473    default:
1474        if (no_space)
1475            return false;
1476        break;
1477    case 'n':
1478        if (no_space)
1479            return false;
1480        if  (strcmp (post_op_name, "new") == 0)
1481            op_kind = OO_New;
1482        else if (strcmp (post_op_name, "new[]") == 0)
1483            op_kind = OO_Array_New;
1484        break;
1485
1486    case 'd':
1487        if (no_space)
1488            return false;
1489        if (strcmp (post_op_name, "delete") == 0)
1490            op_kind = OO_Delete;
1491        else if (strcmp (post_op_name, "delete[]") == 0)
1492            op_kind = OO_Array_Delete;
1493        break;
1494
1495    case '+':
1496        if (post_op_name[1] == '\0')
1497            op_kind = OO_Plus;
1498        else if (post_op_name[2] == '\0')
1499        {
1500            if (post_op_name[1] == '=')
1501                op_kind = OO_PlusEqual;
1502            else if (post_op_name[1] == '+')
1503                op_kind = OO_PlusPlus;
1504        }
1505        break;
1506
1507    case '-':
1508        if (post_op_name[1] == '\0')
1509            op_kind = OO_Minus;
1510        else if (post_op_name[2] == '\0')
1511        {
1512            switch (post_op_name[1])
1513            {
1514            case '=': op_kind = OO_MinusEqual; break;
1515            case '-': op_kind = OO_MinusMinus; break;
1516            case '>': op_kind = OO_Arrow; break;
1517            }
1518        }
1519        else if (post_op_name[3] == '\0')
1520        {
1521            if (post_op_name[2] == '*')
1522                op_kind = OO_ArrowStar; break;
1523        }
1524        break;
1525
1526    case '*':
1527        if (post_op_name[1] == '\0')
1528            op_kind = OO_Star;
1529        else if (post_op_name[1] == '=' && post_op_name[2] == '\0')
1530            op_kind = OO_StarEqual;
1531        break;
1532
1533    case '/':
1534        if (post_op_name[1] == '\0')
1535            op_kind = OO_Slash;
1536        else if (post_op_name[1] == '=' && post_op_name[2] == '\0')
1537            op_kind = OO_SlashEqual;
1538        break;
1539
1540    case '%':
1541        if (post_op_name[1] == '\0')
1542            op_kind = OO_Percent;
1543        else if (post_op_name[1] == '=' && post_op_name[2] == '\0')
1544            op_kind = OO_PercentEqual;
1545        break;
1546
1547
1548    case '^':
1549        if (post_op_name[1] == '\0')
1550            op_kind = OO_Caret;
1551        else if (post_op_name[1] == '=' && post_op_name[2] == '\0')
1552            op_kind = OO_CaretEqual;
1553        break;
1554
1555    case '&':
1556        if (post_op_name[1] == '\0')
1557            op_kind = OO_Amp;
1558        else if (post_op_name[2] == '\0')
1559        {
1560            switch (post_op_name[1])
1561            {
1562            case '=': op_kind = OO_AmpEqual; break;
1563            case '&': op_kind = OO_AmpAmp; break;
1564            }
1565        }
1566        break;
1567
1568    case '|':
1569        if (post_op_name[1] == '\0')
1570            op_kind = OO_Pipe;
1571        else if (post_op_name[2] == '\0')
1572        {
1573            switch (post_op_name[1])
1574            {
1575            case '=': op_kind = OO_PipeEqual; break;
1576            case '|': op_kind = OO_PipePipe; break;
1577            }
1578        }
1579        break;
1580
1581    case '~':
1582        if (post_op_name[1] == '\0')
1583            op_kind = OO_Tilde;
1584        break;
1585
1586    case '!':
1587        if (post_op_name[1] == '\0')
1588            op_kind = OO_Exclaim;
1589        else if (post_op_name[1] == '=' && post_op_name[2] == '\0')
1590            op_kind = OO_ExclaimEqual;
1591        break;
1592
1593    case '=':
1594        if (post_op_name[1] == '\0')
1595            op_kind = OO_Equal;
1596        else if (post_op_name[1] == '=' && post_op_name[2] == '\0')
1597            op_kind = OO_EqualEqual;
1598        break;
1599
1600    case '<':
1601        if (post_op_name[1] == '\0')
1602            op_kind = OO_Less;
1603        else if (post_op_name[2] == '\0')
1604        {
1605            switch (post_op_name[1])
1606            {
1607            case '<': op_kind = OO_LessLess; break;
1608            case '=': op_kind = OO_LessEqual; break;
1609            }
1610        }
1611        else if (post_op_name[3] == '\0')
1612        {
1613            if (post_op_name[2] == '=')
1614                op_kind = OO_LessLessEqual;
1615        }
1616        break;
1617
1618    case '>':
1619        if (post_op_name[1] == '\0')
1620            op_kind = OO_Greater;
1621        else if (post_op_name[2] == '\0')
1622        {
1623            switch (post_op_name[1])
1624            {
1625            case '>': op_kind = OO_GreaterGreater; break;
1626            case '=': op_kind = OO_GreaterEqual; break;
1627            }
1628        }
1629        else if (post_op_name[1] == '>' &&
1630                 post_op_name[2] == '=' &&
1631                 post_op_name[3] == '\0')
1632        {
1633                op_kind = OO_GreaterGreaterEqual;
1634        }
1635        break;
1636
1637    case ',':
1638        if (post_op_name[1] == '\0')
1639            op_kind = OO_Comma;
1640        break;
1641
1642    case '(':
1643        if (post_op_name[1] == ')' && post_op_name[2] == '\0')
1644            op_kind = OO_Call;
1645        break;
1646
1647    case '[':
1648        if (post_op_name[1] == ']' && post_op_name[2] == '\0')
1649            op_kind = OO_Subscript;
1650        break;
1651    }
1652
1653    return true;
1654}
1655
1656static inline bool
1657check_op_param (uint32_t op_kind, bool unary, bool binary, uint32_t num_params)
1658{
1659    // Special-case call since it can take any number of operands
1660    if(op_kind == OO_Call)
1661        return true;
1662
1663    // The parameter count doens't include "this"
1664    if (num_params == 0)
1665        return unary;
1666    if (num_params == 1)
1667        return binary;
1668    else
1669    return false;
1670}
1671
1672bool
1673ClangASTContext::CheckOverloadedOperatorKindParameterCount (uint32_t op_kind, uint32_t num_params)
1674{
1675    switch (op_kind)
1676    {
1677    default:
1678        break;
1679    // C++ standard allows any number of arguments to new/delete
1680    case OO_New:
1681    case OO_Array_New:
1682    case OO_Delete:
1683    case OO_Array_Delete:
1684        return true;
1685    }
1686
1687#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) case OO_##Name: return check_op_param (op_kind, Unary, Binary, num_params);
1688    switch (op_kind)
1689    {
1690#include "clang/Basic/OperatorKinds.def"
1691        default: break;
1692    }
1693    return false;
1694}
1695
1696CXXMethodDecl *
1697ClangASTContext::AddMethodToCXXRecordType
1698(
1699    ASTContext *ast,
1700    clang_type_t record_opaque_type,
1701    const char *name,
1702    clang_type_t method_opaque_type,
1703    lldb::AccessType access,
1704    bool is_virtual,
1705    bool is_static,
1706    bool is_inline,
1707    bool is_explicit,
1708    bool is_attr_used,
1709    bool is_artificial
1710)
1711{
1712    if (!record_opaque_type || !method_opaque_type || !name)
1713        return NULL;
1714
1715    assert(ast);
1716
1717    IdentifierTable *identifier_table = &ast->Idents;
1718
1719    assert(identifier_table);
1720
1721    QualType record_qual_type(QualType::getFromOpaquePtr(record_opaque_type));
1722
1723    CXXRecordDecl *cxx_record_decl = record_qual_type->getAsCXXRecordDecl();
1724
1725    if (cxx_record_decl == NULL)
1726        return NULL;
1727
1728    QualType method_qual_type (QualType::getFromOpaquePtr (method_opaque_type));
1729
1730    CXXMethodDecl *cxx_method_decl = NULL;
1731
1732    DeclarationName decl_name (&identifier_table->get(name));
1733
1734    const clang::FunctionType *function_Type = dyn_cast<FunctionType>(method_qual_type.getTypePtr());
1735
1736    if (function_Type == NULL)
1737        return NULL;
1738
1739    const FunctionProtoType *method_function_prototype (dyn_cast<FunctionProtoType>(function_Type));
1740
1741    if (!method_function_prototype)
1742        return NULL;
1743
1744    unsigned int num_params = method_function_prototype->getNumArgs();
1745
1746    CXXDestructorDecl *cxx_dtor_decl(NULL);
1747    CXXConstructorDecl *cxx_ctor_decl(NULL);
1748
1749    if (name[0] == '~')
1750    {
1751        cxx_dtor_decl = CXXDestructorDecl::Create (*ast,
1752                                                   cxx_record_decl,
1753                                                   SourceLocation(),
1754                                                   DeclarationNameInfo (ast->DeclarationNames.getCXXDestructorName (ast->getCanonicalType (record_qual_type)), SourceLocation()),
1755                                                   method_qual_type,
1756                                                   NULL,
1757                                                   is_inline,
1758                                                   is_artificial);
1759        cxx_method_decl = cxx_dtor_decl;
1760    }
1761    else if (decl_name == cxx_record_decl->getDeclName())
1762    {
1763       cxx_ctor_decl = CXXConstructorDecl::Create (*ast,
1764                                                   cxx_record_decl,
1765                                                   SourceLocation(),
1766                                                   DeclarationNameInfo (ast->DeclarationNames.getCXXConstructorName (ast->getCanonicalType (record_qual_type)), SourceLocation()),
1767                                                   method_qual_type,
1768                                                   NULL, // TypeSourceInfo *
1769                                                   is_explicit,
1770                                                   is_inline,
1771                                                   is_artificial,
1772                                                   false /*is_constexpr*/);
1773        cxx_method_decl = cxx_ctor_decl;
1774    }
1775    else
1776    {
1777
1778        OverloadedOperatorKind op_kind = NUM_OVERLOADED_OPERATORS;
1779        if (IsOperator (name, op_kind))
1780        {
1781            if (op_kind != NUM_OVERLOADED_OPERATORS)
1782            {
1783                // Check the number of operator parameters. Sometimes we have
1784                // seen bad DWARF that doesn't correctly describe operators and
1785                // if we try to create a methed and add it to the class, clang
1786                // will assert and crash, so we need to make sure things are
1787                // acceptable.
1788                if (!ClangASTContext::CheckOverloadedOperatorKindParameterCount (op_kind, num_params))
1789                    return NULL;
1790                cxx_method_decl = CXXMethodDecl::Create (*ast,
1791                                                         cxx_record_decl,
1792                                                         SourceLocation(),
1793                                                         DeclarationNameInfo (ast->DeclarationNames.getCXXOperatorName (op_kind), SourceLocation()),
1794                                                         method_qual_type,
1795                                                         NULL, // TypeSourceInfo *
1796                                                         is_static,
1797                                                         SC_None,
1798                                                         is_inline,
1799                                                         false /*is_constexpr*/,
1800                                                         SourceLocation());
1801            }
1802            else if (num_params == 0)
1803            {
1804                // Conversion operators don't take params...
1805                cxx_method_decl = CXXConversionDecl::Create (*ast,
1806                                                             cxx_record_decl,
1807                                                             SourceLocation(),
1808                                                             DeclarationNameInfo (ast->DeclarationNames.getCXXConversionFunctionName (ast->getCanonicalType (function_Type->getResultType())), SourceLocation()),
1809                                                             method_qual_type,
1810                                                             NULL, // TypeSourceInfo *
1811                                                             is_inline,
1812                                                             is_explicit,
1813                                                             false /*is_constexpr*/,
1814                                                             SourceLocation());
1815            }
1816        }
1817
1818        if (cxx_method_decl == NULL)
1819        {
1820            cxx_method_decl = CXXMethodDecl::Create (*ast,
1821                                                     cxx_record_decl,
1822                                                     SourceLocation(),
1823                                                     DeclarationNameInfo (decl_name, SourceLocation()),
1824                                                     method_qual_type,
1825                                                     NULL, // TypeSourceInfo *
1826                                                     is_static,
1827                                                     SC_None,
1828                                                     is_inline,
1829                                                     false /*is_constexpr*/,
1830                                                     SourceLocation());
1831        }
1832    }
1833
1834    AccessSpecifier access_specifier = ConvertAccessTypeToAccessSpecifier (access);
1835
1836    cxx_method_decl->setAccess (access_specifier);
1837    cxx_method_decl->setVirtualAsWritten (is_virtual);
1838
1839    if (is_attr_used)
1840        cxx_method_decl->addAttr(::new (*ast) UsedAttr(SourceRange(), *ast));
1841
1842    // Populate the method decl with parameter decls
1843
1844    llvm::SmallVector<ParmVarDecl *, 12> params;
1845
1846    for (int param_index = 0;
1847         param_index < num_params;
1848         ++param_index)
1849    {
1850        params.push_back (ParmVarDecl::Create (*ast,
1851                                               cxx_method_decl,
1852                                               SourceLocation(),
1853                                               SourceLocation(),
1854                                               NULL, // anonymous
1855                                               method_function_prototype->getArgType(param_index),
1856                                               NULL,
1857                                               SC_None,
1858                                               SC_None,
1859                                               NULL));
1860    }
1861
1862    cxx_method_decl->setParams (ArrayRef<ParmVarDecl*>(params));
1863
1864    cxx_record_decl->addDecl (cxx_method_decl);
1865
1866    // Sometimes the debug info will mention a constructor (default/copy/move),
1867    // destructor, or assignment operator (copy/move) but there won't be any
1868    // version of this in the code. So we check if the function was artificially
1869    // generated and if it is trivial and this lets the compiler/backend know
1870    // that it can inline the IR for these when it needs to and we can avoid a
1871    // "missing function" error when running expressions.
1872
1873    if (is_artificial)
1874    {
1875        if (cxx_ctor_decl &&
1876            ((cxx_ctor_decl->isDefaultConstructor() && cxx_record_decl->hasTrivialDefaultConstructor ()) ||
1877             (cxx_ctor_decl->isCopyConstructor()    && cxx_record_decl->hasTrivialCopyConstructor    ()) ||
1878             (cxx_ctor_decl->isMoveConstructor()    && cxx_record_decl->hasTrivialMoveConstructor    ()) ))
1879        {
1880            cxx_ctor_decl->setDefaulted();
1881            cxx_ctor_decl->setTrivial(true);
1882        }
1883        else if (cxx_dtor_decl)
1884        {
1885            if (cxx_record_decl->hasTrivialDestructor())
1886            {
1887                cxx_dtor_decl->setDefaulted();
1888                cxx_dtor_decl->setTrivial(true);
1889            }
1890        }
1891        else if ((cxx_method_decl->isCopyAssignmentOperator() && cxx_record_decl->hasTrivialCopyAssignment()) ||
1892                 (cxx_method_decl->isMoveAssignmentOperator() && cxx_record_decl->hasTrivialMoveAssignment()))
1893        {
1894            cxx_method_decl->setDefaulted();
1895            cxx_method_decl->setTrivial(true);
1896        }
1897    }
1898
1899#ifdef LLDB_CONFIGURATION_DEBUG
1900    VerifyDecl(cxx_method_decl);
1901#endif
1902
1903//    printf ("decl->isPolymorphic()             = %i\n", cxx_record_decl->isPolymorphic());
1904//    printf ("decl->isAggregate()               = %i\n", cxx_record_decl->isAggregate());
1905//    printf ("decl->isPOD()                     = %i\n", cxx_record_decl->isPOD());
1906//    printf ("decl->isEmpty()                   = %i\n", cxx_record_decl->isEmpty());
1907//    printf ("decl->isAbstract()                = %i\n", cxx_record_decl->isAbstract());
1908//    printf ("decl->hasTrivialConstructor()     = %i\n", cxx_record_decl->hasTrivialConstructor());
1909//    printf ("decl->hasTrivialCopyConstructor() = %i\n", cxx_record_decl->hasTrivialCopyConstructor());
1910//    printf ("decl->hasTrivialCopyAssignment()  = %i\n", cxx_record_decl->hasTrivialCopyAssignment());
1911//    printf ("decl->hasTrivialDestructor()      = %i\n", cxx_record_decl->hasTrivialDestructor());
1912    return cxx_method_decl;
1913}
1914
1915clang::FieldDecl *
1916ClangASTContext::AddFieldToRecordType
1917(
1918    ASTContext *ast,
1919    clang_type_t record_clang_type,
1920    const char *name,
1921    clang_type_t field_type,
1922    AccessType access,
1923    uint32_t bitfield_bit_size
1924)
1925{
1926    if (record_clang_type == NULL || field_type == NULL)
1927        return NULL;
1928
1929    FieldDecl *field = NULL;
1930    IdentifierTable *identifier_table = &ast->Idents;
1931
1932    assert (ast != NULL);
1933    assert (identifier_table != NULL);
1934
1935    QualType record_qual_type(QualType::getFromOpaquePtr(record_clang_type));
1936
1937    const clang::Type *clang_type = record_qual_type.getTypePtr();
1938    if (clang_type)
1939    {
1940        const RecordType *record_type = dyn_cast<RecordType>(clang_type);
1941
1942        if (record_type)
1943        {
1944            RecordDecl *record_decl = record_type->getDecl();
1945
1946            clang::Expr *bit_width = NULL;
1947            if (bitfield_bit_size != 0)
1948            {
1949                APInt bitfield_bit_size_apint(ast->getTypeSize(ast->IntTy), bitfield_bit_size);
1950                bit_width = new (*ast)IntegerLiteral (*ast, bitfield_bit_size_apint, ast->IntTy, SourceLocation());
1951            }
1952            field = FieldDecl::Create (*ast,
1953                                       record_decl,
1954                                       SourceLocation(),
1955                                       SourceLocation(),
1956                                       name ? &identifier_table->get(name) : NULL, // Identifier
1957                                       QualType::getFromOpaquePtr(field_type), // Field type
1958                                       NULL,            // TInfo *
1959                                       bit_width,       // BitWidth
1960                                       false,           // Mutable
1961                                       ICIS_NoInit);    // HasInit
1962
1963            if (!name) {
1964                // Determine whether this field corresponds to an anonymous
1965                // struct or union.
1966                if (const TagType *TagT = field->getType()->getAs<TagType>()) {
1967                  if (RecordDecl *Rec = dyn_cast<RecordDecl>(TagT->getDecl()))
1968                    if (!Rec->getDeclName()) {
1969                      Rec->setAnonymousStructOrUnion(true);
1970                      field->setImplicit();
1971
1972                    }
1973                }
1974            }
1975
1976            field->setAccess (ConvertAccessTypeToAccessSpecifier (access));
1977
1978            if (field)
1979            {
1980                record_decl->addDecl(field);
1981
1982#ifdef LLDB_CONFIGURATION_DEBUG
1983                VerifyDecl(field);
1984#endif
1985            }
1986        }
1987        else
1988        {
1989            const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(clang_type);
1990            if (objc_class_type)
1991            {
1992                bool is_synthesized = false;
1993                field = ClangASTContext::AddObjCClassIVar (ast,
1994                                                   record_clang_type,
1995                                                   name,
1996                                                   field_type,
1997                                                   access,
1998                                                   bitfield_bit_size,
1999                                                   is_synthesized);
2000            }
2001        }
2002    }
2003    return field;
2004}
2005
2006static clang::AccessSpecifier UnifyAccessSpecifiers (clang::AccessSpecifier lhs,
2007                                                     clang::AccessSpecifier rhs)
2008{
2009    clang::AccessSpecifier ret = lhs;
2010
2011    // Make the access equal to the stricter of the field and the nested field's access
2012    switch (ret)
2013    {
2014        case clang::AS_none:
2015            break;
2016        case clang::AS_private:
2017            break;
2018        case clang::AS_protected:
2019            if (rhs == AS_private)
2020                ret = AS_private;
2021            break;
2022        case clang::AS_public:
2023            ret = rhs;
2024            break;
2025    }
2026
2027    return ret;
2028}
2029
2030void
2031ClangASTContext::BuildIndirectFields (clang::ASTContext *ast,
2032                                      lldb::clang_type_t record_clang_type)
2033{
2034    QualType record_qual_type(QualType::getFromOpaquePtr(record_clang_type));
2035
2036    const RecordType *record_type = record_qual_type->getAs<RecordType>();
2037
2038    if (!record_type)
2039        return;
2040
2041    RecordDecl *record_decl = record_type->getDecl();
2042
2043    if (!record_decl)
2044        return;
2045
2046    typedef llvm::SmallVector <IndirectFieldDecl *, 1> IndirectFieldVector;
2047
2048    IndirectFieldVector indirect_fields;
2049    RecordDecl::field_iterator field_pos;
2050    RecordDecl::field_iterator field_end_pos = record_decl->field_end();
2051    RecordDecl::field_iterator last_field_pos = field_end_pos;
2052    for (field_pos = record_decl->field_begin(); field_pos != field_end_pos; last_field_pos = field_pos++)
2053    {
2054        if (field_pos->isAnonymousStructOrUnion())
2055        {
2056            QualType field_qual_type = field_pos->getType();
2057
2058            const RecordType *field_record_type = field_qual_type->getAs<RecordType>();
2059
2060            if (!field_record_type)
2061                continue;
2062
2063            RecordDecl *field_record_decl = field_record_type->getDecl();
2064
2065            if (!field_record_decl)
2066                continue;
2067
2068            for (RecordDecl::decl_iterator di = field_record_decl->decls_begin(), de = field_record_decl->decls_end();
2069                 di != de;
2070                 ++di)
2071            {
2072                if (FieldDecl *nested_field_decl = dyn_cast<FieldDecl>(*di))
2073                {
2074                    NamedDecl **chain = new (*ast) NamedDecl*[2];
2075                    chain[0] = *field_pos;
2076                    chain[1] = nested_field_decl;
2077                    IndirectFieldDecl *indirect_field = IndirectFieldDecl::Create(*ast,
2078                                                                                  record_decl,
2079                                                                                  SourceLocation(),
2080                                                                                  nested_field_decl->getIdentifier(),
2081                                                                                  nested_field_decl->getType(),
2082                                                                                  chain,
2083                                                                                  2);
2084
2085                    indirect_field->setAccess(UnifyAccessSpecifiers(field_pos->getAccess(),
2086                                                                    nested_field_decl->getAccess()));
2087
2088                    indirect_fields.push_back(indirect_field);
2089                }
2090                else if (IndirectFieldDecl *nested_indirect_field_decl = dyn_cast<IndirectFieldDecl>(*di))
2091                {
2092                    int nested_chain_size = nested_indirect_field_decl->getChainingSize();
2093                    NamedDecl **chain = new (*ast) NamedDecl*[nested_chain_size + 1];
2094                    chain[0] = *field_pos;
2095
2096                    int chain_index = 1;
2097                    for (IndirectFieldDecl::chain_iterator nci = nested_indirect_field_decl->chain_begin(),
2098                         nce = nested_indirect_field_decl->chain_end();
2099                         nci < nce;
2100                         ++nci)
2101                    {
2102                        chain[chain_index] = *nci;
2103                        chain_index++;
2104                    }
2105
2106                    IndirectFieldDecl *indirect_field = IndirectFieldDecl::Create(*ast,
2107                                                                                  record_decl,
2108                                                                                  SourceLocation(),
2109                                                                                  nested_indirect_field_decl->getIdentifier(),
2110                                                                                  nested_indirect_field_decl->getType(),
2111                                                                                  chain,
2112                                                                                  nested_chain_size + 1);
2113
2114                    indirect_field->setAccess(UnifyAccessSpecifiers(field_pos->getAccess(),
2115                                                                    nested_indirect_field_decl->getAccess()));
2116
2117                    indirect_fields.push_back(indirect_field);
2118                }
2119            }
2120        }
2121    }
2122
2123    // Check the last field to see if it has an incomplete array type as its
2124    // last member and if it does, the tell the record decl about it
2125    if (last_field_pos != field_end_pos)
2126    {
2127        if (last_field_pos->getType()->isIncompleteArrayType())
2128            record_decl->hasFlexibleArrayMember();
2129    }
2130
2131    for (IndirectFieldVector::iterator ifi = indirect_fields.begin(), ife = indirect_fields.end();
2132         ifi < ife;
2133         ++ifi)
2134    {
2135        record_decl->addDecl(*ifi);
2136    }
2137}
2138
2139bool
2140ClangASTContext::FieldIsBitfield (FieldDecl* field, uint32_t& bitfield_bit_size)
2141{
2142    return FieldIsBitfield(getASTContext(), field, bitfield_bit_size);
2143}
2144
2145bool
2146ClangASTContext::FieldIsBitfield
2147(
2148    ASTContext *ast,
2149    FieldDecl* field,
2150    uint32_t& bitfield_bit_size
2151)
2152{
2153    if (ast == NULL || field == NULL)
2154        return false;
2155
2156    if (field->isBitField())
2157    {
2158        Expr* bit_width_expr = field->getBitWidth();
2159        if (bit_width_expr)
2160        {
2161            llvm::APSInt bit_width_apsint;
2162            if (bit_width_expr->isIntegerConstantExpr(bit_width_apsint, *ast))
2163            {
2164                bitfield_bit_size = bit_width_apsint.getLimitedValue(UINT32_MAX);
2165                return true;
2166            }
2167        }
2168    }
2169    return false;
2170}
2171
2172bool
2173ClangASTContext::RecordHasFields (const RecordDecl *record_decl)
2174{
2175    if (record_decl == NULL)
2176        return false;
2177
2178    if (!record_decl->field_empty())
2179        return true;
2180
2181    // No fields, lets check this is a CXX record and check the base classes
2182    const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
2183    if (cxx_record_decl)
2184    {
2185        CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
2186        for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
2187             base_class != base_class_end;
2188             ++base_class)
2189        {
2190            const CXXRecordDecl *base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
2191            if (RecordHasFields(base_class_decl))
2192                return true;
2193        }
2194    }
2195    return false;
2196}
2197
2198void
2199ClangASTContext::SetDefaultAccessForRecordFields (clang_type_t clang_type, int default_accessibility, int *assigned_accessibilities, size_t num_assigned_accessibilities)
2200{
2201    if (clang_type)
2202    {
2203        QualType qual_type(QualType::getFromOpaquePtr(clang_type));
2204
2205        const RecordType *record_type = dyn_cast<RecordType>(qual_type.getTypePtr());
2206        if (record_type)
2207        {
2208            RecordDecl *record_decl = record_type->getDecl();
2209            if (record_decl)
2210            {
2211                uint32_t field_idx;
2212                RecordDecl::field_iterator field, field_end;
2213                for (field = record_decl->field_begin(), field_end = record_decl->field_end(), field_idx = 0;
2214                     field != field_end;
2215                     ++field, ++field_idx)
2216                {
2217                    // If no accessibility was assigned, assign the correct one
2218                    if (field_idx < num_assigned_accessibilities && assigned_accessibilities[field_idx] == clang::AS_none)
2219                        field->setAccess ((AccessSpecifier)default_accessibility);
2220                }
2221            }
2222        }
2223    }
2224}
2225
2226#pragma mark C++ Base Classes
2227
2228CXXBaseSpecifier *
2229ClangASTContext::CreateBaseClassSpecifier (clang_type_t base_class_type, AccessType access, bool is_virtual, bool base_of_class)
2230{
2231    if (base_class_type)
2232        return new CXXBaseSpecifier (SourceRange(),
2233                                     is_virtual,
2234                                     base_of_class,
2235                                     ConvertAccessTypeToAccessSpecifier (access),
2236                                     getASTContext()->CreateTypeSourceInfo (QualType::getFromOpaquePtr(base_class_type)),
2237                                     SourceLocation());
2238    return NULL;
2239}
2240
2241void
2242ClangASTContext::DeleteBaseClassSpecifiers (CXXBaseSpecifier **base_classes, unsigned num_base_classes)
2243{
2244    for (unsigned i=0; i<num_base_classes; ++i)
2245    {
2246        delete base_classes[i];
2247        base_classes[i] = NULL;
2248    }
2249}
2250
2251bool
2252ClangASTContext::SetBaseClassesForClassType (clang_type_t class_clang_type, CXXBaseSpecifier const * const *base_classes, unsigned num_base_classes)
2253{
2254    if (class_clang_type)
2255    {
2256        CXXRecordDecl *cxx_record_decl = QualType::getFromOpaquePtr(class_clang_type)->getAsCXXRecordDecl();
2257        if (cxx_record_decl)
2258        {
2259            cxx_record_decl->setBases(base_classes, num_base_classes);
2260            return true;
2261        }
2262    }
2263    return false;
2264}
2265#pragma mark Objective C Classes
2266
2267clang_type_t
2268ClangASTContext::CreateObjCClass
2269(
2270    const char *name,
2271    DeclContext *decl_ctx,
2272    bool isForwardDecl,
2273    bool isInternal,
2274    ClangASTMetadata *metadata
2275)
2276{
2277    ASTContext *ast = getASTContext();
2278    assert (ast != NULL);
2279    assert (name && name[0]);
2280    if (decl_ctx == NULL)
2281        decl_ctx = ast->getTranslationUnitDecl();
2282
2283    // NOTE: Eventually CXXRecordDecl will be merged back into RecordDecl and
2284    // we will need to update this code. I was told to currently always use
2285    // the CXXRecordDecl class since we often don't know from debug information
2286    // if something is struct or a class, so we default to always use the more
2287    // complete definition just in case.
2288    ObjCInterfaceDecl *decl = ObjCInterfaceDecl::Create (*ast,
2289                                                         decl_ctx,
2290                                                         SourceLocation(),
2291                                                         &ast->Idents.get(name),
2292                                                         NULL,
2293                                                         SourceLocation(),
2294                                                         /*isForwardDecl,*/
2295                                                         isInternal);
2296
2297    if (decl && metadata)
2298        SetMetadata(ast, (uintptr_t)decl, *metadata);
2299
2300    return ast->getObjCInterfaceType(decl).getAsOpaquePtr();
2301}
2302
2303bool
2304ClangASTContext::SetObjCSuperClass (clang_type_t class_opaque_type, clang_type_t super_opaque_type)
2305{
2306    if (class_opaque_type && super_opaque_type)
2307    {
2308        QualType class_qual_type(QualType::getFromOpaquePtr(class_opaque_type));
2309        QualType super_qual_type(QualType::getFromOpaquePtr(super_opaque_type));
2310        const clang::Type *class_type = class_qual_type.getTypePtr();
2311        const clang::Type *super_type = super_qual_type.getTypePtr();
2312        if (class_type && super_type)
2313        {
2314            const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(class_type);
2315            const ObjCObjectType *objc_super_type = dyn_cast<ObjCObjectType>(super_type);
2316            if (objc_class_type && objc_super_type)
2317            {
2318                ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
2319                ObjCInterfaceDecl *super_interface_decl = objc_super_type->getInterface();
2320                if (class_interface_decl && super_interface_decl)
2321                {
2322                    class_interface_decl->setSuperClass(super_interface_decl);
2323                    return true;
2324                }
2325            }
2326        }
2327    }
2328    return false;
2329}
2330
2331
2332FieldDecl *
2333ClangASTContext::AddObjCClassIVar
2334(
2335    ASTContext *ast,
2336    clang_type_t class_opaque_type,
2337    const char *name,
2338    clang_type_t ivar_opaque_type,
2339    AccessType access,
2340    uint32_t bitfield_bit_size,
2341    bool is_synthesized
2342)
2343{
2344    if (class_opaque_type == NULL || ivar_opaque_type == NULL)
2345        return NULL;
2346
2347    ObjCIvarDecl *field = NULL;
2348
2349    IdentifierTable *identifier_table = &ast->Idents;
2350
2351    assert (ast != NULL);
2352    assert (identifier_table != NULL);
2353
2354    QualType class_qual_type(QualType::getFromOpaquePtr(class_opaque_type));
2355
2356    const clang::Type *class_type = class_qual_type.getTypePtr();
2357    if (class_type)
2358    {
2359        const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(class_type);
2360
2361        if (objc_class_type)
2362        {
2363            ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
2364
2365            if (class_interface_decl)
2366            {
2367                clang::Expr *bit_width = NULL;
2368                if (bitfield_bit_size != 0)
2369                {
2370                    APInt bitfield_bit_size_apint(ast->getTypeSize(ast->IntTy), bitfield_bit_size);
2371                    bit_width = new (*ast)IntegerLiteral (*ast, bitfield_bit_size_apint, ast->IntTy, SourceLocation());
2372                }
2373
2374                field = ObjCIvarDecl::Create (*ast,
2375                                              class_interface_decl,
2376                                              SourceLocation(),
2377                                              SourceLocation(),
2378                                              name ? &identifier_table->get(name) : NULL, // Identifier
2379                                              QualType::getFromOpaquePtr(ivar_opaque_type), // Field type
2380                                              NULL, // TypeSourceInfo *
2381                                              ConvertAccessTypeToObjCIvarAccessControl (access),
2382                                              bit_width,
2383                                              is_synthesized);
2384
2385                if (field)
2386                {
2387                    class_interface_decl->addDecl(field);
2388
2389#ifdef LLDB_CONFIGURATION_DEBUG
2390                    VerifyDecl(field);
2391#endif
2392
2393                    return field;
2394                }
2395            }
2396        }
2397    }
2398    return NULL;
2399}
2400
2401bool
2402ClangASTContext::AddObjCClassProperty
2403(
2404    ASTContext *ast,
2405    clang_type_t class_opaque_type,
2406    const char *property_name,
2407    clang_type_t property_opaque_type,
2408    ObjCIvarDecl *ivar_decl,
2409    const char *property_setter_name,
2410    const char *property_getter_name,
2411    uint32_t property_attributes,
2412    ClangASTMetadata *metadata
2413)
2414{
2415    if (class_opaque_type == NULL || property_name == NULL || property_name[0] == '\0')
2416        return false;
2417
2418    IdentifierTable *identifier_table = &ast->Idents;
2419
2420    assert (ast != NULL);
2421    assert (identifier_table != NULL);
2422
2423    QualType class_qual_type(QualType::getFromOpaquePtr(class_opaque_type));
2424    const clang::Type *class_type = class_qual_type.getTypePtr();
2425    if (class_type)
2426    {
2427        const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(class_type);
2428
2429        if (objc_class_type)
2430        {
2431            ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
2432
2433            clang_type_t property_opaque_type_to_access = NULL;
2434
2435            if (property_opaque_type)
2436                property_opaque_type_to_access = property_opaque_type;
2437            else if (ivar_decl)
2438                property_opaque_type_to_access = ivar_decl->getType().getAsOpaquePtr();
2439
2440            if (class_interface_decl && property_opaque_type_to_access)
2441            {
2442                clang::TypeSourceInfo *prop_type_source;
2443                if (ivar_decl)
2444                    prop_type_source = ast->CreateTypeSourceInfo (ivar_decl->getType());
2445                else
2446                    prop_type_source = ast->CreateTypeSourceInfo (QualType::getFromOpaquePtr(property_opaque_type));
2447
2448                ObjCPropertyDecl *property_decl = ObjCPropertyDecl::Create(*ast,
2449                                                                           class_interface_decl,
2450                                                                           SourceLocation(), // Source Location
2451                                                                           &identifier_table->get(property_name),
2452                                                                           SourceLocation(), //Source Location for AT
2453                                                                           SourceLocation(), //Source location for (
2454                                                                           prop_type_source
2455                                                                           );
2456
2457                if (property_decl)
2458                {
2459                    if (metadata)
2460                        SetMetadata(ast, (uintptr_t)property_decl, *metadata);
2461
2462                    class_interface_decl->addDecl (property_decl);
2463
2464                    Selector setter_sel, getter_sel;
2465
2466                    if (property_setter_name != NULL)
2467                    {
2468                        std::string property_setter_no_colon(property_setter_name, strlen(property_setter_name) - 1);
2469                        clang::IdentifierInfo *setter_ident = &identifier_table->get(property_setter_no_colon.c_str());
2470                        setter_sel = ast->Selectors.getSelector(1, &setter_ident);
2471                    }
2472                    else if (!(property_attributes & DW_APPLE_PROPERTY_readonly))
2473                    {
2474                        std::string setter_sel_string("set");
2475                        setter_sel_string.push_back(::toupper(property_name[0]));
2476                        setter_sel_string.append(&property_name[1]);
2477                        clang::IdentifierInfo *setter_ident = &identifier_table->get(setter_sel_string.c_str());
2478                        setter_sel = ast->Selectors.getSelector(1, &setter_ident);
2479                    }
2480                    property_decl->setSetterName(setter_sel);
2481                    property_decl->setPropertyAttributes (clang::ObjCPropertyDecl::OBJC_PR_setter);
2482
2483                    if (property_getter_name != NULL)
2484                    {
2485                        clang::IdentifierInfo *getter_ident = &identifier_table->get(property_getter_name);
2486                        getter_sel = ast->Selectors.getSelector(0, &getter_ident);
2487                    }
2488                    else
2489                    {
2490                        clang::IdentifierInfo *getter_ident = &identifier_table->get(property_name);
2491                        getter_sel = ast->Selectors.getSelector(0, &getter_ident);
2492                    }
2493                    property_decl->setGetterName(getter_sel);
2494                    property_decl->setPropertyAttributes (clang::ObjCPropertyDecl::OBJC_PR_getter);
2495
2496                    if (ivar_decl)
2497                        property_decl->setPropertyIvarDecl (ivar_decl);
2498
2499                    if (property_attributes & DW_APPLE_PROPERTY_readonly)
2500                        property_decl->setPropertyAttributes (clang::ObjCPropertyDecl::OBJC_PR_readonly);
2501                    if (property_attributes & DW_APPLE_PROPERTY_readwrite)
2502                        property_decl->setPropertyAttributes (clang::ObjCPropertyDecl::OBJC_PR_readwrite);
2503                    if (property_attributes & DW_APPLE_PROPERTY_assign)
2504                        property_decl->setPropertyAttributes (clang::ObjCPropertyDecl::OBJC_PR_assign);
2505                    if (property_attributes & DW_APPLE_PROPERTY_retain)
2506                        property_decl->setPropertyAttributes (clang::ObjCPropertyDecl::OBJC_PR_retain);
2507                    if (property_attributes & DW_APPLE_PROPERTY_copy)
2508                        property_decl->setPropertyAttributes (clang::ObjCPropertyDecl::OBJC_PR_copy);
2509                    if (property_attributes & DW_APPLE_PROPERTY_nonatomic)
2510                        property_decl->setPropertyAttributes (clang::ObjCPropertyDecl::OBJC_PR_nonatomic);
2511
2512                    if (!getter_sel.isNull() && !class_interface_decl->lookupInstanceMethod(getter_sel))
2513                    {
2514                        QualType result_type = QualType::getFromOpaquePtr(property_opaque_type_to_access);
2515
2516                        const bool isInstance = true;
2517                        const bool isVariadic = false;
2518                        const bool isSynthesized = false;
2519                        const bool isImplicitlyDeclared = true;
2520                        const bool isDefined = false;
2521                        const ObjCMethodDecl::ImplementationControl impControl = ObjCMethodDecl::None;
2522                        const bool HasRelatedResultType = false;
2523
2524                        ObjCMethodDecl *getter = ObjCMethodDecl::Create(*ast,
2525                                                                        SourceLocation(),
2526                                                                        SourceLocation(),
2527                                                                        getter_sel,
2528                                                                        result_type,
2529                                                                        NULL,
2530                                                                        class_interface_decl,
2531                                                                        isInstance,
2532                                                                        isVariadic,
2533                                                                        isSynthesized,
2534                                                                        isImplicitlyDeclared,
2535                                                                        isDefined,
2536                                                                        impControl,
2537                                                                        HasRelatedResultType);
2538
2539                        if (getter && metadata)
2540                            SetMetadata(ast, (uintptr_t)getter, *metadata);
2541
2542                        getter->setMethodParams(*ast, ArrayRef<ParmVarDecl*>(), ArrayRef<SourceLocation>());
2543
2544                        class_interface_decl->addDecl(getter);
2545                    }
2546
2547                    if (!setter_sel.isNull() && !class_interface_decl->lookupInstanceMethod(setter_sel))
2548                    {
2549                        QualType result_type = ast->VoidTy;
2550
2551                        const bool isInstance = true;
2552                        const bool isVariadic = false;
2553                        const bool isSynthesized = false;
2554                        const bool isImplicitlyDeclared = true;
2555                        const bool isDefined = false;
2556                        const ObjCMethodDecl::ImplementationControl impControl = ObjCMethodDecl::None;
2557                        const bool HasRelatedResultType = false;
2558
2559                        ObjCMethodDecl *setter = ObjCMethodDecl::Create(*ast,
2560                                                                        SourceLocation(),
2561                                                                        SourceLocation(),
2562                                                                        setter_sel,
2563                                                                        result_type,
2564                                                                        NULL,
2565                                                                        class_interface_decl,
2566                                                                        isInstance,
2567                                                                        isVariadic,
2568                                                                        isSynthesized,
2569                                                                        isImplicitlyDeclared,
2570                                                                        isDefined,
2571                                                                        impControl,
2572                                                                        HasRelatedResultType);
2573
2574                        if (setter && metadata)
2575                            SetMetadata(ast, (uintptr_t)setter, *metadata);
2576
2577                        llvm::SmallVector<ParmVarDecl *, 1> params;
2578
2579                        params.push_back (ParmVarDecl::Create (*ast,
2580                                                               setter,
2581                                                               SourceLocation(),
2582                                                               SourceLocation(),
2583                                                               NULL, // anonymous
2584                                                               QualType::getFromOpaquePtr(property_opaque_type_to_access),
2585                                                               NULL,
2586                                                               SC_Auto,
2587                                                               SC_Auto,
2588                                                               NULL));
2589
2590                        setter->setMethodParams(*ast, ArrayRef<ParmVarDecl*>(params), ArrayRef<SourceLocation>());
2591
2592                        class_interface_decl->addDecl(setter);
2593                    }
2594
2595                    return true;
2596                }
2597            }
2598        }
2599    }
2600    return false;
2601}
2602
2603bool
2604ClangASTContext::ObjCTypeHasIVars (clang_type_t class_opaque_type, bool check_superclass)
2605{
2606    QualType class_qual_type(QualType::getFromOpaquePtr(class_opaque_type));
2607
2608    const clang::Type *class_type = class_qual_type.getTypePtr();
2609    if (class_type)
2610    {
2611        const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(class_type);
2612
2613        if (objc_class_type)
2614            return ObjCDeclHasIVars (objc_class_type->getInterface(), check_superclass);
2615    }
2616    return false;
2617}
2618
2619bool
2620ClangASTContext::ObjCDeclHasIVars (ObjCInterfaceDecl *class_interface_decl, bool check_superclass)
2621{
2622    while (class_interface_decl)
2623    {
2624        if (class_interface_decl->ivar_size() > 0)
2625            return true;
2626
2627        if (check_superclass)
2628            class_interface_decl = class_interface_decl->getSuperClass();
2629        else
2630            break;
2631    }
2632    return false;
2633}
2634
2635ObjCMethodDecl *
2636ClangASTContext::AddMethodToObjCObjectType
2637(
2638    ASTContext *ast,
2639    clang_type_t class_opaque_type,
2640    const char *name,  // the full symbol name as seen in the symbol table ("-[NString stringWithCString:]")
2641    clang_type_t method_opaque_type,
2642    lldb::AccessType access
2643)
2644{
2645    if (class_opaque_type == NULL || method_opaque_type == NULL)
2646        return NULL;
2647
2648    IdentifierTable *identifier_table = &ast->Idents;
2649
2650    assert (ast != NULL);
2651    assert (identifier_table != NULL);
2652
2653    QualType class_qual_type(QualType::getFromOpaquePtr(class_opaque_type));
2654
2655    const clang::Type *class_type = class_qual_type.getTypePtr();
2656    if (class_type == NULL)
2657        return NULL;
2658
2659    const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(class_type);
2660
2661    if (objc_class_type == NULL)
2662        return NULL;
2663
2664    ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
2665
2666    if (class_interface_decl == NULL)
2667        return NULL;
2668
2669    const char *selector_start = ::strchr (name, ' ');
2670    if (selector_start == NULL)
2671        return NULL;
2672
2673    selector_start++;
2674    if (!(::isalpha (selector_start[0]) || selector_start[0] == '_'))
2675        return NULL;
2676    llvm::SmallVector<IdentifierInfo *, 12> selector_idents;
2677
2678    size_t len = 0;
2679    const char *start;
2680    //printf ("name = '%s'\n", name);
2681
2682    unsigned num_selectors_with_args = 0;
2683    for (start = selector_start;
2684         start && *start != '\0' && *start != ']';
2685         start += len)
2686    {
2687        len = ::strcspn(start, ":]");
2688        bool has_arg = (start[len] == ':');
2689        if (has_arg)
2690            ++num_selectors_with_args;
2691        selector_idents.push_back (&identifier_table->get (StringRef (start, len)));
2692        if (has_arg)
2693            len += 1;
2694    }
2695
2696
2697    if (selector_idents.size() == 0)
2698        return 0;
2699
2700    clang::Selector method_selector = ast->Selectors.getSelector (num_selectors_with_args ? selector_idents.size() : 0,
2701                                                                          selector_idents.data());
2702
2703    QualType method_qual_type (QualType::getFromOpaquePtr (method_opaque_type));
2704
2705    // Populate the method decl with parameter decls
2706    const clang::Type *method_type(method_qual_type.getTypePtr());
2707
2708    if (method_type == NULL)
2709        return NULL;
2710
2711    const FunctionProtoType *method_function_prototype (dyn_cast<FunctionProtoType>(method_type));
2712
2713    if (!method_function_prototype)
2714        return NULL;
2715
2716
2717    bool is_variadic = false;
2718    bool is_synthesized = false;
2719    bool is_defined = false;
2720    ObjCMethodDecl::ImplementationControl imp_control = ObjCMethodDecl::None;
2721
2722    const unsigned num_args = method_function_prototype->getNumArgs();
2723
2724    ObjCMethodDecl *objc_method_decl = ObjCMethodDecl::Create (*ast,
2725                                                               SourceLocation(), // beginLoc,
2726                                                               SourceLocation(), // endLoc,
2727                                                               method_selector,
2728                                                               method_function_prototype->getResultType(),
2729                                                               NULL, // TypeSourceInfo *ResultTInfo,
2730                                                               GetDeclContextForType (class_opaque_type),
2731                                                               name[0] == '-',
2732                                                               is_variadic,
2733                                                               is_synthesized,
2734                                                               true, // is_implicitly_declared
2735                                                               is_defined,
2736                                                               imp_control,
2737                                                               false /*has_related_result_type*/);
2738
2739
2740    if (objc_method_decl == NULL)
2741        return NULL;
2742
2743    if (num_args > 0)
2744    {
2745        llvm::SmallVector<ParmVarDecl *, 12> params;
2746
2747        for (int param_index = 0; param_index < num_args; ++param_index)
2748        {
2749            params.push_back (ParmVarDecl::Create (*ast,
2750                                                   objc_method_decl,
2751                                                   SourceLocation(),
2752                                                   SourceLocation(),
2753                                                   NULL, // anonymous
2754                                                   method_function_prototype->getArgType(param_index),
2755                                                   NULL,
2756                                                   SC_Auto,
2757                                                   SC_Auto,
2758                                                   NULL));
2759        }
2760
2761        objc_method_decl->setMethodParams(*ast, ArrayRef<ParmVarDecl*>(params), ArrayRef<SourceLocation>());
2762    }
2763
2764    class_interface_decl->addDecl (objc_method_decl);
2765
2766#ifdef LLDB_CONFIGURATION_DEBUG
2767    VerifyDecl(objc_method_decl);
2768#endif
2769
2770    return objc_method_decl;
2771}
2772
2773size_t
2774ClangASTContext::GetNumTemplateArguments (clang::ASTContext *ast, clang_type_t clang_type)
2775{
2776    if (clang_type)
2777    {
2778        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
2779
2780        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2781        switch (type_class)
2782        {
2783            case clang::Type::Record:
2784                if (GetCompleteQualType (ast, qual_type))
2785                {
2786                    const CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
2787                    if (cxx_record_decl)
2788                    {
2789                        const ClassTemplateSpecializationDecl *template_decl = dyn_cast<ClassTemplateSpecializationDecl>(cxx_record_decl);
2790                        if (template_decl)
2791                            return template_decl->getTemplateArgs().size();
2792                    }
2793                }
2794                break;
2795
2796            case clang::Type::Typedef:
2797                return ClangASTContext::GetNumTemplateArguments (ast, cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
2798
2799            case clang::Type::Elaborated:
2800                return ClangASTContext::GetNumTemplateArguments (ast, cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
2801
2802            default:
2803                break;
2804        }
2805    }
2806    return 0;
2807}
2808
2809clang_type_t
2810ClangASTContext::GetTemplateArgument (clang::ASTContext *ast, clang_type_t clang_type, size_t arg_idx, lldb::TemplateArgumentKind &kind)
2811{
2812    if (clang_type)
2813    {
2814        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
2815
2816        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2817        switch (type_class)
2818        {
2819            case clang::Type::Record:
2820                if (GetCompleteQualType (ast, qual_type))
2821                {
2822                    const CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
2823                    if (cxx_record_decl)
2824                    {
2825                        const ClassTemplateSpecializationDecl *template_decl = dyn_cast<ClassTemplateSpecializationDecl>(cxx_record_decl);
2826                        if (template_decl && arg_idx < template_decl->getTemplateArgs().size())
2827                        {
2828                            const TemplateArgument &template_arg = template_decl->getTemplateArgs()[arg_idx];
2829                            switch (template_arg.getKind())
2830                            {
2831                                case clang::TemplateArgument::Null:
2832                                    kind = eTemplateArgumentKindNull;
2833                                    return NULL;
2834
2835                                case clang::TemplateArgument::Type:
2836                                    kind = eTemplateArgumentKindType;
2837                                    return template_arg.getAsType().getAsOpaquePtr();
2838
2839                                case clang::TemplateArgument::Declaration:
2840                                    kind = eTemplateArgumentKindDeclaration;
2841                                    return NULL;
2842
2843                                case clang::TemplateArgument::Integral:
2844                                    kind = eTemplateArgumentKindIntegral;
2845                                    return template_arg.getIntegralType().getAsOpaquePtr();
2846
2847                                case clang::TemplateArgument::Template:
2848                                    kind = eTemplateArgumentKindTemplate;
2849                                    return NULL;
2850
2851                                case clang::TemplateArgument::TemplateExpansion:
2852                                    kind = eTemplateArgumentKindTemplateExpansion;
2853                                    return NULL;
2854
2855                                case clang::TemplateArgument::Expression:
2856                                    kind = eTemplateArgumentKindExpression;
2857                                    return NULL;
2858
2859                                case clang::TemplateArgument::Pack:
2860                                    kind = eTemplateArgumentKindPack;
2861                                    return NULL;
2862
2863                                default:
2864                                    assert (!"Unhandled TemplateArgument::ArgKind");
2865                                    kind = eTemplateArgumentKindNull;
2866                                    return NULL;
2867                            }
2868                        }
2869                    }
2870                }
2871                break;
2872
2873            case clang::Type::Typedef:
2874                return ClangASTContext::GetTemplateArgument (ast, cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(), arg_idx, kind);
2875
2876            case clang::Type::Elaborated:
2877                return ClangASTContext::GetTemplateArgument (ast, cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(), arg_idx, kind);
2878
2879            default:
2880                break;
2881        }
2882    }
2883    kind = eTemplateArgumentKindNull;
2884    return NULL;
2885}
2886
2887uint32_t
2888ClangASTContext::GetTypeInfo
2889(
2890    clang_type_t clang_type,
2891    clang::ASTContext *ast,
2892    clang_type_t *pointee_or_element_clang_type
2893)
2894{
2895    if (clang_type == NULL)
2896        return 0;
2897
2898    if (pointee_or_element_clang_type)
2899        *pointee_or_element_clang_type = NULL;
2900
2901    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
2902
2903    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2904    switch (type_class)
2905    {
2906    case clang::Type::Builtin:
2907        switch (cast<clang::BuiltinType>(qual_type)->getKind())
2908        {
2909        case clang::BuiltinType::ObjCId:
2910        case clang::BuiltinType::ObjCClass:
2911            if (ast && pointee_or_element_clang_type)
2912                *pointee_or_element_clang_type = ast->ObjCBuiltinClassTy.getAsOpaquePtr();
2913            return eTypeIsBuiltIn | eTypeIsPointer | eTypeHasValue;
2914                break;
2915        case clang::BuiltinType::Bool:
2916        case clang::BuiltinType::Char_U:
2917        case clang::BuiltinType::UChar:
2918        case clang::BuiltinType::WChar_U:
2919        case clang::BuiltinType::Char16:
2920        case clang::BuiltinType::Char32:
2921        case clang::BuiltinType::UShort:
2922        case clang::BuiltinType::UInt:
2923        case clang::BuiltinType::ULong:
2924        case clang::BuiltinType::ULongLong:
2925        case clang::BuiltinType::UInt128:
2926        case clang::BuiltinType::Char_S:
2927        case clang::BuiltinType::SChar:
2928        case clang::BuiltinType::WChar_S:
2929        case clang::BuiltinType::Short:
2930        case clang::BuiltinType::Int:
2931        case clang::BuiltinType::Long:
2932        case clang::BuiltinType::LongLong:
2933        case clang::BuiltinType::Int128:
2934        case clang::BuiltinType::Float:
2935        case clang::BuiltinType::Double:
2936        case clang::BuiltinType::LongDouble:
2937                return eTypeIsBuiltIn | eTypeHasValue | eTypeIsScalar;
2938        default:
2939            break;
2940        }
2941        return eTypeIsBuiltIn | eTypeHasValue;
2942
2943    case clang::Type::BlockPointer:
2944        if (pointee_or_element_clang_type)
2945            *pointee_or_element_clang_type = qual_type->getPointeeType().getAsOpaquePtr();
2946        return eTypeIsPointer | eTypeHasChildren | eTypeIsBlock;
2947
2948    case clang::Type::Complex:                          return eTypeIsBuiltIn | eTypeHasValue;
2949
2950    case clang::Type::ConstantArray:
2951    case clang::Type::DependentSizedArray:
2952    case clang::Type::IncompleteArray:
2953    case clang::Type::VariableArray:
2954        if (pointee_or_element_clang_type)
2955            *pointee_or_element_clang_type = cast<ArrayType>(qual_type.getTypePtr())->getElementType().getAsOpaquePtr();
2956        return eTypeHasChildren | eTypeIsArray;
2957
2958    case clang::Type::DependentName:                    return 0;
2959    case clang::Type::DependentSizedExtVector:          return eTypeHasChildren | eTypeIsVector;
2960    case clang::Type::DependentTemplateSpecialization:  return eTypeIsTemplate;
2961    case clang::Type::Decltype:                         return 0;
2962
2963    case clang::Type::Enum:
2964        if (pointee_or_element_clang_type)
2965            *pointee_or_element_clang_type = cast<EnumType>(qual_type)->getDecl()->getIntegerType().getAsOpaquePtr();
2966        return eTypeIsEnumeration | eTypeHasValue;
2967
2968    case clang::Type::Elaborated:
2969        return ClangASTContext::GetTypeInfo (cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(),
2970                                             ast,
2971                                             pointee_or_element_clang_type);
2972    case clang::Type::ExtVector:                        return eTypeHasChildren | eTypeIsVector;
2973    case clang::Type::FunctionProto:                    return eTypeIsFuncPrototype | eTypeHasValue;
2974    case clang::Type::FunctionNoProto:                  return eTypeIsFuncPrototype | eTypeHasValue;
2975    case clang::Type::InjectedClassName:                return 0;
2976
2977    case clang::Type::LValueReference:
2978    case clang::Type::RValueReference:
2979        if (pointee_or_element_clang_type)
2980            *pointee_or_element_clang_type = cast<ReferenceType>(qual_type.getTypePtr())->getPointeeType().getAsOpaquePtr();
2981        return eTypeHasChildren | eTypeIsReference | eTypeHasValue;
2982
2983    case clang::Type::MemberPointer:                    return eTypeIsPointer   | eTypeIsMember | eTypeHasValue;
2984
2985    case clang::Type::ObjCObjectPointer:
2986        if (pointee_or_element_clang_type)
2987            *pointee_or_element_clang_type = qual_type->getPointeeType().getAsOpaquePtr();
2988        return eTypeHasChildren | eTypeIsObjC | eTypeIsClass | eTypeIsPointer | eTypeHasValue;
2989
2990    case clang::Type::ObjCObject:                       return eTypeHasChildren | eTypeIsObjC | eTypeIsClass;
2991    case clang::Type::ObjCInterface:                    return eTypeHasChildren | eTypeIsObjC | eTypeIsClass;
2992
2993    case clang::Type::Pointer:
2994        if (pointee_or_element_clang_type)
2995            *pointee_or_element_clang_type = qual_type->getPointeeType().getAsOpaquePtr();
2996        return eTypeHasChildren | eTypeIsPointer | eTypeHasValue;
2997
2998    case clang::Type::Record:
2999        if (qual_type->getAsCXXRecordDecl())
3000            return eTypeHasChildren | eTypeIsClass | eTypeIsCPlusPlus;
3001        else
3002            return eTypeHasChildren | eTypeIsStructUnion;
3003        break;
3004    case clang::Type::SubstTemplateTypeParm:            return eTypeIsTemplate;
3005    case clang::Type::TemplateTypeParm:                 return eTypeIsTemplate;
3006    case clang::Type::TemplateSpecialization:           return eTypeIsTemplate;
3007
3008    case clang::Type::Typedef:
3009        return eTypeIsTypedef | ClangASTContext::GetTypeInfo (cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(),
3010                                                                  ast,
3011                                                                  pointee_or_element_clang_type);
3012
3013    case clang::Type::TypeOfExpr:                       return 0;
3014    case clang::Type::TypeOf:                           return 0;
3015    case clang::Type::UnresolvedUsing:                  return 0;
3016    case clang::Type::Vector:                           return eTypeHasChildren | eTypeIsVector;
3017    default:                                            return 0;
3018    }
3019    return 0;
3020}
3021
3022
3023#pragma mark Aggregate Types
3024
3025bool
3026ClangASTContext::IsAggregateType (clang_type_t clang_type)
3027{
3028    if (clang_type == NULL)
3029        return false;
3030
3031    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
3032
3033    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3034    switch (type_class)
3035    {
3036    case clang::Type::IncompleteArray:
3037    case clang::Type::VariableArray:
3038    case clang::Type::ConstantArray:
3039    case clang::Type::ExtVector:
3040    case clang::Type::Vector:
3041    case clang::Type::Record:
3042    case clang::Type::ObjCObject:
3043    case clang::Type::ObjCInterface:
3044        return true;
3045    case clang::Type::Elaborated:
3046        return ClangASTContext::IsAggregateType (cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
3047    case clang::Type::Typedef:
3048        return ClangASTContext::IsAggregateType (cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
3049
3050    default:
3051        break;
3052    }
3053    // The clang type does have a value
3054    return false;
3055}
3056
3057uint32_t
3058ClangASTContext::GetNumChildren (clang::ASTContext *ast, clang_type_t clang_type, bool omit_empty_base_classes)
3059{
3060    if (clang_type == NULL)
3061        return 0;
3062
3063    uint32_t num_children = 0;
3064    QualType qual_type(QualType::getFromOpaquePtr(clang_type));
3065    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3066    switch (type_class)
3067    {
3068    case clang::Type::Builtin:
3069        switch (cast<clang::BuiltinType>(qual_type)->getKind())
3070        {
3071        case clang::BuiltinType::ObjCId:    // child is Class
3072        case clang::BuiltinType::ObjCClass: // child is Class
3073            num_children = 1;
3074            break;
3075
3076        default:
3077            break;
3078        }
3079        break;
3080
3081    case clang::Type::Complex: return 0;
3082
3083    case clang::Type::Record:
3084        if (GetCompleteQualType (ast, qual_type))
3085        {
3086            const RecordType *record_type = cast<RecordType>(qual_type.getTypePtr());
3087            const RecordDecl *record_decl = record_type->getDecl();
3088            assert(record_decl);
3089            const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
3090            if (cxx_record_decl)
3091            {
3092                if (omit_empty_base_classes)
3093                {
3094                    // Check each base classes to see if it or any of its
3095                    // base classes contain any fields. This can help
3096                    // limit the noise in variable views by not having to
3097                    // show base classes that contain no members.
3098                    CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
3099                    for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
3100                         base_class != base_class_end;
3101                         ++base_class)
3102                    {
3103                        const CXXRecordDecl *base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
3104
3105                        // Skip empty base classes
3106                        if (RecordHasFields(base_class_decl) == false)
3107                            continue;
3108
3109                        num_children++;
3110                    }
3111                }
3112                else
3113                {
3114                    // Include all base classes
3115                    num_children += cxx_record_decl->getNumBases();
3116                }
3117
3118            }
3119            RecordDecl::field_iterator field, field_end;
3120            for (field = record_decl->field_begin(), field_end = record_decl->field_end(); field != field_end; ++field)
3121                ++num_children;
3122        }
3123        break;
3124
3125    case clang::Type::ObjCObject:
3126    case clang::Type::ObjCInterface:
3127        if (GetCompleteQualType (ast, qual_type))
3128        {
3129            const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(qual_type.getTypePtr());
3130            assert (objc_class_type);
3131            if (objc_class_type)
3132            {
3133                ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
3134
3135                if (class_interface_decl)
3136                {
3137
3138                    ObjCInterfaceDecl *superclass_interface_decl = class_interface_decl->getSuperClass();
3139                    if (superclass_interface_decl)
3140                    {
3141                        if (omit_empty_base_classes)
3142                        {
3143                            if (ClangASTContext::ObjCDeclHasIVars (superclass_interface_decl, true))
3144                                ++num_children;
3145                        }
3146                        else
3147                            ++num_children;
3148                    }
3149
3150                    num_children += class_interface_decl->ivar_size();
3151                }
3152            }
3153        }
3154        break;
3155
3156    case clang::Type::ObjCObjectPointer:
3157        {
3158            const ObjCObjectPointerType *pointer_type = cast<ObjCObjectPointerType>(qual_type.getTypePtr());
3159            QualType pointee_type = pointer_type->getPointeeType();
3160            uint32_t num_pointee_children = ClangASTContext::GetNumChildren (ast,
3161                                                                             pointee_type.getAsOpaquePtr(),
3162                                                                             omit_empty_base_classes);
3163            // If this type points to a simple type, then it has 1 child
3164            if (num_pointee_children == 0)
3165                num_children = 1;
3166            else
3167                num_children = num_pointee_children;
3168        }
3169        break;
3170
3171    case clang::Type::ConstantArray:
3172        num_children = cast<ConstantArrayType>(qual_type.getTypePtr())->getSize().getLimitedValue();
3173        break;
3174
3175    case clang::Type::Pointer:
3176        {
3177            const PointerType *pointer_type = cast<PointerType>(qual_type.getTypePtr());
3178            QualType pointee_type (pointer_type->getPointeeType());
3179            uint32_t num_pointee_children = ClangASTContext::GetNumChildren (ast,
3180                                                                             pointee_type.getAsOpaquePtr(),
3181                                                                             omit_empty_base_classes);
3182            if (num_pointee_children == 0)
3183            {
3184                // We have a pointer to a pointee type that claims it has no children.
3185                // We will want to look at
3186                num_children = ClangASTContext::GetNumPointeeChildren (pointee_type.getAsOpaquePtr());
3187            }
3188            else
3189                num_children = num_pointee_children;
3190        }
3191        break;
3192
3193    case clang::Type::LValueReference:
3194    case clang::Type::RValueReference:
3195        {
3196            const ReferenceType *reference_type = cast<ReferenceType>(qual_type.getTypePtr());
3197            QualType pointee_type = reference_type->getPointeeType();
3198            uint32_t num_pointee_children = ClangASTContext::GetNumChildren (ast,
3199                                                                             pointee_type.getAsOpaquePtr(),
3200                                                                             omit_empty_base_classes);
3201            // If this type points to a simple type, then it has 1 child
3202            if (num_pointee_children == 0)
3203                num_children = 1;
3204            else
3205                num_children = num_pointee_children;
3206        }
3207        break;
3208
3209
3210    case clang::Type::Typedef:
3211        num_children = ClangASTContext::GetNumChildren (ast,
3212                                                        cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(),
3213                                                        omit_empty_base_classes);
3214        break;
3215
3216    case clang::Type::Elaborated:
3217        num_children = ClangASTContext::GetNumChildren (ast,
3218                                                        cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(),
3219                                                        omit_empty_base_classes);
3220        break;
3221
3222    default:
3223        break;
3224    }
3225    return num_children;
3226}
3227
3228uint32_t
3229ClangASTContext::GetNumDirectBaseClasses (clang::ASTContext *ast, clang_type_t clang_type)
3230{
3231    if (clang_type == NULL)
3232        return 0;
3233
3234    uint32_t count = 0;
3235    QualType qual_type(QualType::getFromOpaquePtr(clang_type));
3236    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3237    switch (type_class)
3238    {
3239        case clang::Type::Record:
3240            if (GetCompleteQualType (ast, qual_type))
3241            {
3242                const CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
3243                if (cxx_record_decl)
3244                    count = cxx_record_decl->getNumBases();
3245            }
3246            break;
3247
3248        case clang::Type::ObjCObject:
3249        case clang::Type::ObjCInterface:
3250            if (GetCompleteQualType (ast, qual_type))
3251            {
3252                const ObjCObjectType *objc_class_type = qual_type->getAsObjCQualifiedInterfaceType();
3253                if (objc_class_type)
3254                {
3255                    ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
3256
3257                    if (class_interface_decl && class_interface_decl->getSuperClass())
3258                        count = 1;
3259                }
3260            }
3261            break;
3262
3263
3264        case clang::Type::Typedef:
3265            count = ClangASTContext::GetNumDirectBaseClasses (ast, cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
3266            break;
3267
3268        case clang::Type::Elaborated:
3269            count = ClangASTContext::GetNumDirectBaseClasses (ast, cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
3270            break;
3271
3272        default:
3273            break;
3274    }
3275    return count;
3276}
3277
3278uint32_t
3279ClangASTContext::GetNumVirtualBaseClasses (clang::ASTContext *ast,
3280                                           clang_type_t clang_type)
3281{
3282    if (clang_type == NULL)
3283        return 0;
3284
3285    uint32_t count = 0;
3286    QualType qual_type(QualType::getFromOpaquePtr(clang_type));
3287    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3288    switch (type_class)
3289    {
3290        case clang::Type::Record:
3291            if (GetCompleteQualType (ast, qual_type))
3292            {
3293                const CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
3294                if (cxx_record_decl)
3295                    count = cxx_record_decl->getNumVBases();
3296            }
3297            break;
3298
3299        case clang::Type::Typedef:
3300            count = ClangASTContext::GetNumVirtualBaseClasses (ast, cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
3301            break;
3302
3303        case clang::Type::Elaborated:
3304            count = ClangASTContext::GetNumVirtualBaseClasses (ast, cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
3305            break;
3306
3307        default:
3308            break;
3309    }
3310    return count;
3311}
3312
3313uint32_t
3314ClangASTContext::GetNumFields (clang::ASTContext *ast, clang_type_t clang_type)
3315{
3316    if (clang_type == NULL)
3317        return 0;
3318
3319    uint32_t count = 0;
3320    QualType qual_type(QualType::getFromOpaquePtr(clang_type));
3321    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3322    switch (type_class)
3323    {
3324        case clang::Type::Record:
3325            if (GetCompleteQualType (ast, qual_type))
3326            {
3327                const RecordType *record_type = dyn_cast<RecordType>(qual_type.getTypePtr());
3328                if (record_type)
3329                {
3330                    RecordDecl *record_decl = record_type->getDecl();
3331                    if (record_decl)
3332                    {
3333                        uint32_t field_idx = 0;
3334                        RecordDecl::field_iterator field, field_end;
3335                        for (field = record_decl->field_begin(), field_end = record_decl->field_end(); field != field_end; ++field)
3336                            ++field_idx;
3337                        count = field_idx;
3338                    }
3339                }
3340            }
3341            break;
3342
3343        case clang::Type::Typedef:
3344            count = ClangASTContext::GetNumFields (ast, cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
3345            break;
3346
3347        case clang::Type::Elaborated:
3348            count = ClangASTContext::GetNumFields (ast, cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
3349            break;
3350
3351        case clang::Type::ObjCObject:
3352        case clang::Type::ObjCInterface:
3353            if (GetCompleteQualType (ast, qual_type))
3354            {
3355                const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(qual_type.getTypePtr());
3356                if (objc_class_type)
3357                {
3358                    ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
3359
3360                    if (class_interface_decl)
3361                        count = class_interface_decl->ivar_size();
3362                }
3363            }
3364            break;
3365
3366        default:
3367            break;
3368    }
3369    return count;
3370}
3371
3372clang_type_t
3373ClangASTContext::GetDirectBaseClassAtIndex (clang::ASTContext *ast,
3374                                            clang_type_t clang_type,
3375                                            size_t idx,
3376                                            uint32_t *bit_offset_ptr)
3377{
3378    if (clang_type == NULL)
3379        return 0;
3380
3381    QualType qual_type(QualType::getFromOpaquePtr(clang_type));
3382    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3383    switch (type_class)
3384    {
3385        case clang::Type::Record:
3386            if (GetCompleteQualType (ast, qual_type))
3387            {
3388                const CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
3389                if (cxx_record_decl)
3390                {
3391                    uint32_t curr_idx = 0;
3392                    CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
3393                    for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
3394                         base_class != base_class_end;
3395                         ++base_class, ++curr_idx)
3396                    {
3397                        if (curr_idx == idx)
3398                        {
3399                            if (bit_offset_ptr)
3400                            {
3401                                const ASTRecordLayout &record_layout = ast->getASTRecordLayout(cxx_record_decl);
3402                                const CXXRecordDecl *base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
3403//                                if (base_class->isVirtual())
3404//                                    *bit_offset_ptr = record_layout.getVBaseClassOffset(base_class_decl).getQuantity() * 8;
3405//                                else
3406                                    *bit_offset_ptr = record_layout.getBaseClassOffset(base_class_decl).getQuantity() * 8;
3407                            }
3408                            return base_class->getType().getAsOpaquePtr();
3409                        }
3410                    }
3411                }
3412            }
3413            break;
3414
3415        case clang::Type::ObjCObject:
3416        case clang::Type::ObjCInterface:
3417            if (idx == 0 && GetCompleteQualType (ast, qual_type))
3418            {
3419                const ObjCObjectType *objc_class_type = qual_type->getAsObjCQualifiedInterfaceType();
3420                if (objc_class_type)
3421                {
3422                    ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
3423
3424                    if (class_interface_decl)
3425                    {
3426                        ObjCInterfaceDecl *superclass_interface_decl = class_interface_decl->getSuperClass();
3427                        if (superclass_interface_decl)
3428                        {
3429                            if (bit_offset_ptr)
3430                                *bit_offset_ptr = 0;
3431                            return ast->getObjCInterfaceType(superclass_interface_decl).getAsOpaquePtr();
3432                        }
3433                    }
3434                }
3435            }
3436            break;
3437
3438
3439        case clang::Type::Typedef:
3440            return ClangASTContext::GetDirectBaseClassAtIndex (ast,
3441                                                               cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(),
3442                                                               idx,
3443                                                               bit_offset_ptr);
3444
3445        case clang::Type::Elaborated:
3446            return  ClangASTContext::GetDirectBaseClassAtIndex (ast,
3447                                                                cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(),
3448                                                                idx,
3449                                                                bit_offset_ptr);
3450
3451        default:
3452            break;
3453    }
3454    return NULL;
3455}
3456
3457clang_type_t
3458ClangASTContext::GetVirtualBaseClassAtIndex (clang::ASTContext *ast,
3459                                             clang_type_t clang_type,
3460                                             size_t idx,
3461                                             uint32_t *bit_offset_ptr)
3462{
3463    if (clang_type == NULL)
3464        return 0;
3465
3466    QualType qual_type(QualType::getFromOpaquePtr(clang_type));
3467    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3468    switch (type_class)
3469    {
3470        case clang::Type::Record:
3471            if (GetCompleteQualType (ast, qual_type))
3472            {
3473                const CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
3474                if (cxx_record_decl)
3475                {
3476                    uint32_t curr_idx = 0;
3477                    CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
3478                    for (base_class = cxx_record_decl->vbases_begin(), base_class_end = cxx_record_decl->vbases_end();
3479                         base_class != base_class_end;
3480                         ++base_class, ++curr_idx)
3481                    {
3482                        if (curr_idx == idx)
3483                        {
3484                            if (bit_offset_ptr)
3485                            {
3486                                const ASTRecordLayout &record_layout = ast->getASTRecordLayout(cxx_record_decl);
3487                                const CXXRecordDecl *base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
3488                                *bit_offset_ptr = record_layout.getVBaseClassOffset(base_class_decl).getQuantity() * 8;
3489
3490                            }
3491                            return base_class->getType().getAsOpaquePtr();
3492                        }
3493                    }
3494                }
3495            }
3496            break;
3497
3498        case clang::Type::Typedef:
3499            return ClangASTContext::GetVirtualBaseClassAtIndex (ast,
3500                                                                cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(),
3501                                                                idx,
3502                                                                bit_offset_ptr);
3503
3504        case clang::Type::Elaborated:
3505            return  ClangASTContext::GetVirtualBaseClassAtIndex (ast,
3506                                                                 cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(),
3507                                                                 idx,
3508                                                                 bit_offset_ptr);
3509
3510        default:
3511            break;
3512    }
3513    return NULL;
3514}
3515
3516clang_type_t
3517ClangASTContext::GetFieldAtIndex (clang::ASTContext *ast,
3518                                  clang_type_t clang_type,
3519                                  size_t idx,
3520                                  std::string& name,
3521                                  uint64_t *bit_offset_ptr,
3522                                  uint32_t *bitfield_bit_size_ptr,
3523                                  bool *is_bitfield_ptr)
3524{
3525    if (clang_type == NULL)
3526        return 0;
3527
3528    QualType qual_type(QualType::getFromOpaquePtr(clang_type));
3529    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3530    switch (type_class)
3531    {
3532        case clang::Type::Record:
3533            if (GetCompleteQualType (ast, qual_type))
3534            {
3535                const RecordType *record_type = cast<RecordType>(qual_type.getTypePtr());
3536                const RecordDecl *record_decl = record_type->getDecl();
3537                uint32_t field_idx = 0;
3538                RecordDecl::field_iterator field, field_end;
3539                for (field = record_decl->field_begin(), field_end = record_decl->field_end(); field != field_end; ++field, ++field_idx)
3540                {
3541                    if (idx == field_idx)
3542                    {
3543                        // Print the member type if requested
3544                        // Print the member name and equal sign
3545                        name.assign(field->getNameAsString());
3546
3547                        // Figure out the type byte size (field_type_info.first) and
3548                        // alignment (field_type_info.second) from the AST context.
3549                        if (bit_offset_ptr)
3550                        {
3551                            const ASTRecordLayout &record_layout = ast->getASTRecordLayout(record_decl);
3552                            *bit_offset_ptr = record_layout.getFieldOffset (field_idx);
3553                        }
3554
3555                        const bool is_bitfield = field->isBitField();
3556
3557                        if (bitfield_bit_size_ptr)
3558                        {
3559                            *bitfield_bit_size_ptr = 0;
3560
3561                            if (is_bitfield && ast)
3562                            {
3563                                Expr *bitfield_bit_size_expr = field->getBitWidth();
3564                                llvm::APSInt bitfield_apsint;
3565                                if (bitfield_bit_size_expr && bitfield_bit_size_expr->EvaluateAsInt(bitfield_apsint, *ast))
3566                                {
3567                                    *bitfield_bit_size_ptr = bitfield_apsint.getLimitedValue();
3568                                }
3569                            }
3570                        }
3571                        if (is_bitfield_ptr)
3572                            *is_bitfield_ptr = is_bitfield;
3573
3574                        return field->getType().getAsOpaquePtr();
3575                    }
3576                }
3577            }
3578            break;
3579
3580        case clang::Type::ObjCObject:
3581        case clang::Type::ObjCInterface:
3582            if (GetCompleteQualType (ast, qual_type))
3583            {
3584                const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(qual_type.getTypePtr());
3585                assert (objc_class_type);
3586                if (objc_class_type)
3587                {
3588                    ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
3589
3590                    if (class_interface_decl)
3591                    {
3592                        if (idx < (class_interface_decl->ivar_size()))
3593                        {
3594                            ObjCInterfaceDecl::ivar_iterator ivar_pos, ivar_end = class_interface_decl->ivar_end();
3595                            uint32_t ivar_idx = 0;
3596
3597                            for (ivar_pos = class_interface_decl->ivar_begin(); ivar_pos != ivar_end; ++ivar_pos, ++ivar_idx)
3598                            {
3599                                if (ivar_idx == idx)
3600                                {
3601                                    const ObjCIvarDecl* ivar_decl = *ivar_pos;
3602
3603                                    QualType ivar_qual_type(ivar_decl->getType());
3604
3605                                    name.assign(ivar_decl->getNameAsString());
3606
3607                                    if (bit_offset_ptr)
3608                                    {
3609                                        const ASTRecordLayout &interface_layout = ast->getASTObjCInterfaceLayout(class_interface_decl);
3610                                        *bit_offset_ptr = interface_layout.getFieldOffset (ivar_idx);
3611                                    }
3612
3613                                    const bool is_bitfield = ivar_pos->isBitField();
3614
3615                                    if (bitfield_bit_size_ptr)
3616                                    {
3617                                        *bitfield_bit_size_ptr = 0;
3618
3619                                        if (is_bitfield && ast)
3620                                        {
3621                                            Expr *bitfield_bit_size_expr = ivar_pos->getBitWidth();
3622                                            llvm::APSInt bitfield_apsint;
3623                                            if (bitfield_bit_size_expr && bitfield_bit_size_expr->EvaluateAsInt(bitfield_apsint, *ast))
3624                                            {
3625                                                *bitfield_bit_size_ptr = bitfield_apsint.getLimitedValue();
3626                                            }
3627                                        }
3628                                    }
3629                                    if (is_bitfield_ptr)
3630                                        *is_bitfield_ptr = is_bitfield;
3631
3632                                    return ivar_qual_type.getAsOpaquePtr();
3633                                }
3634                            }
3635                        }
3636                    }
3637                }
3638            }
3639            break;
3640
3641
3642        case clang::Type::Typedef:
3643            return ClangASTContext::GetFieldAtIndex (ast,
3644                                                     cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(),
3645                                                     idx,
3646                                                     name,
3647                                                     bit_offset_ptr,
3648                                                     bitfield_bit_size_ptr,
3649                                                     is_bitfield_ptr);
3650
3651        case clang::Type::Elaborated:
3652            return  ClangASTContext::GetFieldAtIndex (ast,
3653                                                      cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(),
3654                                                      idx,
3655                                                      name,
3656                                                      bit_offset_ptr,
3657                                                      bitfield_bit_size_ptr,
3658                                                      is_bitfield_ptr);
3659
3660        default:
3661            break;
3662    }
3663    return NULL;
3664}
3665
3666lldb::BasicType
3667ClangASTContext::GetLLDBBasicTypeEnumeration (clang_type_t clang_type)
3668{
3669    if (clang_type)
3670    {
3671        QualType qual_type(QualType::getFromOpaquePtr(clang_type));
3672        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3673        if (type_class == clang::Type::Builtin)
3674        {
3675            switch (cast<clang::BuiltinType>(qual_type)->getKind())
3676            {
3677            case clang::BuiltinType::Void:      return eBasicTypeVoid;
3678            case clang::BuiltinType::Bool:      return eBasicTypeBool;
3679            case clang::BuiltinType::Char_S:    return eBasicTypeSignedChar;
3680            case clang::BuiltinType::Char_U:    return eBasicTypeUnsignedChar;
3681            case clang::BuiltinType::Char16:    return eBasicTypeChar16;
3682            case clang::BuiltinType::Char32:    return eBasicTypeChar32;
3683            case clang::BuiltinType::UChar:     return eBasicTypeUnsignedChar;
3684            case clang::BuiltinType::SChar:     return eBasicTypeSignedChar;
3685            case clang::BuiltinType::WChar_S:   return eBasicTypeSignedWChar;
3686            case clang::BuiltinType::WChar_U:   return eBasicTypeUnsignedWChar;
3687            case clang::BuiltinType::Short:     return eBasicTypeShort;
3688            case clang::BuiltinType::UShort:    return eBasicTypeUnsignedShort;
3689            case clang::BuiltinType::Int:       return eBasicTypeInt;
3690            case clang::BuiltinType::UInt:      return eBasicTypeUnsignedInt;
3691            case clang::BuiltinType::Long:      return eBasicTypeLong;
3692            case clang::BuiltinType::ULong:     return eBasicTypeUnsignedLong;
3693            case clang::BuiltinType::LongLong:  return eBasicTypeLongLong;
3694            case clang::BuiltinType::ULongLong: return eBasicTypeUnsignedLongLong;
3695            case clang::BuiltinType::Int128:    return eBasicTypeInt128;
3696            case clang::BuiltinType::UInt128:   return eBasicTypeUnsignedInt128;
3697
3698            case clang::BuiltinType::Half:      return eBasicTypeHalf;
3699            case clang::BuiltinType::Float:     return eBasicTypeFloat;
3700            case clang::BuiltinType::Double:    return eBasicTypeDouble;
3701            case clang::BuiltinType::LongDouble:return eBasicTypeLongDouble;
3702
3703            case clang::BuiltinType::NullPtr:   return eBasicTypeNullPtr;
3704            case clang::BuiltinType::ObjCId:    return eBasicTypeObjCID;
3705            case clang::BuiltinType::ObjCClass: return eBasicTypeObjCClass;
3706            case clang::BuiltinType::ObjCSel:   return eBasicTypeObjCSel;
3707            case clang::BuiltinType::Dependent:
3708            case clang::BuiltinType::Overload:
3709            case clang::BuiltinType::BoundMember:
3710            case clang::BuiltinType::PseudoObject:
3711            case clang::BuiltinType::UnknownAny:
3712            case clang::BuiltinType::BuiltinFn:
3713            case clang::BuiltinType::ARCUnbridgedCast:
3714            case clang::BuiltinType::OCLEvent:
3715            case clang::BuiltinType::OCLImage1d:
3716            case clang::BuiltinType::OCLImage1dArray:
3717            case clang::BuiltinType::OCLImage1dBuffer:
3718            case clang::BuiltinType::OCLImage2d:
3719            case clang::BuiltinType::OCLImage2dArray:
3720            case clang::BuiltinType::OCLImage3d:
3721                return eBasicTypeOther;
3722            }
3723        }
3724    }
3725
3726    return eBasicTypeInvalid;
3727}
3728
3729
3730
3731// If a pointer to a pointee type (the clang_type arg) says that it has no
3732// children, then we either need to trust it, or override it and return a
3733// different result. For example, an "int *" has one child that is an integer,
3734// but a function pointer doesn't have any children. Likewise if a Record type
3735// claims it has no children, then there really is nothing to show.
3736uint32_t
3737ClangASTContext::GetNumPointeeChildren (clang_type_t clang_type)
3738{
3739    if (clang_type == NULL)
3740        return 0;
3741
3742    QualType qual_type(QualType::getFromOpaquePtr(clang_type));
3743    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3744    switch (type_class)
3745    {
3746    case clang::Type::Builtin:
3747        switch (cast<clang::BuiltinType>(qual_type)->getKind())
3748        {
3749        case clang::BuiltinType::UnknownAny:
3750        case clang::BuiltinType::Void:
3751        case clang::BuiltinType::NullPtr:
3752        case clang::BuiltinType::OCLEvent:
3753        case clang::BuiltinType::OCLImage1d:
3754        case clang::BuiltinType::OCLImage1dArray:
3755        case clang::BuiltinType::OCLImage1dBuffer:
3756        case clang::BuiltinType::OCLImage2d:
3757        case clang::BuiltinType::OCLImage2dArray:
3758        case clang::BuiltinType::OCLImage3d:
3759            return 0;
3760        case clang::BuiltinType::Bool:
3761        case clang::BuiltinType::Char_U:
3762        case clang::BuiltinType::UChar:
3763        case clang::BuiltinType::WChar_U:
3764        case clang::BuiltinType::Char16:
3765        case clang::BuiltinType::Char32:
3766        case clang::BuiltinType::UShort:
3767        case clang::BuiltinType::UInt:
3768        case clang::BuiltinType::ULong:
3769        case clang::BuiltinType::ULongLong:
3770        case clang::BuiltinType::UInt128:
3771        case clang::BuiltinType::Char_S:
3772        case clang::BuiltinType::SChar:
3773        case clang::BuiltinType::WChar_S:
3774        case clang::BuiltinType::Short:
3775        case clang::BuiltinType::Int:
3776        case clang::BuiltinType::Long:
3777        case clang::BuiltinType::LongLong:
3778        case clang::BuiltinType::Int128:
3779        case clang::BuiltinType::Float:
3780        case clang::BuiltinType::Double:
3781        case clang::BuiltinType::LongDouble:
3782        case clang::BuiltinType::Dependent:
3783        case clang::BuiltinType::Overload:
3784        case clang::BuiltinType::ObjCId:
3785        case clang::BuiltinType::ObjCClass:
3786        case clang::BuiltinType::ObjCSel:
3787        case clang::BuiltinType::BoundMember:
3788        case clang::BuiltinType::Half:
3789        case clang::BuiltinType::ARCUnbridgedCast:
3790        case clang::BuiltinType::PseudoObject:
3791        case clang::BuiltinType::BuiltinFn:
3792            return 1;
3793        }
3794        break;
3795
3796    case clang::Type::Complex:                  return 1;
3797    case clang::Type::Pointer:                  return 1;
3798    case clang::Type::BlockPointer:             return 0;   // If block pointers don't have debug info, then no children for them
3799    case clang::Type::LValueReference:          return 1;
3800    case clang::Type::RValueReference:          return 1;
3801    case clang::Type::MemberPointer:            return 0;
3802    case clang::Type::ConstantArray:            return 0;
3803    case clang::Type::IncompleteArray:          return 0;
3804    case clang::Type::VariableArray:            return 0;
3805    case clang::Type::DependentSizedArray:      return 0;
3806    case clang::Type::DependentSizedExtVector:  return 0;
3807    case clang::Type::Vector:                   return 0;
3808    case clang::Type::ExtVector:                return 0;
3809    case clang::Type::FunctionProto:            return 0;   // When we function pointers, they have no children...
3810    case clang::Type::FunctionNoProto:          return 0;   // When we function pointers, they have no children...
3811    case clang::Type::UnresolvedUsing:          return 0;
3812    case clang::Type::Paren:                    return 0;
3813    case clang::Type::Typedef:                  return ClangASTContext::GetNumPointeeChildren (cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
3814    case clang::Type::Elaborated:               return ClangASTContext::GetNumPointeeChildren (cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
3815    case clang::Type::TypeOfExpr:               return 0;
3816    case clang::Type::TypeOf:                   return 0;
3817    case clang::Type::Decltype:                 return 0;
3818    case clang::Type::Record:                   return 0;
3819    case clang::Type::Enum:                     return 1;
3820    case clang::Type::TemplateTypeParm:         return 1;
3821    case clang::Type::SubstTemplateTypeParm:    return 1;
3822    case clang::Type::TemplateSpecialization:   return 1;
3823    case clang::Type::InjectedClassName:        return 0;
3824    case clang::Type::DependentName:            return 1;
3825    case clang::Type::DependentTemplateSpecialization:  return 1;
3826    case clang::Type::ObjCObject:               return 0;
3827    case clang::Type::ObjCInterface:            return 0;
3828    case clang::Type::ObjCObjectPointer:        return 1;
3829    default:
3830        break;
3831    }
3832    return 0;
3833}
3834
3835clang_type_t
3836ClangASTContext::GetChildClangTypeAtIndex
3837(
3838    ExecutionContext *exe_ctx,
3839    const char *parent_name,
3840    clang_type_t parent_clang_type,
3841    size_t idx,
3842    bool transparent_pointers,
3843    bool omit_empty_base_classes,
3844    bool ignore_array_bounds,
3845    std::string& child_name,
3846    uint32_t &child_byte_size,
3847    int32_t &child_byte_offset,
3848    uint32_t &child_bitfield_bit_size,
3849    uint32_t &child_bitfield_bit_offset,
3850    bool &child_is_base_class,
3851    bool &child_is_deref_of_parent
3852)
3853{
3854    if (parent_clang_type)
3855
3856        return GetChildClangTypeAtIndex (exe_ctx,
3857                                         getASTContext(),
3858                                         parent_name,
3859                                         parent_clang_type,
3860                                         idx,
3861                                         transparent_pointers,
3862                                         omit_empty_base_classes,
3863                                         ignore_array_bounds,
3864                                         child_name,
3865                                         child_byte_size,
3866                                         child_byte_offset,
3867                                         child_bitfield_bit_size,
3868                                         child_bitfield_bit_offset,
3869                                         child_is_base_class,
3870                                         child_is_deref_of_parent);
3871    return NULL;
3872}
3873
3874clang_type_t
3875ClangASTContext::GetChildClangTypeAtIndex
3876(
3877    ExecutionContext *exe_ctx,
3878    ASTContext *ast,
3879    const char *parent_name,
3880    clang_type_t parent_clang_type,
3881    size_t idx,
3882    bool transparent_pointers,
3883    bool omit_empty_base_classes,
3884    bool ignore_array_bounds,
3885    std::string& child_name,
3886    uint32_t &child_byte_size,
3887    int32_t &child_byte_offset,
3888    uint32_t &child_bitfield_bit_size,
3889    uint32_t &child_bitfield_bit_offset,
3890    bool &child_is_base_class,
3891    bool &child_is_deref_of_parent
3892)
3893{
3894    if (parent_clang_type == NULL)
3895        return NULL;
3896
3897    QualType parent_qual_type(QualType::getFromOpaquePtr(parent_clang_type));
3898    const clang::Type::TypeClass parent_type_class = parent_qual_type->getTypeClass();
3899    child_bitfield_bit_size = 0;
3900    child_bitfield_bit_offset = 0;
3901    child_is_base_class = false;
3902
3903    const bool idx_is_valid = idx < ClangASTContext::GetNumChildren (ast, parent_clang_type, omit_empty_base_classes);
3904    uint32_t bit_offset;
3905    switch (parent_type_class)
3906    {
3907    case clang::Type::Builtin:
3908        if (idx_is_valid)
3909        {
3910            switch (cast<clang::BuiltinType>(parent_qual_type)->getKind())
3911            {
3912            case clang::BuiltinType::ObjCId:
3913            case clang::BuiltinType::ObjCClass:
3914                child_name = "isa";
3915                child_byte_size = ast->getTypeSize(ast->ObjCBuiltinClassTy) / CHAR_BIT;
3916                return ast->ObjCBuiltinClassTy.getAsOpaquePtr();
3917
3918            default:
3919                break;
3920            }
3921        }
3922        break;
3923
3924    case clang::Type::Record:
3925        if (idx_is_valid && GetCompleteQualType (ast, parent_qual_type))
3926        {
3927            const RecordType *record_type = cast<RecordType>(parent_qual_type.getTypePtr());
3928            const RecordDecl *record_decl = record_type->getDecl();
3929            assert(record_decl);
3930            const ASTRecordLayout &record_layout = ast->getASTRecordLayout(record_decl);
3931            uint32_t child_idx = 0;
3932
3933            const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
3934            if (cxx_record_decl)
3935            {
3936                // We might have base classes to print out first
3937                CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
3938                for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
3939                     base_class != base_class_end;
3940                     ++base_class)
3941                {
3942                    const CXXRecordDecl *base_class_decl = NULL;
3943
3944                    // Skip empty base classes
3945                    if (omit_empty_base_classes)
3946                    {
3947                        base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
3948                        if (RecordHasFields(base_class_decl) == false)
3949                            continue;
3950                    }
3951
3952                    if (idx == child_idx)
3953                    {
3954                        if (base_class_decl == NULL)
3955                            base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
3956
3957
3958                        if (base_class->isVirtual())
3959                            bit_offset = record_layout.getVBaseClassOffset(base_class_decl).getQuantity() * 8;
3960                        else
3961                            bit_offset = record_layout.getBaseClassOffset(base_class_decl).getQuantity() * 8;
3962
3963                        // Base classes should be a multiple of 8 bits in size
3964                        child_byte_offset = bit_offset/8;
3965
3966                        child_name = ClangASTType::GetTypeNameForQualType(ast, base_class->getType());
3967
3968                        uint64_t clang_type_info_bit_size = ast->getTypeSize(base_class->getType());
3969
3970                        // Base classes bit sizes should be a multiple of 8 bits in size
3971                        assert (clang_type_info_bit_size % 8 == 0);
3972                        child_byte_size = clang_type_info_bit_size / 8;
3973                        child_is_base_class = true;
3974                        return base_class->getType().getAsOpaquePtr();
3975                    }
3976                    // We don't increment the child index in the for loop since we might
3977                    // be skipping empty base classes
3978                    ++child_idx;
3979                }
3980            }
3981            // Make sure index is in range...
3982            uint32_t field_idx = 0;
3983            RecordDecl::field_iterator field, field_end;
3984            for (field = record_decl->field_begin(), field_end = record_decl->field_end(); field != field_end; ++field, ++field_idx, ++child_idx)
3985            {
3986                if (idx == child_idx)
3987                {
3988                    // Print the member type if requested
3989                    // Print the member name and equal sign
3990                    child_name.assign(field->getNameAsString().c_str());
3991
3992                    // Figure out the type byte size (field_type_info.first) and
3993                    // alignment (field_type_info.second) from the AST context.
3994                    std::pair<uint64_t, unsigned> field_type_info = ast->getTypeInfo(field->getType());
3995                    assert(field_idx < record_layout.getFieldCount());
3996
3997                    child_byte_size = field_type_info.first / 8;
3998
3999                    // Figure out the field offset within the current struct/union/class type
4000                    bit_offset = record_layout.getFieldOffset (field_idx);
4001                    child_byte_offset = bit_offset / 8;
4002                    if (ClangASTContext::FieldIsBitfield (ast, *field, child_bitfield_bit_size))
4003                        child_bitfield_bit_offset = bit_offset % 8;
4004
4005                    return field->getType().getAsOpaquePtr();
4006                }
4007            }
4008        }
4009        break;
4010
4011    case clang::Type::ObjCObject:
4012    case clang::Type::ObjCInterface:
4013        if (idx_is_valid && GetCompleteQualType (ast, parent_qual_type))
4014        {
4015            const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(parent_qual_type.getTypePtr());
4016            assert (objc_class_type);
4017            if (objc_class_type)
4018            {
4019                uint32_t child_idx = 0;
4020                ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
4021
4022                if (class_interface_decl)
4023                {
4024
4025                    const ASTRecordLayout &interface_layout = ast->getASTObjCInterfaceLayout(class_interface_decl);
4026                    ObjCInterfaceDecl *superclass_interface_decl = class_interface_decl->getSuperClass();
4027                    if (superclass_interface_decl)
4028                    {
4029                        if (omit_empty_base_classes)
4030                        {
4031                            if (ClangASTContext::GetNumChildren(ast, ast->getObjCInterfaceType(superclass_interface_decl).getAsOpaquePtr(), omit_empty_base_classes) > 0)
4032                            {
4033                                if (idx == 0)
4034                                {
4035                                    QualType ivar_qual_type(ast->getObjCInterfaceType(superclass_interface_decl));
4036
4037
4038                                    child_name.assign(superclass_interface_decl->getNameAsString().c_str());
4039
4040                                    std::pair<uint64_t, unsigned> ivar_type_info = ast->getTypeInfo(ivar_qual_type.getTypePtr());
4041
4042                                    child_byte_size = ivar_type_info.first / 8;
4043                                    child_byte_offset = 0;
4044                                    child_is_base_class = true;
4045
4046                                    return ivar_qual_type.getAsOpaquePtr();
4047                                }
4048
4049                                ++child_idx;
4050                            }
4051                        }
4052                        else
4053                            ++child_idx;
4054                    }
4055
4056                    const uint32_t superclass_idx = child_idx;
4057
4058                    if (idx < (child_idx + class_interface_decl->ivar_size()))
4059                    {
4060                        ObjCInterfaceDecl::ivar_iterator ivar_pos, ivar_end = class_interface_decl->ivar_end();
4061
4062                        for (ivar_pos = class_interface_decl->ivar_begin(); ivar_pos != ivar_end; ++ivar_pos)
4063                        {
4064                            if (child_idx == idx)
4065                            {
4066                                ObjCIvarDecl* ivar_decl = *ivar_pos;
4067
4068                                QualType ivar_qual_type(ivar_decl->getType());
4069
4070                                child_name.assign(ivar_decl->getNameAsString().c_str());
4071
4072                                std::pair<uint64_t, unsigned> ivar_type_info = ast->getTypeInfo(ivar_qual_type.getTypePtr());
4073
4074                                child_byte_size = ivar_type_info.first / 8;
4075
4076                                // Figure out the field offset within the current struct/union/class type
4077                                // For ObjC objects, we can't trust the bit offset we get from the Clang AST, since
4078                                // that doesn't account for the space taken up by unbacked properties, or from
4079                                // the changing size of base classes that are newer than this class.
4080                                // So if we have a process around that we can ask about this object, do so.
4081                                child_byte_offset = LLDB_INVALID_IVAR_OFFSET;
4082                                Process *process = NULL;
4083                                if (exe_ctx)
4084                                    process = exe_ctx->GetProcessPtr();
4085                                if (process)
4086                                {
4087                                    ObjCLanguageRuntime *objc_runtime = process->GetObjCLanguageRuntime();
4088                                    if (objc_runtime != NULL)
4089                                    {
4090                                        ClangASTType parent_ast_type (ast, parent_qual_type.getAsOpaquePtr());
4091                                        child_byte_offset = objc_runtime->GetByteOffsetForIvar (parent_ast_type, ivar_decl->getNameAsString().c_str());
4092                                    }
4093                                }
4094
4095                                // Setting this to UINT32_MAX to make sure we don't compute it twice...
4096                                bit_offset = UINT32_MAX;
4097
4098                                if (child_byte_offset == LLDB_INVALID_IVAR_OFFSET)
4099                                {
4100                                    bit_offset = interface_layout.getFieldOffset (child_idx - superclass_idx);
4101                                    child_byte_offset = bit_offset / 8;
4102                                }
4103
4104                                // Note, the ObjC Ivar Byte offset is just that, it doesn't account for the bit offset
4105                                // of a bitfield within its containing object.  So regardless of where we get the byte
4106                                // offset from, we still need to get the bit offset for bitfields from the layout.
4107
4108                                if (ClangASTContext::FieldIsBitfield (ast, ivar_decl, child_bitfield_bit_size))
4109                                {
4110                                    if (bit_offset == UINT32_MAX)
4111                                        bit_offset = interface_layout.getFieldOffset (child_idx - superclass_idx);
4112
4113                                    child_bitfield_bit_offset = bit_offset % 8;
4114                                }
4115                                return ivar_qual_type.getAsOpaquePtr();
4116                            }
4117                            ++child_idx;
4118                        }
4119                    }
4120                }
4121            }
4122        }
4123        break;
4124
4125    case clang::Type::ObjCObjectPointer:
4126        if (idx_is_valid)
4127        {
4128            const ObjCObjectPointerType *pointer_type = cast<ObjCObjectPointerType>(parent_qual_type.getTypePtr());
4129            QualType pointee_type = pointer_type->getPointeeType();
4130
4131            if (transparent_pointers && ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
4132            {
4133                child_is_deref_of_parent = false;
4134                bool tmp_child_is_deref_of_parent = false;
4135                return GetChildClangTypeAtIndex (exe_ctx,
4136                                                 ast,
4137                                                 parent_name,
4138                                                 pointer_type->getPointeeType().getAsOpaquePtr(),
4139                                                 idx,
4140                                                 transparent_pointers,
4141                                                 omit_empty_base_classes,
4142                                                 ignore_array_bounds,
4143                                                 child_name,
4144                                                 child_byte_size,
4145                                                 child_byte_offset,
4146                                                 child_bitfield_bit_size,
4147                                                 child_bitfield_bit_offset,
4148                                                 child_is_base_class,
4149                                                 tmp_child_is_deref_of_parent);
4150            }
4151            else
4152            {
4153                child_is_deref_of_parent = true;
4154                if (parent_name)
4155                {
4156                    child_name.assign(1, '*');
4157                    child_name += parent_name;
4158                }
4159
4160                // We have a pointer to an simple type
4161                if (idx == 0 && GetCompleteQualType(ast, pointee_type))
4162                {
4163                    std::pair<uint64_t, unsigned> clang_type_info = ast->getTypeInfo(pointee_type);
4164                    assert(clang_type_info.first % 8 == 0);
4165                    child_byte_size = clang_type_info.first / 8;
4166                    child_byte_offset = 0;
4167                    return pointee_type.getAsOpaquePtr();
4168                }
4169            }
4170        }
4171        break;
4172
4173        case clang::Type::ConstantArray:
4174        case clang::Type::IncompleteArray:
4175            if (ignore_array_bounds || idx_is_valid)
4176            {
4177                const ArrayType *array = cast<ArrayType>(parent_qual_type.getTypePtr());
4178                if (array)
4179                {
4180                    if (GetCompleteQualType (ast, array->getElementType()))
4181                    {
4182                        std::pair<uint64_t, unsigned> field_type_info = ast->getTypeInfo(array->getElementType());
4183
4184                        char element_name[64];
4185                        ::snprintf (element_name, sizeof (element_name), "[%zu]", idx);
4186
4187                        child_name.assign(element_name);
4188                        assert(field_type_info.first % 8 == 0);
4189                        child_byte_size = field_type_info.first / 8;
4190                        child_byte_offset = (int32_t)idx * (int32_t)child_byte_size;
4191                        return array->getElementType().getAsOpaquePtr();
4192                    }
4193                }
4194            }
4195            break;
4196
4197
4198    case clang::Type::Pointer:
4199        if (idx_is_valid)
4200        {
4201            const PointerType *pointer_type = cast<PointerType>(parent_qual_type.getTypePtr());
4202            QualType pointee_type = pointer_type->getPointeeType();
4203
4204            // Don't dereference "void *" pointers
4205            if (pointee_type->isVoidType())
4206                return NULL;
4207
4208            if (transparent_pointers && ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
4209            {
4210                child_is_deref_of_parent = false;
4211                bool tmp_child_is_deref_of_parent = false;
4212                return GetChildClangTypeAtIndex (exe_ctx,
4213                                                 ast,
4214                                                 parent_name,
4215                                                 pointer_type->getPointeeType().getAsOpaquePtr(),
4216                                                 idx,
4217                                                 transparent_pointers,
4218                                                 omit_empty_base_classes,
4219                                                 ignore_array_bounds,
4220                                                 child_name,
4221                                                 child_byte_size,
4222                                                 child_byte_offset,
4223                                                 child_bitfield_bit_size,
4224                                                 child_bitfield_bit_offset,
4225                                                 child_is_base_class,
4226                                                 tmp_child_is_deref_of_parent);
4227            }
4228            else
4229            {
4230                child_is_deref_of_parent = true;
4231
4232                if (parent_name)
4233                {
4234                    child_name.assign(1, '*');
4235                    child_name += parent_name;
4236                }
4237
4238                // We have a pointer to an simple type
4239                if (idx == 0)
4240                {
4241                    std::pair<uint64_t, unsigned> clang_type_info = ast->getTypeInfo(pointee_type);
4242                    assert(clang_type_info.first % 8 == 0);
4243                    child_byte_size = clang_type_info.first / 8;
4244                    child_byte_offset = 0;
4245                    return pointee_type.getAsOpaquePtr();
4246                }
4247            }
4248        }
4249        break;
4250
4251    case clang::Type::LValueReference:
4252    case clang::Type::RValueReference:
4253        if (idx_is_valid)
4254        {
4255            const ReferenceType *reference_type = cast<ReferenceType>(parent_qual_type.getTypePtr());
4256            QualType pointee_type(reference_type->getPointeeType());
4257            clang_type_t pointee_clang_type = pointee_type.getAsOpaquePtr();
4258            if (transparent_pointers && ClangASTContext::IsAggregateType (pointee_clang_type))
4259            {
4260                child_is_deref_of_parent = false;
4261                bool tmp_child_is_deref_of_parent = false;
4262                return GetChildClangTypeAtIndex (exe_ctx,
4263                                                 ast,
4264                                                 parent_name,
4265                                                 pointee_clang_type,
4266                                                 idx,
4267                                                 transparent_pointers,
4268                                                 omit_empty_base_classes,
4269                                                 ignore_array_bounds,
4270                                                 child_name,
4271                                                 child_byte_size,
4272                                                 child_byte_offset,
4273                                                 child_bitfield_bit_size,
4274                                                 child_bitfield_bit_offset,
4275                                                 child_is_base_class,
4276                                                 tmp_child_is_deref_of_parent);
4277            }
4278            else
4279            {
4280                if (parent_name)
4281                {
4282                    child_name.assign(1, '&');
4283                    child_name += parent_name;
4284                }
4285
4286                // We have a pointer to an simple type
4287                if (idx == 0)
4288                {
4289                    std::pair<uint64_t, unsigned> clang_type_info = ast->getTypeInfo(pointee_type);
4290                    assert(clang_type_info.first % 8 == 0);
4291                    child_byte_size = clang_type_info.first / 8;
4292                    child_byte_offset = 0;
4293                    return pointee_type.getAsOpaquePtr();
4294                }
4295            }
4296        }
4297        break;
4298
4299    case clang::Type::Typedef:
4300        return GetChildClangTypeAtIndex (exe_ctx,
4301                                         ast,
4302                                         parent_name,
4303                                         cast<TypedefType>(parent_qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(),
4304                                         idx,
4305                                         transparent_pointers,
4306                                         omit_empty_base_classes,
4307                                         ignore_array_bounds,
4308                                         child_name,
4309                                         child_byte_size,
4310                                         child_byte_offset,
4311                                         child_bitfield_bit_size,
4312                                         child_bitfield_bit_offset,
4313                                         child_is_base_class,
4314                                         child_is_deref_of_parent);
4315        break;
4316
4317    case clang::Type::Elaborated:
4318        return GetChildClangTypeAtIndex (exe_ctx,
4319                                         ast,
4320                                         parent_name,
4321                                         cast<ElaboratedType>(parent_qual_type)->getNamedType().getAsOpaquePtr(),
4322                                         idx,
4323                                         transparent_pointers,
4324                                         omit_empty_base_classes,
4325                                         ignore_array_bounds,
4326                                         child_name,
4327                                         child_byte_size,
4328                                         child_byte_offset,
4329                                         child_bitfield_bit_size,
4330                                         child_bitfield_bit_offset,
4331                                         child_is_base_class,
4332                                         child_is_deref_of_parent);
4333
4334    default:
4335        break;
4336    }
4337    return NULL;
4338}
4339
4340static inline bool
4341BaseSpecifierIsEmpty (const CXXBaseSpecifier *b)
4342{
4343    return ClangASTContext::RecordHasFields(b->getType()->getAsCXXRecordDecl()) == false;
4344}
4345
4346static uint32_t
4347GetNumBaseClasses (const CXXRecordDecl *cxx_record_decl, bool omit_empty_base_classes)
4348{
4349    uint32_t num_bases = 0;
4350    if (cxx_record_decl)
4351    {
4352        if (omit_empty_base_classes)
4353        {
4354            CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
4355            for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
4356                 base_class != base_class_end;
4357                 ++base_class)
4358            {
4359                // Skip empty base classes
4360                if (omit_empty_base_classes)
4361                {
4362                    if (BaseSpecifierIsEmpty (base_class))
4363                        continue;
4364                }
4365                ++num_bases;
4366            }
4367        }
4368        else
4369            num_bases = cxx_record_decl->getNumBases();
4370    }
4371    return num_bases;
4372}
4373
4374
4375static uint32_t
4376GetIndexForRecordBase
4377(
4378    const RecordDecl *record_decl,
4379    const CXXBaseSpecifier *base_spec,
4380    bool omit_empty_base_classes
4381)
4382{
4383    uint32_t child_idx = 0;
4384
4385    const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
4386
4387//    const char *super_name = record_decl->getNameAsCString();
4388//    const char *base_name = base_spec->getType()->getAs<RecordType>()->getDecl()->getNameAsCString();
4389//    printf ("GetIndexForRecordChild (%s, %s)\n", super_name, base_name);
4390//
4391    if (cxx_record_decl)
4392    {
4393        CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
4394        for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
4395             base_class != base_class_end;
4396             ++base_class)
4397        {
4398            if (omit_empty_base_classes)
4399            {
4400                if (BaseSpecifierIsEmpty (base_class))
4401                    continue;
4402            }
4403
4404//            printf ("GetIndexForRecordChild (%s, %s) base[%u] = %s\n", super_name, base_name,
4405//                    child_idx,
4406//                    base_class->getType()->getAs<RecordType>()->getDecl()->getNameAsCString());
4407//
4408//
4409            if (base_class == base_spec)
4410                return child_idx;
4411            ++child_idx;
4412        }
4413    }
4414
4415    return UINT32_MAX;
4416}
4417
4418
4419static uint32_t
4420GetIndexForRecordChild
4421(
4422    const RecordDecl *record_decl,
4423    NamedDecl *canonical_decl,
4424    bool omit_empty_base_classes
4425)
4426{
4427    uint32_t child_idx = GetNumBaseClasses (dyn_cast<CXXRecordDecl>(record_decl), omit_empty_base_classes);
4428
4429//    const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
4430//
4431////    printf ("GetIndexForRecordChild (%s, %s)\n", record_decl->getNameAsCString(), canonical_decl->getNameAsCString());
4432//    if (cxx_record_decl)
4433//    {
4434//        CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
4435//        for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
4436//             base_class != base_class_end;
4437//             ++base_class)
4438//        {
4439//            if (omit_empty_base_classes)
4440//            {
4441//                if (BaseSpecifierIsEmpty (base_class))
4442//                    continue;
4443//            }
4444//
4445////            printf ("GetIndexForRecordChild (%s, %s) base[%u] = %s\n",
4446////                    record_decl->getNameAsCString(),
4447////                    canonical_decl->getNameAsCString(),
4448////                    child_idx,
4449////                    base_class->getType()->getAs<RecordType>()->getDecl()->getNameAsCString());
4450//
4451//
4452//            CXXRecordDecl *curr_base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
4453//            if (curr_base_class_decl == canonical_decl)
4454//            {
4455//                return child_idx;
4456//            }
4457//            ++child_idx;
4458//        }
4459//    }
4460//
4461//    const uint32_t num_bases = child_idx;
4462    RecordDecl::field_iterator field, field_end;
4463    for (field = record_decl->field_begin(), field_end = record_decl->field_end();
4464         field != field_end;
4465         ++field, ++child_idx)
4466    {
4467//            printf ("GetIndexForRecordChild (%s, %s) field[%u] = %s\n",
4468//                    record_decl->getNameAsCString(),
4469//                    canonical_decl->getNameAsCString(),
4470//                    child_idx - num_bases,
4471//                    field->getNameAsCString());
4472
4473        if (field->getCanonicalDecl() == canonical_decl)
4474            return child_idx;
4475    }
4476
4477    return UINT32_MAX;
4478}
4479
4480// Look for a child member (doesn't include base classes, but it does include
4481// their members) in the type hierarchy. Returns an index path into "clang_type"
4482// on how to reach the appropriate member.
4483//
4484//    class A
4485//    {
4486//    public:
4487//        int m_a;
4488//        int m_b;
4489//    };
4490//
4491//    class B
4492//    {
4493//    };
4494//
4495//    class C :
4496//        public B,
4497//        public A
4498//    {
4499//    };
4500//
4501// If we have a clang type that describes "class C", and we wanted to looked
4502// "m_b" in it:
4503//
4504// With omit_empty_base_classes == false we would get an integer array back with:
4505// { 1,  1 }
4506// The first index 1 is the child index for "class A" within class C
4507// The second index 1 is the child index for "m_b" within class A
4508//
4509// With omit_empty_base_classes == true we would get an integer array back with:
4510// { 0,  1 }
4511// 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)
4512// The second index 1 is the child index for "m_b" within class A
4513
4514size_t
4515ClangASTContext::GetIndexOfChildMemberWithName
4516(
4517    ASTContext *ast,
4518    clang_type_t clang_type,
4519    const char *name,
4520    bool omit_empty_base_classes,
4521    std::vector<uint32_t>& child_indexes
4522)
4523{
4524    if (clang_type && name && name[0])
4525    {
4526        QualType qual_type(QualType::getFromOpaquePtr(clang_type));
4527        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
4528        switch (type_class)
4529        {
4530        case clang::Type::Record:
4531            if (GetCompleteQualType (ast, qual_type))
4532            {
4533                const RecordType *record_type = cast<RecordType>(qual_type.getTypePtr());
4534                const RecordDecl *record_decl = record_type->getDecl();
4535
4536                assert(record_decl);
4537                uint32_t child_idx = 0;
4538
4539                const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
4540
4541                // Try and find a field that matches NAME
4542                RecordDecl::field_iterator field, field_end;
4543                StringRef name_sref(name);
4544                for (field = record_decl->field_begin(), field_end = record_decl->field_end();
4545                     field != field_end;
4546                     ++field, ++child_idx)
4547                {
4548                    if (field->getName().equals (name_sref))
4549                    {
4550                        // We have to add on the number of base classes to this index!
4551                        child_indexes.push_back (child_idx + GetNumBaseClasses (cxx_record_decl, omit_empty_base_classes));
4552                        return child_indexes.size();
4553                    }
4554                }
4555
4556                if (cxx_record_decl)
4557                {
4558                    const RecordDecl *parent_record_decl = cxx_record_decl;
4559
4560                    //printf ("parent = %s\n", parent_record_decl->getNameAsCString());
4561
4562                    //const Decl *root_cdecl = cxx_record_decl->getCanonicalDecl();
4563                    // Didn't find things easily, lets let clang do its thang...
4564                    IdentifierInfo & ident_ref = ast->Idents.get(name_sref);
4565                    DeclarationName decl_name(&ident_ref);
4566
4567                    CXXBasePaths paths;
4568                    if (cxx_record_decl->lookupInBases(CXXRecordDecl::FindOrdinaryMember,
4569                                                       decl_name.getAsOpaquePtr(),
4570                                                       paths))
4571                    {
4572                        CXXBasePaths::const_paths_iterator path, path_end = paths.end();
4573                        for (path = paths.begin(); path != path_end; ++path)
4574                        {
4575                            const size_t num_path_elements = path->size();
4576                            for (size_t e=0; e<num_path_elements; ++e)
4577                            {
4578                                CXXBasePathElement elem = (*path)[e];
4579
4580                                child_idx = GetIndexForRecordBase (parent_record_decl, elem.Base, omit_empty_base_classes);
4581                                if (child_idx == UINT32_MAX)
4582                                {
4583                                    child_indexes.clear();
4584                                    return 0;
4585                                }
4586                                else
4587                                {
4588                                    child_indexes.push_back (child_idx);
4589                                    parent_record_decl = cast<RecordDecl>(elem.Base->getType()->getAs<RecordType>()->getDecl());
4590                                }
4591                            }
4592                            for (NamedDecl *path_decl : path->Decls)
4593                            {
4594                                child_idx = GetIndexForRecordChild (parent_record_decl, path_decl, omit_empty_base_classes);
4595                                if (child_idx == UINT32_MAX)
4596                                {
4597                                    child_indexes.clear();
4598                                    return 0;
4599                                }
4600                                else
4601                                {
4602                                    child_indexes.push_back (child_idx);
4603                                }
4604                            }
4605                        }
4606                        return child_indexes.size();
4607                    }
4608                }
4609
4610            }
4611            break;
4612
4613        case clang::Type::ObjCObject:
4614        case clang::Type::ObjCInterface:
4615            if (GetCompleteQualType (ast, qual_type))
4616            {
4617                StringRef name_sref(name);
4618                const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(qual_type.getTypePtr());
4619                assert (objc_class_type);
4620                if (objc_class_type)
4621                {
4622                    uint32_t child_idx = 0;
4623                    ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
4624
4625                    if (class_interface_decl)
4626                    {
4627                        ObjCInterfaceDecl::ivar_iterator ivar_pos, ivar_end = class_interface_decl->ivar_end();
4628                        ObjCInterfaceDecl *superclass_interface_decl = class_interface_decl->getSuperClass();
4629
4630                        for (ivar_pos = class_interface_decl->ivar_begin(); ivar_pos != ivar_end; ++ivar_pos, ++child_idx)
4631                        {
4632                            const ObjCIvarDecl* ivar_decl = *ivar_pos;
4633
4634                            if (ivar_decl->getName().equals (name_sref))
4635                            {
4636                                if ((!omit_empty_base_classes && superclass_interface_decl) ||
4637                                    ( omit_empty_base_classes && ObjCDeclHasIVars (superclass_interface_decl, true)))
4638                                    ++child_idx;
4639
4640                                child_indexes.push_back (child_idx);
4641                                return child_indexes.size();
4642                            }
4643                        }
4644
4645                        if (superclass_interface_decl)
4646                        {
4647                            // The super class index is always zero for ObjC classes,
4648                            // so we push it onto the child indexes in case we find
4649                            // an ivar in our superclass...
4650                            child_indexes.push_back (0);
4651
4652                            if (GetIndexOfChildMemberWithName (ast,
4653                                                               ast->getObjCInterfaceType(superclass_interface_decl).getAsOpaquePtr(),
4654                                                               name,
4655                                                               omit_empty_base_classes,
4656                                                               child_indexes))
4657                            {
4658                                // We did find an ivar in a superclass so just
4659                                // return the results!
4660                                return child_indexes.size();
4661                            }
4662
4663                            // We didn't find an ivar matching "name" in our
4664                            // superclass, pop the superclass zero index that
4665                            // we pushed on above.
4666                            child_indexes.pop_back();
4667                        }
4668                    }
4669                }
4670            }
4671            break;
4672
4673        case clang::Type::ObjCObjectPointer:
4674            {
4675                return GetIndexOfChildMemberWithName (ast,
4676                                                      cast<ObjCObjectPointerType>(qual_type.getTypePtr())->getPointeeType().getAsOpaquePtr(),
4677                                                      name,
4678                                                      omit_empty_base_classes,
4679                                                      child_indexes);
4680            }
4681            break;
4682
4683
4684        case clang::Type::ConstantArray:
4685            {
4686//                const ConstantArrayType *array = cast<ConstantArrayType>(parent_qual_type.getTypePtr());
4687//                const uint64_t element_count = array->getSize().getLimitedValue();
4688//
4689//                if (idx < element_count)
4690//                {
4691//                    std::pair<uint64_t, unsigned> field_type_info = ast->getTypeInfo(array->getElementType());
4692//
4693//                    char element_name[32];
4694//                    ::snprintf (element_name, sizeof (element_name), "%s[%u]", parent_name ? parent_name : "", idx);
4695//
4696//                    child_name.assign(element_name);
4697//                    assert(field_type_info.first % 8 == 0);
4698//                    child_byte_size = field_type_info.first / 8;
4699//                    child_byte_offset = idx * child_byte_size;
4700//                    return array->getElementType().getAsOpaquePtr();
4701//                }
4702            }
4703            break;
4704
4705//        case clang::Type::MemberPointerType:
4706//            {
4707//                MemberPointerType *mem_ptr_type = cast<MemberPointerType>(qual_type.getTypePtr());
4708//                QualType pointee_type = mem_ptr_type->getPointeeType();
4709//
4710//                if (ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
4711//                {
4712//                    return GetIndexOfChildWithName (ast,
4713//                                                    mem_ptr_type->getPointeeType().getAsOpaquePtr(),
4714//                                                    name);
4715//                }
4716//            }
4717//            break;
4718//
4719        case clang::Type::LValueReference:
4720        case clang::Type::RValueReference:
4721            {
4722                const ReferenceType *reference_type = cast<ReferenceType>(qual_type.getTypePtr());
4723                QualType pointee_type = reference_type->getPointeeType();
4724
4725                if (ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
4726                {
4727                    return GetIndexOfChildMemberWithName (ast,
4728                                                          reference_type->getPointeeType().getAsOpaquePtr(),
4729                                                          name,
4730                                                          omit_empty_base_classes,
4731                                                          child_indexes);
4732                }
4733            }
4734            break;
4735
4736        case clang::Type::Pointer:
4737            {
4738                const PointerType *pointer_type = cast<PointerType>(qual_type.getTypePtr());
4739                QualType pointee_type = pointer_type->getPointeeType();
4740
4741                if (ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
4742                {
4743                    return GetIndexOfChildMemberWithName (ast,
4744                                                          pointer_type->getPointeeType().getAsOpaquePtr(),
4745                                                          name,
4746                                                          omit_empty_base_classes,
4747                                                          child_indexes);
4748                }
4749                else
4750                {
4751//                    if (parent_name)
4752//                    {
4753//                        child_name.assign(1, '*');
4754//                        child_name += parent_name;
4755//                    }
4756//
4757//                    // We have a pointer to an simple type
4758//                    if (idx == 0)
4759//                    {
4760//                        std::pair<uint64_t, unsigned> clang_type_info = ast->getTypeInfo(pointee_type);
4761//                        assert(clang_type_info.first % 8 == 0);
4762//                        child_byte_size = clang_type_info.first / 8;
4763//                        child_byte_offset = 0;
4764//                        return pointee_type.getAsOpaquePtr();
4765//                    }
4766                }
4767            }
4768            break;
4769
4770        case clang::Type::Typedef:
4771            return GetIndexOfChildMemberWithName (ast,
4772                                                  cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(),
4773                                                  name,
4774                                                  omit_empty_base_classes,
4775                                                  child_indexes);
4776
4777        case clang::Type::Elaborated:
4778            return GetIndexOfChildMemberWithName (ast,
4779                                                  cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(),
4780                                                  name,
4781                                                  omit_empty_base_classes,
4782                                                  child_indexes);
4783
4784        default:
4785            break;
4786        }
4787    }
4788    return 0;
4789}
4790
4791
4792// Get the index of the child of "clang_type" whose name matches. This function
4793// doesn't descend into the children, but only looks one level deep and name
4794// matches can include base class names.
4795
4796uint32_t
4797ClangASTContext::GetIndexOfChildWithName
4798(
4799    ASTContext *ast,
4800    clang_type_t clang_type,
4801    const char *name,
4802    bool omit_empty_base_classes
4803)
4804{
4805    if (clang_type && name && name[0])
4806    {
4807        QualType qual_type(QualType::getFromOpaquePtr(clang_type));
4808
4809        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
4810
4811        switch (type_class)
4812        {
4813        case clang::Type::Record:
4814            if (GetCompleteQualType (ast, qual_type))
4815            {
4816                const RecordType *record_type = cast<RecordType>(qual_type.getTypePtr());
4817                const RecordDecl *record_decl = record_type->getDecl();
4818
4819                assert(record_decl);
4820                uint32_t child_idx = 0;
4821
4822                const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
4823
4824                if (cxx_record_decl)
4825                {
4826                    CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
4827                    for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
4828                         base_class != base_class_end;
4829                         ++base_class)
4830                    {
4831                        // Skip empty base classes
4832                        CXXRecordDecl *base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
4833                        if (omit_empty_base_classes && RecordHasFields(base_class_decl) == false)
4834                            continue;
4835
4836                        std::string base_class_type_name (ClangASTType::GetTypeNameForQualType(ast, base_class->getType()));
4837                        if (base_class_type_name.compare (name) == 0)
4838                            return child_idx;
4839                        ++child_idx;
4840                    }
4841                }
4842
4843                // Try and find a field that matches NAME
4844                RecordDecl::field_iterator field, field_end;
4845                StringRef name_sref(name);
4846                for (field = record_decl->field_begin(), field_end = record_decl->field_end();
4847                     field != field_end;
4848                     ++field, ++child_idx)
4849                {
4850                    if (field->getName().equals (name_sref))
4851                        return child_idx;
4852                }
4853
4854            }
4855            break;
4856
4857        case clang::Type::ObjCObject:
4858        case clang::Type::ObjCInterface:
4859            if (GetCompleteQualType (ast, qual_type))
4860            {
4861                StringRef name_sref(name);
4862                const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(qual_type.getTypePtr());
4863                assert (objc_class_type);
4864                if (objc_class_type)
4865                {
4866                    uint32_t child_idx = 0;
4867                    ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
4868
4869                    if (class_interface_decl)
4870                    {
4871                        ObjCInterfaceDecl::ivar_iterator ivar_pos, ivar_end = class_interface_decl->ivar_end();
4872                        ObjCInterfaceDecl *superclass_interface_decl = class_interface_decl->getSuperClass();
4873
4874                        for (ivar_pos = class_interface_decl->ivar_begin(); ivar_pos != ivar_end; ++ivar_pos, ++child_idx)
4875                        {
4876                            const ObjCIvarDecl* ivar_decl = *ivar_pos;
4877
4878                            if (ivar_decl->getName().equals (name_sref))
4879                            {
4880                                if ((!omit_empty_base_classes && superclass_interface_decl) ||
4881                                    ( omit_empty_base_classes && ObjCDeclHasIVars (superclass_interface_decl, true)))
4882                                    ++child_idx;
4883
4884                                return child_idx;
4885                            }
4886                        }
4887
4888                        if (superclass_interface_decl)
4889                        {
4890                            if (superclass_interface_decl->getName().equals (name_sref))
4891                                return 0;
4892                        }
4893                    }
4894                }
4895            }
4896            break;
4897
4898        case clang::Type::ObjCObjectPointer:
4899            {
4900                return GetIndexOfChildWithName (ast,
4901                                                cast<ObjCObjectPointerType>(qual_type.getTypePtr())->getPointeeType().getAsOpaquePtr(),
4902                                                name,
4903                                                omit_empty_base_classes);
4904            }
4905            break;
4906
4907        case clang::Type::ConstantArray:
4908            {
4909//                const ConstantArrayType *array = cast<ConstantArrayType>(parent_qual_type.getTypePtr());
4910//                const uint64_t element_count = array->getSize().getLimitedValue();
4911//
4912//                if (idx < element_count)
4913//                {
4914//                    std::pair<uint64_t, unsigned> field_type_info = ast->getTypeInfo(array->getElementType());
4915//
4916//                    char element_name[32];
4917//                    ::snprintf (element_name, sizeof (element_name), "%s[%u]", parent_name ? parent_name : "", idx);
4918//
4919//                    child_name.assign(element_name);
4920//                    assert(field_type_info.first % 8 == 0);
4921//                    child_byte_size = field_type_info.first / 8;
4922//                    child_byte_offset = idx * child_byte_size;
4923//                    return array->getElementType().getAsOpaquePtr();
4924//                }
4925            }
4926            break;
4927
4928//        case clang::Type::MemberPointerType:
4929//            {
4930//                MemberPointerType *mem_ptr_type = cast<MemberPointerType>(qual_type.getTypePtr());
4931//                QualType pointee_type = mem_ptr_type->getPointeeType();
4932//
4933//                if (ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
4934//                {
4935//                    return GetIndexOfChildWithName (ast,
4936//                                                    mem_ptr_type->getPointeeType().getAsOpaquePtr(),
4937//                                                    name);
4938//                }
4939//            }
4940//            break;
4941//
4942        case clang::Type::LValueReference:
4943        case clang::Type::RValueReference:
4944            {
4945                const ReferenceType *reference_type = cast<ReferenceType>(qual_type.getTypePtr());
4946                QualType pointee_type = reference_type->getPointeeType();
4947
4948                if (ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
4949                {
4950                    return GetIndexOfChildWithName (ast,
4951                                                    reference_type->getPointeeType().getAsOpaquePtr(),
4952                                                    name,
4953                                                    omit_empty_base_classes);
4954                }
4955            }
4956            break;
4957
4958        case clang::Type::Pointer:
4959            {
4960                const PointerType *pointer_type = cast<PointerType>(qual_type.getTypePtr());
4961                QualType pointee_type = pointer_type->getPointeeType();
4962
4963                if (ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
4964                {
4965                    return GetIndexOfChildWithName (ast,
4966                                                    pointer_type->getPointeeType().getAsOpaquePtr(),
4967                                                    name,
4968                                                    omit_empty_base_classes);
4969                }
4970                else
4971                {
4972//                    if (parent_name)
4973//                    {
4974//                        child_name.assign(1, '*');
4975//                        child_name += parent_name;
4976//                    }
4977//
4978//                    // We have a pointer to an simple type
4979//                    if (idx == 0)
4980//                    {
4981//                        std::pair<uint64_t, unsigned> clang_type_info = ast->getTypeInfo(pointee_type);
4982//                        assert(clang_type_info.first % 8 == 0);
4983//                        child_byte_size = clang_type_info.first / 8;
4984//                        child_byte_offset = 0;
4985//                        return pointee_type.getAsOpaquePtr();
4986//                    }
4987                }
4988            }
4989            break;
4990
4991        case clang::Type::Elaborated:
4992            return GetIndexOfChildWithName (ast,
4993                                            cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(),
4994                                            name,
4995                                            omit_empty_base_classes);
4996
4997        case clang::Type::Typedef:
4998            return GetIndexOfChildWithName (ast,
4999                                            cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(),
5000                                            name,
5001                                            omit_empty_base_classes);
5002
5003        default:
5004            break;
5005        }
5006    }
5007    return UINT32_MAX;
5008}
5009
5010#pragma mark TagType
5011
5012bool
5013ClangASTContext::SetTagTypeKind (clang_type_t tag_clang_type, int kind)
5014{
5015    if (tag_clang_type)
5016    {
5017        QualType tag_qual_type(QualType::getFromOpaquePtr(tag_clang_type));
5018        const clang::Type *clang_type = tag_qual_type.getTypePtr();
5019        if (clang_type)
5020        {
5021            const TagType *tag_type = dyn_cast<TagType>(clang_type);
5022            if (tag_type)
5023            {
5024                TagDecl *tag_decl = dyn_cast<TagDecl>(tag_type->getDecl());
5025                if (tag_decl)
5026                {
5027                    tag_decl->setTagKind ((TagDecl::TagKind)kind);
5028                    return true;
5029                }
5030            }
5031        }
5032    }
5033    return false;
5034}
5035
5036
5037#pragma mark DeclContext Functions
5038
5039DeclContext *
5040ClangASTContext::GetDeclContextForType (clang_type_t clang_type)
5041{
5042    if (clang_type == NULL)
5043        return NULL;
5044
5045    QualType qual_type(QualType::getFromOpaquePtr(clang_type));
5046    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5047    switch (type_class)
5048    {
5049    case clang::Type::UnaryTransform:           break;
5050    case clang::Type::FunctionNoProto:          break;
5051    case clang::Type::FunctionProto:            break;
5052    case clang::Type::IncompleteArray:          break;
5053    case clang::Type::VariableArray:            break;
5054    case clang::Type::ConstantArray:            break;
5055    case clang::Type::DependentSizedArray:      break;
5056    case clang::Type::ExtVector:                break;
5057    case clang::Type::DependentSizedExtVector:  break;
5058    case clang::Type::Vector:                   break;
5059    case clang::Type::Builtin:                  break;
5060    case clang::Type::BlockPointer:             break;
5061    case clang::Type::Pointer:                  break;
5062    case clang::Type::LValueReference:          break;
5063    case clang::Type::RValueReference:          break;
5064    case clang::Type::MemberPointer:            break;
5065    case clang::Type::Complex:                  break;
5066    case clang::Type::ObjCObject:               break;
5067    case clang::Type::ObjCInterface:            return cast<ObjCObjectType>(qual_type.getTypePtr())->getInterface();
5068    case clang::Type::ObjCObjectPointer:        return ClangASTContext::GetDeclContextForType (cast<ObjCObjectPointerType>(qual_type.getTypePtr())->getPointeeType().getAsOpaquePtr());
5069    case clang::Type::Record:                   return cast<RecordType>(qual_type)->getDecl();
5070    case clang::Type::Enum:                     return cast<EnumType>(qual_type)->getDecl();
5071    case clang::Type::Typedef:                  return ClangASTContext::GetDeclContextForType (cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
5072    case clang::Type::Elaborated:               return ClangASTContext::GetDeclContextForType (cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
5073    case clang::Type::TypeOfExpr:               break;
5074    case clang::Type::TypeOf:                   break;
5075    case clang::Type::Decltype:                 break;
5076    //case clang::Type::QualifiedName:          break;
5077    case clang::Type::TemplateSpecialization:   break;
5078    case clang::Type::DependentTemplateSpecialization:  break;
5079    case clang::Type::TemplateTypeParm:         break;
5080    case clang::Type::SubstTemplateTypeParm:    break;
5081    case clang::Type::SubstTemplateTypeParmPack:break;
5082    case clang::Type::PackExpansion:            break;
5083    case clang::Type::UnresolvedUsing:          break;
5084    case clang::Type::Paren:                    break;
5085    case clang::Type::Attributed:               break;
5086    case clang::Type::Auto:                     break;
5087    case clang::Type::InjectedClassName:        break;
5088    case clang::Type::DependentName:            break;
5089    case clang::Type::Atomic:                   break;
5090    }
5091    // No DeclContext in this type...
5092    return NULL;
5093}
5094
5095#pragma mark Namespace Declarations
5096
5097NamespaceDecl *
5098ClangASTContext::GetUniqueNamespaceDeclaration (const char *name, DeclContext *decl_ctx)
5099{
5100    NamespaceDecl *namespace_decl = NULL;
5101    ASTContext *ast = getASTContext();
5102    TranslationUnitDecl *translation_unit_decl = ast->getTranslationUnitDecl ();
5103    if (decl_ctx == NULL)
5104        decl_ctx = translation_unit_decl;
5105
5106    if (name)
5107    {
5108        IdentifierInfo &identifier_info = ast->Idents.get(name);
5109        DeclarationName decl_name (&identifier_info);
5110        clang::DeclContext::lookup_result result = decl_ctx->lookup(decl_name);
5111        for (NamedDecl *decl : result)
5112        {
5113            namespace_decl = dyn_cast<clang::NamespaceDecl>(decl);
5114            if (namespace_decl)
5115                return namespace_decl;
5116        }
5117
5118        namespace_decl = NamespaceDecl::Create(*ast,
5119                                               decl_ctx,
5120                                               false,
5121                                               SourceLocation(),
5122                                               SourceLocation(),
5123                                               &identifier_info,
5124                                               NULL);
5125
5126        decl_ctx->addDecl (namespace_decl);
5127    }
5128    else
5129    {
5130        if (decl_ctx == translation_unit_decl)
5131        {
5132            namespace_decl = translation_unit_decl->getAnonymousNamespace();
5133            if (namespace_decl)
5134                return namespace_decl;
5135
5136            namespace_decl = NamespaceDecl::Create(*ast,
5137                                                   decl_ctx,
5138                                                   false,
5139                                                   SourceLocation(),
5140                                                   SourceLocation(),
5141                                                   NULL,
5142                                                   NULL);
5143            translation_unit_decl->setAnonymousNamespace (namespace_decl);
5144            translation_unit_decl->addDecl (namespace_decl);
5145            assert (namespace_decl == translation_unit_decl->getAnonymousNamespace());
5146        }
5147        else
5148        {
5149            NamespaceDecl *parent_namespace_decl = cast<NamespaceDecl>(decl_ctx);
5150            if (parent_namespace_decl)
5151            {
5152                namespace_decl = parent_namespace_decl->getAnonymousNamespace();
5153                if (namespace_decl)
5154                    return namespace_decl;
5155                namespace_decl = NamespaceDecl::Create(*ast,
5156                                                       decl_ctx,
5157                                                       false,
5158                                                       SourceLocation(),
5159                                                       SourceLocation(),
5160                                                       NULL,
5161                                                       NULL);
5162                parent_namespace_decl->setAnonymousNamespace (namespace_decl);
5163                parent_namespace_decl->addDecl (namespace_decl);
5164                assert (namespace_decl == parent_namespace_decl->getAnonymousNamespace());
5165            }
5166            else
5167            {
5168                // BAD!!!
5169            }
5170        }
5171
5172
5173        if (namespace_decl)
5174        {
5175            // If we make it here, we are creating the anonymous namespace decl
5176            // for the first time, so we need to do the using directive magic
5177            // like SEMA does
5178            UsingDirectiveDecl* using_directive_decl = UsingDirectiveDecl::Create (*ast,
5179                                                                                   decl_ctx,
5180                                                                                   SourceLocation(),
5181                                                                                   SourceLocation(),
5182                                                                                   NestedNameSpecifierLoc(),
5183                                                                                   SourceLocation(),
5184                                                                                   namespace_decl,
5185                                                                                   decl_ctx);
5186            using_directive_decl->setImplicit();
5187            decl_ctx->addDecl(using_directive_decl);
5188        }
5189    }
5190#ifdef LLDB_CONFIGURATION_DEBUG
5191    VerifyDecl(namespace_decl);
5192#endif
5193    return namespace_decl;
5194}
5195
5196
5197#pragma mark Function Types
5198
5199FunctionDecl *
5200ClangASTContext::CreateFunctionDeclaration (DeclContext *decl_ctx, const char *name, clang_type_t function_clang_type, int storage, bool is_inline)
5201{
5202    FunctionDecl *func_decl = NULL;
5203    ASTContext *ast = getASTContext();
5204    if (decl_ctx == NULL)
5205        decl_ctx = ast->getTranslationUnitDecl();
5206
5207    if (name && name[0])
5208    {
5209        func_decl = FunctionDecl::Create (*ast,
5210                                          decl_ctx,
5211                                          SourceLocation(),
5212                                          SourceLocation(),
5213                                          DeclarationName (&ast->Idents.get(name)),
5214                                          QualType::getFromOpaquePtr(function_clang_type),
5215                                          NULL,
5216                                          (FunctionDecl::StorageClass)storage,
5217                                          (FunctionDecl::StorageClass)storage,
5218                                          is_inline);
5219    }
5220    else
5221    {
5222        func_decl = FunctionDecl::Create (*ast,
5223                                          decl_ctx,
5224                                          SourceLocation(),
5225                                          SourceLocation(),
5226                                          DeclarationName (),
5227                                          QualType::getFromOpaquePtr(function_clang_type),
5228                                          NULL,
5229                                          (FunctionDecl::StorageClass)storage,
5230                                          (FunctionDecl::StorageClass)storage,
5231                                          is_inline);
5232    }
5233    if (func_decl)
5234        decl_ctx->addDecl (func_decl);
5235
5236#ifdef LLDB_CONFIGURATION_DEBUG
5237    VerifyDecl(func_decl);
5238#endif
5239
5240    return func_decl;
5241}
5242
5243clang_type_t
5244ClangASTContext::CreateFunctionType (ASTContext *ast,
5245                                     clang_type_t result_type,
5246                                     clang_type_t *args,
5247                                     unsigned num_args,
5248                                     bool is_variadic,
5249                                     unsigned type_quals)
5250{
5251    assert (ast != NULL);
5252    std::vector<QualType> qual_type_args;
5253    for (unsigned i=0; i<num_args; ++i)
5254        qual_type_args.push_back (QualType::getFromOpaquePtr(args[i]));
5255
5256    // TODO: Detect calling convention in DWARF?
5257    FunctionProtoType::ExtProtoInfo proto_info;
5258    proto_info.Variadic = is_variadic;
5259    proto_info.ExceptionSpecType = EST_None;
5260    proto_info.TypeQuals = type_quals;
5261    proto_info.RefQualifier = RQ_None;
5262    proto_info.NumExceptions = 0;
5263    proto_info.Exceptions = NULL;
5264
5265    return ast->getFunctionType (QualType::getFromOpaquePtr(result_type),
5266                                 qual_type_args.empty() ? NULL : &qual_type_args.front(),
5267                                 qual_type_args.size(),
5268                                 proto_info).getAsOpaquePtr();    // NoReturn);
5269}
5270
5271ParmVarDecl *
5272ClangASTContext::CreateParameterDeclaration (const char *name, clang_type_t param_type, int storage)
5273{
5274    ASTContext *ast = getASTContext();
5275    assert (ast != NULL);
5276    return ParmVarDecl::Create(*ast,
5277                                ast->getTranslationUnitDecl(),
5278                                SourceLocation(),
5279                                SourceLocation(),
5280                                name && name[0] ? &ast->Idents.get(name) : NULL,
5281                                QualType::getFromOpaquePtr(param_type),
5282                                NULL,
5283                                (VarDecl::StorageClass)storage,
5284                                (VarDecl::StorageClass)storage,
5285                                0);
5286}
5287
5288void
5289ClangASTContext::SetFunctionParameters (FunctionDecl *function_decl, ParmVarDecl **params, unsigned num_params)
5290{
5291    if (function_decl)
5292        function_decl->setParams (ArrayRef<ParmVarDecl*>(params, num_params));
5293}
5294
5295
5296#pragma mark Array Types
5297
5298clang_type_t
5299ClangASTContext::CreateArrayType (clang_type_t element_type, size_t element_count)
5300{
5301    if (element_type)
5302    {
5303        ASTContext *ast = getASTContext();
5304        assert (ast != NULL);
5305        llvm::APInt ap_element_count (64, element_count);
5306        if (element_count == 0)
5307        {
5308            return ast->getIncompleteArrayType(QualType::getFromOpaquePtr(element_type),
5309                                               ArrayType::Normal,
5310                                               0).getAsOpaquePtr();
5311
5312        }
5313        else
5314        {
5315            return ast->getConstantArrayType(QualType::getFromOpaquePtr(element_type),
5316                                                     ap_element_count,
5317                                                     ArrayType::Normal,
5318                                                     0).getAsOpaquePtr(); // ElemQuals
5319        }
5320    }
5321    return NULL;
5322}
5323
5324
5325#pragma mark TagDecl
5326
5327bool
5328ClangASTContext::StartTagDeclarationDefinition (clang_type_t clang_type)
5329{
5330    if (clang_type)
5331    {
5332        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
5333        const clang::Type *t = qual_type.getTypePtr();
5334        if (t)
5335        {
5336            const TagType *tag_type = dyn_cast<TagType>(t);
5337            if (tag_type)
5338            {
5339                TagDecl *tag_decl = tag_type->getDecl();
5340                if (tag_decl)
5341                {
5342                    tag_decl->startDefinition();
5343                    return true;
5344                }
5345            }
5346
5347            const ObjCObjectType *object_type = dyn_cast<ObjCObjectType>(t);
5348            if (object_type)
5349            {
5350                ObjCInterfaceDecl *interface_decl = object_type->getInterface();
5351                if (interface_decl)
5352                {
5353                    interface_decl->startDefinition();
5354                    return true;
5355                }
5356            }
5357        }
5358    }
5359    return false;
5360}
5361
5362bool
5363ClangASTContext::CompleteTagDeclarationDefinition (clang_type_t clang_type)
5364{
5365    if (clang_type)
5366    {
5367        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
5368
5369        CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
5370
5371        if (cxx_record_decl)
5372        {
5373            cxx_record_decl->completeDefinition();
5374
5375            return true;
5376        }
5377
5378        const EnumType *enum_type = dyn_cast<EnumType>(qual_type.getTypePtr());
5379
5380        if (enum_type)
5381        {
5382            EnumDecl *enum_decl = enum_type->getDecl();
5383
5384            if (enum_decl)
5385            {
5386                /// TODO This really needs to be fixed.
5387
5388                unsigned NumPositiveBits = 1;
5389                unsigned NumNegativeBits = 0;
5390
5391                ASTContext *ast = getASTContext();
5392
5393                QualType promotion_qual_type;
5394                // If the enum integer type is less than an integer in bit width,
5395                // then we must promote it to an integer size.
5396                if (ast->getTypeSize(enum_decl->getIntegerType()) < ast->getTypeSize(ast->IntTy))
5397                {
5398                    if (enum_decl->getIntegerType()->isSignedIntegerType())
5399                        promotion_qual_type = ast->IntTy;
5400                    else
5401                        promotion_qual_type = ast->UnsignedIntTy;
5402                }
5403                else
5404                    promotion_qual_type = enum_decl->getIntegerType();
5405
5406                enum_decl->completeDefinition(enum_decl->getIntegerType(), promotion_qual_type, NumPositiveBits, NumNegativeBits);
5407                return true;
5408            }
5409        }
5410    }
5411    return false;
5412}
5413
5414
5415#pragma mark Enumeration Types
5416
5417clang_type_t
5418ClangASTContext::CreateEnumerationType
5419(
5420    const char *name,
5421    DeclContext *decl_ctx,
5422    const Declaration &decl,
5423    clang_type_t integer_qual_type
5424)
5425{
5426    // TODO: Do something intelligent with the Declaration object passed in
5427    // like maybe filling in the SourceLocation with it...
5428    ASTContext *ast = getASTContext();
5429    assert (ast != NULL);
5430
5431    // TODO: ask about these...
5432//    const bool IsScoped = false;
5433//    const bool IsFixed = false;
5434
5435    EnumDecl *enum_decl = EnumDecl::Create (*ast,
5436                                            decl_ctx,
5437                                            SourceLocation(),
5438                                            SourceLocation(),
5439                                            name && name[0] ? &ast->Idents.get(name) : NULL,
5440                                            NULL,
5441                                            false,  // IsScoped
5442                                            false,  // IsScopedUsingClassTag
5443                                            false); // IsFixed
5444
5445
5446    if (enum_decl)
5447    {
5448        // TODO: check if we should be setting the promotion type too?
5449        enum_decl->setIntegerType(QualType::getFromOpaquePtr (integer_qual_type));
5450
5451        enum_decl->setAccess(AS_public); // TODO respect what's in the debug info
5452
5453        return ast->getTagDeclType(enum_decl).getAsOpaquePtr();
5454    }
5455    return NULL;
5456}
5457
5458clang_type_t
5459ClangASTContext::GetEnumerationIntegerType (clang_type_t enum_clang_type)
5460{
5461    QualType enum_qual_type (QualType::getFromOpaquePtr(enum_clang_type));
5462
5463    const clang::Type *clang_type = enum_qual_type.getTypePtr();
5464    if (clang_type)
5465    {
5466        const EnumType *enum_type = dyn_cast<EnumType>(clang_type);
5467        if (enum_type)
5468        {
5469            EnumDecl *enum_decl = enum_type->getDecl();
5470            if (enum_decl)
5471                return enum_decl->getIntegerType().getAsOpaquePtr();
5472        }
5473    }
5474    return NULL;
5475}
5476bool
5477ClangASTContext::AddEnumerationValueToEnumerationType
5478(
5479    clang_type_t enum_clang_type,
5480    clang_type_t enumerator_clang_type,
5481    const Declaration &decl,
5482    const char *name,
5483    int64_t enum_value,
5484    uint32_t enum_value_bit_size
5485)
5486{
5487    if (enum_clang_type && enumerator_clang_type && name)
5488    {
5489        // TODO: Do something intelligent with the Declaration object passed in
5490        // like maybe filling in the SourceLocation with it...
5491        ASTContext *ast = getASTContext();
5492        IdentifierTable *identifier_table = getIdentifierTable();
5493
5494        assert (ast != NULL);
5495        assert (identifier_table != NULL);
5496        QualType enum_qual_type (QualType::getFromOpaquePtr(enum_clang_type));
5497
5498        const clang::Type *clang_type = enum_qual_type.getTypePtr();
5499        if (clang_type)
5500        {
5501            const EnumType *enum_type = dyn_cast<EnumType>(clang_type);
5502
5503            if (enum_type)
5504            {
5505                llvm::APSInt enum_llvm_apsint(enum_value_bit_size, false);
5506                enum_llvm_apsint = enum_value;
5507                EnumConstantDecl *enumerator_decl =
5508                    EnumConstantDecl::Create (*ast,
5509                                              enum_type->getDecl(),
5510                                              SourceLocation(),
5511                                              name ? &identifier_table->get(name) : NULL,    // Identifier
5512                                              QualType::getFromOpaquePtr(enumerator_clang_type),
5513                                              NULL,
5514                                              enum_llvm_apsint);
5515
5516                if (enumerator_decl)
5517                {
5518                    enum_type->getDecl()->addDecl(enumerator_decl);
5519
5520#ifdef LLDB_CONFIGURATION_DEBUG
5521                    VerifyDecl(enumerator_decl);
5522#endif
5523
5524                    return true;
5525                }
5526            }
5527        }
5528    }
5529    return false;
5530}
5531
5532#pragma mark Pointers & References
5533
5534clang_type_t
5535ClangASTContext::CreatePointerType (clang_type_t clang_type)
5536{
5537    return CreatePointerType (getASTContext(), clang_type);
5538}
5539
5540clang_type_t
5541ClangASTContext::CreatePointerType (clang::ASTContext *ast, clang_type_t clang_type)
5542{
5543    if (ast && clang_type)
5544    {
5545        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
5546
5547        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5548        switch (type_class)
5549        {
5550        case clang::Type::ObjCObject:
5551        case clang::Type::ObjCInterface:
5552            return ast->getObjCObjectPointerType(qual_type).getAsOpaquePtr();
5553
5554        default:
5555            return ast->getPointerType(qual_type).getAsOpaquePtr();
5556        }
5557    }
5558    return NULL;
5559}
5560
5561clang_type_t
5562ClangASTContext::CreateLValueReferenceType (clang::ASTContext *ast,
5563                                            clang_type_t clang_type)
5564{
5565    if (clang_type)
5566        return ast->getLValueReferenceType (QualType::getFromOpaquePtr(clang_type)).getAsOpaquePtr();
5567    return NULL;
5568}
5569
5570clang_type_t
5571ClangASTContext::CreateRValueReferenceType (clang::ASTContext *ast,
5572                                            clang_type_t clang_type)
5573{
5574    if (clang_type)
5575        return ast->getRValueReferenceType (QualType::getFromOpaquePtr(clang_type)).getAsOpaquePtr();
5576    return NULL;
5577}
5578
5579clang_type_t
5580ClangASTContext::CreateMemberPointerType (clang_type_t clang_pointee_type, clang_type_t clang_class_type)
5581{
5582    if (clang_pointee_type && clang_pointee_type)
5583        return getASTContext()->getMemberPointerType(QualType::getFromOpaquePtr(clang_pointee_type),
5584                                                     QualType::getFromOpaquePtr(clang_class_type).getTypePtr()).getAsOpaquePtr();
5585    return NULL;
5586}
5587
5588uint32_t
5589ClangASTContext::GetPointerBitSize ()
5590{
5591    ASTContext *ast = getASTContext();
5592    return ast->getTypeSize(ast->VoidPtrTy);
5593}
5594
5595bool
5596ClangASTContext::IsPossibleDynamicType (clang::ASTContext *ast,
5597                                        clang_type_t clang_type,
5598                                        clang_type_t *dynamic_pointee_type,
5599                                        bool check_cplusplus,
5600                                        bool check_objc)
5601{
5602    QualType pointee_qual_type;
5603    if (clang_type)
5604    {
5605        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
5606        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5607        bool success = false;
5608        switch (type_class)
5609        {
5610            case clang::Type::Builtin:
5611                if (check_objc && cast<clang::BuiltinType>(qual_type)->getKind() == clang::BuiltinType::ObjCId)
5612                {
5613                    if (dynamic_pointee_type)
5614                        *dynamic_pointee_type = clang_type;
5615                    return true;
5616                }
5617                break;
5618
5619            case clang::Type::ObjCObjectPointer:
5620                if (check_objc)
5621                {
5622                    if (dynamic_pointee_type)
5623                        *dynamic_pointee_type = cast<ObjCObjectPointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
5624                    return true;
5625                }
5626                break;
5627
5628            case clang::Type::Pointer:
5629                pointee_qual_type = cast<PointerType>(qual_type)->getPointeeType();
5630                success = true;
5631                break;
5632
5633            case clang::Type::LValueReference:
5634            case clang::Type::RValueReference:
5635                pointee_qual_type = cast<ReferenceType>(qual_type)->getPointeeType();
5636                success = true;
5637                break;
5638
5639            case clang::Type::Typedef:
5640                return ClangASTContext::IsPossibleDynamicType (ast,
5641                                                               cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(),
5642                                                               dynamic_pointee_type,
5643                                                               check_cplusplus,
5644                                                               check_objc);
5645
5646            case clang::Type::Elaborated:
5647                return ClangASTContext::IsPossibleDynamicType (ast,
5648                                                               cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(),
5649                                                               dynamic_pointee_type,
5650                                                               check_cplusplus,
5651                                                               check_objc);
5652
5653            default:
5654                break;
5655        }
5656
5657        if (success)
5658        {
5659            // Check to make sure what we are pointing too is a possible dynamic C++ type
5660            // We currently accept any "void *" (in case we have a class that has been
5661            // watered down to an opaque pointer) and virtual C++ classes.
5662            const clang::Type::TypeClass pointee_type_class = pointee_qual_type->getTypeClass();
5663            switch (pointee_type_class)
5664            {
5665                case clang::Type::Builtin:
5666                    switch (cast<clang::BuiltinType>(pointee_qual_type)->getKind())
5667                    {
5668                        case clang::BuiltinType::UnknownAny:
5669                        case clang::BuiltinType::Void:
5670                            if (dynamic_pointee_type)
5671                                *dynamic_pointee_type = pointee_qual_type.getAsOpaquePtr();
5672                            return true;
5673
5674                        case clang::BuiltinType::NullPtr:
5675                        case clang::BuiltinType::Bool:
5676                        case clang::BuiltinType::Char_U:
5677                        case clang::BuiltinType::UChar:
5678                        case clang::BuiltinType::WChar_U:
5679                        case clang::BuiltinType::Char16:
5680                        case clang::BuiltinType::Char32:
5681                        case clang::BuiltinType::UShort:
5682                        case clang::BuiltinType::UInt:
5683                        case clang::BuiltinType::ULong:
5684                        case clang::BuiltinType::ULongLong:
5685                        case clang::BuiltinType::UInt128:
5686                        case clang::BuiltinType::Char_S:
5687                        case clang::BuiltinType::SChar:
5688                        case clang::BuiltinType::WChar_S:
5689                        case clang::BuiltinType::Short:
5690                        case clang::BuiltinType::Int:
5691                        case clang::BuiltinType::Long:
5692                        case clang::BuiltinType::LongLong:
5693                        case clang::BuiltinType::Int128:
5694                        case clang::BuiltinType::Float:
5695                        case clang::BuiltinType::Double:
5696                        case clang::BuiltinType::LongDouble:
5697                        case clang::BuiltinType::Dependent:
5698                        case clang::BuiltinType::Overload:
5699                        case clang::BuiltinType::ObjCId:
5700                        case clang::BuiltinType::ObjCClass:
5701                        case clang::BuiltinType::ObjCSel:
5702                        case clang::BuiltinType::BoundMember:
5703                        case clang::BuiltinType::Half:
5704                        case clang::BuiltinType::ARCUnbridgedCast:
5705                        case clang::BuiltinType::PseudoObject:
5706                        case clang::BuiltinType::BuiltinFn:
5707                        case clang::BuiltinType::OCLEvent:
5708                        case clang::BuiltinType::OCLImage1d:
5709                        case clang::BuiltinType::OCLImage1dArray:
5710                        case clang::BuiltinType::OCLImage1dBuffer:
5711                        case clang::BuiltinType::OCLImage2d:
5712                        case clang::BuiltinType::OCLImage2dArray:
5713                        case clang::BuiltinType::OCLImage3d:
5714                            break;
5715                    }
5716                    break;
5717
5718                case clang::Type::Record:
5719                    if (check_cplusplus)
5720                    {
5721                        CXXRecordDecl *cxx_record_decl = pointee_qual_type->getAsCXXRecordDecl();
5722                        if (cxx_record_decl)
5723                        {
5724                            bool is_complete = cxx_record_decl->isCompleteDefinition();
5725                            if (!is_complete)
5726                                is_complete = ClangASTContext::GetCompleteType (ast, pointee_qual_type.getAsOpaquePtr());
5727
5728                            if (is_complete)
5729                            {
5730                                success = cxx_record_decl->isDynamicClass();
5731                            }
5732                            else
5733                            {
5734                                success = false;
5735                            }
5736
5737                            if (success)
5738                            {
5739                                if (dynamic_pointee_type)
5740                                    *dynamic_pointee_type = pointee_qual_type.getAsOpaquePtr();
5741                                return true;
5742                            }
5743                        }
5744                    }
5745                    break;
5746
5747                case clang::Type::ObjCObject:
5748                case clang::Type::ObjCInterface:
5749                    if (check_objc)
5750                    {
5751                        if (dynamic_pointee_type)
5752                            *dynamic_pointee_type = pointee_qual_type.getAsOpaquePtr();
5753                        return true;
5754                    }
5755                    break;
5756
5757                default:
5758                    break;
5759            }
5760        }
5761    }
5762    if (dynamic_pointee_type)
5763        *dynamic_pointee_type = NULL;
5764    return false;
5765}
5766
5767
5768bool
5769ClangASTContext::IsPossibleCPlusPlusDynamicType (clang::ASTContext *ast, clang_type_t clang_type, clang_type_t *dynamic_pointee_type)
5770{
5771    return IsPossibleDynamicType (ast,
5772                                  clang_type,
5773                                  dynamic_pointee_type,
5774                                  true,     // Check for dynamic C++ types
5775                                  false);   // Check for dynamic ObjC types
5776}
5777
5778bool
5779ClangASTContext::IsReferenceType (clang_type_t clang_type, clang_type_t *target_type)
5780{
5781    if (clang_type == NULL)
5782        return false;
5783
5784    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
5785    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5786
5787    switch (type_class)
5788    {
5789    case clang::Type::LValueReference:
5790        if (target_type)
5791            *target_type = cast<LValueReferenceType>(qual_type)->desugar().getAsOpaquePtr();
5792        return true;
5793    case clang::Type::RValueReference:
5794        if (target_type)
5795            *target_type = cast<LValueReferenceType>(qual_type)->desugar().getAsOpaquePtr();
5796        return true;
5797    case clang::Type::Typedef:
5798        return ClangASTContext::IsReferenceType (cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
5799    case clang::Type::Elaborated:
5800        return ClangASTContext::IsReferenceType (cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
5801    default:
5802        break;
5803    }
5804
5805    return false;
5806}
5807
5808bool
5809ClangASTContext::IsPointerOrReferenceType (clang_type_t clang_type, clang_type_t*target_type)
5810{
5811    if (clang_type == NULL)
5812        return false;
5813
5814    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
5815    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5816    switch (type_class)
5817    {
5818    case clang::Type::Builtin:
5819        switch (cast<clang::BuiltinType>(qual_type)->getKind())
5820        {
5821        default:
5822            break;
5823        case clang::BuiltinType::ObjCId:
5824        case clang::BuiltinType::ObjCClass:
5825            return true;
5826        }
5827        return false;
5828    case clang::Type::ObjCObjectPointer:
5829        if (target_type)
5830            *target_type = cast<ObjCObjectPointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
5831        return true;
5832    case clang::Type::BlockPointer:
5833        if (target_type)
5834            *target_type = cast<BlockPointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
5835        return true;
5836    case clang::Type::Pointer:
5837        if (target_type)
5838            *target_type = cast<PointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
5839        return true;
5840    case clang::Type::MemberPointer:
5841        if (target_type)
5842            *target_type = cast<MemberPointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
5843        return true;
5844    case clang::Type::LValueReference:
5845        if (target_type)
5846            *target_type = cast<LValueReferenceType>(qual_type)->desugar().getAsOpaquePtr();
5847        return true;
5848    case clang::Type::RValueReference:
5849        if (target_type)
5850            *target_type = cast<LValueReferenceType>(qual_type)->desugar().getAsOpaquePtr();
5851        return true;
5852    case clang::Type::Typedef:
5853        return ClangASTContext::IsPointerOrReferenceType (cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
5854    case clang::Type::Elaborated:
5855        return ClangASTContext::IsPointerOrReferenceType (cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
5856    default:
5857        break;
5858    }
5859    return false;
5860}
5861
5862bool
5863ClangASTContext::IsIntegerType (clang_type_t clang_type, bool &is_signed)
5864{
5865    if (!clang_type)
5866        return false;
5867
5868    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
5869    const BuiltinType *builtin_type = dyn_cast<BuiltinType>(qual_type->getCanonicalTypeInternal());
5870
5871    if (builtin_type)
5872    {
5873        if (builtin_type->isInteger())
5874        {
5875            is_signed = builtin_type->isSignedInteger();
5876            return true;
5877        }
5878    }
5879
5880    return false;
5881}
5882
5883bool
5884ClangASTContext::IsPointerType (clang_type_t clang_type, clang_type_t *target_type)
5885{
5886    if (target_type)
5887        *target_type = NULL;
5888
5889    if (clang_type)
5890    {
5891        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
5892        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5893        switch (type_class)
5894        {
5895        case clang::Type::Builtin:
5896            switch (cast<clang::BuiltinType>(qual_type)->getKind())
5897            {
5898            default:
5899                break;
5900            case clang::BuiltinType::ObjCId:
5901            case clang::BuiltinType::ObjCClass:
5902                return true;
5903            }
5904            return false;
5905        case clang::Type::ObjCObjectPointer:
5906            if (target_type)
5907                *target_type = cast<ObjCObjectPointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
5908            return true;
5909        case clang::Type::BlockPointer:
5910            if (target_type)
5911                *target_type = cast<BlockPointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
5912            return true;
5913        case clang::Type::Pointer:
5914            if (target_type)
5915                *target_type = cast<PointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
5916            return true;
5917        case clang::Type::MemberPointer:
5918            if (target_type)
5919                *target_type = cast<MemberPointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
5920            return true;
5921        case clang::Type::Typedef:
5922            return ClangASTContext::IsPointerType (cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(), target_type);
5923        case clang::Type::Elaborated:
5924            return ClangASTContext::IsPointerType (cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(), target_type);
5925        default:
5926            break;
5927        }
5928    }
5929    return false;
5930}
5931
5932bool
5933ClangASTContext::IsFloatingPointType (clang_type_t clang_type, uint32_t &count, bool &is_complex)
5934{
5935    if (clang_type)
5936    {
5937        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
5938
5939        if (const BuiltinType *BT = dyn_cast<BuiltinType>(qual_type->getCanonicalTypeInternal()))
5940        {
5941            clang::BuiltinType::Kind kind = BT->getKind();
5942            if (kind >= BuiltinType::Float && kind <= BuiltinType::LongDouble)
5943            {
5944                count = 1;
5945                is_complex = false;
5946                return true;
5947            }
5948        }
5949        else if (const ComplexType *CT = dyn_cast<ComplexType>(qual_type->getCanonicalTypeInternal()))
5950        {
5951            if (IsFloatingPointType(CT->getElementType().getAsOpaquePtr(), count, is_complex))
5952            {
5953                count = 2;
5954                is_complex = true;
5955                return true;
5956            }
5957        }
5958        else if (const VectorType *VT = dyn_cast<VectorType>(qual_type->getCanonicalTypeInternal()))
5959        {
5960            if (IsFloatingPointType(VT->getElementType().getAsOpaquePtr(), count, is_complex))
5961            {
5962                count = VT->getNumElements();
5963                is_complex = false;
5964                return true;
5965            }
5966        }
5967    }
5968    return false;
5969}
5970
5971bool
5972ClangASTContext::IsScalarType (lldb::clang_type_t clang_type)
5973{
5974    bool is_signed;
5975    if (ClangASTContext::IsIntegerType(clang_type, is_signed))
5976        return true;
5977
5978    uint32_t count;
5979    bool is_complex;
5980    return ClangASTContext::IsFloatingPointType(clang_type, count, is_complex) && !is_complex;
5981}
5982
5983bool
5984ClangASTContext::IsPointerToScalarType (lldb::clang_type_t clang_type)
5985{
5986    if (!IsPointerType(clang_type))
5987        return false;
5988
5989    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
5990    lldb::clang_type_t pointee_type = qual_type.getTypePtr()->getPointeeType().getAsOpaquePtr();
5991    return IsScalarType(pointee_type);
5992}
5993
5994bool
5995ClangASTContext::IsArrayOfScalarType (lldb::clang_type_t clang_type)
5996{
5997    clang_type = GetAsArrayType(clang_type, NULL, NULL, NULL);
5998
5999    if (clang_type == 0)
6000        return false;
6001
6002    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6003    lldb::clang_type_t item_type = cast<ArrayType>(qual_type.getTypePtr())->getElementType().getAsOpaquePtr();
6004    return IsScalarType(item_type);
6005}
6006
6007
6008bool
6009ClangASTContext::GetCXXClassName (clang_type_t clang_type, std::string &class_name)
6010{
6011    if (clang_type)
6012    {
6013        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6014
6015        CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
6016        if (cxx_record_decl)
6017        {
6018            class_name.assign (cxx_record_decl->getIdentifier()->getNameStart());
6019            return true;
6020        }
6021    }
6022    class_name.clear();
6023    return false;
6024}
6025
6026
6027bool
6028ClangASTContext::IsCXXClassType (clang_type_t clang_type)
6029{
6030    if (clang_type)
6031    {
6032        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6033        if (qual_type->getAsCXXRecordDecl() != NULL)
6034            return true;
6035    }
6036    return false;
6037}
6038
6039bool
6040ClangASTContext::IsBeingDefined (lldb::clang_type_t clang_type)
6041{
6042    if (clang_type)
6043    {
6044        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6045        const clang::TagType *tag_type = dyn_cast<clang::TagType>(qual_type);
6046        if (tag_type)
6047            return tag_type->isBeingDefined();
6048    }
6049    return false;
6050}
6051
6052bool
6053ClangASTContext::IsObjCClassType (clang_type_t clang_type)
6054{
6055    if (clang_type)
6056    {
6057        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6058        if (qual_type->isObjCObjectOrInterfaceType())
6059            return true;
6060    }
6061    return false;
6062}
6063
6064bool
6065ClangASTContext::IsObjCObjectPointerType (lldb::clang_type_t clang_type, clang_type_t *class_type)
6066{
6067    if (clang_type)
6068    {
6069        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6070        if (qual_type->isObjCObjectPointerType())
6071        {
6072            if (class_type)
6073            {
6074                *class_type = NULL;
6075
6076                if (!qual_type->isObjCClassType() &&
6077                    !qual_type->isObjCIdType())
6078                {
6079                    const ObjCObjectPointerType *obj_pointer_type = dyn_cast<ObjCObjectPointerType>(qual_type);
6080                    if (!obj_pointer_type)
6081                        *class_type = NULL;
6082                    else
6083                        *class_type = QualType(obj_pointer_type->getInterfaceType(), 0).getAsOpaquePtr();
6084                }
6085            }
6086            return true;
6087        }
6088    }
6089    return false;
6090}
6091
6092bool
6093ClangASTContext::GetObjCClassName (lldb::clang_type_t clang_type,
6094                                   std::string &class_name)
6095{
6096    if (!clang_type)
6097        return false;
6098
6099    const ObjCObjectType *object_type = dyn_cast<ObjCObjectType>(QualType::getFromOpaquePtr(clang_type));
6100    if (!object_type)
6101        return false;
6102
6103    const ObjCInterfaceDecl *interface = object_type->getInterface();
6104    if (!interface)
6105        return false;
6106
6107    class_name = interface->getNameAsString();
6108    return true;
6109}
6110
6111bool
6112ClangASTContext::IsCharType (clang_type_t clang_type)
6113{
6114    if (clang_type)
6115        return QualType::getFromOpaquePtr(clang_type)->isCharType();
6116    return false;
6117}
6118
6119bool
6120ClangASTContext::IsCStringType (clang_type_t clang_type, uint32_t &length)
6121{
6122    clang_type_t pointee_or_element_clang_type = NULL;
6123    Flags type_flags (ClangASTContext::GetTypeInfo (clang_type, NULL, &pointee_or_element_clang_type));
6124
6125    if (pointee_or_element_clang_type == NULL)
6126        return false;
6127
6128    if (type_flags.AnySet (eTypeIsArray | eTypeIsPointer))
6129    {
6130        QualType pointee_or_element_qual_type (QualType::getFromOpaquePtr (pointee_or_element_clang_type));
6131
6132        if (pointee_or_element_qual_type.getUnqualifiedType()->isCharType())
6133        {
6134            QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6135            if (type_flags.Test (eTypeIsArray))
6136            {
6137                // We know the size of the array and it could be a C string
6138                // since it is an array of characters
6139                length = cast<ConstantArrayType>(qual_type.getTypePtr())->getSize().getLimitedValue();
6140                return true;
6141            }
6142            else
6143            {
6144                length = 0;
6145                return true;
6146            }
6147
6148        }
6149    }
6150    return false;
6151}
6152
6153bool
6154ClangASTContext::IsFunctionPointerType (clang_type_t clang_type)
6155{
6156    if (clang_type)
6157    {
6158        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6159
6160        if (qual_type->isFunctionPointerType())
6161            return true;
6162
6163        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
6164        switch (type_class)
6165        {
6166        default:
6167            break;
6168        case clang::Type::Typedef:
6169            return ClangASTContext::IsFunctionPointerType (cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
6170        case clang::Type::Elaborated:
6171            return ClangASTContext::IsFunctionPointerType (cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
6172
6173        case clang::Type::LValueReference:
6174        case clang::Type::RValueReference:
6175            {
6176                const ReferenceType *reference_type = cast<ReferenceType>(qual_type.getTypePtr());
6177                if (reference_type)
6178                    return ClangASTContext::IsFunctionPointerType (reference_type->getPointeeType().getAsOpaquePtr());
6179            }
6180            break;
6181        }
6182    }
6183    return false;
6184}
6185
6186size_t
6187ClangASTContext::GetArraySize (clang_type_t clang_type)
6188{
6189    if (clang_type)
6190    {
6191        QualType qual_type(QualType::getFromOpaquePtr(clang_type));
6192        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
6193        switch (type_class)
6194        {
6195        case clang::Type::ConstantArray:
6196            {
6197                const ConstantArrayType *array = cast<ConstantArrayType>(QualType::getFromOpaquePtr(clang_type).getTypePtr());
6198                if (array)
6199                    return array->getSize().getLimitedValue();
6200            }
6201            break;
6202
6203        case clang::Type::Typedef:
6204            return ClangASTContext::GetArraySize(cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
6205
6206        case clang::Type::Elaborated:
6207            return ClangASTContext::GetArraySize(cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
6208
6209        default:
6210            break;
6211        }
6212    }
6213    return 0;
6214}
6215
6216clang_type_t
6217ClangASTContext::GetAsArrayType (clang_type_t clang_type, clang_type_t*member_type, uint64_t *size, bool *is_incomplete)
6218{
6219    if (is_incomplete)
6220        *is_incomplete = false;
6221    if (!clang_type)
6222        return 0;
6223
6224    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6225
6226    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
6227    switch (type_class)
6228    {
6229    default:
6230        break;
6231
6232    case clang::Type::ConstantArray:
6233        if (member_type)
6234            *member_type = cast<ConstantArrayType>(qual_type)->getElementType().getAsOpaquePtr();
6235        if (size)
6236            *size = cast<ConstantArrayType>(qual_type)->getSize().getLimitedValue(ULLONG_MAX);
6237        return clang_type;
6238
6239    case clang::Type::IncompleteArray:
6240        if (member_type)
6241            *member_type = cast<IncompleteArrayType>(qual_type)->getElementType().getAsOpaquePtr();
6242        if (size)
6243            *size = 0;
6244        if (is_incomplete)
6245            *is_incomplete = true;
6246        return clang_type;
6247
6248    case clang::Type::VariableArray:
6249        if (member_type)
6250            *member_type = cast<VariableArrayType>(qual_type)->getElementType().getAsOpaquePtr();
6251        if (size)
6252            *size = 0;
6253        return clang_type;
6254
6255    case clang::Type::DependentSizedArray:
6256        if (member_type)
6257            *member_type = cast<DependentSizedArrayType>(qual_type)->getElementType().getAsOpaquePtr();
6258        if (size)
6259            *size = 0;
6260        return clang_type;
6261
6262    case clang::Type::Typedef:
6263        return ClangASTContext::GetAsArrayType (cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(),
6264                                                member_type,
6265                                                size,
6266                                                is_incomplete);
6267
6268    case clang::Type::Elaborated:
6269        return ClangASTContext::GetAsArrayType (cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(),
6270                                                member_type,
6271                                                size,
6272                                                is_incomplete);
6273    }
6274    return 0;
6275}
6276
6277
6278#pragma mark Typedefs
6279
6280clang_type_t
6281ClangASTContext::CreateTypedefType (const char *name, clang_type_t clang_type, DeclContext *decl_ctx)
6282{
6283    if (clang_type)
6284    {
6285        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6286        ASTContext *ast = getASTContext();
6287        IdentifierTable *identifier_table = getIdentifierTable();
6288        assert (ast != NULL);
6289        assert (identifier_table != NULL);
6290        if (decl_ctx == NULL)
6291            decl_ctx = ast->getTranslationUnitDecl();
6292        TypedefDecl *decl = TypedefDecl::Create (*ast,
6293                                                 decl_ctx,
6294                                                 SourceLocation(),
6295                                                 SourceLocation(),
6296                                                 name ? &identifier_table->get(name) : NULL, // Identifier
6297                                                 ast->CreateTypeSourceInfo(qual_type));
6298
6299        //decl_ctx->addDecl (decl);
6300
6301        decl->setAccess(AS_public); // TODO respect proper access specifier
6302
6303        // Get a uniqued QualType for the typedef decl type
6304        return ast->getTypedefType (decl).getAsOpaquePtr();
6305    }
6306    return NULL;
6307}
6308
6309// Disable this for now since I can't seem to get a nicely formatted float
6310// out of the APFloat class without just getting the float, double or quad
6311// and then using a formatted print on it which defeats the purpose. We ideally
6312// would like to get perfect string values for any kind of float semantics
6313// so we can support remote targets. The code below also requires a patch to
6314// llvm::APInt.
6315//bool
6316//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)
6317//{
6318//  uint32_t count = 0;
6319//  bool is_complex = false;
6320//  if (ClangASTContext::IsFloatingPointType (clang_type, count, is_complex))
6321//  {
6322//      unsigned num_bytes_per_float = byte_size / count;
6323//      unsigned num_bits_per_float = num_bytes_per_float * 8;
6324//
6325//      float_str.clear();
6326//      uint32_t i;
6327//      for (i=0; i<count; i++)
6328//      {
6329//          APInt ap_int(num_bits_per_float, bytes + i * num_bytes_per_float, (APInt::ByteOrder)apint_byte_order);
6330//          bool is_ieee = false;
6331//          APFloat ap_float(ap_int, is_ieee);
6332//          char s[1024];
6333//          unsigned int hex_digits = 0;
6334//          bool upper_case = false;
6335//
6336//          if (ap_float.convertToHexString(s, hex_digits, upper_case, APFloat::rmNearestTiesToEven) > 0)
6337//          {
6338//              if (i > 0)
6339//                  float_str.append(", ");
6340//              float_str.append(s);
6341//              if (i == 1 && is_complex)
6342//                  float_str.append(1, 'i');
6343//          }
6344//      }
6345//      return !float_str.empty();
6346//  }
6347//  return false;
6348//}
6349
6350size_t
6351ClangASTContext::ConvertStringToFloatValue (ASTContext *ast, clang_type_t clang_type, const char *s, uint8_t *dst, size_t dst_size)
6352{
6353    if (clang_type)
6354    {
6355        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6356        uint32_t count = 0;
6357        bool is_complex = false;
6358        if (ClangASTContext::IsFloatingPointType (clang_type, count, is_complex))
6359        {
6360            // TODO: handle complex and vector types
6361            if (count != 1)
6362                return false;
6363
6364            StringRef s_sref(s);
6365            APFloat ap_float(ast->getFloatTypeSemantics(qual_type), s_sref);
6366
6367            const uint64_t bit_size = ast->getTypeSize (qual_type);
6368            const uint64_t byte_size = bit_size / 8;
6369            if (dst_size >= byte_size)
6370            {
6371                if (bit_size == sizeof(float)*8)
6372                {
6373                    float float32 = ap_float.convertToFloat();
6374                    ::memcpy (dst, &float32, byte_size);
6375                    return byte_size;
6376                }
6377                else if (bit_size >= 64)
6378                {
6379                    llvm::APInt ap_int(ap_float.bitcastToAPInt());
6380                    ::memcpy (dst, ap_int.getRawData(), byte_size);
6381                    return byte_size;
6382                }
6383            }
6384        }
6385    }
6386    return 0;
6387}
6388
6389unsigned
6390ClangASTContext::GetTypeQualifiers(clang_type_t clang_type)
6391{
6392    assert (clang_type);
6393
6394    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6395
6396    return qual_type.getQualifiers().getCVRQualifiers();
6397}
6398
6399bool
6400ClangASTContext::GetCompleteType (clang::ASTContext *ast, lldb::clang_type_t clang_type)
6401{
6402    if (clang_type == NULL)
6403        return false;
6404
6405    return GetCompleteQualType (ast, clang::QualType::getFromOpaquePtr(clang_type));
6406}
6407
6408
6409bool
6410ClangASTContext::GetCompleteType (clang_type_t clang_type)
6411{
6412    return ClangASTContext::GetCompleteType (getASTContext(), clang_type);
6413}
6414
6415bool
6416ClangASTContext::IsCompleteType (clang::ASTContext *ast, lldb::clang_type_t clang_type)
6417{
6418    if (clang_type == NULL)
6419        return false;
6420
6421    return GetCompleteQualType (ast, clang::QualType::getFromOpaquePtr(clang_type), false); // just check but don't let it actually complete
6422}
6423
6424
6425bool
6426ClangASTContext::IsCompleteType (clang_type_t clang_type)
6427{
6428    return ClangASTContext::IsCompleteType (getASTContext(), clang_type);
6429}
6430
6431bool
6432ClangASTContext::GetCompleteDecl (clang::ASTContext *ast,
6433                                  clang::Decl *decl)
6434{
6435    if (!decl)
6436        return false;
6437
6438    ExternalASTSource *ast_source = ast->getExternalSource();
6439
6440    if (!ast_source)
6441        return false;
6442
6443    if (clang::TagDecl *tag_decl = llvm::dyn_cast<clang::TagDecl>(decl))
6444    {
6445        if (tag_decl->isCompleteDefinition())
6446            return true;
6447
6448        if (!tag_decl->hasExternalLexicalStorage())
6449            return false;
6450
6451        ast_source->CompleteType(tag_decl);
6452
6453        return !tag_decl->getTypeForDecl()->isIncompleteType();
6454    }
6455    else if (clang::ObjCInterfaceDecl *objc_interface_decl = llvm::dyn_cast<clang::ObjCInterfaceDecl>(decl))
6456    {
6457        if (objc_interface_decl->getDefinition())
6458            return true;
6459
6460        if (!objc_interface_decl->hasExternalLexicalStorage())
6461            return false;
6462
6463        ast_source->CompleteType(objc_interface_decl);
6464
6465        return !objc_interface_decl->getTypeForDecl()->isIncompleteType();
6466    }
6467    else
6468    {
6469        return false;
6470    }
6471}
6472
6473void
6474ClangASTContext::SetMetadataAsUserID (uintptr_t object,
6475                                      user_id_t user_id)
6476{
6477    ClangASTMetadata meta_data;
6478    meta_data.SetUserID (user_id);
6479    SetMetadata (object, meta_data);
6480}
6481
6482void
6483ClangASTContext::SetMetadata (clang::ASTContext *ast,
6484                              uintptr_t object,
6485                              ClangASTMetadata &metadata)
6486{
6487    ClangExternalASTSourceCommon *external_source =
6488        static_cast<ClangExternalASTSourceCommon*>(ast->getExternalSource());
6489
6490    if (external_source)
6491        external_source->SetMetadata(object, metadata);
6492}
6493
6494ClangASTMetadata *
6495ClangASTContext::GetMetadata (clang::ASTContext *ast,
6496                              uintptr_t object)
6497{
6498    ClangExternalASTSourceCommon *external_source =
6499        static_cast<ClangExternalASTSourceCommon*>(ast->getExternalSource());
6500
6501    if (external_source && external_source->HasMetadata(object))
6502        return external_source->GetMetadata(object);
6503    else
6504        return NULL;
6505}
6506
6507clang::DeclContext *
6508ClangASTContext::GetAsDeclContext (clang::CXXMethodDecl *cxx_method_decl)
6509{
6510    return llvm::dyn_cast<clang::DeclContext>(cxx_method_decl);
6511}
6512
6513clang::DeclContext *
6514ClangASTContext::GetAsDeclContext (clang::ObjCMethodDecl *objc_method_decl)
6515{
6516    return llvm::dyn_cast<clang::DeclContext>(objc_method_decl);
6517}
6518
6519
6520bool
6521ClangASTContext::GetClassMethodInfoForDeclContext (clang::DeclContext *decl_ctx,
6522                                                   lldb::LanguageType &language,
6523                                                   bool &is_instance_method,
6524                                                   ConstString &language_object_name)
6525{
6526    language_object_name.Clear();
6527    language = eLanguageTypeUnknown;
6528    is_instance_method = false;
6529
6530    if (decl_ctx)
6531    {
6532        if (clang::CXXMethodDecl *method_decl = llvm::dyn_cast<clang::CXXMethodDecl>(decl_ctx))
6533        {
6534            if (method_decl->isStatic())
6535            {
6536                is_instance_method = false;
6537            }
6538            else
6539            {
6540                language_object_name.SetCString("this");
6541                is_instance_method = true;
6542            }
6543            language = eLanguageTypeC_plus_plus;
6544            return true;
6545        }
6546        else if (clang::ObjCMethodDecl *method_decl = llvm::dyn_cast<clang::ObjCMethodDecl>(decl_ctx))
6547        {
6548            // Both static and instance methods have a "self" object in objective C
6549            language_object_name.SetCString("self");
6550            if (method_decl->isInstanceMethod())
6551            {
6552                is_instance_method = true;
6553            }
6554            else
6555            {
6556                is_instance_method = false;
6557            }
6558            language = eLanguageTypeObjC;
6559            return true;
6560        }
6561        else if (clang::FunctionDecl *function_decl = llvm::dyn_cast<clang::FunctionDecl>(decl_ctx))
6562        {
6563            ClangASTMetadata *metadata = GetMetadata (&decl_ctx->getParentASTContext(), (uintptr_t) function_decl);
6564            if (metadata && metadata->HasObjectPtr())
6565            {
6566                language_object_name.SetCString (metadata->GetObjectPtrName());
6567                language = eLanguageTypeObjC;
6568                is_instance_method = true;
6569            }
6570            return true;
6571        }
6572    }
6573    return false;
6574}
6575
6576