1 //===-- ClangASTContext.cpp -------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "lldb/Symbol/ClangASTContext.h"
17 // Other libraries and framework includes
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
29 #if !defined(NDEBUG) && !defined(LLVM_NDEBUG_OFF)
30 #define LLDB_DEFINED_NDEBUG_FOR_CLANG
32 // Need to include assert.h so it is as clang would expect it to be (disabled)
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"
54 #ifdef LLDB_DEFINED_NDEBUG_FOR_CLANG
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)
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"
80 using namespace lldb_private;
82 using namespace clang;
84 typedef lldb_private::ThreadSafeDenseMap<clang::ASTContext *, ClangASTContext*> ClangASTMap;
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
98 clang::AccessSpecifier
99 ClangASTContext::ConvertAccessTypeToAccessSpecifier (AccessType access)
104 case eAccessNone: return AS_none;
105 case eAccessPublic: return AS_public;
106 case eAccessPrivate: return AS_private;
107 case eAccessProtected: return AS_protected;
120 // FIXME: Cleanup per-file based stuff.
122 // Set some properties which depend solely on the input kind; it would be nice
123 // to move these to the language standard, and have the driver resolve the
124 // input kind + language standard.
126 Opts.AsmPreprocessor = 1;
127 } else if (IK == IK_ObjC ||
129 IK == IK_PreprocessedObjC ||
130 IK == IK_PreprocessedObjCXX) {
131 Opts.ObjC1 = Opts.ObjC2 = 1;
134 LangStandard::Kind LangStd = LangStandard::lang_unspecified;
136 if (LangStd == LangStandard::lang_unspecified) {
137 // Based on the base language, pick one.
142 assert (!"Invalid input kind!");
144 LangStd = LangStandard::lang_opencl;
147 LangStd = LangStandard::lang_cuda;
151 case IK_PreprocessedC:
153 case IK_PreprocessedObjC:
154 LangStd = LangStandard::lang_gnu99;
157 case IK_PreprocessedCXX:
159 case IK_PreprocessedObjCXX:
160 LangStd = LangStandard::lang_gnucxx98;
165 const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd);
166 Opts.LineComment = Std.hasLineComments();
167 Opts.C99 = Std.isC99();
168 Opts.CPlusPlus = Std.isCPlusPlus();
169 Opts.CPlusPlus11 = Std.isCPlusPlus11();
170 Opts.Digraphs = Std.hasDigraphs();
171 Opts.GNUMode = Std.isGNUMode();
172 Opts.GNUInline = !Std.isC99();
173 Opts.HexFloats = Std.hasHexFloats();
174 Opts.ImplicitInt = Std.hasImplicitInt();
178 // OpenCL has some additional defaults.
179 if (LangStd == LangStandard::lang_opencl) {
182 Opts.CXXOperatorNames = 1;
183 Opts.LaxVectorConversions = 1;
186 // OpenCL and C++ both have bool, true, false keywords.
187 Opts.Bool = Opts.OpenCL || Opts.CPlusPlus;
189 // if (Opts.CPlusPlus)
190 // Opts.CXXOperatorNames = !Args.hasArg(OPT_fno_operator_names);
192 // if (Args.hasArg(OPT_fobjc_gc_only))
193 // Opts.setGCMode(LangOptions::GCOnly);
194 // else if (Args.hasArg(OPT_fobjc_gc))
195 // Opts.setGCMode(LangOptions::HybridGC);
197 // if (Args.hasArg(OPT_print_ivar_layout))
198 // Opts.ObjCGCBitmapPrint = 1;
200 // if (Args.hasArg(OPT_faltivec))
203 // if (Args.hasArg(OPT_pthread))
204 // Opts.POSIXThreads = 1;
206 // llvm::StringRef Vis = getLastArgValue(Args, OPT_fvisibility,
208 // if (Vis == "default")
209 Opts.setValueVisibilityMode(DefaultVisibility);
210 // else if (Vis == "hidden")
211 // Opts.setVisibilityMode(LangOptions::Hidden);
212 // else if (Vis == "protected")
213 // Opts.setVisibilityMode(LangOptions::Protected);
215 // Diags.Report(diag::err_drv_invalid_value)
216 // << Args.getLastArg(OPT_fvisibility)->getAsString(Args) << Vis;
218 // Opts.OverflowChecking = Args.hasArg(OPT_ftrapv);
220 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs
221 // is specified, or -std is set to a conforming mode.
222 Opts.Trigraphs = !Opts.GNUMode;
223 // if (Args.hasArg(OPT_trigraphs))
224 // Opts.Trigraphs = 1;
226 // Opts.DollarIdents = Args.hasFlag(OPT_fdollars_in_identifiers,
227 // OPT_fno_dollars_in_identifiers,
228 // !Opts.AsmPreprocessor);
229 // Opts.PascalStrings = Args.hasArg(OPT_fpascal_strings);
230 // Opts.Microsoft = Args.hasArg(OPT_fms_extensions);
231 // Opts.WritableStrings = Args.hasArg(OPT_fwritable_strings);
232 // if (Args.hasArg(OPT_fno_lax_vector_conversions))
233 // Opts.LaxVectorConversions = 0;
234 // Opts.Exceptions = Args.hasArg(OPT_fexceptions);
235 // Opts.RTTI = !Args.hasArg(OPT_fno_rtti);
236 // Opts.Blocks = Args.hasArg(OPT_fblocks);
237 // Opts.CharIsSigned = !Args.hasArg(OPT_fno_signed_char);
238 // Opts.ShortWChar = Args.hasArg(OPT_fshort_wchar);
239 // Opts.Freestanding = Args.hasArg(OPT_ffreestanding);
240 // Opts.NoBuiltin = Args.hasArg(OPT_fno_builtin) || Opts.Freestanding;
241 // Opts.AssumeSaneOperatorNew = !Args.hasArg(OPT_fno_assume_sane_operator_new);
242 // Opts.HeinousExtensions = Args.hasArg(OPT_fheinous_gnu_extensions);
243 // Opts.AccessControl = Args.hasArg(OPT_faccess_control);
244 // Opts.ElideConstructors = !Args.hasArg(OPT_fno_elide_constructors);
245 // Opts.MathErrno = !Args.hasArg(OPT_fno_math_errno);
246 // Opts.InstantiationDepth = getLastArgIntValue(Args, OPT_ftemplate_depth, 99,
248 // Opts.NeXTRuntime = !Args.hasArg(OPT_fgnu_runtime);
249 // Opts.ObjCConstantStringClass = getLastArgValue(Args,
250 // OPT_fconstant_string_class);
251 // Opts.ObjCNonFragileABI = Args.hasArg(OPT_fobjc_nonfragile_abi);
252 // Opts.CatchUndefined = Args.hasArg(OPT_fcatch_undefined_behavior);
253 // Opts.EmitAllDecls = Args.hasArg(OPT_femit_all_decls);
254 // Opts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags);
255 // Opts.Static = Args.hasArg(OPT_static_define);
256 Opts.OptimizeSize = 0;
258 // FIXME: Eliminate this dependency.
260 // Args.hasArg(OPT_Os) ? 2 : getLastArgIntValue(Args, OPT_O, 0, Diags);
261 // Opts.Optimize = Opt != 0;
264 // This is the __NO_INLINE__ define, which just depends on things like the
265 // optimization level and -fno-inline, not actually whether the backend has
268 // FIXME: This is affected by other options (-fno-inline).
269 Opts.NoInlineDefine = !Opt;
271 // unsigned SSP = getLastArgIntValue(Args, OPT_stack_protector, 0, Diags);
274 // Diags.Report(diag::err_drv_invalid_value)
275 // << Args.getLastArg(OPT_stack_protector)->getAsString(Args) << SSP;
277 // case 0: Opts.setStackProtectorMode(LangOptions::SSPOff); break;
278 // case 1: Opts.setStackProtectorMode(LangOptions::SSPOn); break;
279 // case 2: Opts.setStackProtectorMode(LangOptions::SSPReq); break;
284 ClangASTContext::ClangASTContext (const char *target_triple) :
287 m_language_options_ap(),
288 m_source_manager_ap(),
289 m_diagnostics_engine_ap(),
290 m_target_options_rp(),
292 m_identifier_table_ap(),
293 m_selector_table_ap(),
295 m_callback_tag_decl (nullptr),
296 m_callback_objc_decl (nullptr),
297 m_callback_baton (nullptr),
298 m_pointer_byte_size (0)
301 if (target_triple && target_triple[0])
302 SetTargetTriple (target_triple);
305 //----------------------------------------------------------------------
307 //----------------------------------------------------------------------
308 ClangASTContext::~ClangASTContext()
312 GetASTMap().Erase(m_ast_ap.get());
315 m_builtins_ap.reset();
316 m_selector_table_ap.reset();
317 m_identifier_table_ap.reset();
318 m_target_info_ap.reset();
319 m_target_options_rp.reset();
320 m_diagnostics_engine_ap.reset();
321 m_source_manager_ap.reset();
322 m_language_options_ap.reset();
328 ClangASTContext::Clear()
331 m_language_options_ap.reset();
332 m_source_manager_ap.reset();
333 m_diagnostics_engine_ap.reset();
334 m_target_options_rp.reset();
335 m_target_info_ap.reset();
336 m_identifier_table_ap.reset();
337 m_selector_table_ap.reset();
338 m_builtins_ap.reset();
339 m_pointer_byte_size = 0;
343 ClangASTContext::GetTargetTriple ()
345 return m_target_triple.c_str();
349 ClangASTContext::SetTargetTriple (const char *target_triple)
352 m_target_triple.assign(target_triple);
356 ClangASTContext::SetArchitecture (const ArchSpec &arch)
358 SetTargetTriple(arch.GetTriple().str().c_str());
362 ClangASTContext::HasExternalSource ()
364 ASTContext *ast = getASTContext();
366 return ast->getExternalSource () != nullptr;
371 ClangASTContext::SetExternalSource (llvm::IntrusiveRefCntPtr<ExternalASTSource> &ast_source_ap)
373 ASTContext *ast = getASTContext();
376 ast->setExternalSource (ast_source_ap);
377 ast->getTranslationUnitDecl()->setHasExternalLexicalStorage(true);
378 //ast->getTranslationUnitDecl()->setHasExternalVisibleStorage(true);
383 ClangASTContext::RemoveExternalSource ()
385 ASTContext *ast = getASTContext();
389 llvm::IntrusiveRefCntPtr<ExternalASTSource> empty_ast_source_ap;
390 ast->setExternalSource (empty_ast_source_ap);
391 ast->getTranslationUnitDecl()->setHasExternalLexicalStorage(false);
392 //ast->getTranslationUnitDecl()->setHasExternalVisibleStorage(false);
399 ClangASTContext::getASTContext()
401 if (m_ast_ap.get() == nullptr)
403 m_ast_ap.reset(new ASTContext (*getLanguageOptions(),
405 *getIdentifierTable(),
407 *getBuiltinContext()));
408 m_ast_ap->InitBuiltinTypes(*getTargetInfo());
410 if ((m_callback_tag_decl || m_callback_objc_decl) && m_callback_baton)
412 m_ast_ap->getTranslationUnitDecl()->setHasExternalLexicalStorage();
413 //m_ast_ap->getTranslationUnitDecl()->setHasExternalVisibleStorage();
416 m_ast_ap->getDiagnostics().setClient(getDiagnosticConsumer(), false);
418 GetASTMap().Insert(m_ast_ap.get(), this);
420 return m_ast_ap.get();
424 ClangASTContext::GetASTContext (clang::ASTContext* ast)
426 ClangASTContext *clang_ast = GetASTMap().Lookup(ast);
431 ClangASTContext::getBuiltinContext()
433 if (m_builtins_ap.get() == nullptr)
434 m_builtins_ap.reset (new Builtin::Context());
435 return m_builtins_ap.get();
439 ClangASTContext::getIdentifierTable()
441 if (m_identifier_table_ap.get() == nullptr)
442 m_identifier_table_ap.reset(new IdentifierTable (*ClangASTContext::getLanguageOptions(), nullptr));
443 return m_identifier_table_ap.get();
447 ClangASTContext::getLanguageOptions()
449 if (m_language_options_ap.get() == nullptr)
451 m_language_options_ap.reset(new LangOptions());
452 ParseLangArgs(*m_language_options_ap, IK_ObjCXX);
453 // InitializeLangOptions(*m_language_options_ap, IK_ObjCXX);
455 return m_language_options_ap.get();
459 ClangASTContext::getSelectorTable()
461 if (m_selector_table_ap.get() == nullptr)
462 m_selector_table_ap.reset (new SelectorTable());
463 return m_selector_table_ap.get();
467 ClangASTContext::getFileManager()
469 if (m_file_manager_ap.get() == nullptr)
471 clang::FileSystemOptions file_system_options;
472 m_file_manager_ap.reset(new clang::FileManager(file_system_options));
474 return m_file_manager_ap.get();
477 clang::SourceManager *
478 ClangASTContext::getSourceManager()
480 if (m_source_manager_ap.get() == nullptr)
481 m_source_manager_ap.reset(new clang::SourceManager(*getDiagnosticsEngine(), *getFileManager()));
482 return m_source_manager_ap.get();
485 clang::DiagnosticsEngine *
486 ClangASTContext::getDiagnosticsEngine()
488 if (m_diagnostics_engine_ap.get() == nullptr)
490 llvm::IntrusiveRefCntPtr<DiagnosticIDs> diag_id_sp(new DiagnosticIDs());
491 m_diagnostics_engine_ap.reset(new DiagnosticsEngine(diag_id_sp, new DiagnosticOptions()));
493 return m_diagnostics_engine_ap.get();
496 class NullDiagnosticConsumer : public DiagnosticConsumer
499 NullDiagnosticConsumer ()
501 m_log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
504 void HandleDiagnostic (DiagnosticsEngine::Level DiagLevel, const Diagnostic &info)
508 llvm::SmallVector<char, 32> diag_str(10);
509 info.FormatDiagnostic(diag_str);
510 diag_str.push_back('\0');
511 m_log->Printf("Compiler diagnostic: %s\n", diag_str.data());
515 DiagnosticConsumer *clone (DiagnosticsEngine &Diags) const
517 return new NullDiagnosticConsumer ();
524 ClangASTContext::getDiagnosticConsumer()
526 if (m_diagnostic_consumer_ap.get() == nullptr)
527 m_diagnostic_consumer_ap.reset(new NullDiagnosticConsumer);
529 return m_diagnostic_consumer_ap.get();
532 std::shared_ptr<TargetOptions> &
533 ClangASTContext::getTargetOptions() {
534 if (m_target_options_rp.get() == nullptr && !m_target_triple.empty())
536 m_target_options_rp = std::make_shared<TargetOptions>();
537 if (m_target_options_rp.get() != nullptr)
538 m_target_options_rp->Triple = m_target_triple;
540 return m_target_options_rp;
545 ClangASTContext::getTargetInfo()
547 // target_triple should be something like "x86_64-apple-macosx"
548 if (m_target_info_ap.get() == nullptr && !m_target_triple.empty())
549 m_target_info_ap.reset (TargetInfo::CreateTargetInfo(*getDiagnosticsEngine(), getTargetOptions()));
550 return m_target_info_ap.get();
553 #pragma mark Basic Types
556 QualTypeMatchesBitSize(const uint64_t bit_size, ASTContext *ast, QualType qual_type)
558 uint64_t qual_type_bit_size = ast->getTypeSize(qual_type);
559 if (qual_type_bit_size == bit_size)
564 ClangASTContext::GetBuiltinTypeForEncodingAndBitSize (Encoding encoding, uint32_t bit_size)
566 return ClangASTContext::GetBuiltinTypeForEncodingAndBitSize (getASTContext(), encoding, bit_size);
570 ClangASTContext::GetBuiltinTypeForEncodingAndBitSize (ASTContext *ast, Encoding encoding, uint32_t bit_size)
573 return ClangASTType();
577 case eEncodingInvalid:
578 if (QualTypeMatchesBitSize (bit_size, ast, ast->VoidPtrTy))
579 return ClangASTType (ast, ast->VoidPtrTy.getAsOpaquePtr());
583 if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedCharTy))
584 return ClangASTType (ast, ast->UnsignedCharTy.getAsOpaquePtr());
585 if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedShortTy))
586 return ClangASTType (ast, ast->UnsignedShortTy.getAsOpaquePtr());
587 if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedIntTy))
588 return ClangASTType (ast, ast->UnsignedIntTy.getAsOpaquePtr());
589 if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedLongTy))
590 return ClangASTType (ast, ast->UnsignedLongTy.getAsOpaquePtr());
591 if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedLongLongTy))
592 return ClangASTType (ast, ast->UnsignedLongLongTy.getAsOpaquePtr());
593 if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedInt128Ty))
594 return ClangASTType (ast, ast->UnsignedInt128Ty.getAsOpaquePtr());
598 if (QualTypeMatchesBitSize (bit_size, ast, ast->CharTy))
599 return ClangASTType (ast, ast->CharTy.getAsOpaquePtr());
600 if (QualTypeMatchesBitSize (bit_size, ast, ast->ShortTy))
601 return ClangASTType (ast, ast->ShortTy.getAsOpaquePtr());
602 if (QualTypeMatchesBitSize (bit_size, ast, ast->IntTy))
603 return ClangASTType (ast, ast->IntTy.getAsOpaquePtr());
604 if (QualTypeMatchesBitSize (bit_size, ast, ast->LongTy))
605 return ClangASTType (ast, ast->LongTy.getAsOpaquePtr());
606 if (QualTypeMatchesBitSize (bit_size, ast, ast->LongLongTy))
607 return ClangASTType (ast, ast->LongLongTy.getAsOpaquePtr());
608 if (QualTypeMatchesBitSize (bit_size, ast, ast->Int128Ty))
609 return ClangASTType (ast, ast->Int128Ty.getAsOpaquePtr());
612 case eEncodingIEEE754:
613 if (QualTypeMatchesBitSize (bit_size, ast, ast->FloatTy))
614 return ClangASTType (ast, ast->FloatTy.getAsOpaquePtr());
615 if (QualTypeMatchesBitSize (bit_size, ast, ast->DoubleTy))
616 return ClangASTType (ast, ast->DoubleTy.getAsOpaquePtr());
617 if (QualTypeMatchesBitSize (bit_size, ast, ast->LongDoubleTy))
618 return ClangASTType (ast, ast->LongDoubleTy.getAsOpaquePtr());
621 case eEncodingVector:
622 // Sanity check that bit_size is a multiple of 8's.
623 if (bit_size && !(bit_size & 0x7u))
624 return ClangASTType (ast, ast->getExtVectorType (ast->UnsignedCharTy, bit_size/8).getAsOpaquePtr());
628 return ClangASTType();
634 ClangASTContext::GetBasicTypeEnumeration (const ConstString &name)
638 typedef UniqueCStringMap<lldb::BasicType> TypeNameToBasicTypeMap;
639 static TypeNameToBasicTypeMap g_type_map;
640 static std::once_flag g_once_flag;
641 std::call_once(g_once_flag, [](){
643 g_type_map.Append(ConstString("void").GetCString(), eBasicTypeVoid);
646 g_type_map.Append(ConstString("char").GetCString(), eBasicTypeChar);
647 g_type_map.Append(ConstString("signed char").GetCString(), eBasicTypeSignedChar);
648 g_type_map.Append(ConstString("unsigned char").GetCString(), eBasicTypeUnsignedChar);
649 g_type_map.Append(ConstString("wchar_t").GetCString(), eBasicTypeWChar);
650 g_type_map.Append(ConstString("signed wchar_t").GetCString(), eBasicTypeSignedWChar);
651 g_type_map.Append(ConstString("unsigned wchar_t").GetCString(), eBasicTypeUnsignedWChar);
653 g_type_map.Append(ConstString("short").GetCString(), eBasicTypeShort);
654 g_type_map.Append(ConstString("short int").GetCString(), eBasicTypeShort);
655 g_type_map.Append(ConstString("unsigned short").GetCString(), eBasicTypeUnsignedShort);
656 g_type_map.Append(ConstString("unsigned short int").GetCString(), eBasicTypeUnsignedShort);
659 g_type_map.Append(ConstString("int").GetCString(), eBasicTypeInt);
660 g_type_map.Append(ConstString("signed int").GetCString(), eBasicTypeInt);
661 g_type_map.Append(ConstString("unsigned int").GetCString(), eBasicTypeUnsignedInt);
662 g_type_map.Append(ConstString("unsigned").GetCString(), eBasicTypeUnsignedInt);
665 g_type_map.Append(ConstString("long").GetCString(), eBasicTypeLong);
666 g_type_map.Append(ConstString("long int").GetCString(), eBasicTypeLong);
667 g_type_map.Append(ConstString("unsigned long").GetCString(), eBasicTypeUnsignedLong);
668 g_type_map.Append(ConstString("unsigned long int").GetCString(), eBasicTypeUnsignedLong);
671 g_type_map.Append(ConstString("long long").GetCString(), eBasicTypeLongLong);
672 g_type_map.Append(ConstString("long long int").GetCString(), eBasicTypeLongLong);
673 g_type_map.Append(ConstString("unsigned long long").GetCString(), eBasicTypeUnsignedLongLong);
674 g_type_map.Append(ConstString("unsigned long long int").GetCString(), eBasicTypeUnsignedLongLong);
677 g_type_map.Append(ConstString("__int128_t").GetCString(), eBasicTypeInt128);
678 g_type_map.Append(ConstString("__uint128_t").GetCString(), eBasicTypeUnsignedInt128);
681 g_type_map.Append(ConstString("bool").GetCString(), eBasicTypeBool);
682 g_type_map.Append(ConstString("float").GetCString(), eBasicTypeFloat);
683 g_type_map.Append(ConstString("double").GetCString(), eBasicTypeDouble);
684 g_type_map.Append(ConstString("long double").GetCString(), eBasicTypeLongDouble);
685 g_type_map.Append(ConstString("id").GetCString(), eBasicTypeObjCID);
686 g_type_map.Append(ConstString("SEL").GetCString(), eBasicTypeObjCSel);
687 g_type_map.Append(ConstString("nullptr").GetCString(), eBasicTypeNullPtr);
691 return g_type_map.Find(name.GetCString(), eBasicTypeInvalid);
693 return eBasicTypeInvalid;
697 ClangASTContext::GetBasicType (ASTContext *ast, const ConstString &name)
701 lldb::BasicType basic_type = ClangASTContext::GetBasicTypeEnumeration (name);
702 return ClangASTContext::GetBasicType (ast, basic_type);
704 return ClangASTType();
708 ClangASTContext::GetPointerByteSize ()
710 if (m_pointer_byte_size == 0)
711 m_pointer_byte_size = GetBasicType(lldb::eBasicTypeVoid).GetPointerType().GetByteSize();
712 return m_pointer_byte_size;
716 ClangASTContext::GetBasicType (lldb::BasicType basic_type)
718 return GetBasicType (getASTContext(), basic_type);
722 ClangASTContext::GetBasicType (ASTContext *ast, lldb::BasicType basic_type)
726 clang_type_t clang_type = nullptr;
730 case eBasicTypeInvalid:
731 case eBasicTypeOther:
734 clang_type = ast->VoidTy.getAsOpaquePtr();
737 clang_type = ast->CharTy.getAsOpaquePtr();
739 case eBasicTypeSignedChar:
740 clang_type = ast->SignedCharTy.getAsOpaquePtr();
742 case eBasicTypeUnsignedChar:
743 clang_type = ast->UnsignedCharTy.getAsOpaquePtr();
745 case eBasicTypeWChar:
746 clang_type = ast->getWCharType().getAsOpaquePtr();
748 case eBasicTypeSignedWChar:
749 clang_type = ast->getSignedWCharType().getAsOpaquePtr();
751 case eBasicTypeUnsignedWChar:
752 clang_type = ast->getUnsignedWCharType().getAsOpaquePtr();
754 case eBasicTypeChar16:
755 clang_type = ast->Char16Ty.getAsOpaquePtr();
757 case eBasicTypeChar32:
758 clang_type = ast->Char32Ty.getAsOpaquePtr();
760 case eBasicTypeShort:
761 clang_type = ast->ShortTy.getAsOpaquePtr();
763 case eBasicTypeUnsignedShort:
764 clang_type = ast->UnsignedShortTy.getAsOpaquePtr();
767 clang_type = ast->IntTy.getAsOpaquePtr();
769 case eBasicTypeUnsignedInt:
770 clang_type = ast->UnsignedIntTy.getAsOpaquePtr();
773 clang_type = ast->LongTy.getAsOpaquePtr();
775 case eBasicTypeUnsignedLong:
776 clang_type = ast->UnsignedLongTy.getAsOpaquePtr();
778 case eBasicTypeLongLong:
779 clang_type = ast->LongLongTy.getAsOpaquePtr();
781 case eBasicTypeUnsignedLongLong:
782 clang_type = ast->UnsignedLongLongTy.getAsOpaquePtr();
784 case eBasicTypeInt128:
785 clang_type = ast->Int128Ty.getAsOpaquePtr();
787 case eBasicTypeUnsignedInt128:
788 clang_type = ast->UnsignedInt128Ty.getAsOpaquePtr();
791 clang_type = ast->BoolTy.getAsOpaquePtr();
794 clang_type = ast->HalfTy.getAsOpaquePtr();
796 case eBasicTypeFloat:
797 clang_type = ast->FloatTy.getAsOpaquePtr();
799 case eBasicTypeDouble:
800 clang_type = ast->DoubleTy.getAsOpaquePtr();
802 case eBasicTypeLongDouble:
803 clang_type = ast->LongDoubleTy.getAsOpaquePtr();
805 case eBasicTypeFloatComplex:
806 clang_type = ast->FloatComplexTy.getAsOpaquePtr();
808 case eBasicTypeDoubleComplex:
809 clang_type = ast->DoubleComplexTy.getAsOpaquePtr();
811 case eBasicTypeLongDoubleComplex:
812 clang_type = ast->LongDoubleComplexTy.getAsOpaquePtr();
814 case eBasicTypeObjCID:
815 clang_type = ast->getObjCIdType().getAsOpaquePtr();
817 case eBasicTypeObjCClass:
818 clang_type = ast->getObjCClassType().getAsOpaquePtr();
820 case eBasicTypeObjCSel:
821 clang_type = ast->getObjCSelType().getAsOpaquePtr();
823 case eBasicTypeNullPtr:
824 clang_type = ast->NullPtrTy.getAsOpaquePtr();
829 return ClangASTType (ast, clang_type);
831 return ClangASTType();
836 ClangASTContext::GetBuiltinTypeForDWARFEncodingAndBitSize (const char *type_name, uint32_t dw_ate, uint32_t bit_size)
838 ASTContext *ast = getASTContext();
840 #define streq(a,b) strcmp(a,b) == 0
841 assert (ast != nullptr);
850 if (QualTypeMatchesBitSize (bit_size, ast, ast->VoidPtrTy))
851 return ClangASTType (ast, ast->VoidPtrTy.getAsOpaquePtr());
855 if (QualTypeMatchesBitSize (bit_size, ast, ast->BoolTy))
856 return ClangASTType (ast, ast->BoolTy.getAsOpaquePtr());
857 if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedCharTy))
858 return ClangASTType (ast, ast->UnsignedCharTy.getAsOpaquePtr());
859 if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedShortTy))
860 return ClangASTType (ast, ast->UnsignedShortTy.getAsOpaquePtr());
861 if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedIntTy))
862 return ClangASTType (ast, ast->UnsignedIntTy.getAsOpaquePtr());
866 // This has been seen to mean DW_AT_complex_integer
869 if (::strstr(type_name, "complex"))
871 ClangASTType complex_int_clang_type = GetBuiltinTypeForDWARFEncodingAndBitSize ("int", DW_ATE_signed, bit_size/2);
872 return ClangASTType (ast, ast->getComplexType (complex_int_clang_type.GetQualType()).getAsOpaquePtr());
877 case DW_ATE_complex_float:
878 if (QualTypeMatchesBitSize (bit_size, ast, ast->FloatComplexTy))
879 return ClangASTType (ast, ast->FloatComplexTy.getAsOpaquePtr());
880 else if (QualTypeMatchesBitSize (bit_size, ast, ast->DoubleComplexTy))
881 return ClangASTType (ast, ast->DoubleComplexTy.getAsOpaquePtr());
882 else if (QualTypeMatchesBitSize (bit_size, ast, ast->LongDoubleComplexTy))
883 return ClangASTType (ast, ast->LongDoubleComplexTy.getAsOpaquePtr());
886 ClangASTType complex_float_clang_type = GetBuiltinTypeForDWARFEncodingAndBitSize ("float", DW_ATE_float, bit_size/2);
887 return ClangASTType (ast, ast->getComplexType (complex_float_clang_type.GetQualType()).getAsOpaquePtr());
892 if (streq(type_name, "float") && QualTypeMatchesBitSize (bit_size, ast, ast->FloatTy))
893 return ClangASTType (ast, ast->FloatTy.getAsOpaquePtr());
894 if (streq(type_name, "double") && QualTypeMatchesBitSize (bit_size, ast, ast->DoubleTy))
895 return ClangASTType (ast, ast->DoubleTy.getAsOpaquePtr());
896 if (streq(type_name, "long double") && QualTypeMatchesBitSize (bit_size, ast, ast->LongDoubleTy))
897 return ClangASTType (ast, ast->LongDoubleTy.getAsOpaquePtr());
898 // Fall back to not requring a name match
899 if (QualTypeMatchesBitSize (bit_size, ast, ast->FloatTy))
900 return ClangASTType (ast, ast->FloatTy.getAsOpaquePtr());
901 if (QualTypeMatchesBitSize (bit_size, ast, ast->DoubleTy))
902 return ClangASTType (ast, ast->DoubleTy.getAsOpaquePtr());
903 if (QualTypeMatchesBitSize (bit_size, ast, ast->LongDoubleTy))
904 return ClangASTType (ast, ast->LongDoubleTy.getAsOpaquePtr());
910 if (streq(type_name, "wchar_t") &&
911 QualTypeMatchesBitSize (bit_size, ast, ast->WCharTy))
912 return ClangASTType (ast, ast->WCharTy.getAsOpaquePtr());
913 if (streq(type_name, "void") &&
914 QualTypeMatchesBitSize (bit_size, ast, ast->VoidTy))
915 return ClangASTType (ast, ast->VoidTy.getAsOpaquePtr());
916 if (strstr(type_name, "long long") &&
917 QualTypeMatchesBitSize (bit_size, ast, ast->LongLongTy))
918 return ClangASTType (ast, ast->LongLongTy.getAsOpaquePtr());
919 if (strstr(type_name, "long") &&
920 QualTypeMatchesBitSize (bit_size, ast, ast->LongTy))
921 return ClangASTType (ast, ast->LongTy.getAsOpaquePtr());
922 if (strstr(type_name, "short") &&
923 QualTypeMatchesBitSize (bit_size, ast, ast->ShortTy))
924 return ClangASTType (ast, ast->ShortTy.getAsOpaquePtr());
925 if (strstr(type_name, "char"))
927 if (QualTypeMatchesBitSize (bit_size, ast, ast->CharTy))
928 return ClangASTType (ast, ast->CharTy.getAsOpaquePtr());
929 if (QualTypeMatchesBitSize (bit_size, ast, ast->SignedCharTy))
930 return ClangASTType (ast, ast->SignedCharTy.getAsOpaquePtr());
932 if (strstr(type_name, "int"))
934 if (QualTypeMatchesBitSize (bit_size, ast, ast->IntTy))
935 return ClangASTType (ast, ast->IntTy.getAsOpaquePtr());
936 if (QualTypeMatchesBitSize (bit_size, ast, ast->Int128Ty))
937 return ClangASTType (ast, ast->Int128Ty.getAsOpaquePtr());
940 // We weren't able to match up a type name, just search by size
941 if (QualTypeMatchesBitSize (bit_size, ast, ast->CharTy))
942 return ClangASTType (ast, ast->CharTy.getAsOpaquePtr());
943 if (QualTypeMatchesBitSize (bit_size, ast, ast->ShortTy))
944 return ClangASTType (ast, ast->ShortTy.getAsOpaquePtr());
945 if (QualTypeMatchesBitSize (bit_size, ast, ast->IntTy))
946 return ClangASTType (ast, ast->IntTy.getAsOpaquePtr());
947 if (QualTypeMatchesBitSize (bit_size, ast, ast->LongTy))
948 return ClangASTType (ast, ast->LongTy.getAsOpaquePtr());
949 if (QualTypeMatchesBitSize (bit_size, ast, ast->LongLongTy))
950 return ClangASTType (ast, ast->LongLongTy.getAsOpaquePtr());
951 if (QualTypeMatchesBitSize (bit_size, ast, ast->Int128Ty))
952 return ClangASTType (ast, ast->Int128Ty.getAsOpaquePtr());
955 case DW_ATE_signed_char:
958 if (streq(type_name, "signed char"))
960 if (QualTypeMatchesBitSize (bit_size, ast, ast->SignedCharTy))
961 return ClangASTType (ast, ast->SignedCharTy.getAsOpaquePtr());
964 if (QualTypeMatchesBitSize (bit_size, ast, ast->CharTy))
965 return ClangASTType (ast, ast->CharTy.getAsOpaquePtr());
966 if (QualTypeMatchesBitSize (bit_size, ast, ast->SignedCharTy))
967 return ClangASTType (ast, ast->SignedCharTy.getAsOpaquePtr());
970 case DW_ATE_unsigned:
973 if (strstr(type_name, "long long"))
975 if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedLongLongTy))
976 return ClangASTType (ast, ast->UnsignedLongLongTy.getAsOpaquePtr());
978 else if (strstr(type_name, "long"))
980 if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedLongTy))
981 return ClangASTType (ast, ast->UnsignedLongTy.getAsOpaquePtr());
983 else if (strstr(type_name, "short"))
985 if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedShortTy))
986 return ClangASTType (ast, ast->UnsignedShortTy.getAsOpaquePtr());
988 else if (strstr(type_name, "char"))
990 if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedCharTy))
991 return ClangASTType (ast, ast->UnsignedCharTy.getAsOpaquePtr());
993 else if (strstr(type_name, "int"))
995 if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedIntTy))
996 return ClangASTType (ast, ast->UnsignedIntTy.getAsOpaquePtr());
997 if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedInt128Ty))
998 return ClangASTType (ast, ast->UnsignedInt128Ty.getAsOpaquePtr());
1001 // We weren't able to match up a type name, just search by size
1002 if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedCharTy))
1003 return ClangASTType (ast, ast->UnsignedCharTy.getAsOpaquePtr());
1004 if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedShortTy))
1005 return ClangASTType (ast, ast->UnsignedShortTy.getAsOpaquePtr());
1006 if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedIntTy))
1007 return ClangASTType (ast, ast->UnsignedIntTy.getAsOpaquePtr());
1008 if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedLongTy))
1009 return ClangASTType (ast, ast->UnsignedLongTy.getAsOpaquePtr());
1010 if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedLongLongTy))
1011 return ClangASTType (ast, ast->UnsignedLongLongTy.getAsOpaquePtr());
1012 if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedInt128Ty))
1013 return ClangASTType (ast, ast->UnsignedInt128Ty.getAsOpaquePtr());
1016 case DW_ATE_unsigned_char:
1017 if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedCharTy))
1018 return ClangASTType (ast, ast->UnsignedCharTy.getAsOpaquePtr());
1019 if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedShortTy))
1020 return ClangASTType (ast, ast->UnsignedShortTy.getAsOpaquePtr());
1023 case DW_ATE_imaginary_float:
1029 if (streq(type_name, "char16_t"))
1031 return ClangASTType (ast, ast->Char16Ty.getAsOpaquePtr());
1033 else if (streq(type_name, "char32_t"))
1035 return ClangASTType (ast, ast->Char32Ty.getAsOpaquePtr());
1041 // This assert should fire for anything that we don't catch above so we know
1042 // to fix any issues we run into.
1045 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);
1049 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);
1051 return ClangASTType ();
1055 ClangASTContext::GetUnknownAnyType(clang::ASTContext *ast)
1058 return ClangASTType (ast, ast->UnknownAnyTy.getAsOpaquePtr());
1059 return ClangASTType();
1063 ClangASTContext::GetCStringType (bool is_const)
1065 ASTContext *ast = getASTContext();
1066 QualType char_type(ast->CharTy);
1069 char_type.addConst();
1071 return ClangASTType (ast, ast->getPointerType(char_type).getAsOpaquePtr());
1074 clang::DeclContext *
1075 ClangASTContext::GetTranslationUnitDecl (clang::ASTContext *ast)
1077 return ast->getTranslationUnitDecl();
1081 ClangASTContext::CopyType (ASTContext *dst_ast,
1084 FileSystemOptions file_system_options;
1085 ASTContext *src_ast = src.GetASTContext();
1086 FileManager file_manager (file_system_options);
1087 ASTImporter importer(*dst_ast, file_manager,
1088 *src_ast, file_manager,
1091 QualType dst (importer.Import(src.GetQualType()));
1093 return ClangASTType (dst_ast, dst.getAsOpaquePtr());
1098 ClangASTContext::CopyDecl (ASTContext *dst_ast,
1099 ASTContext *src_ast,
1100 clang::Decl *source_decl)
1102 FileSystemOptions file_system_options;
1103 FileManager file_manager (file_system_options);
1104 ASTImporter importer(*dst_ast, file_manager,
1105 *src_ast, file_manager,
1108 return importer.Import(source_decl);
1112 ClangASTContext::AreTypesSame (ClangASTType type1,
1114 bool ignore_qualifiers)
1116 ASTContext *ast = type1.GetASTContext();
1117 if (ast != type2.GetASTContext())
1120 if (type1.GetOpaqueQualType() == type2.GetOpaqueQualType())
1123 QualType type1_qual = type1.GetQualType();
1124 QualType type2_qual = type2.GetQualType();
1126 if (ignore_qualifiers)
1128 type1_qual = type1_qual.getUnqualifiedType();
1129 type2_qual = type2_qual.getUnqualifiedType();
1132 return ast->hasSameType (type1_qual, type2_qual);
1136 ClangASTContext::GetTypeForDecl (clang::NamedDecl *decl)
1138 if (clang::ObjCInterfaceDecl *interface_decl = llvm::dyn_cast<clang::ObjCInterfaceDecl>(decl))
1139 return GetTypeForDecl(interface_decl);
1140 if (clang::TagDecl *tag_decl = llvm::dyn_cast<clang::TagDecl>(decl))
1141 return GetTypeForDecl(tag_decl);
1142 return ClangASTType();
1147 ClangASTContext::GetTypeForDecl (TagDecl *decl)
1149 // No need to call the getASTContext() accessor (which can create the AST
1150 // if it isn't created yet, because we can't have created a decl in this
1151 // AST if our AST didn't already exist...
1152 ASTContext *ast = &decl->getASTContext();
1154 return ClangASTType (ast, ast->getTagDeclType(decl).getAsOpaquePtr());
1155 return ClangASTType();
1159 ClangASTContext::GetTypeForDecl (ObjCInterfaceDecl *decl)
1161 // No need to call the getASTContext() accessor (which can create the AST
1162 // if it isn't created yet, because we can't have created a decl in this
1163 // AST if our AST didn't already exist...
1164 ASTContext *ast = &decl->getASTContext();
1166 return ClangASTType (ast, ast->getObjCInterfaceType(decl).getAsOpaquePtr());
1167 return ClangASTType();
1170 #pragma mark Structure, Unions, Classes
1173 ClangASTContext::CreateRecordType (DeclContext *decl_ctx,
1174 AccessType access_type,
1177 LanguageType language,
1178 ClangASTMetadata *metadata)
1180 ASTContext *ast = getASTContext();
1181 assert (ast != nullptr);
1183 if (decl_ctx == nullptr)
1184 decl_ctx = ast->getTranslationUnitDecl();
1187 if (language == eLanguageTypeObjC || language == eLanguageTypeObjC_plus_plus)
1189 bool isForwardDecl = true;
1190 bool isInternal = false;
1191 return CreateObjCClass (name, decl_ctx, isForwardDecl, isInternal, metadata);
1194 // NOTE: Eventually CXXRecordDecl will be merged back into RecordDecl and
1195 // we will need to update this code. I was told to currently always use
1196 // the CXXRecordDecl class since we often don't know from debug information
1197 // if something is struct or a class, so we default to always use the more
1198 // complete definition just in case.
1200 bool is_anonymous = (!name) || (!name[0]);
1202 CXXRecordDecl *decl = CXXRecordDecl::Create (*ast,
1203 (TagDecl::TagKind)kind,
1207 is_anonymous ? nullptr : &ast->Idents.get(name));
1210 decl->setAnonymousStructOrUnion(true);
1215 SetMetadata(ast, decl, *metadata);
1217 if (access_type != eAccessNone)
1218 decl->setAccess (ConvertAccessTypeToAccessSpecifier (access_type));
1221 decl_ctx->addDecl (decl);
1223 return ClangASTType(ast, ast->getTagDeclType(decl).getAsOpaquePtr());
1225 return ClangASTType();
1228 static TemplateParameterList *
1229 CreateTemplateParameterList (ASTContext *ast,
1230 const ClangASTContext::TemplateParameterInfos &template_param_infos,
1231 llvm::SmallVector<NamedDecl *, 8> &template_param_decls)
1233 const bool parameter_pack = false;
1234 const bool is_typename = false;
1235 const unsigned depth = 0;
1236 const size_t num_template_params = template_param_infos.GetSize();
1237 for (size_t i=0; i<num_template_params; ++i)
1239 const char *name = template_param_infos.names[i];
1241 IdentifierInfo *identifier_info = nullptr;
1242 if (name && name[0])
1243 identifier_info = &ast->Idents.get(name);
1244 if (template_param_infos.args[i].getKind() == TemplateArgument::Integral)
1246 template_param_decls.push_back (NonTypeTemplateParmDecl::Create (*ast,
1247 ast->getTranslationUnitDecl(), // Is this the right decl context?, SourceLocation StartLoc,
1253 template_param_infos.args[i].getIntegralType(),
1260 template_param_decls.push_back (TemplateTypeParmDecl::Create (*ast,
1261 ast->getTranslationUnitDecl(), // Is this the right decl context?
1272 TemplateParameterList *template_param_list = TemplateParameterList::Create (*ast,
1275 &template_param_decls.front(),
1276 template_param_decls.size(),
1278 return template_param_list;
1281 clang::FunctionTemplateDecl *
1282 ClangASTContext::CreateFunctionTemplateDecl (clang::DeclContext *decl_ctx,
1283 clang::FunctionDecl *func_decl,
1285 const TemplateParameterInfos &template_param_infos)
1287 // /// \brief Create a function template node.
1288 ASTContext *ast = getASTContext();
1290 llvm::SmallVector<NamedDecl *, 8> template_param_decls;
1292 TemplateParameterList *template_param_list = CreateTemplateParameterList (ast,
1293 template_param_infos,
1294 template_param_decls);
1295 FunctionTemplateDecl *func_tmpl_decl = FunctionTemplateDecl::Create (*ast,
1297 func_decl->getLocation(),
1298 func_decl->getDeclName(),
1299 template_param_list,
1302 for (size_t i=0, template_param_decl_count = template_param_decls.size();
1303 i < template_param_decl_count;
1306 // TODO: verify which decl context we should put template_param_decls into..
1307 template_param_decls[i]->setDeclContext (func_decl);
1310 return func_tmpl_decl;
1314 ClangASTContext::CreateFunctionTemplateSpecializationInfo (FunctionDecl *func_decl,
1315 clang::FunctionTemplateDecl *func_tmpl_decl,
1316 const TemplateParameterInfos &infos)
1318 TemplateArgumentList template_args (TemplateArgumentList::OnStack,
1322 func_decl->setFunctionTemplateSpecialization (func_tmpl_decl,
1329 ClangASTContext::CreateClassTemplateDecl (DeclContext *decl_ctx,
1330 lldb::AccessType access_type,
1331 const char *class_name,
1333 const TemplateParameterInfos &template_param_infos)
1335 ASTContext *ast = getASTContext();
1337 ClassTemplateDecl *class_template_decl = nullptr;
1338 if (decl_ctx == nullptr)
1339 decl_ctx = ast->getTranslationUnitDecl();
1341 IdentifierInfo &identifier_info = ast->Idents.get(class_name);
1342 DeclarationName decl_name (&identifier_info);
1344 clang::DeclContext::lookup_result result = decl_ctx->lookup(decl_name);
1346 for (NamedDecl *decl : result)
1348 class_template_decl = dyn_cast<clang::ClassTemplateDecl>(decl);
1349 if (class_template_decl)
1350 return class_template_decl;
1353 llvm::SmallVector<NamedDecl *, 8> template_param_decls;
1355 TemplateParameterList *template_param_list = CreateTemplateParameterList (ast,
1356 template_param_infos,
1357 template_param_decls);
1359 CXXRecordDecl *template_cxx_decl = CXXRecordDecl::Create (*ast,
1360 (TagDecl::TagKind)kind,
1361 decl_ctx, // What decl context do we use here? TU? The actual decl context?
1366 for (size_t i=0, template_param_decl_count = template_param_decls.size();
1367 i < template_param_decl_count;
1370 template_param_decls[i]->setDeclContext (template_cxx_decl);
1373 // With templated classes, we say that a class is templated with
1374 // specializations, but that the bare class has no functions.
1375 //template_cxx_decl->startDefinition();
1376 //template_cxx_decl->completeDefinition();
1378 class_template_decl = ClassTemplateDecl::Create (*ast,
1379 decl_ctx, // What decl context do we use here? TU? The actual decl context?
1382 template_param_list,
1386 if (class_template_decl)
1388 if (access_type != eAccessNone)
1389 class_template_decl->setAccess (ConvertAccessTypeToAccessSpecifier (access_type));
1391 //if (TagDecl *ctx_tag_decl = dyn_cast<TagDecl>(decl_ctx))
1392 // CompleteTagDeclarationDefinition(GetTypeForDecl(ctx_tag_decl));
1394 decl_ctx->addDecl (class_template_decl);
1396 #ifdef LLDB_CONFIGURATION_DEBUG
1397 VerifyDecl(class_template_decl);
1401 return class_template_decl;
1405 ClassTemplateSpecializationDecl *
1406 ClangASTContext::CreateClassTemplateSpecializationDecl (DeclContext *decl_ctx,
1407 ClassTemplateDecl *class_template_decl,
1409 const TemplateParameterInfos &template_param_infos)
1411 ASTContext *ast = getASTContext();
1412 ClassTemplateSpecializationDecl *class_template_specialization_decl = ClassTemplateSpecializationDecl::Create (*ast,
1413 (TagDecl::TagKind)kind,
1417 class_template_decl,
1418 &template_param_infos.args.front(),
1419 template_param_infos.args.size(),
1422 class_template_specialization_decl->setSpecializationKind(TSK_ExplicitSpecialization);
1424 return class_template_specialization_decl;
1428 ClangASTContext::CreateClassTemplateSpecializationType (ClassTemplateSpecializationDecl *class_template_specialization_decl)
1430 if (class_template_specialization_decl)
1432 ASTContext *ast = getASTContext();
1434 return ClangASTType(ast, ast->getTagDeclType(class_template_specialization_decl).getAsOpaquePtr());
1436 return ClangASTType();
1440 check_op_param (uint32_t op_kind, bool unary, bool binary, uint32_t num_params)
1442 // Special-case call since it can take any number of operands
1443 if(op_kind == OO_Call)
1446 // The parameter count doesn't include "this"
1447 if (num_params == 0)
1449 if (num_params == 1)
1456 ClangASTContext::CheckOverloadedOperatorKindParameterCount (uint32_t op_kind, uint32_t num_params)
1462 // C++ standard allows any number of arguments to new/delete
1466 case OO_Array_Delete:
1470 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) case OO_##Name: return check_op_param (op_kind, Unary, Binary, num_params);
1473 #include "clang/Basic/OperatorKinds.def"
1479 clang::AccessSpecifier
1480 ClangASTContext::UnifyAccessSpecifiers (clang::AccessSpecifier lhs, clang::AccessSpecifier rhs)
1482 clang::AccessSpecifier ret = lhs;
1484 // Make the access equal to the stricter of the field and the nested field's access
1487 case clang::AS_none:
1489 case clang::AS_private:
1491 case clang::AS_protected:
1492 if (rhs == AS_private)
1495 case clang::AS_public:
1504 ClangASTContext::FieldIsBitfield (FieldDecl* field, uint32_t& bitfield_bit_size)
1506 return FieldIsBitfield(getASTContext(), field, bitfield_bit_size);
1510 ClangASTContext::FieldIsBitfield
1514 uint32_t& bitfield_bit_size
1517 if (ast == nullptr || field == nullptr)
1520 if (field->isBitField())
1522 Expr* bit_width_expr = field->getBitWidth();
1525 llvm::APSInt bit_width_apsint;
1526 if (bit_width_expr->isIntegerConstantExpr(bit_width_apsint, *ast))
1528 bitfield_bit_size = bit_width_apsint.getLimitedValue(UINT32_MAX);
1537 ClangASTContext::RecordHasFields (const RecordDecl *record_decl)
1539 if (record_decl == nullptr)
1542 if (!record_decl->field_empty())
1545 // No fields, lets check this is a CXX record and check the base classes
1546 const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
1547 if (cxx_record_decl)
1549 CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
1550 for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
1551 base_class != base_class_end;
1554 const CXXRecordDecl *base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
1555 if (RecordHasFields(base_class_decl))
1562 #pragma mark Objective C Classes
1565 ClangASTContext::CreateObjCClass
1568 DeclContext *decl_ctx,
1571 ClangASTMetadata *metadata
1574 ASTContext *ast = getASTContext();
1575 assert (ast != nullptr);
1576 assert (name && name[0]);
1577 if (decl_ctx == nullptr)
1578 decl_ctx = ast->getTranslationUnitDecl();
1580 ObjCInterfaceDecl *decl = ObjCInterfaceDecl::Create (*ast,
1583 &ast->Idents.get(name),
1589 if (decl && metadata)
1590 SetMetadata(ast, decl, *metadata);
1592 return ClangASTType (ast, ast->getObjCInterfaceType(decl));
1596 BaseSpecifierIsEmpty (const CXXBaseSpecifier *b)
1598 return ClangASTContext::RecordHasFields(b->getType()->getAsCXXRecordDecl()) == false;
1602 ClangASTContext::GetNumBaseClasses (const CXXRecordDecl *cxx_record_decl, bool omit_empty_base_classes)
1604 uint32_t num_bases = 0;
1605 if (cxx_record_decl)
1607 if (omit_empty_base_classes)
1609 CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
1610 for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
1611 base_class != base_class_end;
1614 // Skip empty base classes
1615 if (omit_empty_base_classes)
1617 if (BaseSpecifierIsEmpty (base_class))
1624 num_bases = cxx_record_decl->getNumBases();
1630 #pragma mark Namespace Declarations
1633 ClangASTContext::GetUniqueNamespaceDeclaration (const char *name, DeclContext *decl_ctx)
1635 NamespaceDecl *namespace_decl = nullptr;
1636 ASTContext *ast = getASTContext();
1637 TranslationUnitDecl *translation_unit_decl = ast->getTranslationUnitDecl ();
1638 if (decl_ctx == nullptr)
1639 decl_ctx = translation_unit_decl;
1643 IdentifierInfo &identifier_info = ast->Idents.get(name);
1644 DeclarationName decl_name (&identifier_info);
1645 clang::DeclContext::lookup_result result = decl_ctx->lookup(decl_name);
1646 for (NamedDecl *decl : result)
1648 namespace_decl = dyn_cast<clang::NamespaceDecl>(decl);
1650 return namespace_decl;
1653 namespace_decl = NamespaceDecl::Create(*ast,
1661 decl_ctx->addDecl (namespace_decl);
1665 if (decl_ctx == translation_unit_decl)
1667 namespace_decl = translation_unit_decl->getAnonymousNamespace();
1669 return namespace_decl;
1671 namespace_decl = NamespaceDecl::Create(*ast,
1678 translation_unit_decl->setAnonymousNamespace (namespace_decl);
1679 translation_unit_decl->addDecl (namespace_decl);
1680 assert (namespace_decl == translation_unit_decl->getAnonymousNamespace());
1684 NamespaceDecl *parent_namespace_decl = cast<NamespaceDecl>(decl_ctx);
1685 if (parent_namespace_decl)
1687 namespace_decl = parent_namespace_decl->getAnonymousNamespace();
1689 return namespace_decl;
1690 namespace_decl = NamespaceDecl::Create(*ast,
1697 parent_namespace_decl->setAnonymousNamespace (namespace_decl);
1698 parent_namespace_decl->addDecl (namespace_decl);
1699 assert (namespace_decl == parent_namespace_decl->getAnonymousNamespace());
1710 // If we make it here, we are creating the anonymous namespace decl
1711 // for the first time, so we need to do the using directive magic
1713 UsingDirectiveDecl* using_directive_decl = UsingDirectiveDecl::Create (*ast,
1717 NestedNameSpecifierLoc(),
1721 using_directive_decl->setImplicit();
1722 decl_ctx->addDecl(using_directive_decl);
1725 #ifdef LLDB_CONFIGURATION_DEBUG
1726 VerifyDecl(namespace_decl);
1728 return namespace_decl;
1732 #pragma mark Function Types
1735 ClangASTContext::CreateFunctionDeclaration (DeclContext *decl_ctx,
1737 const ClangASTType &function_clang_type,
1741 FunctionDecl *func_decl = nullptr;
1742 ASTContext *ast = getASTContext();
1743 if (decl_ctx == nullptr)
1744 decl_ctx = ast->getTranslationUnitDecl();
1747 const bool hasWrittenPrototype = true;
1748 const bool isConstexprSpecified = false;
1750 if (name && name[0])
1752 func_decl = FunctionDecl::Create (*ast,
1756 DeclarationName (&ast->Idents.get(name)),
1757 function_clang_type.GetQualType(),
1759 (clang::StorageClass)storage,
1761 hasWrittenPrototype,
1762 isConstexprSpecified);
1766 func_decl = FunctionDecl::Create (*ast,
1771 function_clang_type.GetQualType(),
1773 (clang::StorageClass)storage,
1775 hasWrittenPrototype,
1776 isConstexprSpecified);
1779 decl_ctx->addDecl (func_decl);
1781 #ifdef LLDB_CONFIGURATION_DEBUG
1782 VerifyDecl(func_decl);
1789 ClangASTContext::CreateFunctionType (ASTContext *ast,
1790 const ClangASTType& result_type,
1791 const ClangASTType *args,
1794 unsigned type_quals)
1796 assert (ast != nullptr);
1797 std::vector<QualType> qual_type_args;
1798 for (unsigned i=0; i<num_args; ++i)
1799 qual_type_args.push_back (args[i].GetQualType());
1801 // TODO: Detect calling convention in DWARF?
1802 FunctionProtoType::ExtProtoInfo proto_info;
1803 proto_info.Variadic = is_variadic;
1804 proto_info.ExceptionSpecType = EST_None;
1805 proto_info.TypeQuals = type_quals;
1806 proto_info.RefQualifier = RQ_None;
1807 proto_info.NumExceptions = 0;
1808 proto_info.Exceptions = nullptr;
1810 return ClangASTType (ast, ast->getFunctionType (result_type.GetQualType(),
1812 proto_info).getAsOpaquePtr());
1816 ClangASTContext::CreateParameterDeclaration (const char *name, const ClangASTType ¶m_type, int storage)
1818 ASTContext *ast = getASTContext();
1819 assert (ast != nullptr);
1820 return ParmVarDecl::Create(*ast,
1821 ast->getTranslationUnitDecl(),
1824 name && name[0] ? &ast->Idents.get(name) : nullptr,
1825 param_type.GetQualType(),
1827 (clang::StorageClass)storage,
1832 ClangASTContext::SetFunctionParameters (FunctionDecl *function_decl, ParmVarDecl **params, unsigned num_params)
1835 function_decl->setParams (ArrayRef<ParmVarDecl*>(params, num_params));
1839 #pragma mark Array Types
1842 ClangASTContext::CreateArrayType (const ClangASTType &element_type,
1843 size_t element_count,
1846 if (element_type.IsValid())
1848 ASTContext *ast = getASTContext();
1849 assert (ast != nullptr);
1853 return ClangASTType (ast, ast->getExtVectorType(element_type.GetQualType(), element_count).getAsOpaquePtr());
1858 llvm::APInt ap_element_count (64, element_count);
1859 if (element_count == 0)
1861 return ClangASTType (ast, ast->getIncompleteArrayType (element_type.GetQualType(),
1863 0).getAsOpaquePtr());
1867 return ClangASTType (ast, ast->getConstantArrayType (element_type.GetQualType(),
1870 0).getAsOpaquePtr());
1874 return ClangASTType();
1878 ClangASTContext::GetOrCreateStructForIdentifier (const ConstString &type_name,
1879 const std::initializer_list< std::pair < const char *, ClangASTType > >& type_fields,
1883 if ((type = GetTypeForIdentifier<clang::CXXRecordDecl>(type_name)).IsValid())
1885 type = CreateRecordType(nullptr, lldb::eAccessPublic, type_name.GetCString(), clang::TTK_Struct, lldb::eLanguageTypeC);
1886 type.StartTagDeclarationDefinition();
1887 for (const auto& field : type_fields)
1888 type.AddFieldToRecordType(field.first, field.second, lldb::eAccessPublic, 0);
1891 type.CompleteTagDeclarationDefinition();
1895 #pragma mark Enumeration Types
1898 ClangASTContext::CreateEnumerationType
1901 DeclContext *decl_ctx,
1902 const Declaration &decl,
1903 const ClangASTType &integer_clang_type
1906 // TODO: Do something intelligent with the Declaration object passed in
1907 // like maybe filling in the SourceLocation with it...
1908 ASTContext *ast = getASTContext();
1910 // TODO: ask about these...
1911 // const bool IsScoped = false;
1912 // const bool IsFixed = false;
1914 EnumDecl *enum_decl = EnumDecl::Create (*ast,
1918 name && name[0] ? &ast->Idents.get(name) : nullptr,
1921 false, // IsScopedUsingClassTag
1927 // TODO: check if we should be setting the promotion type too?
1928 enum_decl->setIntegerType(integer_clang_type.GetQualType());
1930 enum_decl->setAccess(AS_public); // TODO respect what's in the debug info
1932 return ClangASTType (ast, ast->getTagDeclType(enum_decl).getAsOpaquePtr());
1934 return ClangASTType();
1937 // Disable this for now since I can't seem to get a nicely formatted float
1938 // out of the APFloat class without just getting the float, double or quad
1939 // and then using a formatted print on it which defeats the purpose. We ideally
1940 // would like to get perfect string values for any kind of float semantics
1941 // so we can support remote targets. The code below also requires a patch to
1944 //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)
1946 // uint32_t count = 0;
1947 // bool is_complex = false;
1948 // if (ClangASTContext::IsFloatingPointType (clang_type, count, is_complex))
1950 // unsigned num_bytes_per_float = byte_size / count;
1951 // unsigned num_bits_per_float = num_bytes_per_float * 8;
1953 // float_str.clear();
1955 // for (i=0; i<count; i++)
1957 // APInt ap_int(num_bits_per_float, bytes + i * num_bytes_per_float, (APInt::ByteOrder)apint_byte_order);
1958 // bool is_ieee = false;
1959 // APFloat ap_float(ap_int, is_ieee);
1961 // unsigned int hex_digits = 0;
1962 // bool upper_case = false;
1964 // if (ap_float.convertToHexString(s, hex_digits, upper_case, APFloat::rmNearestTiesToEven) > 0)
1967 // float_str.append(", ");
1968 // float_str.append(s);
1969 // if (i == 1 && is_complex)
1970 // float_str.append(1, 'i');
1973 // return !float_str.empty();
1979 ClangASTContext::GetIntTypeFromBitSize (clang::ASTContext *ast,
1980 size_t bit_size, bool is_signed)
1986 if (bit_size == ast->getTypeSize(ast->SignedCharTy))
1987 return ClangASTType(ast, ast->SignedCharTy.getAsOpaquePtr());
1989 if (bit_size == ast->getTypeSize(ast->ShortTy))
1990 return ClangASTType(ast, ast->ShortTy.getAsOpaquePtr());
1992 if (bit_size == ast->getTypeSize(ast->IntTy))
1993 return ClangASTType(ast, ast->IntTy.getAsOpaquePtr());
1995 if (bit_size == ast->getTypeSize(ast->LongTy))
1996 return ClangASTType(ast, ast->LongTy.getAsOpaquePtr());
1998 if (bit_size == ast->getTypeSize(ast->LongLongTy))
1999 return ClangASTType(ast, ast->LongLongTy.getAsOpaquePtr());
2001 if (bit_size == ast->getTypeSize(ast->Int128Ty))
2002 return ClangASTType(ast, ast->Int128Ty.getAsOpaquePtr());
2006 if (bit_size == ast->getTypeSize(ast->UnsignedCharTy))
2007 return ClangASTType(ast, ast->UnsignedCharTy.getAsOpaquePtr());
2009 if (bit_size == ast->getTypeSize(ast->UnsignedShortTy))
2010 return ClangASTType(ast, ast->UnsignedShortTy.getAsOpaquePtr());
2012 if (bit_size == ast->getTypeSize(ast->UnsignedIntTy))
2013 return ClangASTType(ast, ast->UnsignedIntTy.getAsOpaquePtr());
2015 if (bit_size == ast->getTypeSize(ast->UnsignedLongTy))
2016 return ClangASTType(ast, ast->UnsignedLongTy.getAsOpaquePtr());
2018 if (bit_size == ast->getTypeSize(ast->UnsignedLongLongTy))
2019 return ClangASTType(ast, ast->UnsignedLongLongTy.getAsOpaquePtr());
2021 if (bit_size == ast->getTypeSize(ast->UnsignedInt128Ty))
2022 return ClangASTType(ast, ast->UnsignedInt128Ty.getAsOpaquePtr());
2025 return ClangASTType();
2029 ClangASTContext::GetPointerSizedIntType (clang::ASTContext *ast, bool is_signed)
2032 return GetIntTypeFromBitSize(ast, ast->getTypeSize(ast->VoidPtrTy), is_signed);
2033 return ClangASTType();
2037 ClangASTContext::GetFloatTypeFromBitSize (clang::ASTContext *ast,
2042 if (bit_size == ast->getTypeSize(ast->FloatTy))
2043 return ClangASTType(ast, ast->FloatTy.getAsOpaquePtr());
2044 else if (bit_size == ast->getTypeSize(ast->DoubleTy))
2045 return ClangASTType(ast, ast->DoubleTy.getAsOpaquePtr());
2046 else if (bit_size == ast->getTypeSize(ast->LongDoubleTy))
2047 return ClangASTType(ast, ast->LongDoubleTy.getAsOpaquePtr());
2048 else if (bit_size == ast->getTypeSize(ast->HalfTy))
2049 return ClangASTType(ast, ast->HalfTy.getAsOpaquePtr());
2051 return ClangASTType();
2055 ClangASTContext::GetCompleteDecl (clang::ASTContext *ast,
2061 ExternalASTSource *ast_source = ast->getExternalSource();
2066 if (clang::TagDecl *tag_decl = llvm::dyn_cast<clang::TagDecl>(decl))
2068 if (tag_decl->isCompleteDefinition())
2071 if (!tag_decl->hasExternalLexicalStorage())
2074 ast_source->CompleteType(tag_decl);
2076 return !tag_decl->getTypeForDecl()->isIncompleteType();
2078 else if (clang::ObjCInterfaceDecl *objc_interface_decl = llvm::dyn_cast<clang::ObjCInterfaceDecl>(decl))
2080 if (objc_interface_decl->getDefinition())
2083 if (!objc_interface_decl->hasExternalLexicalStorage())
2086 ast_source->CompleteType(objc_interface_decl);
2088 return !objc_interface_decl->getTypeForDecl()->isIncompleteType();
2097 ClangASTContext::SetMetadataAsUserID (const void *object,
2100 ClangASTMetadata meta_data;
2101 meta_data.SetUserID (user_id);
2102 SetMetadata (object, meta_data);
2106 ClangASTContext::SetMetadata (clang::ASTContext *ast,
2108 ClangASTMetadata &metadata)
2110 ClangExternalASTSourceCommon *external_source =
2111 ClangExternalASTSourceCommon::Lookup(ast->getExternalSource());
2113 if (external_source)
2114 external_source->SetMetadata(object, metadata);
2118 ClangASTContext::GetMetadata (clang::ASTContext *ast,
2121 ClangExternalASTSourceCommon *external_source =
2122 ClangExternalASTSourceCommon::Lookup(ast->getExternalSource());
2124 if (external_source && external_source->HasMetadata(object))
2125 return external_source->GetMetadata(object);
2130 clang::DeclContext *
2131 ClangASTContext::GetAsDeclContext (clang::CXXMethodDecl *cxx_method_decl)
2133 return llvm::dyn_cast<clang::DeclContext>(cxx_method_decl);
2136 clang::DeclContext *
2137 ClangASTContext::GetAsDeclContext (clang::ObjCMethodDecl *objc_method_decl)
2139 return llvm::dyn_cast<clang::DeclContext>(objc_method_decl);
2144 ClangASTContext::GetClassMethodInfoForDeclContext (clang::DeclContext *decl_ctx,
2145 lldb::LanguageType &language,
2146 bool &is_instance_method,
2147 ConstString &language_object_name)
2149 language_object_name.Clear();
2150 language = eLanguageTypeUnknown;
2151 is_instance_method = false;
2155 if (clang::CXXMethodDecl *method_decl = llvm::dyn_cast<clang::CXXMethodDecl>(decl_ctx))
2157 if (method_decl->isStatic())
2159 is_instance_method = false;
2163 language_object_name.SetCString("this");
2164 is_instance_method = true;
2166 language = eLanguageTypeC_plus_plus;
2169 else if (clang::ObjCMethodDecl *method_decl = llvm::dyn_cast<clang::ObjCMethodDecl>(decl_ctx))
2171 // Both static and instance methods have a "self" object in objective C
2172 language_object_name.SetCString("self");
2173 if (method_decl->isInstanceMethod())
2175 is_instance_method = true;
2179 is_instance_method = false;
2181 language = eLanguageTypeObjC;
2184 else if (clang::FunctionDecl *function_decl = llvm::dyn_cast<clang::FunctionDecl>(decl_ctx))
2186 ClangASTMetadata *metadata = GetMetadata (&decl_ctx->getParentASTContext(), function_decl);
2187 if (metadata && metadata->HasObjectPtr())
2189 language_object_name.SetCString (metadata->GetObjectPtrName());
2190 language = eLanguageTypeObjC;
2191 is_instance_method = true;