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