]> CyberLeo.Net >> Repos - FreeBSD/releng/10.2.git/blob - contrib/llvm/tools/lldb/source/Symbol/ClangASTContext.cpp
- Copy stable/10@285827 to releng/10.2 in preparation for 10.2-RC1
[FreeBSD/releng/10.2.git] / contrib / llvm / tools / lldb / source / Symbol / ClangASTContext.cpp
1 //===-- ClangASTContext.cpp -------------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "lldb/Symbol/ClangASTContext.h"
11
12 // C Includes
13 // C++ Includes
14 #include <string>
15
16 // Other libraries and framework includes
17
18 // Clang headers like to use NDEBUG inside of them to enable/disable debug 
19 // releated features using "#ifndef NDEBUG" preprocessor blocks to do one thing
20 // or another. This is bad because it means that if clang was built in release
21 // mode, it assumes that you are building in release mode which is not always
22 // the case. You can end up with functions that are defined as empty in header
23 // files when NDEBUG is not defined, and this can cause link errors with the
24 // clang .a files that you have since you might be missing functions in the .a
25 // file. So we have to define NDEBUG when including clang headers to avoid any
26 // mismatches. This is covered by rdar://problem/8691220
27
28 #if !defined(NDEBUG) && !defined(LLVM_NDEBUG_OFF)
29 #define LLDB_DEFINED_NDEBUG_FOR_CLANG
30 #define NDEBUG
31 // Need to include assert.h so it is as clang would expect it to be (disabled)
32 #include <assert.h>
33 #endif
34
35 #include "clang/AST/ASTContext.h"
36 #include "clang/AST/ASTImporter.h"
37 #include "clang/AST/Attr.h"
38 #include "clang/AST/CXXInheritance.h"
39 #include "clang/AST/DeclObjC.h"
40 #include "clang/AST/DeclTemplate.h"
41 #include "clang/AST/RecordLayout.h"
42 #include "clang/AST/Type.h"
43 #include "clang/Basic/Builtins.h"
44 #include "clang/Basic/Diagnostic.h"
45 #include "clang/Basic/FileManager.h"
46 #include "clang/Basic/FileSystemOptions.h"
47 #include "clang/Basic/SourceManager.h"
48 #include "clang/Basic/TargetInfo.h"
49 #include "clang/Basic/TargetOptions.h"
50 #include "clang/Frontend/FrontendOptions.h"
51 #include "clang/Frontend/LangStandard.h"
52
53 #ifdef LLDB_DEFINED_NDEBUG_FOR_CLANG
54 #undef NDEBUG
55 #undef LLDB_DEFINED_NDEBUG_FOR_CLANG
56 // Need to re-include assert.h so it is as _we_ would expect it to be (enabled)
57 #include <assert.h>
58 #endif
59
60 #include "lldb/Core/ArchSpec.h"
61 #include "lldb/Core/dwarf.h"
62 #include "lldb/Core/Flags.h"
63 #include "lldb/Core/Log.h"
64 #include "lldb/Core/RegularExpression.h"
65 #include "lldb/Core/UniqueCStringMap.h"
66 #include "lldb/Expression/ASTDumper.h"
67 #include "lldb/Symbol/ClangExternalASTSourceCommon.h"
68 #include "lldb/Symbol/VerifyDecl.h"
69 #include "lldb/Target/ExecutionContext.h"
70 #include "lldb/Target/Process.h"
71 #include "lldb/Target/ObjCLanguageRuntime.h"
72
73 #include <stdio.h>
74
75 #include <mutex>
76
77 using namespace lldb;
78 using namespace lldb_private;
79 using namespace llvm;
80 using namespace clang;
81
82 clang::AccessSpecifier
83 ClangASTContext::ConvertAccessTypeToAccessSpecifier (AccessType access)
84 {
85     switch (access)
86     {
87     default:               break;
88     case eAccessNone:      return AS_none;
89     case eAccessPublic:    return AS_public;
90     case eAccessPrivate:   return AS_private;
91     case eAccessProtected: return AS_protected;
92     }
93     return AS_none;
94 }
95
96
97 static void
98 ParseLangArgs
99 (
100     LangOptions &Opts,
101     InputKind IK
102 )
103 {
104     // FIXME: Cleanup per-file based stuff.
105
106     // Set some properties which depend soley on the input kind; it would be nice
107     // to move these to the language standard, and have the driver resolve the
108     // input kind + language standard.
109     if (IK == IK_Asm) {
110         Opts.AsmPreprocessor = 1;
111     } else if (IK == IK_ObjC ||
112                IK == IK_ObjCXX ||
113                IK == IK_PreprocessedObjC ||
114                IK == IK_PreprocessedObjCXX) {
115         Opts.ObjC1 = Opts.ObjC2 = 1;
116     }
117
118     LangStandard::Kind LangStd = LangStandard::lang_unspecified;
119
120     if (LangStd == LangStandard::lang_unspecified) {
121         // Based on the base language, pick one.
122         switch (IK) {
123             case IK_None:
124             case IK_AST:
125             case IK_LLVM_IR:
126                 assert (!"Invalid input kind!");
127             case IK_OpenCL:
128                 LangStd = LangStandard::lang_opencl;
129                 break;
130             case IK_CUDA:
131                 LangStd = LangStandard::lang_cuda;
132                 break;
133             case IK_Asm:
134             case IK_C:
135             case IK_PreprocessedC:
136             case IK_ObjC:
137             case IK_PreprocessedObjC:
138                 LangStd = LangStandard::lang_gnu99;
139                 break;
140             case IK_CXX:
141             case IK_PreprocessedCXX:
142             case IK_ObjCXX:
143             case IK_PreprocessedObjCXX:
144                 LangStd = LangStandard::lang_gnucxx98;
145                 break;
146         }
147     }
148
149     const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd);
150     Opts.LineComment = Std.hasLineComments();
151     Opts.C99 = Std.isC99();
152     Opts.CPlusPlus = Std.isCPlusPlus();
153     Opts.CPlusPlus11 = Std.isCPlusPlus11();
154     Opts.Digraphs = Std.hasDigraphs();
155     Opts.GNUMode = Std.isGNUMode();
156     Opts.GNUInline = !Std.isC99();
157     Opts.HexFloats = Std.hasHexFloats();
158     Opts.ImplicitInt = Std.hasImplicitInt();
159     
160     Opts.WChar = true;
161
162     // OpenCL has some additional defaults.
163     if (LangStd == LangStandard::lang_opencl) {
164         Opts.OpenCL = 1;
165         Opts.AltiVec = 1;
166         Opts.CXXOperatorNames = 1;
167         Opts.LaxVectorConversions = 1;
168     }
169
170     // OpenCL and C++ both have bool, true, false keywords.
171     Opts.Bool = Opts.OpenCL || Opts.CPlusPlus;
172
173 //    if (Opts.CPlusPlus)
174 //        Opts.CXXOperatorNames = !Args.hasArg(OPT_fno_operator_names);
175 //
176 //    if (Args.hasArg(OPT_fobjc_gc_only))
177 //        Opts.setGCMode(LangOptions::GCOnly);
178 //    else if (Args.hasArg(OPT_fobjc_gc))
179 //        Opts.setGCMode(LangOptions::HybridGC);
180 //
181 //    if (Args.hasArg(OPT_print_ivar_layout))
182 //        Opts.ObjCGCBitmapPrint = 1;
183 //
184 //    if (Args.hasArg(OPT_faltivec))
185 //        Opts.AltiVec = 1;
186 //
187 //    if (Args.hasArg(OPT_pthread))
188 //        Opts.POSIXThreads = 1;
189 //
190 //    llvm::StringRef Vis = getLastArgValue(Args, OPT_fvisibility,
191 //                                          "default");
192 //    if (Vis == "default")
193         Opts.setValueVisibilityMode(DefaultVisibility);
194 //    else if (Vis == "hidden")
195 //        Opts.setVisibilityMode(LangOptions::Hidden);
196 //    else if (Vis == "protected")
197 //        Opts.setVisibilityMode(LangOptions::Protected);
198 //    else
199 //        Diags.Report(diag::err_drv_invalid_value)
200 //        << Args.getLastArg(OPT_fvisibility)->getAsString(Args) << Vis;
201
202 //    Opts.OverflowChecking = Args.hasArg(OPT_ftrapv);
203
204     // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs
205     // is specified, or -std is set to a conforming mode.
206     Opts.Trigraphs = !Opts.GNUMode;
207 //    if (Args.hasArg(OPT_trigraphs))
208 //        Opts.Trigraphs = 1;
209 //
210 //    Opts.DollarIdents = Args.hasFlag(OPT_fdollars_in_identifiers,
211 //                                     OPT_fno_dollars_in_identifiers,
212 //                                     !Opts.AsmPreprocessor);
213 //    Opts.PascalStrings = Args.hasArg(OPT_fpascal_strings);
214 //    Opts.Microsoft = Args.hasArg(OPT_fms_extensions);
215 //    Opts.WritableStrings = Args.hasArg(OPT_fwritable_strings);
216 //    if (Args.hasArg(OPT_fno_lax_vector_conversions))
217 //        Opts.LaxVectorConversions = 0;
218 //    Opts.Exceptions = Args.hasArg(OPT_fexceptions);
219 //    Opts.RTTI = !Args.hasArg(OPT_fno_rtti);
220 //    Opts.Blocks = Args.hasArg(OPT_fblocks);
221 //    Opts.CharIsSigned = !Args.hasArg(OPT_fno_signed_char);
222 //    Opts.ShortWChar = Args.hasArg(OPT_fshort_wchar);
223 //    Opts.Freestanding = Args.hasArg(OPT_ffreestanding);
224 //    Opts.NoBuiltin = Args.hasArg(OPT_fno_builtin) || Opts.Freestanding;
225 //    Opts.AssumeSaneOperatorNew = !Args.hasArg(OPT_fno_assume_sane_operator_new);
226 //    Opts.HeinousExtensions = Args.hasArg(OPT_fheinous_gnu_extensions);
227 //    Opts.AccessControl = Args.hasArg(OPT_faccess_control);
228 //    Opts.ElideConstructors = !Args.hasArg(OPT_fno_elide_constructors);
229 //    Opts.MathErrno = !Args.hasArg(OPT_fno_math_errno);
230 //    Opts.InstantiationDepth = getLastArgIntValue(Args, OPT_ftemplate_depth, 99,
231 //                                                 Diags);
232 //    Opts.NeXTRuntime = !Args.hasArg(OPT_fgnu_runtime);
233 //    Opts.ObjCConstantStringClass = getLastArgValue(Args,
234 //                                                   OPT_fconstant_string_class);
235 //    Opts.ObjCNonFragileABI = Args.hasArg(OPT_fobjc_nonfragile_abi);
236 //    Opts.CatchUndefined = Args.hasArg(OPT_fcatch_undefined_behavior);
237 //    Opts.EmitAllDecls = Args.hasArg(OPT_femit_all_decls);
238 //    Opts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags);
239 //    Opts.Static = Args.hasArg(OPT_static_define);
240     Opts.OptimizeSize = 0;
241
242     // FIXME: Eliminate this dependency.
243 //    unsigned Opt =
244 //    Args.hasArg(OPT_Os) ? 2 : getLastArgIntValue(Args, OPT_O, 0, Diags);
245 //    Opts.Optimize = Opt != 0;
246     unsigned Opt = 0;
247
248     // This is the __NO_INLINE__ define, which just depends on things like the
249     // optimization level and -fno-inline, not actually whether the backend has
250     // inlining enabled.
251     //
252     // FIXME: This is affected by other options (-fno-inline).
253     Opts.NoInlineDefine = !Opt;
254
255 //    unsigned SSP = getLastArgIntValue(Args, OPT_stack_protector, 0, Diags);
256 //    switch (SSP) {
257 //        default:
258 //            Diags.Report(diag::err_drv_invalid_value)
259 //            << Args.getLastArg(OPT_stack_protector)->getAsString(Args) << SSP;
260 //            break;
261 //        case 0: Opts.setStackProtectorMode(LangOptions::SSPOff); break;
262 //        case 1: Opts.setStackProtectorMode(LangOptions::SSPOn);  break;
263 //        case 2: Opts.setStackProtectorMode(LangOptions::SSPReq); break;
264 //    }
265 }
266
267
268 ClangASTContext::ClangASTContext (const char *target_triple) :   
269     m_target_triple(),
270     m_ast_ap(),
271     m_language_options_ap(),
272     m_source_manager_ap(),
273     m_diagnostics_engine_ap(),
274     m_target_options_rp(),
275     m_target_info_ap(),
276     m_identifier_table_ap(),
277     m_selector_table_ap(),
278     m_builtins_ap(),
279     m_callback_tag_decl (NULL),
280     m_callback_objc_decl (NULL),
281     m_callback_baton (NULL),
282     m_pointer_byte_size (0)
283
284 {
285     if (target_triple && target_triple[0])
286         SetTargetTriple (target_triple);
287 }
288
289 //----------------------------------------------------------------------
290 // Destructor
291 //----------------------------------------------------------------------
292 ClangASTContext::~ClangASTContext()
293 {
294     m_builtins_ap.reset();
295     m_selector_table_ap.reset();
296     m_identifier_table_ap.reset();
297     m_target_info_ap.reset();
298     m_target_options_rp.reset();
299     m_diagnostics_engine_ap.reset();
300     m_source_manager_ap.reset();
301     m_language_options_ap.reset();
302     m_ast_ap.reset();
303 }
304
305
306 void
307 ClangASTContext::Clear()
308 {
309     m_ast_ap.reset();
310     m_language_options_ap.reset();
311     m_source_manager_ap.reset();
312     m_diagnostics_engine_ap.reset();
313     m_target_options_rp.reset();
314     m_target_info_ap.reset();
315     m_identifier_table_ap.reset();
316     m_selector_table_ap.reset();
317     m_builtins_ap.reset();
318     m_pointer_byte_size = 0;
319 }
320
321 const char *
322 ClangASTContext::GetTargetTriple ()
323 {
324     return m_target_triple.c_str();
325 }
326
327 void
328 ClangASTContext::SetTargetTriple (const char *target_triple)
329 {
330     Clear();
331     m_target_triple.assign(target_triple);
332 }
333
334 void
335 ClangASTContext::SetArchitecture (const ArchSpec &arch)
336 {
337     SetTargetTriple(arch.GetTriple().str().c_str());
338 }
339
340 bool
341 ClangASTContext::HasExternalSource ()
342 {
343     ASTContext *ast = getASTContext();
344     if (ast)
345         return ast->getExternalSource () != NULL;
346     return false;
347 }
348
349 void
350 ClangASTContext::SetExternalSource (llvm::OwningPtr<ExternalASTSource> &ast_source_ap)
351 {
352     ASTContext *ast = getASTContext();
353     if (ast)
354     {
355         ast->setExternalSource (ast_source_ap);
356         ast->getTranslationUnitDecl()->setHasExternalLexicalStorage(true);
357         //ast->getTranslationUnitDecl()->setHasExternalVisibleStorage(true);
358     }
359 }
360
361 void
362 ClangASTContext::RemoveExternalSource ()
363 {
364     ASTContext *ast = getASTContext();
365     
366     if (ast)
367     {
368         llvm::OwningPtr<ExternalASTSource> empty_ast_source_ap;
369         ast->setExternalSource (empty_ast_source_ap);
370         ast->getTranslationUnitDecl()->setHasExternalLexicalStorage(false);
371         //ast->getTranslationUnitDecl()->setHasExternalVisibleStorage(false);
372     }
373 }
374
375
376
377 ASTContext *
378 ClangASTContext::getASTContext()
379 {
380     if (m_ast_ap.get() == NULL)
381     {
382         m_ast_ap.reset(new ASTContext (*getLanguageOptions(),
383                                        *getSourceManager(),
384                                        getTargetInfo(),
385                                        *getIdentifierTable(),
386                                        *getSelectorTable(),
387                                        *getBuiltinContext(),
388                                        0));
389         
390         if ((m_callback_tag_decl || m_callback_objc_decl) && m_callback_baton)
391         {
392             m_ast_ap->getTranslationUnitDecl()->setHasExternalLexicalStorage();
393             //m_ast_ap->getTranslationUnitDecl()->setHasExternalVisibleStorage();
394         }
395         
396         m_ast_ap->getDiagnostics().setClient(getDiagnosticConsumer(), false);
397     }
398     return m_ast_ap.get();
399 }
400
401 Builtin::Context *
402 ClangASTContext::getBuiltinContext()
403 {
404     if (m_builtins_ap.get() == NULL)
405         m_builtins_ap.reset (new Builtin::Context());
406     return m_builtins_ap.get();
407 }
408
409 IdentifierTable *
410 ClangASTContext::getIdentifierTable()
411 {
412     if (m_identifier_table_ap.get() == NULL)
413         m_identifier_table_ap.reset(new IdentifierTable (*ClangASTContext::getLanguageOptions(), NULL));
414     return m_identifier_table_ap.get();
415 }
416
417 LangOptions *
418 ClangASTContext::getLanguageOptions()
419 {
420     if (m_language_options_ap.get() == NULL)
421     {
422         m_language_options_ap.reset(new LangOptions());
423         ParseLangArgs(*m_language_options_ap, IK_ObjCXX);
424 //        InitializeLangOptions(*m_language_options_ap, IK_ObjCXX);
425     }
426     return m_language_options_ap.get();
427 }
428
429 SelectorTable *
430 ClangASTContext::getSelectorTable()
431 {
432     if (m_selector_table_ap.get() == NULL)
433         m_selector_table_ap.reset (new SelectorTable());
434     return m_selector_table_ap.get();
435 }
436
437 clang::FileManager *
438 ClangASTContext::getFileManager()
439 {
440     if (m_file_manager_ap.get() == NULL)
441     {
442         clang::FileSystemOptions file_system_options;
443         m_file_manager_ap.reset(new clang::FileManager(file_system_options));
444     }
445     return m_file_manager_ap.get();
446 }
447
448 clang::SourceManager *
449 ClangASTContext::getSourceManager()
450 {
451     if (m_source_manager_ap.get() == NULL)
452         m_source_manager_ap.reset(new clang::SourceManager(*getDiagnosticsEngine(), *getFileManager()));
453     return m_source_manager_ap.get();
454 }
455
456 clang::DiagnosticsEngine *
457 ClangASTContext::getDiagnosticsEngine()
458 {
459     if (m_diagnostics_engine_ap.get() == NULL)
460     {
461         llvm::IntrusiveRefCntPtr<DiagnosticIDs> diag_id_sp(new DiagnosticIDs());
462         m_diagnostics_engine_ap.reset(new DiagnosticsEngine(diag_id_sp, new DiagnosticOptions()));
463     }
464     return m_diagnostics_engine_ap.get();
465 }
466
467 class NullDiagnosticConsumer : public DiagnosticConsumer
468 {
469 public:
470     NullDiagnosticConsumer ()
471     {
472         m_log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
473     }
474     
475     void HandleDiagnostic (DiagnosticsEngine::Level DiagLevel, const Diagnostic &info)
476     {
477         if (m_log)
478         {
479             llvm::SmallVector<char, 32> diag_str(10);
480             info.FormatDiagnostic(diag_str);
481             diag_str.push_back('\0');
482             m_log->Printf("Compiler diagnostic: %s\n", diag_str.data());
483         }
484     }
485     
486     DiagnosticConsumer *clone (DiagnosticsEngine &Diags) const
487     {
488         return new NullDiagnosticConsumer ();
489     }
490 private:
491     Log * m_log;
492 };
493
494 DiagnosticConsumer *
495 ClangASTContext::getDiagnosticConsumer()
496 {
497     if (m_diagnostic_consumer_ap.get() == NULL)
498         m_diagnostic_consumer_ap.reset(new NullDiagnosticConsumer);
499     
500     return m_diagnostic_consumer_ap.get();
501 }
502
503 TargetOptions *
504 ClangASTContext::getTargetOptions()
505 {
506     if (m_target_options_rp.getPtr() == NULL && !m_target_triple.empty())
507     {
508         m_target_options_rp.reset ();
509         m_target_options_rp = new TargetOptions();
510         if (m_target_options_rp.getPtr() != NULL)
511             m_target_options_rp->Triple = m_target_triple;
512     }
513     return m_target_options_rp.getPtr();
514 }
515
516
517 TargetInfo *
518 ClangASTContext::getTargetInfo()
519 {
520     // target_triple should be something like "x86_64-apple-macosx"
521     if (m_target_info_ap.get() == NULL && !m_target_triple.empty())
522         m_target_info_ap.reset (TargetInfo::CreateTargetInfo(*getDiagnosticsEngine(), getTargetOptions()));
523     return m_target_info_ap.get();
524 }
525
526 #pragma mark Basic Types
527
528 static inline bool
529 QualTypeMatchesBitSize(const uint64_t bit_size, ASTContext *ast, QualType qual_type)
530 {
531     uint64_t qual_type_bit_size = ast->getTypeSize(qual_type);
532     if (qual_type_bit_size == bit_size)
533         return true;
534     return false;
535 }
536 ClangASTType
537 ClangASTContext::GetBuiltinTypeForEncodingAndBitSize (Encoding encoding, uint32_t bit_size)
538 {
539     return ClangASTContext::GetBuiltinTypeForEncodingAndBitSize (getASTContext(), encoding, bit_size);
540 }
541
542 ClangASTType
543 ClangASTContext::GetBuiltinTypeForEncodingAndBitSize (ASTContext *ast, Encoding encoding, uint32_t bit_size)
544 {
545     if (!ast)
546         return ClangASTType();
547     
548     switch (encoding)
549     {
550     case eEncodingInvalid:
551         if (QualTypeMatchesBitSize (bit_size, ast, ast->VoidPtrTy))
552             return ClangASTType (ast, ast->VoidPtrTy.getAsOpaquePtr());
553         break;
554         
555     case eEncodingUint:
556         if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedCharTy))
557             return ClangASTType (ast, ast->UnsignedCharTy.getAsOpaquePtr());
558         if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedShortTy))
559             return ClangASTType (ast, ast->UnsignedShortTy.getAsOpaquePtr());
560         if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedIntTy))
561             return ClangASTType (ast, ast->UnsignedIntTy.getAsOpaquePtr());
562         if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedLongTy))
563             return ClangASTType (ast, ast->UnsignedLongTy.getAsOpaquePtr());
564         if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedLongLongTy))
565             return ClangASTType (ast, ast->UnsignedLongLongTy.getAsOpaquePtr());
566         if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedInt128Ty))
567             return ClangASTType (ast, ast->UnsignedInt128Ty.getAsOpaquePtr());
568         break;
569         
570     case eEncodingSint:
571         if (QualTypeMatchesBitSize (bit_size, ast, ast->CharTy))
572             return ClangASTType (ast, ast->CharTy.getAsOpaquePtr());
573         if (QualTypeMatchesBitSize (bit_size, ast, ast->ShortTy))
574             return ClangASTType (ast, ast->ShortTy.getAsOpaquePtr());
575         if (QualTypeMatchesBitSize (bit_size, ast, ast->IntTy))
576             return ClangASTType (ast, ast->IntTy.getAsOpaquePtr());
577         if (QualTypeMatchesBitSize (bit_size, ast, ast->LongTy))
578             return ClangASTType (ast, ast->LongTy.getAsOpaquePtr());
579         if (QualTypeMatchesBitSize (bit_size, ast, ast->LongLongTy))
580             return ClangASTType (ast, ast->LongLongTy.getAsOpaquePtr());
581         if (QualTypeMatchesBitSize (bit_size, ast, ast->Int128Ty))
582             return ClangASTType (ast, ast->Int128Ty.getAsOpaquePtr());
583         break;
584         
585     case eEncodingIEEE754:
586         if (QualTypeMatchesBitSize (bit_size, ast, ast->FloatTy))
587             return ClangASTType (ast, ast->FloatTy.getAsOpaquePtr());
588         if (QualTypeMatchesBitSize (bit_size, ast, ast->DoubleTy))
589             return ClangASTType (ast, ast->DoubleTy.getAsOpaquePtr());
590         if (QualTypeMatchesBitSize (bit_size, ast, ast->LongDoubleTy))
591             return ClangASTType (ast, ast->LongDoubleTy.getAsOpaquePtr());
592         break;
593         
594     case eEncodingVector:
595         // Sanity check that bit_size is a multiple of 8's.
596         if (bit_size && !(bit_size & 0x7u))
597             return ClangASTType (ast, ast->getExtVectorType (ast->UnsignedCharTy, bit_size/8).getAsOpaquePtr());
598         break;
599     }
600     
601     return ClangASTType();
602 }
603
604
605
606 lldb::BasicType
607 ClangASTContext::GetBasicTypeEnumeration (const ConstString &name)
608 {
609     if (name)
610     {
611         typedef UniqueCStringMap<lldb::BasicType> TypeNameToBasicTypeMap;
612         static TypeNameToBasicTypeMap g_type_map;
613         static std::once_flag g_once_flag;
614         std::call_once(g_once_flag, [](){
615             // "void"
616             g_type_map.Append(ConstString("void").GetCString(), eBasicTypeVoid);
617             
618             // "char"
619             g_type_map.Append(ConstString("char").GetCString(), eBasicTypeChar);
620             g_type_map.Append(ConstString("signed char").GetCString(), eBasicTypeSignedChar);
621             g_type_map.Append(ConstString("unsigned char").GetCString(), eBasicTypeUnsignedChar);
622             g_type_map.Append(ConstString("wchar_t").GetCString(), eBasicTypeWChar);
623             g_type_map.Append(ConstString("signed wchar_t").GetCString(), eBasicTypeSignedWChar);
624             g_type_map.Append(ConstString("unsigned wchar_t").GetCString(), eBasicTypeUnsignedWChar);
625             // "short"
626             g_type_map.Append(ConstString("short").GetCString(), eBasicTypeShort);
627             g_type_map.Append(ConstString("short int").GetCString(), eBasicTypeShort);
628             g_type_map.Append(ConstString("unsigned short").GetCString(), eBasicTypeUnsignedShort);
629             g_type_map.Append(ConstString("unsigned short int").GetCString(), eBasicTypeUnsignedShort);
630             
631             // "int"
632             g_type_map.Append(ConstString("int").GetCString(), eBasicTypeInt);
633             g_type_map.Append(ConstString("signed int").GetCString(), eBasicTypeInt);
634             g_type_map.Append(ConstString("unsigned int").GetCString(), eBasicTypeUnsignedInt);
635             g_type_map.Append(ConstString("unsigned").GetCString(), eBasicTypeUnsignedInt);
636             
637             // "long"
638             g_type_map.Append(ConstString("long").GetCString(), eBasicTypeLong);
639             g_type_map.Append(ConstString("long int").GetCString(), eBasicTypeLong);
640             g_type_map.Append(ConstString("unsigned long").GetCString(), eBasicTypeUnsignedLong);
641             g_type_map.Append(ConstString("unsigned long int").GetCString(), eBasicTypeUnsignedLong);
642             
643             // "long long"
644             g_type_map.Append(ConstString("long long").GetCString(), eBasicTypeLongLong);
645             g_type_map.Append(ConstString("long long int").GetCString(), eBasicTypeLongLong);
646             g_type_map.Append(ConstString("unsigned long long").GetCString(), eBasicTypeUnsignedLongLong);
647             g_type_map.Append(ConstString("unsigned long long int").GetCString(), eBasicTypeUnsignedLongLong);
648             
649             // "int128"
650             g_type_map.Append(ConstString("__int128_t").GetCString(), eBasicTypeInt128);
651             g_type_map.Append(ConstString("__uint128_t").GetCString(), eBasicTypeUnsignedInt128);
652             
653             // Miscelaneous
654             g_type_map.Append(ConstString("bool").GetCString(), eBasicTypeBool);
655             g_type_map.Append(ConstString("float").GetCString(), eBasicTypeFloat);
656             g_type_map.Append(ConstString("double").GetCString(), eBasicTypeDouble);
657             g_type_map.Append(ConstString("long double").GetCString(), eBasicTypeLongDouble);
658             g_type_map.Append(ConstString("id").GetCString(), eBasicTypeObjCID);
659             g_type_map.Append(ConstString("SEL").GetCString(), eBasicTypeObjCSel);
660             g_type_map.Append(ConstString("nullptr").GetCString(), eBasicTypeNullPtr);
661             g_type_map.Sort();
662         });
663         
664         return g_type_map.Find(name.GetCString(), eBasicTypeInvalid);
665     }
666     return eBasicTypeInvalid;
667 }
668
669 ClangASTType
670 ClangASTContext::GetBasicType (ASTContext *ast, const ConstString &name)
671 {
672     if (ast)
673     {
674         lldb::BasicType basic_type = ClangASTContext::GetBasicTypeEnumeration (name);
675         return ClangASTContext::GetBasicType (ast, basic_type);
676     }
677     return ClangASTType();
678 }
679
680 uint32_t
681 ClangASTContext::GetPointerByteSize ()
682 {
683     if (m_pointer_byte_size == 0)
684         m_pointer_byte_size = GetBasicType(lldb::eBasicTypeVoid).GetPointerType().GetByteSize();
685     return m_pointer_byte_size;
686 }
687
688 ClangASTType
689 ClangASTContext::GetBasicType (lldb::BasicType basic_type)
690 {
691     return GetBasicType (getASTContext(), basic_type);
692 }
693
694 ClangASTType
695 ClangASTContext::GetBasicType (ASTContext *ast, lldb::BasicType basic_type)
696 {
697     if (ast)
698     {
699         clang_type_t clang_type = NULL;
700         
701         switch (basic_type)
702         {
703             case eBasicTypeInvalid:
704             case eBasicTypeOther:
705                 break;
706             case eBasicTypeVoid:
707                 clang_type = ast->VoidTy.getAsOpaquePtr();
708                 break;
709             case eBasicTypeChar:
710                 clang_type = ast->CharTy.getAsOpaquePtr();
711                 break;
712             case eBasicTypeSignedChar:
713                 clang_type = ast->SignedCharTy.getAsOpaquePtr();
714                 break;
715             case eBasicTypeUnsignedChar:
716                 clang_type = ast->UnsignedCharTy.getAsOpaquePtr();
717                 break;
718             case eBasicTypeWChar:
719                 clang_type = ast->getWCharType().getAsOpaquePtr();
720                 break;
721             case eBasicTypeSignedWChar:
722                 clang_type = ast->getSignedWCharType().getAsOpaquePtr();
723                 break;
724             case eBasicTypeUnsignedWChar:
725                 clang_type = ast->getUnsignedWCharType().getAsOpaquePtr();
726                 break;
727             case eBasicTypeChar16:
728                 clang_type = ast->Char16Ty.getAsOpaquePtr();
729                 break;
730             case eBasicTypeChar32:
731                 clang_type = ast->Char32Ty.getAsOpaquePtr();
732                 break;
733             case eBasicTypeShort:
734                 clang_type = ast->ShortTy.getAsOpaquePtr();
735                 break;
736             case eBasicTypeUnsignedShort:
737                 clang_type = ast->UnsignedShortTy.getAsOpaquePtr();
738                 break;
739             case eBasicTypeInt:
740                 clang_type = ast->IntTy.getAsOpaquePtr();
741                 break;
742             case eBasicTypeUnsignedInt:
743                 clang_type = ast->UnsignedIntTy.getAsOpaquePtr();
744                 break;
745             case eBasicTypeLong:
746                 clang_type = ast->LongTy.getAsOpaquePtr();
747                 break;
748             case eBasicTypeUnsignedLong:
749                 clang_type = ast->UnsignedLongTy.getAsOpaquePtr();
750                 break;
751             case eBasicTypeLongLong:
752                 clang_type = ast->LongLongTy.getAsOpaquePtr();
753                 break;
754             case eBasicTypeUnsignedLongLong:
755                 clang_type = ast->UnsignedLongLongTy.getAsOpaquePtr();
756                 break;
757             case eBasicTypeInt128:
758                 clang_type = ast->Int128Ty.getAsOpaquePtr();
759                 break;
760             case eBasicTypeUnsignedInt128:
761                 clang_type = ast->UnsignedInt128Ty.getAsOpaquePtr();
762                 break;
763             case eBasicTypeBool:
764                 clang_type = ast->BoolTy.getAsOpaquePtr();
765                 break;
766             case eBasicTypeHalf:
767                 clang_type = ast->HalfTy.getAsOpaquePtr();
768                 break;
769             case eBasicTypeFloat:
770                 clang_type = ast->FloatTy.getAsOpaquePtr();
771                 break;
772             case eBasicTypeDouble:
773                 clang_type = ast->DoubleTy.getAsOpaquePtr();
774                 break;
775             case eBasicTypeLongDouble:
776                 clang_type = ast->LongDoubleTy.getAsOpaquePtr();
777                 break;
778             case eBasicTypeFloatComplex:
779                 clang_type = ast->FloatComplexTy.getAsOpaquePtr();
780                 break;
781             case eBasicTypeDoubleComplex:
782                 clang_type = ast->DoubleComplexTy.getAsOpaquePtr();
783                 break;
784             case eBasicTypeLongDoubleComplex:
785                 clang_type = ast->LongDoubleComplexTy.getAsOpaquePtr();
786                 break;
787             case eBasicTypeObjCID:
788                 clang_type = ast->getObjCIdType().getAsOpaquePtr();
789                 break;
790             case eBasicTypeObjCClass:
791                 clang_type = ast->getObjCClassType().getAsOpaquePtr();
792                 break;
793             case eBasicTypeObjCSel:
794                 clang_type = ast->getObjCSelType().getAsOpaquePtr();
795                 break;
796             case eBasicTypeNullPtr:
797                 clang_type = ast->NullPtrTy.getAsOpaquePtr();
798                 break;
799         }
800         
801         if (clang_type)
802             return ClangASTType (ast, clang_type);
803     }
804     return ClangASTType();
805 }
806
807
808 ClangASTType
809 ClangASTContext::GetBuiltinTypeForDWARFEncodingAndBitSize (const char *type_name, uint32_t dw_ate, uint32_t bit_size)
810 {
811     ASTContext *ast = getASTContext();
812     
813 #define streq(a,b) strcmp(a,b) == 0
814     assert (ast != NULL);
815     if (ast)
816     {
817         switch (dw_ate)
818         {
819             default:
820                 break;
821                 
822             case DW_ATE_address:
823                 if (QualTypeMatchesBitSize (bit_size, ast, ast->VoidPtrTy))
824                     return ClangASTType (ast, ast->VoidPtrTy.getAsOpaquePtr());
825                 break;
826                 
827             case DW_ATE_boolean:
828                 if (QualTypeMatchesBitSize (bit_size, ast, ast->BoolTy))
829                     return ClangASTType (ast, ast->BoolTy.getAsOpaquePtr());
830                 if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedCharTy))
831                     return ClangASTType (ast, ast->UnsignedCharTy.getAsOpaquePtr());
832                 if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedShortTy))
833                     return ClangASTType (ast, ast->UnsignedShortTy.getAsOpaquePtr());
834                 if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedIntTy))
835                     return ClangASTType (ast, ast->UnsignedIntTy.getAsOpaquePtr());
836                 break;
837                 
838             case DW_ATE_lo_user:
839                 // This has been seen to mean DW_AT_complex_integer
840                 if (type_name)
841                 {
842                     if (::strstr(type_name, "complex"))
843                     {
844                         ClangASTType complex_int_clang_type = GetBuiltinTypeForDWARFEncodingAndBitSize ("int", DW_ATE_signed, bit_size/2);
845                         return ClangASTType (ast, ast->getComplexType (complex_int_clang_type.GetQualType()).getAsOpaquePtr());
846                     }
847                 }
848                 break;
849                 
850             case DW_ATE_complex_float:
851                 if (QualTypeMatchesBitSize (bit_size, ast, ast->FloatComplexTy))
852                     return ClangASTType (ast, ast->FloatComplexTy.getAsOpaquePtr());
853                 else if (QualTypeMatchesBitSize (bit_size, ast, ast->DoubleComplexTy))
854                     return ClangASTType (ast, ast->DoubleComplexTy.getAsOpaquePtr());
855                 else if (QualTypeMatchesBitSize (bit_size, ast, ast->LongDoubleComplexTy))
856                     return ClangASTType (ast, ast->LongDoubleComplexTy.getAsOpaquePtr());
857                 else 
858                 {
859                     ClangASTType complex_float_clang_type = GetBuiltinTypeForDWARFEncodingAndBitSize ("float", DW_ATE_float, bit_size/2);
860                     return ClangASTType (ast, ast->getComplexType (complex_float_clang_type.GetQualType()).getAsOpaquePtr());
861                 }
862                 break;
863                 
864             case DW_ATE_float:
865                 if (QualTypeMatchesBitSize (bit_size, ast, ast->FloatTy))
866                     return ClangASTType (ast, ast->FloatTy.getAsOpaquePtr());
867                 if (QualTypeMatchesBitSize (bit_size, ast, ast->DoubleTy))
868                     return ClangASTType (ast, ast->DoubleTy.getAsOpaquePtr());
869                 if (QualTypeMatchesBitSize (bit_size, ast, ast->LongDoubleTy))
870                     return ClangASTType (ast, ast->LongDoubleTy.getAsOpaquePtr());
871                 break;
872                 
873             case DW_ATE_signed:
874                 if (type_name)
875                 {
876                     if (streq(type_name, "wchar_t") &&
877                         QualTypeMatchesBitSize (bit_size, ast, ast->WCharTy))
878                         return ClangASTType (ast, ast->WCharTy.getAsOpaquePtr());
879                     if (streq(type_name, "void") &&
880                         QualTypeMatchesBitSize (bit_size, ast, ast->VoidTy))
881                         return ClangASTType (ast, ast->VoidTy.getAsOpaquePtr());
882                     if (strstr(type_name, "long long") &&
883                         QualTypeMatchesBitSize (bit_size, ast, ast->LongLongTy))
884                         return ClangASTType (ast, ast->LongLongTy.getAsOpaquePtr());
885                     if (strstr(type_name, "long") &&
886                         QualTypeMatchesBitSize (bit_size, ast, ast->LongTy))
887                         return ClangASTType (ast, ast->LongTy.getAsOpaquePtr());
888                     if (strstr(type_name, "short") &&
889                         QualTypeMatchesBitSize (bit_size, ast, ast->ShortTy))
890                         return ClangASTType (ast, ast->ShortTy.getAsOpaquePtr());
891                     if (strstr(type_name, "char"))
892                     {
893                         if (QualTypeMatchesBitSize (bit_size, ast, ast->CharTy))
894                             return ClangASTType (ast, ast->CharTy.getAsOpaquePtr());
895                         if (QualTypeMatchesBitSize (bit_size, ast, ast->SignedCharTy))
896                             return ClangASTType (ast, ast->SignedCharTy.getAsOpaquePtr());
897                     }
898                     if (strstr(type_name, "int"))
899                     {
900                         if (QualTypeMatchesBitSize (bit_size, ast, ast->IntTy))
901                             return ClangASTType (ast, ast->IntTy.getAsOpaquePtr());
902                         if (QualTypeMatchesBitSize (bit_size, ast, ast->Int128Ty))
903                             return ClangASTType (ast, ast->Int128Ty.getAsOpaquePtr());
904                     }
905                 }
906                 // We weren't able to match up a type name, just search by size
907                 if (QualTypeMatchesBitSize (bit_size, ast, ast->CharTy))
908                     return ClangASTType (ast, ast->CharTy.getAsOpaquePtr());
909                 if (QualTypeMatchesBitSize (bit_size, ast, ast->ShortTy))
910                     return ClangASTType (ast, ast->ShortTy.getAsOpaquePtr());
911                 if (QualTypeMatchesBitSize (bit_size, ast, ast->IntTy))
912                     return ClangASTType (ast, ast->IntTy.getAsOpaquePtr());
913                 if (QualTypeMatchesBitSize (bit_size, ast, ast->LongTy))
914                     return ClangASTType (ast, ast->LongTy.getAsOpaquePtr());
915                 if (QualTypeMatchesBitSize (bit_size, ast, ast->LongLongTy))
916                     return ClangASTType (ast, ast->LongLongTy.getAsOpaquePtr());
917                 if (QualTypeMatchesBitSize (bit_size, ast, ast->Int128Ty))
918                     return ClangASTType (ast, ast->Int128Ty.getAsOpaquePtr());
919                 break;
920                 
921             case DW_ATE_signed_char:
922                 if (type_name)
923                 {
924                     if (streq(type_name, "signed char"))
925                     {
926                         if (QualTypeMatchesBitSize (bit_size, ast, ast->SignedCharTy))
927                             return ClangASTType (ast, ast->SignedCharTy.getAsOpaquePtr());
928                     }
929                 }
930                 if (QualTypeMatchesBitSize (bit_size, ast, ast->CharTy))
931                     return ClangASTType (ast, ast->CharTy.getAsOpaquePtr());
932                 if (QualTypeMatchesBitSize (bit_size, ast, ast->SignedCharTy))
933                     return ClangASTType (ast, ast->SignedCharTy.getAsOpaquePtr());
934                 break;
935                 
936             case DW_ATE_unsigned:
937                 if (type_name)
938                 {
939                     if (strstr(type_name, "long long"))
940                     {
941                         if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedLongLongTy))
942                             return ClangASTType (ast, ast->UnsignedLongLongTy.getAsOpaquePtr());
943                     }
944                     else if (strstr(type_name, "long"))
945                     {
946                         if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedLongTy))
947                             return ClangASTType (ast, ast->UnsignedLongTy.getAsOpaquePtr());
948                     }
949                     else if (strstr(type_name, "short"))
950                     {
951                         if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedShortTy))
952                             return ClangASTType (ast, ast->UnsignedShortTy.getAsOpaquePtr());
953                     }
954                     else if (strstr(type_name, "char"))
955                     {
956                         if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedCharTy))
957                             return ClangASTType (ast, ast->UnsignedCharTy.getAsOpaquePtr());
958                     }
959                     else if (strstr(type_name, "int"))
960                     {
961                         if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedIntTy))
962                             return ClangASTType (ast, ast->UnsignedIntTy.getAsOpaquePtr());
963                         if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedInt128Ty))
964                             return ClangASTType (ast, ast->UnsignedInt128Ty.getAsOpaquePtr());
965                     }
966                 }
967                 // We weren't able to match up a type name, just search by size
968                 if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedCharTy))
969                     return ClangASTType (ast, ast->UnsignedCharTy.getAsOpaquePtr());
970                 if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedShortTy))
971                     return ClangASTType (ast, ast->UnsignedShortTy.getAsOpaquePtr());
972                 if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedIntTy))
973                     return ClangASTType (ast, ast->UnsignedIntTy.getAsOpaquePtr());
974                 if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedLongTy))
975                     return ClangASTType (ast, ast->UnsignedLongTy.getAsOpaquePtr());
976                 if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedLongLongTy))
977                     return ClangASTType (ast, ast->UnsignedLongLongTy.getAsOpaquePtr());
978                 if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedInt128Ty))
979                     return ClangASTType (ast, ast->UnsignedInt128Ty.getAsOpaquePtr());
980                 break;
981                 
982             case DW_ATE_unsigned_char:
983                 if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedCharTy))
984                     return ClangASTType (ast, ast->UnsignedCharTy.getAsOpaquePtr());
985                 if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedShortTy))
986                     return ClangASTType (ast, ast->UnsignedShortTy.getAsOpaquePtr());
987                 break;
988                 
989             case DW_ATE_imaginary_float:
990                 break;
991                 
992             case DW_ATE_UTF:
993                 if (type_name)
994                 {
995                     if (streq(type_name, "char16_t"))
996                     {
997                         return ClangASTType (ast, ast->Char16Ty.getAsOpaquePtr());
998                     }
999                     else if (streq(type_name, "char32_t"))
1000                     {
1001                         return ClangASTType (ast, ast->Char32Ty.getAsOpaquePtr());
1002                     }
1003                 }
1004                 break;
1005         }
1006     }
1007     // This assert should fire for anything that we don't catch above so we know
1008     // to fix any issues we run into.
1009     if (type_name)
1010     {
1011         Host::SystemLog (Host::eSystemLogError, "error: need to add support for DW_TAG_base_type '%s' encoded with DW_ATE = 0x%x, bit_size = %u\n", type_name, dw_ate, bit_size);
1012     }
1013     else
1014     {
1015         Host::SystemLog (Host::eSystemLogError, "error: need to add support for DW_TAG_base_type encoded with DW_ATE = 0x%x, bit_size = %u\n", dw_ate, bit_size);
1016     }
1017     return ClangASTType ();
1018 }
1019
1020 ClangASTType
1021 ClangASTContext::GetUnknownAnyType(clang::ASTContext *ast)
1022 {
1023     if (ast)
1024         return ClangASTType (ast, ast->UnknownAnyTy.getAsOpaquePtr());
1025     return ClangASTType();
1026 }
1027
1028 ClangASTType
1029 ClangASTContext::GetCStringType (bool is_const)
1030 {
1031     ASTContext *ast = getASTContext();
1032     QualType char_type(ast->CharTy);
1033     
1034     if (is_const)
1035         char_type.addConst();
1036     
1037     return ClangASTType (ast, ast->getPointerType(char_type).getAsOpaquePtr());
1038 }
1039
1040 clang::DeclContext *
1041 ClangASTContext::GetTranslationUnitDecl (clang::ASTContext *ast)
1042 {
1043     return ast->getTranslationUnitDecl();
1044 }
1045
1046 ClangASTType
1047 ClangASTContext::CopyType (ASTContext *dst_ast, 
1048                            ClangASTType src)
1049 {
1050     FileSystemOptions file_system_options;
1051     ASTContext *src_ast = src.GetASTContext();
1052     FileManager file_manager (file_system_options);
1053     ASTImporter importer(*dst_ast, file_manager,
1054                          *src_ast, file_manager,
1055                          false);
1056     
1057     QualType dst (importer.Import(src.GetQualType()));
1058     
1059     return ClangASTType (dst_ast, dst.getAsOpaquePtr());
1060 }
1061
1062
1063 clang::Decl *
1064 ClangASTContext::CopyDecl (ASTContext *dst_ast, 
1065                            ASTContext *src_ast,
1066                            clang::Decl *source_decl)
1067 {    
1068     FileSystemOptions file_system_options;
1069     FileManager file_manager (file_system_options);
1070     ASTImporter importer(*dst_ast, file_manager,
1071                          *src_ast, file_manager,
1072                          false);
1073     
1074     return importer.Import(source_decl);
1075 }
1076
1077 bool
1078 ClangASTContext::AreTypesSame (ClangASTType type1,
1079                                ClangASTType type2,
1080                                bool ignore_qualifiers)
1081 {
1082     ASTContext *ast = type1.GetASTContext();
1083     if (ast != type2.GetASTContext())
1084         return false;
1085
1086     if (type1.GetOpaqueQualType() == type2.GetOpaqueQualType())
1087         return true;
1088
1089     QualType type1_qual = type1.GetQualType();
1090     QualType type2_qual = type2.GetQualType();
1091     
1092     if (ignore_qualifiers)
1093     {
1094         type1_qual = type1_qual.getUnqualifiedType();
1095         type2_qual = type2_qual.getUnqualifiedType();
1096     }
1097     
1098     return ast->hasSameType (type1_qual, type2_qual);
1099 }
1100
1101
1102 ClangASTType
1103 ClangASTContext::GetTypeForDecl (TagDecl *decl)
1104 {
1105     // No need to call the getASTContext() accessor (which can create the AST
1106     // if it isn't created yet, because we can't have created a decl in this
1107     // AST if our AST didn't already exist...
1108     ASTContext *ast = m_ast_ap.get();
1109     if (ast)
1110         return ClangASTType (ast, ast->getTagDeclType(decl).getAsOpaquePtr());
1111     return ClangASTType();
1112 }
1113
1114 ClangASTType
1115 ClangASTContext::GetTypeForDecl (ObjCInterfaceDecl *decl)
1116 {
1117     // No need to call the getASTContext() accessor (which can create the AST
1118     // if it isn't created yet, because we can't have created a decl in this
1119     // AST if our AST didn't already exist...
1120     ASTContext *ast = m_ast_ap.get();
1121     if (ast)
1122         return ClangASTType (ast, ast->getObjCInterfaceType(decl).getAsOpaquePtr());
1123     return ClangASTType();
1124 }
1125
1126 #pragma mark Structure, Unions, Classes
1127
1128 ClangASTType
1129 ClangASTContext::CreateRecordType (DeclContext *decl_ctx,
1130                                    AccessType access_type,
1131                                    const char *name,
1132                                    int kind,
1133                                    LanguageType language,
1134                                    ClangASTMetadata *metadata)
1135 {
1136     ASTContext *ast = getASTContext();
1137     assert (ast != NULL);
1138      
1139     if (decl_ctx == NULL)
1140         decl_ctx = ast->getTranslationUnitDecl();
1141
1142
1143     if (language == eLanguageTypeObjC || language == eLanguageTypeObjC_plus_plus)
1144     {
1145         bool isForwardDecl = true;
1146         bool isInternal = false;
1147         return CreateObjCClass (name, decl_ctx, isForwardDecl, isInternal, metadata);
1148     }
1149
1150     // NOTE: Eventually CXXRecordDecl will be merged back into RecordDecl and
1151     // we will need to update this code. I was told to currently always use
1152     // the CXXRecordDecl class since we often don't know from debug information
1153     // if something is struct or a class, so we default to always use the more
1154     // complete definition just in case.
1155     
1156     bool is_anonymous = (!name) || (!name[0]);
1157     
1158     CXXRecordDecl *decl = CXXRecordDecl::Create (*ast,
1159                                                  (TagDecl::TagKind)kind,
1160                                                  decl_ctx,
1161                                                  SourceLocation(),
1162                                                  SourceLocation(),
1163                                                  is_anonymous ? NULL : &ast->Idents.get(name));
1164     
1165     if (is_anonymous)
1166         decl->setAnonymousStructOrUnion(true);
1167     
1168     if (decl)
1169     {
1170         if (metadata)
1171             SetMetadata(ast, decl, *metadata);
1172
1173         if (access_type != eAccessNone)
1174             decl->setAccess (ConvertAccessTypeToAccessSpecifier (access_type));
1175     
1176         if (decl_ctx)
1177             decl_ctx->addDecl (decl);
1178
1179         return ClangASTType(ast, ast->getTagDeclType(decl).getAsOpaquePtr());
1180     }
1181     return ClangASTType();
1182 }
1183
1184 static TemplateParameterList *
1185 CreateTemplateParameterList (ASTContext *ast, 
1186                              const ClangASTContext::TemplateParameterInfos &template_param_infos,
1187                              llvm::SmallVector<NamedDecl *, 8> &template_param_decls)
1188 {
1189     const bool parameter_pack = false;
1190     const bool is_typename = false;
1191     const unsigned depth = 0;
1192     const size_t num_template_params = template_param_infos.GetSize();
1193     for (size_t i=0; i<num_template_params; ++i)
1194     {
1195         const char *name = template_param_infos.names[i];
1196         
1197         IdentifierInfo *identifier_info = NULL;
1198         if (name && name[0])
1199             identifier_info = &ast->Idents.get(name);
1200         if (template_param_infos.args[i].getKind() == TemplateArgument::Integral)
1201         {
1202             template_param_decls.push_back (NonTypeTemplateParmDecl::Create (*ast,
1203                                                                              ast->getTranslationUnitDecl(), // Is this the right decl context?, SourceLocation StartLoc,
1204                                                                              SourceLocation(), 
1205                                                                              SourceLocation(), 
1206                                                                              depth, 
1207                                                                              i,
1208                                                                              identifier_info,
1209                                                                              template_param_infos.args[i].getIntegralType(), 
1210                                                                              parameter_pack, 
1211                                                                              NULL));
1212             
1213         }
1214         else
1215         {
1216             template_param_decls.push_back (TemplateTypeParmDecl::Create (*ast, 
1217                                                                           ast->getTranslationUnitDecl(), // Is this the right decl context?
1218                                                                           SourceLocation(),
1219                                                                           SourceLocation(),
1220                                                                           depth, 
1221                                                                           i,
1222                                                                           identifier_info,
1223                                                                           is_typename,
1224                                                                           parameter_pack));
1225         }
1226     }
1227
1228     TemplateParameterList *template_param_list = TemplateParameterList::Create (*ast,
1229                                                                                 SourceLocation(),
1230                                                                                 SourceLocation(),
1231                                                                                 &template_param_decls.front(),
1232                                                                                 template_param_decls.size(),
1233                                                                                 SourceLocation());
1234     return template_param_list;
1235 }
1236
1237 clang::FunctionTemplateDecl *
1238 ClangASTContext::CreateFunctionTemplateDecl (clang::DeclContext *decl_ctx,
1239                                              clang::FunctionDecl *func_decl,
1240                                              const char *name, 
1241                                              const TemplateParameterInfos &template_param_infos)
1242 {
1243 //    /// \brief Create a function template node.
1244     ASTContext *ast = getASTContext();
1245     
1246     llvm::SmallVector<NamedDecl *, 8> template_param_decls;
1247
1248     TemplateParameterList *template_param_list = CreateTemplateParameterList (ast,
1249                                                                               template_param_infos, 
1250                                                                               template_param_decls);
1251     FunctionTemplateDecl *func_tmpl_decl = FunctionTemplateDecl::Create (*ast,
1252                                                                          decl_ctx,
1253                                                                          func_decl->getLocation(),
1254                                                                          func_decl->getDeclName(),
1255                                                                          template_param_list,
1256                                                                          func_decl);
1257     
1258     for (size_t i=0, template_param_decl_count = template_param_decls.size();
1259          i < template_param_decl_count;
1260          ++i)
1261     {
1262         // TODO: verify which decl context we should put template_param_decls into..
1263         template_param_decls[i]->setDeclContext (func_decl); 
1264     }
1265
1266     return func_tmpl_decl;
1267 }
1268
1269 void
1270 ClangASTContext::CreateFunctionTemplateSpecializationInfo (FunctionDecl *func_decl, 
1271                                                            clang::FunctionTemplateDecl *func_tmpl_decl,
1272                                                            const TemplateParameterInfos &infos)
1273 {
1274     TemplateArgumentList template_args (TemplateArgumentList::OnStack,
1275                                         infos.args.data(), 
1276                                         infos.args.size());
1277
1278     func_decl->setFunctionTemplateSpecialization (func_tmpl_decl,
1279                                                   &template_args,
1280                                                   NULL);
1281 }
1282
1283
1284 ClassTemplateDecl *
1285 ClangASTContext::CreateClassTemplateDecl (DeclContext *decl_ctx,
1286                                           lldb::AccessType access_type,
1287                                           const char *class_name, 
1288                                           int kind, 
1289                                           const TemplateParameterInfos &template_param_infos)
1290 {
1291     ASTContext *ast = getASTContext();
1292     
1293     ClassTemplateDecl *class_template_decl = NULL;
1294     if (decl_ctx == NULL)
1295         decl_ctx = ast->getTranslationUnitDecl();
1296     
1297     IdentifierInfo &identifier_info = ast->Idents.get(class_name);
1298     DeclarationName decl_name (&identifier_info);
1299
1300     clang::DeclContext::lookup_result result = decl_ctx->lookup(decl_name);
1301     
1302     for (NamedDecl *decl : result)
1303     {
1304         class_template_decl = dyn_cast<clang::ClassTemplateDecl>(decl);
1305         if (class_template_decl)
1306             return class_template_decl;
1307     }
1308
1309     llvm::SmallVector<NamedDecl *, 8> template_param_decls;
1310
1311     TemplateParameterList *template_param_list = CreateTemplateParameterList (ast,
1312                                                                               template_param_infos, 
1313                                                                               template_param_decls);
1314
1315     CXXRecordDecl *template_cxx_decl = CXXRecordDecl::Create (*ast,
1316                                                               (TagDecl::TagKind)kind,
1317                                                               decl_ctx,  // What decl context do we use here? TU? The actual decl context?
1318                                                               SourceLocation(),
1319                                                               SourceLocation(),
1320                                                               &identifier_info);
1321
1322     for (size_t i=0, template_param_decl_count = template_param_decls.size();
1323          i < template_param_decl_count;
1324          ++i)
1325     {
1326         template_param_decls[i]->setDeclContext (template_cxx_decl);
1327     }
1328
1329     // With templated classes, we say that a class is templated with
1330     // specializations, but that the bare class has no functions.
1331     //template_cxx_decl->startDefinition();
1332     //template_cxx_decl->completeDefinition();
1333     
1334     class_template_decl = ClassTemplateDecl::Create (*ast,
1335                                                      decl_ctx,  // What decl context do we use here? TU? The actual decl context?
1336                                                      SourceLocation(),
1337                                                      decl_name,
1338                                                      template_param_list,
1339                                                      template_cxx_decl,
1340                                                      NULL);
1341     
1342     if (class_template_decl)
1343     {
1344         if (access_type != eAccessNone)
1345             class_template_decl->setAccess (ConvertAccessTypeToAccessSpecifier (access_type));
1346         
1347         //if (TagDecl *ctx_tag_decl = dyn_cast<TagDecl>(decl_ctx))
1348         //    CompleteTagDeclarationDefinition(GetTypeForDecl(ctx_tag_decl));
1349         
1350         decl_ctx->addDecl (class_template_decl);
1351         
1352 #ifdef LLDB_CONFIGURATION_DEBUG
1353         VerifyDecl(class_template_decl);
1354 #endif
1355     }
1356
1357     return class_template_decl;
1358 }
1359
1360
1361 ClassTemplateSpecializationDecl *
1362 ClangASTContext::CreateClassTemplateSpecializationDecl (DeclContext *decl_ctx,
1363                                                         ClassTemplateDecl *class_template_decl,
1364                                                         int kind,
1365                                                         const TemplateParameterInfos &template_param_infos)
1366 {
1367     ASTContext *ast = getASTContext();
1368     ClassTemplateSpecializationDecl *class_template_specialization_decl = ClassTemplateSpecializationDecl::Create (*ast, 
1369                                                                                                                    (TagDecl::TagKind)kind,
1370                                                                                                                    decl_ctx,
1371                                                                                                                    SourceLocation(), 
1372                                                                                                                    SourceLocation(),
1373                                                                                                                    class_template_decl,
1374                                                                                                                    &template_param_infos.args.front(),
1375                                                                                                                    template_param_infos.args.size(),
1376                                                                                                                    NULL);
1377     
1378     class_template_specialization_decl->setSpecializationKind(TSK_ExplicitSpecialization);
1379     
1380     return class_template_specialization_decl;
1381 }
1382
1383 ClangASTType
1384 ClangASTContext::CreateClassTemplateSpecializationType (ClassTemplateSpecializationDecl *class_template_specialization_decl)
1385 {
1386     if (class_template_specialization_decl)
1387     {
1388         ASTContext *ast = getASTContext();
1389         if (ast)
1390             return ClangASTType(ast, ast->getTagDeclType(class_template_specialization_decl).getAsOpaquePtr());
1391     }
1392     return ClangASTType();
1393 }
1394
1395 static bool
1396 IsOperator (const char *name, OverloadedOperatorKind &op_kind)
1397 {
1398     if (name == NULL || name[0] == '\0')
1399         return false;
1400     
1401 #define OPERATOR_PREFIX "operator"
1402 #define OPERATOR_PREFIX_LENGTH (sizeof (OPERATOR_PREFIX) - 1)
1403     
1404     const char *post_op_name = NULL;
1405
1406     bool no_space = true;
1407     
1408     if (::strncmp(name, OPERATOR_PREFIX, OPERATOR_PREFIX_LENGTH))
1409         return false;
1410     
1411     post_op_name = name + OPERATOR_PREFIX_LENGTH;
1412     
1413     if (post_op_name[0] == ' ')
1414     {
1415         post_op_name++;
1416         no_space = false;
1417     }
1418     
1419 #undef OPERATOR_PREFIX
1420 #undef OPERATOR_PREFIX_LENGTH
1421     
1422     // This is an operator, set the overloaded operator kind to invalid
1423     // in case this is a conversion operator...
1424     op_kind = NUM_OVERLOADED_OPERATORS;
1425
1426     switch (post_op_name[0])
1427     {
1428     default:
1429         if (no_space)
1430             return false;
1431         break;
1432     case 'n':
1433         if (no_space)
1434             return false;
1435         if  (strcmp (post_op_name, "new") == 0)  
1436             op_kind = OO_New;
1437         else if (strcmp (post_op_name, "new[]") == 0)  
1438             op_kind = OO_Array_New;
1439         break;
1440
1441     case 'd':
1442         if (no_space)
1443             return false;
1444         if (strcmp (post_op_name, "delete") == 0)
1445             op_kind = OO_Delete;
1446         else if (strcmp (post_op_name, "delete[]") == 0)  
1447             op_kind = OO_Array_Delete;
1448         break;
1449     
1450     case '+':
1451         if (post_op_name[1] == '\0')
1452             op_kind = OO_Plus;
1453         else if (post_op_name[2] == '\0')
1454         {
1455             if (post_op_name[1] == '=')
1456                 op_kind = OO_PlusEqual;
1457             else if (post_op_name[1] == '+')
1458                 op_kind = OO_PlusPlus;
1459         }
1460         break;
1461
1462     case '-':
1463         if (post_op_name[1] == '\0')
1464             op_kind = OO_Minus;
1465         else if (post_op_name[2] == '\0')
1466         {
1467             switch (post_op_name[1])
1468             {
1469             case '=': op_kind = OO_MinusEqual; break;
1470             case '-': op_kind = OO_MinusMinus; break;
1471             case '>': op_kind = OO_Arrow; break;
1472             }
1473         }
1474         else if (post_op_name[3] == '\0')
1475         {
1476             if (post_op_name[2] == '*')
1477                 op_kind = OO_ArrowStar; break;
1478         }
1479         break;
1480         
1481     case '*':
1482         if (post_op_name[1] == '\0')
1483             op_kind = OO_Star;
1484         else if (post_op_name[1] == '=' && post_op_name[2] == '\0')
1485             op_kind = OO_StarEqual;
1486         break;
1487     
1488     case '/':
1489         if (post_op_name[1] == '\0')
1490             op_kind = OO_Slash;
1491         else if (post_op_name[1] == '=' && post_op_name[2] == '\0')
1492             op_kind = OO_SlashEqual;
1493         break;
1494     
1495     case '%':
1496         if (post_op_name[1] == '\0')
1497             op_kind = OO_Percent;
1498         else if (post_op_name[1] == '=' && post_op_name[2] == '\0')
1499             op_kind = OO_PercentEqual;
1500         break;
1501
1502
1503     case '^':
1504         if (post_op_name[1] == '\0')
1505             op_kind = OO_Caret;
1506         else if (post_op_name[1] == '=' && post_op_name[2] == '\0')
1507             op_kind = OO_CaretEqual;
1508         break;
1509
1510     case '&':
1511         if (post_op_name[1] == '\0')
1512             op_kind = OO_Amp;
1513         else if (post_op_name[2] == '\0')
1514         {
1515             switch (post_op_name[1])
1516             {
1517             case '=': op_kind = OO_AmpEqual; break;
1518             case '&': op_kind = OO_AmpAmp; break;
1519             }   
1520         }
1521         break;
1522
1523     case '|':
1524         if (post_op_name[1] == '\0')
1525             op_kind = OO_Pipe;
1526         else if (post_op_name[2] == '\0')
1527         {
1528             switch (post_op_name[1])
1529             {
1530             case '=': op_kind = OO_PipeEqual; break;
1531             case '|': op_kind = OO_PipePipe; break;
1532             }   
1533         }
1534         break;
1535     
1536     case '~':
1537         if (post_op_name[1] == '\0')
1538             op_kind = OO_Tilde;
1539         break;
1540     
1541     case '!':
1542         if (post_op_name[1] == '\0')
1543             op_kind = OO_Exclaim;
1544         else if (post_op_name[1] == '=' && post_op_name[2] == '\0')
1545             op_kind = OO_ExclaimEqual;
1546         break;
1547
1548     case '=':
1549         if (post_op_name[1] == '\0')
1550             op_kind = OO_Equal;
1551         else if (post_op_name[1] == '=' && post_op_name[2] == '\0')
1552             op_kind = OO_EqualEqual;
1553         break;
1554     
1555     case '<':
1556         if (post_op_name[1] == '\0')
1557             op_kind = OO_Less;
1558         else if (post_op_name[2] == '\0')
1559         {
1560             switch (post_op_name[1])
1561             {
1562             case '<': op_kind = OO_LessLess; break;
1563             case '=': op_kind = OO_LessEqual; break;
1564             }   
1565         }
1566         else if (post_op_name[3] == '\0')
1567         {
1568             if (post_op_name[2] == '=')
1569                 op_kind = OO_LessLessEqual;
1570         }
1571         break;
1572
1573     case '>':
1574         if (post_op_name[1] == '\0')
1575             op_kind = OO_Greater;
1576         else if (post_op_name[2] == '\0')
1577         {
1578             switch (post_op_name[1])
1579             {
1580             case '>': op_kind = OO_GreaterGreater; break;
1581             case '=': op_kind = OO_GreaterEqual; break;
1582             }   
1583         }
1584         else if (post_op_name[1] == '>' && 
1585                  post_op_name[2] == '=' && 
1586                  post_op_name[3] == '\0')
1587         {
1588                 op_kind = OO_GreaterGreaterEqual;
1589         }
1590         break;
1591         
1592     case ',':
1593         if (post_op_name[1] == '\0')
1594             op_kind = OO_Comma;
1595         break;
1596     
1597     case '(':
1598         if (post_op_name[1] == ')' && post_op_name[2] == '\0')
1599             op_kind = OO_Call;
1600         break;
1601     
1602     case '[':
1603         if (post_op_name[1] == ']' && post_op_name[2] == '\0')
1604             op_kind = OO_Subscript;
1605         break;
1606     }
1607
1608     return true;
1609 }
1610
1611 static inline bool
1612 check_op_param (uint32_t op_kind, bool unary, bool binary, uint32_t num_params)
1613 {
1614     // Special-case call since it can take any number of operands
1615     if(op_kind == OO_Call)
1616         return true;
1617     
1618     // The parameter count doens't include "this"
1619     if (num_params == 0)
1620         return unary;
1621     if (num_params == 1)
1622         return binary;
1623     else 
1624     return false;
1625 }
1626
1627 bool
1628 ClangASTContext::CheckOverloadedOperatorKindParameterCount (uint32_t op_kind, uint32_t num_params)
1629 {
1630     switch (op_kind)
1631     {
1632     default:
1633         break;
1634     // C++ standard allows any number of arguments to new/delete
1635     case OO_New:
1636     case OO_Array_New:
1637     case OO_Delete:
1638     case OO_Array_Delete:
1639         return true;
1640     }
1641     
1642 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) case OO_##Name: return check_op_param (op_kind, Unary, Binary, num_params);
1643     switch (op_kind)
1644     {
1645 #include "clang/Basic/OperatorKinds.def"
1646         default: break;
1647     }
1648     return false;
1649 }
1650
1651 clang::AccessSpecifier
1652 ClangASTContext::UnifyAccessSpecifiers (clang::AccessSpecifier lhs, clang::AccessSpecifier rhs)
1653 {
1654     clang::AccessSpecifier ret = lhs;
1655     
1656     // Make the access equal to the stricter of the field and the nested field's access
1657     switch (ret)
1658     {
1659         case clang::AS_none:
1660             break;
1661         case clang::AS_private:
1662             break;
1663         case clang::AS_protected:
1664             if (rhs == AS_private)
1665                 ret = AS_private;
1666             break;
1667         case clang::AS_public:
1668             ret = rhs;
1669             break;
1670     }
1671     
1672     return ret;
1673 }
1674
1675 bool
1676 ClangASTContext::FieldIsBitfield (FieldDecl* field, uint32_t& bitfield_bit_size)
1677 {
1678     return FieldIsBitfield(getASTContext(), field, bitfield_bit_size);
1679 }
1680
1681 bool
1682 ClangASTContext::FieldIsBitfield
1683 (
1684     ASTContext *ast,
1685     FieldDecl* field,
1686     uint32_t& bitfield_bit_size
1687 )
1688 {
1689     if (ast == NULL || field == NULL)
1690         return false;
1691
1692     if (field->isBitField())
1693     {
1694         Expr* bit_width_expr = field->getBitWidth();
1695         if (bit_width_expr)
1696         {
1697             llvm::APSInt bit_width_apsint;
1698             if (bit_width_expr->isIntegerConstantExpr(bit_width_apsint, *ast))
1699             {
1700                 bitfield_bit_size = bit_width_apsint.getLimitedValue(UINT32_MAX);
1701                 return true;
1702             }
1703         }
1704     }
1705     return false;
1706 }
1707
1708 bool
1709 ClangASTContext::RecordHasFields (const RecordDecl *record_decl)
1710 {
1711     if (record_decl == NULL)
1712         return false;
1713
1714     if (!record_decl->field_empty())
1715         return true;
1716
1717     // No fields, lets check this is a CXX record and check the base classes
1718     const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
1719     if (cxx_record_decl)
1720     {
1721         CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
1722         for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
1723              base_class != base_class_end;
1724              ++base_class)
1725         {
1726             const CXXRecordDecl *base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
1727             if (RecordHasFields(base_class_decl))
1728                 return true;
1729         }
1730     }
1731     return false;
1732 }
1733
1734 #pragma mark Objective C Classes
1735
1736 ClangASTType
1737 ClangASTContext::CreateObjCClass
1738 (
1739     const char *name, 
1740     DeclContext *decl_ctx, 
1741     bool isForwardDecl, 
1742     bool isInternal,
1743     ClangASTMetadata *metadata
1744 )
1745 {
1746     ASTContext *ast = getASTContext();
1747     assert (ast != NULL);
1748     assert (name && name[0]);
1749     if (decl_ctx == NULL)
1750         decl_ctx = ast->getTranslationUnitDecl();
1751
1752     ObjCInterfaceDecl *decl = ObjCInterfaceDecl::Create (*ast,
1753                                                          decl_ctx,
1754                                                          SourceLocation(),
1755                                                          &ast->Idents.get(name),
1756                                                          NULL,
1757                                                          SourceLocation(),
1758                                                          /*isForwardDecl,*/
1759                                                          isInternal);
1760     
1761     if (decl && metadata)
1762         SetMetadata(ast, decl, *metadata);
1763     
1764     return ClangASTType (ast, ast->getObjCInterfaceType(decl));
1765 }
1766
1767 static inline bool
1768 BaseSpecifierIsEmpty (const CXXBaseSpecifier *b)
1769 {
1770     return ClangASTContext::RecordHasFields(b->getType()->getAsCXXRecordDecl()) == false;
1771 }
1772
1773 uint32_t
1774 ClangASTContext::GetNumBaseClasses (const CXXRecordDecl *cxx_record_decl, bool omit_empty_base_classes)
1775 {
1776     uint32_t num_bases = 0;
1777     if (cxx_record_decl)
1778     {
1779         if (omit_empty_base_classes)
1780         {
1781             CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
1782             for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
1783                  base_class != base_class_end;
1784                  ++base_class)
1785             {
1786                 // Skip empty base classes
1787                 if (omit_empty_base_classes)
1788                 {
1789                     if (BaseSpecifierIsEmpty (base_class))
1790                         continue;
1791                 }
1792                 ++num_bases;
1793             }
1794         }
1795         else
1796             num_bases = cxx_record_decl->getNumBases();
1797     }
1798     return num_bases;
1799 }
1800
1801
1802 #pragma mark Namespace Declarations
1803
1804 NamespaceDecl *
1805 ClangASTContext::GetUniqueNamespaceDeclaration (const char *name, DeclContext *decl_ctx)
1806 {
1807     NamespaceDecl *namespace_decl = NULL;
1808     ASTContext *ast = getASTContext();
1809     TranslationUnitDecl *translation_unit_decl = ast->getTranslationUnitDecl ();
1810     if (decl_ctx == NULL)
1811         decl_ctx = translation_unit_decl;
1812     
1813     if (name)
1814     {
1815         IdentifierInfo &identifier_info = ast->Idents.get(name);
1816         DeclarationName decl_name (&identifier_info);
1817         clang::DeclContext::lookup_result result = decl_ctx->lookup(decl_name);
1818         for (NamedDecl *decl : result)
1819         {
1820             namespace_decl = dyn_cast<clang::NamespaceDecl>(decl);
1821             if (namespace_decl)
1822                 return namespace_decl;
1823         }
1824
1825         namespace_decl = NamespaceDecl::Create(*ast, 
1826                                                decl_ctx, 
1827                                                false, 
1828                                                SourceLocation(), 
1829                                                SourceLocation(),
1830                                                &identifier_info,
1831                                                NULL);
1832         
1833         decl_ctx->addDecl (namespace_decl);        
1834     }
1835     else
1836     {
1837         if (decl_ctx == translation_unit_decl)
1838         {
1839             namespace_decl = translation_unit_decl->getAnonymousNamespace();
1840             if (namespace_decl)
1841                 return namespace_decl;
1842             
1843             namespace_decl = NamespaceDecl::Create(*ast, 
1844                                                    decl_ctx,
1845                                                    false,
1846                                                    SourceLocation(),
1847                                                    SourceLocation(),
1848                                                    NULL,
1849                                                    NULL);
1850             translation_unit_decl->setAnonymousNamespace (namespace_decl);
1851             translation_unit_decl->addDecl (namespace_decl);
1852             assert (namespace_decl == translation_unit_decl->getAnonymousNamespace());
1853         }
1854         else
1855         {
1856             NamespaceDecl *parent_namespace_decl = cast<NamespaceDecl>(decl_ctx);
1857             if (parent_namespace_decl)
1858             {
1859                 namespace_decl = parent_namespace_decl->getAnonymousNamespace();
1860                 if (namespace_decl)
1861                     return namespace_decl;
1862                 namespace_decl = NamespaceDecl::Create(*ast, 
1863                                                        decl_ctx, 
1864                                                        false,
1865                                                        SourceLocation(), 
1866                                                        SourceLocation(), 
1867                                                        NULL,
1868                                                        NULL);
1869                 parent_namespace_decl->setAnonymousNamespace (namespace_decl);
1870                 parent_namespace_decl->addDecl (namespace_decl);
1871                 assert (namespace_decl == parent_namespace_decl->getAnonymousNamespace());
1872             }
1873             else
1874             {
1875                 // BAD!!!
1876             }
1877         }
1878         
1879
1880         if (namespace_decl)
1881         {
1882             // If we make it here, we are creating the anonymous namespace decl
1883             // for the first time, so we need to do the using directive magic
1884             // like SEMA does
1885             UsingDirectiveDecl* using_directive_decl = UsingDirectiveDecl::Create (*ast, 
1886                                                                                    decl_ctx, 
1887                                                                                    SourceLocation(),
1888                                                                                    SourceLocation(),
1889                                                                                    NestedNameSpecifierLoc(),
1890                                                                                    SourceLocation(),
1891                                                                                    namespace_decl,
1892                                                                                    decl_ctx);
1893             using_directive_decl->setImplicit();
1894             decl_ctx->addDecl(using_directive_decl);
1895         }
1896     }
1897 #ifdef LLDB_CONFIGURATION_DEBUG
1898     VerifyDecl(namespace_decl);
1899 #endif
1900     return namespace_decl;
1901 }
1902
1903
1904 #pragma mark Function Types
1905
1906 FunctionDecl *
1907 ClangASTContext::CreateFunctionDeclaration (DeclContext *decl_ctx,
1908                                             const char *name,
1909                                             const ClangASTType &function_clang_type,
1910                                             int storage,
1911                                             bool is_inline)
1912 {
1913     FunctionDecl *func_decl = NULL;
1914     ASTContext *ast = getASTContext();
1915     if (decl_ctx == NULL)
1916         decl_ctx = ast->getTranslationUnitDecl();
1917
1918     
1919     const bool hasWrittenPrototype = true;
1920     const bool isConstexprSpecified = false;
1921
1922     if (name && name[0])
1923     {
1924         func_decl = FunctionDecl::Create (*ast,
1925                                           decl_ctx,
1926                                           SourceLocation(),
1927                                           SourceLocation(),
1928                                           DeclarationName (&ast->Idents.get(name)),
1929                                           function_clang_type.GetQualType(),
1930                                           NULL,
1931                                           (FunctionDecl::StorageClass)storage,
1932                                           is_inline,
1933                                           hasWrittenPrototype,
1934                                           isConstexprSpecified);
1935     }
1936     else
1937     {
1938         func_decl = FunctionDecl::Create (*ast,
1939                                           decl_ctx,
1940                                           SourceLocation(),
1941                                           SourceLocation(),
1942                                           DeclarationName (),
1943                                           function_clang_type.GetQualType(),
1944                                           NULL,
1945                                           (FunctionDecl::StorageClass)storage,
1946                                           is_inline,
1947                                           hasWrittenPrototype,
1948                                           isConstexprSpecified);
1949     }
1950     if (func_decl)
1951         decl_ctx->addDecl (func_decl);
1952     
1953 #ifdef LLDB_CONFIGURATION_DEBUG
1954     VerifyDecl(func_decl);
1955 #endif
1956     
1957     return func_decl;
1958 }
1959
1960 ClangASTType
1961 ClangASTContext::CreateFunctionType (ASTContext *ast,
1962                                      const ClangASTType& result_type,
1963                                      const ClangASTType *args,
1964                                      unsigned num_args, 
1965                                      bool is_variadic, 
1966                                      unsigned type_quals)
1967 {
1968     assert (ast != NULL);
1969     std::vector<QualType> qual_type_args;
1970     for (unsigned i=0; i<num_args; ++i)
1971         qual_type_args.push_back (args[i].GetQualType());
1972
1973     // TODO: Detect calling convention in DWARF?
1974     FunctionProtoType::ExtProtoInfo proto_info;
1975     proto_info.Variadic = is_variadic;
1976     proto_info.ExceptionSpecType = EST_None;
1977     proto_info.TypeQuals = type_quals;
1978     proto_info.RefQualifier = RQ_None;
1979     proto_info.NumExceptions = 0;
1980     proto_info.Exceptions = NULL;
1981     
1982     return ClangASTType (ast, ast->getFunctionType (result_type.GetQualType(),
1983                                                     qual_type_args,
1984                                                     proto_info).getAsOpaquePtr());
1985 }
1986
1987 ParmVarDecl *
1988 ClangASTContext::CreateParameterDeclaration (const char *name, const ClangASTType &param_type, int storage)
1989 {
1990     ASTContext *ast = getASTContext();
1991     assert (ast != NULL);
1992     return ParmVarDecl::Create(*ast,
1993                                 ast->getTranslationUnitDecl(),
1994                                 SourceLocation(),
1995                                 SourceLocation(),
1996                                 name && name[0] ? &ast->Idents.get(name) : NULL,
1997                                 param_type.GetQualType(),
1998                                 NULL,
1999                                 (VarDecl::StorageClass)storage,
2000                                 0);
2001 }
2002
2003 void
2004 ClangASTContext::SetFunctionParameters (FunctionDecl *function_decl, ParmVarDecl **params, unsigned num_params)
2005 {
2006     if (function_decl)
2007         function_decl->setParams (ArrayRef<ParmVarDecl*>(params, num_params));
2008 }
2009
2010
2011 #pragma mark Array Types
2012
2013 ClangASTType
2014 ClangASTContext::CreateArrayType (const ClangASTType &element_type,
2015                                   size_t element_count,
2016                                   bool is_vector)
2017 {
2018     if (element_type.IsValid())
2019     {
2020         ASTContext *ast = getASTContext();
2021         assert (ast != NULL);
2022
2023         if (is_vector)
2024         {
2025             return ClangASTType (ast, ast->getExtVectorType(element_type.GetQualType(), element_count).getAsOpaquePtr());
2026         }
2027         else
2028         {
2029         
2030             llvm::APInt ap_element_count (64, element_count);
2031             if (element_count == 0)
2032             {
2033                 return ClangASTType (ast, ast->getIncompleteArrayType (element_type.GetQualType(),
2034                                                                        ArrayType::Normal,
2035                                                                        0).getAsOpaquePtr());
2036             }
2037             else
2038             {
2039                 return ClangASTType (ast, ast->getConstantArrayType (element_type.GetQualType(),
2040                                                                      ap_element_count,
2041                                                                      ArrayType::Normal,
2042                                                                      0).getAsOpaquePtr());
2043             }
2044         }
2045     }
2046     return ClangASTType();
2047 }
2048
2049
2050
2051 #pragma mark Enumeration Types
2052
2053 ClangASTType
2054 ClangASTContext::CreateEnumerationType 
2055 (
2056     const char *name, 
2057     DeclContext *decl_ctx, 
2058     const Declaration &decl, 
2059     const ClangASTType &integer_clang_type
2060 )
2061 {
2062     // TODO: Do something intelligent with the Declaration object passed in
2063     // like maybe filling in the SourceLocation with it...
2064     ASTContext *ast = getASTContext();
2065
2066     // TODO: ask about these...
2067 //    const bool IsScoped = false;
2068 //    const bool IsFixed = false;
2069
2070     EnumDecl *enum_decl = EnumDecl::Create (*ast,
2071                                             decl_ctx,
2072                                             SourceLocation(),
2073                                             SourceLocation(),
2074                                             name && name[0] ? &ast->Idents.get(name) : NULL,
2075                                             NULL, 
2076                                             false,  // IsScoped
2077                                             false,  // IsScopedUsingClassTag
2078                                             false); // IsFixed
2079     
2080     
2081     if (enum_decl)
2082     {
2083         // TODO: check if we should be setting the promotion type too?
2084         enum_decl->setIntegerType(integer_clang_type.GetQualType());
2085         
2086         enum_decl->setAccess(AS_public); // TODO respect what's in the debug info
2087         
2088         return ClangASTType (ast, ast->getTagDeclType(enum_decl).getAsOpaquePtr());
2089     }
2090     return ClangASTType();
2091 }
2092
2093 // Disable this for now since I can't seem to get a nicely formatted float
2094 // out of the APFloat class without just getting the float, double or quad
2095 // and then using a formatted print on it which defeats the purpose. We ideally
2096 // would like to get perfect string values for any kind of float semantics
2097 // so we can support remote targets. The code below also requires a patch to
2098 // llvm::APInt.
2099 //bool
2100 //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)
2101 //{
2102 //  uint32_t count = 0;
2103 //  bool is_complex = false;
2104 //  if (ClangASTContext::IsFloatingPointType (clang_type, count, is_complex))
2105 //  {
2106 //      unsigned num_bytes_per_float = byte_size / count;
2107 //      unsigned num_bits_per_float = num_bytes_per_float * 8;
2108 //
2109 //      float_str.clear();
2110 //      uint32_t i;
2111 //      for (i=0; i<count; i++)
2112 //      {
2113 //          APInt ap_int(num_bits_per_float, bytes + i * num_bytes_per_float, (APInt::ByteOrder)apint_byte_order);
2114 //          bool is_ieee = false;
2115 //          APFloat ap_float(ap_int, is_ieee);
2116 //          char s[1024];
2117 //          unsigned int hex_digits = 0;
2118 //          bool upper_case = false;
2119 //
2120 //          if (ap_float.convertToHexString(s, hex_digits, upper_case, APFloat::rmNearestTiesToEven) > 0)
2121 //          {
2122 //              if (i > 0)
2123 //                  float_str.append(", ");
2124 //              float_str.append(s);
2125 //              if (i == 1 && is_complex)
2126 //                  float_str.append(1, 'i');
2127 //          }
2128 //      }
2129 //      return !float_str.empty();
2130 //  }
2131 //  return false;
2132 //}
2133
2134
2135 ClangASTType
2136 ClangASTContext::GetFloatTypeFromBitSize (clang::ASTContext *ast,
2137                                           size_t bit_size)
2138 {
2139     if (ast)
2140     {
2141         if (bit_size == ast->getTypeSize(ast->FloatTy))
2142             return ClangASTType(ast, ast->FloatTy.getAsOpaquePtr());
2143         else if (bit_size == ast->getTypeSize(ast->DoubleTy))
2144             return ClangASTType(ast, ast->DoubleTy.getAsOpaquePtr());
2145         else if (bit_size == ast->getTypeSize(ast->LongDoubleTy))
2146             return ClangASTType(ast, ast->LongDoubleTy.getAsOpaquePtr());
2147         else if (bit_size == ast->getTypeSize(ast->HalfTy))
2148             return ClangASTType(ast, ast->HalfTy.getAsOpaquePtr());
2149     }
2150     return ClangASTType();
2151 }
2152
2153 bool
2154 ClangASTContext::GetCompleteDecl (clang::ASTContext *ast,
2155                                   clang::Decl *decl)
2156 {
2157     if (!decl)
2158         return false;
2159     
2160     ExternalASTSource *ast_source = ast->getExternalSource();
2161     
2162     if (!ast_source)
2163         return false;
2164         
2165     if (clang::TagDecl *tag_decl = llvm::dyn_cast<clang::TagDecl>(decl))
2166     {
2167         if (tag_decl->isCompleteDefinition())
2168             return true;
2169         
2170         if (!tag_decl->hasExternalLexicalStorage())
2171             return false;
2172         
2173         ast_source->CompleteType(tag_decl);
2174         
2175         return !tag_decl->getTypeForDecl()->isIncompleteType();
2176     }
2177     else if (clang::ObjCInterfaceDecl *objc_interface_decl = llvm::dyn_cast<clang::ObjCInterfaceDecl>(decl))
2178     {
2179         if (objc_interface_decl->getDefinition())
2180             return true;
2181         
2182         if (!objc_interface_decl->hasExternalLexicalStorage())
2183             return false;
2184         
2185         ast_source->CompleteType(objc_interface_decl);
2186         
2187         return !objc_interface_decl->getTypeForDecl()->isIncompleteType();
2188     }
2189     else
2190     {
2191         return false;
2192     }
2193 }
2194
2195 void
2196 ClangASTContext::SetMetadataAsUserID (const void *object,
2197                                       user_id_t user_id)
2198 {
2199     ClangASTMetadata meta_data;
2200     meta_data.SetUserID (user_id);
2201     SetMetadata (object, meta_data);
2202 }
2203
2204 void
2205 ClangASTContext::SetMetadata (clang::ASTContext *ast,
2206                               const void *object,
2207                               ClangASTMetadata &metadata)
2208 {
2209     ClangExternalASTSourceCommon *external_source =
2210         static_cast<ClangExternalASTSourceCommon*>(ast->getExternalSource());
2211     
2212     if (external_source)
2213         external_source->SetMetadata(object, metadata);
2214 }
2215
2216 ClangASTMetadata *
2217 ClangASTContext::GetMetadata (clang::ASTContext *ast,
2218                               const void *object)
2219 {
2220     ClangExternalASTSourceCommon *external_source =
2221         static_cast<ClangExternalASTSourceCommon*>(ast->getExternalSource());
2222     
2223     if (external_source && external_source->HasMetadata(object))
2224         return external_source->GetMetadata(object);
2225     else
2226         return NULL;
2227 }
2228
2229 clang::DeclContext *
2230 ClangASTContext::GetAsDeclContext (clang::CXXMethodDecl *cxx_method_decl)
2231 {
2232     return llvm::dyn_cast<clang::DeclContext>(cxx_method_decl);
2233 }
2234
2235 clang::DeclContext *
2236 ClangASTContext::GetAsDeclContext (clang::ObjCMethodDecl *objc_method_decl)
2237 {
2238     return llvm::dyn_cast<clang::DeclContext>(objc_method_decl);
2239 }
2240
2241
2242 bool
2243 ClangASTContext::GetClassMethodInfoForDeclContext (clang::DeclContext *decl_ctx,
2244                                                    lldb::LanguageType &language,
2245                                                    bool &is_instance_method,
2246                                                    ConstString &language_object_name)
2247 {
2248     language_object_name.Clear();
2249     language = eLanguageTypeUnknown;
2250     is_instance_method = false;
2251
2252     if (decl_ctx)
2253     {
2254         if (clang::CXXMethodDecl *method_decl = llvm::dyn_cast<clang::CXXMethodDecl>(decl_ctx))
2255         {
2256             if (method_decl->isStatic())
2257             {
2258                 is_instance_method = false;
2259             }
2260             else
2261             {
2262                 language_object_name.SetCString("this");
2263                 is_instance_method = true;
2264             }
2265             language = eLanguageTypeC_plus_plus;
2266             return true;
2267         }
2268         else if (clang::ObjCMethodDecl *method_decl = llvm::dyn_cast<clang::ObjCMethodDecl>(decl_ctx))
2269         {
2270             // Both static and instance methods have a "self" object in objective C
2271             language_object_name.SetCString("self");
2272             if (method_decl->isInstanceMethod())
2273             {
2274                 is_instance_method = true;
2275             }
2276             else
2277             {
2278                 is_instance_method = false;
2279             }
2280             language = eLanguageTypeObjC;
2281             return true;
2282         }
2283         else if (clang::FunctionDecl *function_decl = llvm::dyn_cast<clang::FunctionDecl>(decl_ctx))
2284         {
2285             ClangASTMetadata *metadata = GetMetadata (&decl_ctx->getParentASTContext(), function_decl);
2286             if (metadata && metadata->HasObjectPtr())
2287             {
2288                 language_object_name.SetCString (metadata->GetObjectPtrName());
2289                 language = eLanguageTypeObjC;
2290                 is_instance_method = true;
2291             }
2292             return true;
2293         }
2294     }
2295     return false;
2296 }
2297