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