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