1 //===-- TypeSystemClang.h ---------------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #ifndef LLDB_SOURCE_PLUGINS_TYPESYSTEM_CLANG_TYPESYSTEMCLANG_H
10 #define LLDB_SOURCE_PLUGINS_TYPESYSTEM_CLANG_TYPESYSTEMCLANG_H
11 
12 #include <stdint.h>
13 
14 #include <functional>
15 #include <initializer_list>
16 #include <map>
17 #include <memory>
18 #include <set>
19 #include <string>
20 #include <utility>
21 #include <vector>
22 
23 #include "clang/AST/ASTContext.h"
24 #include "clang/AST/ASTFwd.h"
25 #include "clang/AST/TemplateBase.h"
26 #include "clang/Basic/TargetInfo.h"
27 #include "llvm/ADT/APSInt.h"
28 #include "llvm/ADT/SmallVector.h"
29 
30 #include "Plugins/ExpressionParser/Clang/ClangPersistentVariables.h"
31 #include "lldb/Expression/ExpressionVariable.h"
32 #include "lldb/Symbol/CompilerType.h"
33 #include "lldb/Symbol/TypeSystem.h"
34 #include "lldb/Target/Target.h"
35 #include "lldb/Utility/ConstString.h"
36 #include "lldb/Utility/Flags.h"
37 #include "lldb/Utility/Log.h"
38 #include "lldb/Utility/Logging.h"
39 #include "lldb/lldb-enumerations.h"
40 
41 class DWARFASTParserClang;
42 class PDBASTParser;
43 
44 namespace clang {
45 class FileManager;
46 class HeaderSearch;
47 class ModuleMap;
48 } // namespace clang
49 
50 namespace lldb_private {
51 
52 class ClangASTMetadata;
53 class ClangASTSource;
54 class Declaration;
55 
56 /// A Clang module ID.
57 class OptionalClangModuleID {
58   unsigned m_id = 0;
59 
60 public:
61   OptionalClangModuleID() = default;
62   explicit OptionalClangModuleID(unsigned id) : m_id(id) {}
63   bool HasValue() const { return m_id != 0; }
64   unsigned GetValue() const { return m_id; }
65 };
66 
67 /// The implementation of lldb::Type's m_payload field for TypeSystemClang.
68 class TypePayloadClang {
69   /// The Layout is as follows:
70   /// \verbatim
71   /// bit 0..30 ... Owning Module ID.
72   /// bit 31 ...... IsCompleteObjCClass.
73   /// \endverbatim
74   Type::Payload m_payload = 0;
75 
76 public:
77   TypePayloadClang() = default;
78   explicit TypePayloadClang(OptionalClangModuleID owning_module,
79                             bool is_complete_objc_class = false);
80   explicit TypePayloadClang(uint32_t opaque_payload) : m_payload(opaque_payload) {}
81   operator Type::Payload() { return m_payload; }
82 
83   static constexpr unsigned ObjCClassBit = 1 << 31;
84   bool IsCompleteObjCClass() { return Flags(m_payload).Test(ObjCClassBit); }
85   void SetIsCompleteObjCClass(bool is_complete_objc_class) {
86     m_payload = is_complete_objc_class ? Flags(m_payload).Set(ObjCClassBit)
87                                        : Flags(m_payload).Clear(ObjCClassBit);
88   }
89   OptionalClangModuleID GetOwningModule() {
90     return OptionalClangModuleID(Flags(m_payload).Clear(ObjCClassBit));
91   }
92   void SetOwningModule(OptionalClangModuleID id);
93   /// \}
94 };
95 
96 /// A TypeSystem implementation based on Clang.
97 ///
98 /// This class uses a single clang::ASTContext as the backend for storing
99 /// its types and declarations. Every clang::ASTContext should also just have
100 /// a single associated TypeSystemClang instance that manages it.
101 ///
102 /// The clang::ASTContext instance can either be created by TypeSystemClang
103 /// itself or it can adopt an existing clang::ASTContext (for example, when
104 /// it is necessary to provide a TypeSystem interface for an existing
105 /// clang::ASTContext that was created by clang::CompilerInstance).
106 class TypeSystemClang : public TypeSystem {
107   // LLVM RTTI support
108   static char ID;
109 
110 public:
111   typedef void (*CompleteTagDeclCallback)(void *baton, clang::TagDecl *);
112   typedef void (*CompleteObjCInterfaceDeclCallback)(void *baton,
113                                                     clang::ObjCInterfaceDecl *);
114 
115   // llvm casting support
116   bool isA(const void *ClassID) const override { return ClassID == &ID; }
117   static bool classof(const TypeSystem *ts) { return ts->isA(&ID); }
118 
119   /// Constructs a TypeSystemClang with an ASTContext using the given triple.
120   ///
121   /// \param name The name for the TypeSystemClang (for logging purposes)
122   /// \param triple The llvm::Triple used for the ASTContext. The triple defines
123   ///               certain characteristics of the ASTContext and its types
124   ///               (e.g., whether certain primitive types exist or what their
125   ///               signedness is).
126   explicit TypeSystemClang(llvm::StringRef name, llvm::Triple triple);
127 
128   /// Constructs a TypeSystemClang that uses an existing ASTContext internally.
129   /// Useful when having an existing ASTContext created by Clang.
130   ///
131   /// \param name The name for the TypeSystemClang (for logging purposes)
132   /// \param existing_ctxt An existing ASTContext.
133   explicit TypeSystemClang(llvm::StringRef name,
134                            clang::ASTContext &existing_ctxt);
135 
136   ~TypeSystemClang() override;
137 
138   void Finalize() override;
139 
140   // PluginInterface functions
141   ConstString GetPluginName() override;
142 
143   uint32_t GetPluginVersion() override;
144 
145   static ConstString GetPluginNameStatic();
146 
147   static lldb::TypeSystemSP CreateInstance(lldb::LanguageType language,
148                                            Module *module, Target *target);
149 
150   static LanguageSet GetSupportedLanguagesForTypes();
151   static LanguageSet GetSupportedLanguagesForExpressions();
152 
153   static void Initialize();
154 
155   static void Terminate();
156 
157   static TypeSystemClang *GetASTContext(clang::ASTContext *ast_ctx);
158 
159   /// Returns the display name of this TypeSystemClang that indicates what
160   /// purpose it serves in LLDB. Used for example in logs.
161   llvm::StringRef getDisplayName() const { return m_display_name; }
162 
163   /// Returns the clang::ASTContext instance managed by this TypeSystemClang.
164   clang::ASTContext &getASTContext();
165 
166   clang::MangleContext *getMangleContext();
167 
168   std::shared_ptr<clang::TargetOptions> &getTargetOptions();
169 
170   clang::TargetInfo *getTargetInfo();
171 
172   void setSema(clang::Sema *s);
173   clang::Sema *getSema() { return m_sema; }
174 
175   const char *GetTargetTriple();
176 
177   void SetExternalSource(
178       llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> &ast_source_up);
179 
180   bool GetCompleteDecl(clang::Decl *decl) {
181     return TypeSystemClang::GetCompleteDecl(&getASTContext(), decl);
182   }
183 
184   static void DumpDeclHiearchy(clang::Decl *decl);
185 
186   static void DumpDeclContextHiearchy(clang::DeclContext *decl_ctx);
187 
188   static bool DeclsAreEquivalent(clang::Decl *lhs_decl, clang::Decl *rhs_decl);
189 
190   static bool GetCompleteDecl(clang::ASTContext *ast, clang::Decl *decl);
191 
192   void SetMetadataAsUserID(const clang::Decl *decl, lldb::user_id_t user_id);
193   void SetMetadataAsUserID(const clang::Type *type, lldb::user_id_t user_id);
194 
195   void SetMetadata(const clang::Decl *object, ClangASTMetadata &meta_data);
196 
197   void SetMetadata(const clang::Type *object, ClangASTMetadata &meta_data);
198   ClangASTMetadata *GetMetadata(const clang::Decl *object);
199   ClangASTMetadata *GetMetadata(const clang::Type *object);
200 
201   // Basic Types
202   CompilerType GetBuiltinTypeForEncodingAndBitSize(lldb::Encoding encoding,
203                                                    size_t bit_size) override;
204 
205   CompilerType GetBasicType(lldb::BasicType type);
206 
207   static lldb::BasicType GetBasicTypeEnumeration(ConstString name);
208 
209   CompilerType
210   GetBuiltinTypeForDWARFEncodingAndBitSize(llvm::StringRef type_name,
211                                            uint32_t dw_ate, uint32_t bit_size);
212 
213   CompilerType GetCStringType(bool is_const);
214 
215   static clang::DeclContext *GetDeclContextForType(clang::QualType type);
216 
217   static clang::DeclContext *GetDeclContextForType(const CompilerType &type);
218 
219   uint32_t GetPointerByteSize() override;
220 
221   clang::TranslationUnitDecl *GetTranslationUnitDecl() {
222     return getASTContext().getTranslationUnitDecl();
223   }
224 
225   static bool AreTypesSame(CompilerType type1, CompilerType type2,
226                            bool ignore_qualifiers = false);
227 
228   /// Creates a CompilerType form the given QualType with the current
229   /// TypeSystemClang instance as the CompilerType's typesystem.
230   /// \param qt The QualType for a type that belongs to the ASTContext of this
231   ///           TypeSystemClang.
232   /// \return The CompilerType representing the given QualType. If the
233   ///         QualType's type pointer is a nullptr then the function returns an
234   ///         invalid CompilerType.
235   CompilerType GetType(clang::QualType qt) {
236     if (qt.getTypePtrOrNull() == nullptr)
237       return CompilerType();
238     // Check that the type actually belongs to this TypeSystemClang.
239     assert(qt->getAsTagDecl() == nullptr ||
240            &qt->getAsTagDecl()->getASTContext() == &getASTContext());
241     return CompilerType(this, qt.getAsOpaquePtr());
242   }
243 
244   CompilerType GetTypeForDecl(clang::NamedDecl *decl);
245 
246   CompilerType GetTypeForDecl(clang::TagDecl *decl);
247 
248   CompilerType GetTypeForDecl(clang::ObjCInterfaceDecl *objc_decl);
249 
250   template <typename RecordDeclType>
251   CompilerType
252   GetTypeForIdentifier(ConstString type_name,
253                        clang::DeclContext *decl_context = nullptr) {
254     CompilerType compiler_type;
255 
256     if (type_name.GetLength()) {
257       clang::ASTContext &ast = getASTContext();
258       if (!decl_context)
259         decl_context = ast.getTranslationUnitDecl();
260 
261       clang::IdentifierInfo &myIdent = ast.Idents.get(type_name.GetCString());
262       clang::DeclarationName myName =
263           ast.DeclarationNames.getIdentifier(&myIdent);
264 
265       clang::DeclContext::lookup_result result = decl_context->lookup(myName);
266 
267       if (!result.empty()) {
268         clang::NamedDecl *named_decl = result[0];
269         if (const RecordDeclType *record_decl =
270                 llvm::dyn_cast<RecordDeclType>(named_decl))
271           compiler_type.SetCompilerType(
272               this, clang::QualType(record_decl->getTypeForDecl(), 0)
273                         .getAsOpaquePtr());
274       }
275     }
276 
277     return compiler_type;
278   }
279 
280   CompilerType CreateStructForIdentifier(
281       ConstString type_name,
282       const std::initializer_list<std::pair<const char *, CompilerType>>
283           &type_fields,
284       bool packed = false);
285 
286   CompilerType GetOrCreateStructForIdentifier(
287       ConstString type_name,
288       const std::initializer_list<std::pair<const char *, CompilerType>>
289           &type_fields,
290       bool packed = false);
291 
292   static bool IsOperator(llvm::StringRef name,
293                          clang::OverloadedOperatorKind &op_kind);
294 
295   // Structure, Unions, Classes
296 
297   static clang::AccessSpecifier
298   ConvertAccessTypeToAccessSpecifier(lldb::AccessType access);
299 
300   static clang::AccessSpecifier
301   UnifyAccessSpecifiers(clang::AccessSpecifier lhs, clang::AccessSpecifier rhs);
302 
303   static uint32_t GetNumBaseClasses(const clang::CXXRecordDecl *cxx_record_decl,
304                                     bool omit_empty_base_classes);
305 
306   /// Synthesize a clang::Module and return its ID or a default-constructed ID.
307   OptionalClangModuleID GetOrCreateClangModule(llvm::StringRef name,
308                                                OptionalClangModuleID parent,
309                                                bool is_framework = false,
310                                                bool is_explicit = false);
311 
312   CompilerType CreateRecordType(clang::DeclContext *decl_ctx,
313                                 OptionalClangModuleID owning_module,
314                                 lldb::AccessType access_type,
315                                 llvm::StringRef name, int kind,
316                                 lldb::LanguageType language,
317                                 ClangASTMetadata *metadata = nullptr,
318                                 bool exports_symbols = false);
319 
320   class TemplateParameterInfos {
321   public:
322     bool IsValid() const {
323       // Having a pack name but no packed args doesn't make sense, so mark
324       // these template parameters as invalid.
325       if (pack_name && !packed_args)
326         return false;
327       return args.size() == names.size() &&
328         (!packed_args || !packed_args->packed_args);
329     }
330 
331     llvm::SmallVector<const char *, 2> names;
332     llvm::SmallVector<clang::TemplateArgument, 2> args;
333 
334     const char * pack_name = nullptr;
335     std::unique_ptr<TemplateParameterInfos> packed_args;
336   };
337 
338   clang::FunctionTemplateDecl *CreateFunctionTemplateDecl(
339       clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module,
340       clang::FunctionDecl *func_decl, const TemplateParameterInfos &infos);
341 
342   void CreateFunctionTemplateSpecializationInfo(
343       clang::FunctionDecl *func_decl, clang::FunctionTemplateDecl *Template,
344       const TemplateParameterInfos &infos);
345 
346   clang::ClassTemplateDecl *
347   CreateClassTemplateDecl(clang::DeclContext *decl_ctx,
348                           OptionalClangModuleID owning_module,
349                           lldb::AccessType access_type, const char *class_name,
350                           int kind, const TemplateParameterInfos &infos);
351 
352   clang::TemplateTemplateParmDecl *
353   CreateTemplateTemplateParmDecl(const char *template_name);
354 
355   clang::ClassTemplateSpecializationDecl *CreateClassTemplateSpecializationDecl(
356       clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module,
357       clang::ClassTemplateDecl *class_template_decl, int kind,
358       const TemplateParameterInfos &infos);
359 
360   CompilerType
361   CreateClassTemplateSpecializationType(clang::ClassTemplateSpecializationDecl *
362                                             class_template_specialization_decl);
363 
364   static clang::DeclContext *
365   GetAsDeclContext(clang::FunctionDecl *function_decl);
366 
367   static bool CheckOverloadedOperatorKindParameterCount(
368       bool is_method, clang::OverloadedOperatorKind op_kind,
369       uint32_t num_params);
370 
371   bool FieldIsBitfield(clang::FieldDecl *field, uint32_t &bitfield_bit_size);
372 
373   static bool RecordHasFields(const clang::RecordDecl *record_decl);
374 
375   CompilerType CreateObjCClass(llvm::StringRef name,
376                                clang::DeclContext *decl_ctx,
377                                OptionalClangModuleID owning_module,
378                                bool isForwardDecl, bool isInternal,
379                                ClangASTMetadata *metadata = nullptr);
380 
381   bool SetTagTypeKind(clang::QualType type, int kind) const;
382 
383   bool SetDefaultAccessForRecordFields(clang::RecordDecl *record_decl,
384                                        int default_accessibility,
385                                        int *assigned_accessibilities,
386                                        size_t num_assigned_accessibilities);
387 
388   // Returns a mask containing bits from the TypeSystemClang::eTypeXXX
389   // enumerations
390 
391   // Namespace Declarations
392 
393   clang::NamespaceDecl *
394   GetUniqueNamespaceDeclaration(const char *name, clang::DeclContext *decl_ctx,
395                                 OptionalClangModuleID owning_module,
396                                 bool is_inline = false);
397 
398   // Function Types
399 
400   clang::FunctionDecl *CreateFunctionDeclaration(
401       clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module,
402       llvm::StringRef name, const CompilerType &function_Type,
403       clang::StorageClass storage, bool is_inline);
404 
405   CompilerType CreateFunctionType(const CompilerType &result_type,
406                                   const CompilerType *args, unsigned num_args,
407                                   bool is_variadic, unsigned type_quals,
408                                   clang::CallingConv cc);
409 
410   CompilerType CreateFunctionType(const CompilerType &result_type,
411                                   const CompilerType *args, unsigned num_args,
412                                   bool is_variadic, unsigned type_quals) {
413     return CreateFunctionType(result_type, args, num_args, is_variadic,
414                               type_quals, clang::CC_C);
415   }
416 
417   clang::ParmVarDecl *
418   CreateParameterDeclaration(clang::DeclContext *decl_ctx,
419                              OptionalClangModuleID owning_module,
420                              const char *name, const CompilerType &param_type,
421                              int storage, bool add_decl = false);
422 
423   void SetFunctionParameters(clang::FunctionDecl *function_decl,
424                              clang::ParmVarDecl **params, unsigned num_params);
425 
426   CompilerType CreateBlockPointerType(const CompilerType &function_type);
427 
428   // Array Types
429 
430   CompilerType CreateArrayType(const CompilerType &element_type,
431                                size_t element_count, bool is_vector);
432 
433   // Enumeration Types
434   CompilerType CreateEnumerationType(const char *name,
435                                      clang::DeclContext *decl_ctx,
436                                      OptionalClangModuleID owning_module,
437                                      const Declaration &decl,
438                                      const CompilerType &integer_qual_type,
439                                      bool is_scoped);
440 
441   // Integer type functions
442 
443   CompilerType GetIntTypeFromBitSize(size_t bit_size, bool is_signed);
444 
445   CompilerType GetPointerSizedIntType(bool is_signed);
446 
447   // Floating point functions
448 
449   static CompilerType GetFloatTypeFromBitSize(clang::ASTContext *ast,
450                                               size_t bit_size);
451 
452   // TypeSystem methods
453   DWARFASTParser *GetDWARFParser() override;
454 #ifdef LLDB_ENABLE_ALL
455   PDBASTParser *GetPDBParser() override;
456 #endif // LLDB_ENABLE_ALL
457 
458   // TypeSystemClang callbacks for external source lookups.
459   void CompleteTagDecl(clang::TagDecl *);
460 
461   void CompleteObjCInterfaceDecl(clang::ObjCInterfaceDecl *);
462 
463   bool LayoutRecordType(
464       const clang::RecordDecl *record_decl, uint64_t &size, uint64_t &alignment,
465       llvm::DenseMap<const clang::FieldDecl *, uint64_t> &field_offsets,
466       llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits>
467           &base_offsets,
468       llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits>
469           &vbase_offsets);
470 
471   /// Creates a CompilerDecl from the given Decl with the current
472   /// TypeSystemClang instance as its typesystem.
473   /// The Decl has to come from the ASTContext of this
474   /// TypeSystemClang.
475   CompilerDecl GetCompilerDecl(clang::Decl *decl) {
476     assert(&decl->getASTContext() == &getASTContext() &&
477            "CreateCompilerDecl for Decl from wrong ASTContext?");
478     return CompilerDecl(this, decl);
479   }
480 
481   // CompilerDecl override functions
482   ConstString DeclGetName(void *opaque_decl) override;
483 
484   ConstString DeclGetMangledName(void *opaque_decl) override;
485 
486   CompilerDeclContext DeclGetDeclContext(void *opaque_decl) override;
487 
488   CompilerType DeclGetFunctionReturnType(void *opaque_decl) override;
489 
490   size_t DeclGetFunctionNumArguments(void *opaque_decl) override;
491 
492   CompilerType DeclGetFunctionArgumentType(void *opaque_decl,
493                                            size_t arg_idx) override;
494 
495   CompilerType GetTypeForDecl(void *opaque_decl) override;
496 
497   // CompilerDeclContext override functions
498 
499   /// Creates a CompilerDeclContext from the given DeclContext
500   /// with the current TypeSystemClang instance as its typesystem.
501   /// The DeclContext has to come from the ASTContext of this
502   /// TypeSystemClang.
503   CompilerDeclContext CreateDeclContext(clang::DeclContext *ctx);
504 
505   /// Set the owning module for \p decl.
506   static void SetOwningModule(clang::Decl *decl,
507                               OptionalClangModuleID owning_module);
508 
509   std::vector<CompilerDecl>
510   DeclContextFindDeclByName(void *opaque_decl_ctx, ConstString name,
511                             const bool ignore_using_decls) override;
512 
513   ConstString DeclContextGetName(void *opaque_decl_ctx) override;
514 
515   ConstString DeclContextGetScopeQualifiedName(void *opaque_decl_ctx) override;
516 
517   bool DeclContextIsClassMethod(void *opaque_decl_ctx,
518                                 lldb::LanguageType *language_ptr,
519                                 bool *is_instance_method_ptr,
520                                 ConstString *language_object_name_ptr) override;
521 
522   bool DeclContextIsContainedInLookup(void *opaque_decl_ctx,
523                                       void *other_opaque_decl_ctx) override;
524 
525   // Clang specific clang::DeclContext functions
526 
527   static clang::DeclContext *
528   DeclContextGetAsDeclContext(const CompilerDeclContext &dc);
529 
530   static clang::ObjCMethodDecl *
531   DeclContextGetAsObjCMethodDecl(const CompilerDeclContext &dc);
532 
533   static clang::CXXMethodDecl *
534   DeclContextGetAsCXXMethodDecl(const CompilerDeclContext &dc);
535 
536   static clang::FunctionDecl *
537   DeclContextGetAsFunctionDecl(const CompilerDeclContext &dc);
538 
539   static clang::NamespaceDecl *
540   DeclContextGetAsNamespaceDecl(const CompilerDeclContext &dc);
541 
542   static ClangASTMetadata *DeclContextGetMetaData(const CompilerDeclContext &dc,
543                                                   const clang::Decl *object);
544 
545   static clang::ASTContext *
546   DeclContextGetTypeSystemClang(const CompilerDeclContext &dc);
547 
548   // Tests
549 
550 #ifndef NDEBUG
551   bool Verify(lldb::opaque_compiler_type_t type) override;
552 #endif
553 
554   bool IsArrayType(lldb::opaque_compiler_type_t type,
555                    CompilerType *element_type, uint64_t *size,
556                    bool *is_incomplete) override;
557 
558   bool IsVectorType(lldb::opaque_compiler_type_t type,
559                     CompilerType *element_type, uint64_t *size) override;
560 
561   bool IsAggregateType(lldb::opaque_compiler_type_t type) override;
562 
563   bool IsAnonymousType(lldb::opaque_compiler_type_t type) override;
564 
565   bool IsBeingDefined(lldb::opaque_compiler_type_t type) override;
566 
567   bool IsCharType(lldb::opaque_compiler_type_t type) override;
568 
569   bool IsCompleteType(lldb::opaque_compiler_type_t type) override;
570 
571   bool IsConst(lldb::opaque_compiler_type_t type) override;
572 
573   bool IsCStringType(lldb::opaque_compiler_type_t type,
574                      uint32_t &length) override;
575 
576   static bool IsCXXClassType(const CompilerType &type);
577 
578   bool IsDefined(lldb::opaque_compiler_type_t type) override;
579 
580   bool IsFloatingPointType(lldb::opaque_compiler_type_t type, uint32_t &count,
581                            bool &is_complex) override;
582 
583   bool IsFunctionType(lldb::opaque_compiler_type_t type) override;
584 
585   uint32_t IsHomogeneousAggregate(lldb::opaque_compiler_type_t type,
586                                   CompilerType *base_type_ptr) override;
587 
588   size_t
589   GetNumberOfFunctionArguments(lldb::opaque_compiler_type_t type) override;
590 
591   CompilerType GetFunctionArgumentAtIndex(lldb::opaque_compiler_type_t type,
592                                           const size_t index) override;
593 
594   bool IsFunctionPointerType(lldb::opaque_compiler_type_t type) override;
595 
596   bool IsBlockPointerType(lldb::opaque_compiler_type_t type,
597                           CompilerType *function_pointer_type_ptr) override;
598 
599   bool IsIntegerType(lldb::opaque_compiler_type_t type,
600                      bool &is_signed) override;
601 
602   bool IsEnumerationType(lldb::opaque_compiler_type_t type,
603                          bool &is_signed) override;
604 
605   bool IsScopedEnumerationType(lldb::opaque_compiler_type_t type) override;
606 
607   static bool IsObjCClassType(const CompilerType &type);
608 
609   static bool IsObjCClassTypeAndHasIVars(const CompilerType &type,
610                                          bool check_superclass);
611 
612   static bool IsObjCObjectOrInterfaceType(const CompilerType &type);
613 
614   static bool IsObjCObjectPointerType(const CompilerType &type,
615                                       CompilerType *target_type = nullptr);
616 
617   bool IsPolymorphicClass(lldb::opaque_compiler_type_t type) override;
618 
619   static bool IsClassType(lldb::opaque_compiler_type_t type);
620 
621   static bool IsEnumType(lldb::opaque_compiler_type_t type);
622 
623   bool IsPossibleDynamicType(lldb::opaque_compiler_type_t type,
624                              CompilerType *target_type, // Can pass nullptr
625                              bool check_cplusplus, bool check_objc) override;
626 
627   bool IsRuntimeGeneratedType(lldb::opaque_compiler_type_t type) override;
628 
629   bool IsPointerType(lldb::opaque_compiler_type_t type,
630                      CompilerType *pointee_type) override;
631 
632   bool IsPointerOrReferenceType(lldb::opaque_compiler_type_t type,
633                                 CompilerType *pointee_type) override;
634 
635   bool IsReferenceType(lldb::opaque_compiler_type_t type,
636                        CompilerType *pointee_type, bool *is_rvalue) override;
637 
638   bool IsScalarType(lldb::opaque_compiler_type_t type) override;
639 
640   bool IsTypedefType(lldb::opaque_compiler_type_t type) override;
641 
642   bool IsVoidType(lldb::opaque_compiler_type_t type) override;
643 
644   bool CanPassInRegisters(const CompilerType &type) override;
645 
646   bool SupportsLanguage(lldb::LanguageType language) override;
647 
648   static llvm::Optional<std::string> GetCXXClassName(const CompilerType &type);
649 
650   // Type Completion
651 
652   bool GetCompleteType(lldb::opaque_compiler_type_t type) override;
653 
654   // Accessors
655 
656   ConstString GetTypeName(lldb::opaque_compiler_type_t type) override;
657 
658   ConstString GetDisplayTypeName(lldb::opaque_compiler_type_t type) override;
659 
660   uint32_t GetTypeInfo(lldb::opaque_compiler_type_t type,
661                        CompilerType *pointee_or_element_compiler_type) override;
662 
663   lldb::LanguageType
664   GetMinimumLanguage(lldb::opaque_compiler_type_t type) override;
665 
666   lldb::TypeClass GetTypeClass(lldb::opaque_compiler_type_t type) override;
667 
668   unsigned GetTypeQualifiers(lldb::opaque_compiler_type_t type) override;
669 
670   // Creating related types
671 
672   CompilerType GetArrayElementType(lldb::opaque_compiler_type_t type,
673                                    ExecutionContextScope *exe_scope) override;
674 
675   CompilerType GetArrayType(lldb::opaque_compiler_type_t type,
676                             uint64_t size) override;
677 
678   CompilerType GetCanonicalType(lldb::opaque_compiler_type_t type) override;
679 
680   CompilerType
681   GetFullyUnqualifiedType(lldb::opaque_compiler_type_t type) override;
682 
683   CompilerType
684   GetEnumerationIntegerType(lldb::opaque_compiler_type_t type) override;
685 
686   // Returns -1 if this isn't a function of if the function doesn't have a
687   // prototype Returns a value >= 0 if there is a prototype.
688   int GetFunctionArgumentCount(lldb::opaque_compiler_type_t type) override;
689 
690   CompilerType GetFunctionArgumentTypeAtIndex(lldb::opaque_compiler_type_t type,
691                                               size_t idx) override;
692 
693   CompilerType
694   GetFunctionReturnType(lldb::opaque_compiler_type_t type) override;
695 
696   size_t GetNumMemberFunctions(lldb::opaque_compiler_type_t type) override;
697 
698   TypeMemberFunctionImpl
699   GetMemberFunctionAtIndex(lldb::opaque_compiler_type_t type,
700                            size_t idx) override;
701 
702   CompilerType GetNonReferenceType(lldb::opaque_compiler_type_t type) override;
703 
704   CompilerType GetPointeeType(lldb::opaque_compiler_type_t type) override;
705 
706   CompilerType GetPointerType(lldb::opaque_compiler_type_t type) override;
707 
708   CompilerType
709   GetLValueReferenceType(lldb::opaque_compiler_type_t type) override;
710 
711   CompilerType
712   GetRValueReferenceType(lldb::opaque_compiler_type_t type) override;
713 
714   CompilerType GetAtomicType(lldb::opaque_compiler_type_t type) override;
715 
716   CompilerType AddConstModifier(lldb::opaque_compiler_type_t type) override;
717 
718   CompilerType AddVolatileModifier(lldb::opaque_compiler_type_t type) override;
719 
720   CompilerType AddRestrictModifier(lldb::opaque_compiler_type_t type) override;
721 
722   /// Using the current type, create a new typedef to that type using
723   /// "typedef_name" as the name and "decl_ctx" as the decl context.
724   /// \param opaque_payload is an opaque TypePayloadClang.
725   CompilerType CreateTypedef(lldb::opaque_compiler_type_t type,
726                              const char *name,
727                              const CompilerDeclContext &decl_ctx,
728                              uint32_t opaque_payload) override;
729 
730   // If the current object represents a typedef type, get the underlying type
731   CompilerType GetTypedefedType(lldb::opaque_compiler_type_t type) override;
732 
733   // Create related types using the current type's AST
734   CompilerType GetBasicTypeFromAST(lldb::BasicType basic_type) override;
735 
736   // Exploring the type
737 
738   const llvm::fltSemantics &GetFloatTypeSemantics(size_t byte_size) override;
739 
740   llvm::Optional<uint64_t> GetByteSize(lldb::opaque_compiler_type_t type,
741                        ExecutionContextScope *exe_scope) {
742     if (llvm::Optional<uint64_t> bit_size = GetBitSize(type, exe_scope))
743       return (*bit_size + 7) / 8;
744     return llvm::None;
745   }
746 
747   llvm::Optional<uint64_t>
748   GetBitSize(lldb::opaque_compiler_type_t type,
749              ExecutionContextScope *exe_scope) override;
750 
751   lldb::Encoding GetEncoding(lldb::opaque_compiler_type_t type,
752                              uint64_t &count) override;
753 
754   lldb::Format GetFormat(lldb::opaque_compiler_type_t type) override;
755 
756   llvm::Optional<size_t>
757   GetTypeBitAlign(lldb::opaque_compiler_type_t type,
758                   ExecutionContextScope *exe_scope) override;
759 
760   uint32_t GetNumChildren(lldb::opaque_compiler_type_t type,
761                           bool omit_empty_base_classes,
762                           const ExecutionContext *exe_ctx) override;
763 
764   CompilerType GetBuiltinTypeByName(ConstString name) override;
765 
766   lldb::BasicType
767   GetBasicTypeEnumeration(lldb::opaque_compiler_type_t type) override;
768 
769   static lldb::BasicType
770   GetBasicTypeEnumeration(lldb::opaque_compiler_type_t type,
771                           ConstString name);
772 
773   void ForEachEnumerator(
774       lldb::opaque_compiler_type_t type,
775       std::function<bool(const CompilerType &integer_type,
776                          ConstString name,
777                          const llvm::APSInt &value)> const &callback) override;
778 
779   uint32_t GetNumFields(lldb::opaque_compiler_type_t type) override;
780 
781   CompilerType GetFieldAtIndex(lldb::opaque_compiler_type_t type, size_t idx,
782                                std::string &name, uint64_t *bit_offset_ptr,
783                                uint32_t *bitfield_bit_size_ptr,
784                                bool *is_bitfield_ptr) override;
785 
786   uint32_t GetNumDirectBaseClasses(lldb::opaque_compiler_type_t type) override;
787 
788   uint32_t GetNumVirtualBaseClasses(lldb::opaque_compiler_type_t type) override;
789 
790   CompilerType GetDirectBaseClassAtIndex(lldb::opaque_compiler_type_t type,
791                                          size_t idx,
792                                          uint32_t *bit_offset_ptr) override;
793 
794   CompilerType GetVirtualBaseClassAtIndex(lldb::opaque_compiler_type_t type,
795                                           size_t idx,
796                                           uint32_t *bit_offset_ptr) override;
797 
798   static uint32_t GetNumPointeeChildren(clang::QualType type);
799 
800   CompilerType GetChildCompilerTypeAtIndex(
801       lldb::opaque_compiler_type_t type, ExecutionContext *exe_ctx, size_t idx,
802       bool transparent_pointers, bool omit_empty_base_classes,
803       bool ignore_array_bounds, std::string &child_name,
804       uint32_t &child_byte_size, int32_t &child_byte_offset,
805       uint32_t &child_bitfield_bit_size, uint32_t &child_bitfield_bit_offset,
806       bool &child_is_base_class, bool &child_is_deref_of_parent,
807       ValueObject *valobj, uint64_t &language_flags) override;
808 
809   // Lookup a child given a name. This function will match base class names and
810   // member member names in "clang_type" only, not descendants.
811   uint32_t GetIndexOfChildWithName(lldb::opaque_compiler_type_t type,
812                                    const char *name,
813                                    bool omit_empty_base_classes) override;
814 
815   // Lookup a child member given a name. This function will match member names
816   // only and will descend into "clang_type" children in search for the first
817   // member in this class, or any base class that matches "name".
818   // TODO: Return all matches for a given name by returning a
819   // vector<vector<uint32_t>>
820   // so we catch all names that match a given child name, not just the first.
821   size_t
822   GetIndexOfChildMemberWithName(lldb::opaque_compiler_type_t type,
823                                 const char *name, bool omit_empty_base_classes,
824                                 std::vector<uint32_t> &child_indexes) override;
825 
826   size_t GetNumTemplateArguments(lldb::opaque_compiler_type_t type) override;
827 
828   lldb::TemplateArgumentKind
829   GetTemplateArgumentKind(lldb::opaque_compiler_type_t type,
830                           size_t idx) override;
831   CompilerType GetTypeTemplateArgument(lldb::opaque_compiler_type_t type,
832                                        size_t idx) override;
833   llvm::Optional<CompilerType::IntegralTemplateArgument>
834   GetIntegralTemplateArgument(lldb::opaque_compiler_type_t type,
835                               size_t idx) override;
836 
837   CompilerType GetTypeForFormatters(void *type) override;
838 
839 #define LLDB_INVALID_DECL_LEVEL UINT32_MAX
840   // LLDB_INVALID_DECL_LEVEL is returned by CountDeclLevels if child_decl_ctx
841   // could not be found in decl_ctx.
842   uint32_t CountDeclLevels(clang::DeclContext *frame_decl_ctx,
843                            clang::DeclContext *child_decl_ctx,
844                            ConstString *child_name = nullptr,
845                            CompilerType *child_type = nullptr);
846 
847   // Modifying RecordType
848   static clang::FieldDecl *AddFieldToRecordType(const CompilerType &type,
849                                                 llvm::StringRef name,
850                                                 const CompilerType &field_type,
851                                                 lldb::AccessType access,
852                                                 uint32_t bitfield_bit_size);
853 
854   static void BuildIndirectFields(const CompilerType &type);
855 
856   static void SetIsPacked(const CompilerType &type);
857 
858   static clang::VarDecl *AddVariableToRecordType(const CompilerType &type,
859                                                  llvm::StringRef name,
860                                                  const CompilerType &var_type,
861                                                  lldb::AccessType access);
862 
863   /// Initializes a variable with an integer value.
864   /// \param var The variable to initialize. Must not already have an
865   ///            initializer and must have an integer or enum type.
866   /// \param init_value The integer value that the variable should be
867   ///                   initialized to. Has to match the bit width of the
868   ///                   variable type.
869   static void SetIntegerInitializerForVariable(clang::VarDecl *var,
870                                                const llvm::APInt &init_value);
871 
872   /// Initializes a variable with a floating point value.
873   /// \param var The variable to initialize. Must not already have an
874   ///            initializer and must have a floating point type.
875   /// \param init_value The float value that the variable should be
876   ///                   initialized to.
877   static void
878   SetFloatingInitializerForVariable(clang::VarDecl *var,
879                                     const llvm::APFloat &init_value);
880 
881   clang::CXXMethodDecl *AddMethodToCXXRecordType(
882       lldb::opaque_compiler_type_t type, llvm::StringRef name,
883       const char *mangled_name, const CompilerType &method_type,
884       lldb::AccessType access, bool is_virtual, bool is_static, bool is_inline,
885       bool is_explicit, bool is_attr_used, bool is_artificial);
886 
887   void AddMethodOverridesForCXXRecordType(lldb::opaque_compiler_type_t type);
888 
889   // C++ Base Classes
890   std::unique_ptr<clang::CXXBaseSpecifier>
891   CreateBaseClassSpecifier(lldb::opaque_compiler_type_t type,
892                            lldb::AccessType access, bool is_virtual,
893                            bool base_of_class);
894 
895   bool TransferBaseClasses(
896       lldb::opaque_compiler_type_t type,
897       std::vector<std::unique_ptr<clang::CXXBaseSpecifier>> bases);
898 
899   static bool SetObjCSuperClass(const CompilerType &type,
900                                 const CompilerType &superclass_compiler_type);
901 
902   static bool AddObjCClassProperty(const CompilerType &type,
903                                    const char *property_name,
904                                    const CompilerType &property_compiler_type,
905                                    clang::ObjCIvarDecl *ivar_decl,
906                                    const char *property_setter_name,
907                                    const char *property_getter_name,
908                                    uint32_t property_attributes,
909                                    ClangASTMetadata *metadata);
910 
911   static clang::ObjCMethodDecl *AddMethodToObjCObjectType(
912       const CompilerType &type,
913       const char *name, // the full symbol name as seen in the symbol table
914                         // (lldb::opaque_compiler_type_t type, "-[NString
915                         // stringWithCString:]")
916       const CompilerType &method_compiler_type, lldb::AccessType access,
917       bool is_artificial, bool is_variadic, bool is_objc_direct_call);
918 
919   static bool SetHasExternalStorage(lldb::opaque_compiler_type_t type,
920                                     bool has_extern);
921 
922   // Tag Declarations
923   static bool StartTagDeclarationDefinition(const CompilerType &type);
924 
925   static bool CompleteTagDeclarationDefinition(const CompilerType &type);
926 
927   // Modifying Enumeration types
928   clang::EnumConstantDecl *AddEnumerationValueToEnumerationType(
929       const CompilerType &enum_type, const Declaration &decl, const char *name,
930       int64_t enum_value, uint32_t enum_value_bit_size);
931   clang::EnumConstantDecl *AddEnumerationValueToEnumerationType(
932       const CompilerType &enum_type, const Declaration &decl, const char *name,
933       const llvm::APSInt &value);
934 
935   /// Returns the underlying integer type for an enum type. If the given type
936   /// is invalid or not an enum-type, the function returns an invalid
937   /// CompilerType.
938   CompilerType GetEnumerationIntegerType(CompilerType type);
939 
940   // Pointers & References
941 
942   // Call this function using the class type when you want to make a member
943   // pointer type to pointee_type.
944   static CompilerType CreateMemberPointerType(const CompilerType &type,
945                                               const CompilerType &pointee_type);
946 
947   // Dumping types
948 #ifndef NDEBUG
949   /// Convenience LLVM-style dump method for use in the debugger only.
950   /// In contrast to the other \p Dump() methods this directly invokes
951   /// \p clang::QualType::dump().
952   LLVM_DUMP_METHOD void dump(lldb::opaque_compiler_type_t type) const override;
953 #endif
954 
955   void Dump(Stream &s);
956 
957   /// Dump clang AST types from the symbol file.
958   ///
959   /// \param[in] s
960   ///       A stream to send the dumped AST node(s) to
961   /// \param[in] symbol_name
962   ///       The name of the symbol to dump, if it is empty dump all the symbols
963   void DumpFromSymbolFile(Stream &s, llvm::StringRef symbol_name);
964 
965   void DumpValue(lldb::opaque_compiler_type_t type, ExecutionContext *exe_ctx,
966                  Stream *s, lldb::Format format, const DataExtractor &data,
967                  lldb::offset_t data_offset, size_t data_byte_size,
968                  uint32_t bitfield_bit_size, uint32_t bitfield_bit_offset,
969                  bool show_types, bool show_summary, bool verbose,
970                  uint32_t depth) override;
971 
972   bool DumpTypeValue(lldb::opaque_compiler_type_t type, Stream *s,
973                      lldb::Format format, const DataExtractor &data,
974                      lldb::offset_t data_offset, size_t data_byte_size,
975                      uint32_t bitfield_bit_size, uint32_t bitfield_bit_offset,
976                      ExecutionContextScope *exe_scope) override;
977 
978   void DumpSummary(lldb::opaque_compiler_type_t type, ExecutionContext *exe_ctx,
979                    Stream *s, const DataExtractor &data,
980                    lldb::offset_t data_offset, size_t data_byte_size) override;
981 
982   void DumpTypeDescription(
983       lldb::opaque_compiler_type_t type,
984       lldb::DescriptionLevel level = lldb::eDescriptionLevelFull) override;
985 
986   void DumpTypeDescription(
987       lldb::opaque_compiler_type_t type, Stream *s,
988       lldb::DescriptionLevel level = lldb::eDescriptionLevelFull) override;
989 
990   static void DumpTypeName(const CompilerType &type);
991 
992   static clang::EnumDecl *GetAsEnumDecl(const CompilerType &type);
993 
994   static clang::RecordDecl *GetAsRecordDecl(const CompilerType &type);
995 
996   static clang::TagDecl *GetAsTagDecl(const CompilerType &type);
997 
998   static clang::TypedefNameDecl *GetAsTypedefDecl(const CompilerType &type);
999 
1000   static clang::CXXRecordDecl *
1001   GetAsCXXRecordDecl(lldb::opaque_compiler_type_t type);
1002 
1003   static clang::ObjCInterfaceDecl *
1004   GetAsObjCInterfaceDecl(const CompilerType &type);
1005 
1006   clang::ClassTemplateDecl *ParseClassTemplateDecl(
1007       clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module,
1008       lldb::AccessType access_type, const char *parent_name, int tag_decl_kind,
1009       const TypeSystemClang::TemplateParameterInfos &template_param_infos);
1010 
1011   clang::BlockDecl *CreateBlockDeclaration(clang::DeclContext *ctx,
1012                                            OptionalClangModuleID owning_module);
1013 
1014   clang::UsingDirectiveDecl *
1015   CreateUsingDirectiveDeclaration(clang::DeclContext *decl_ctx,
1016                                   OptionalClangModuleID owning_module,
1017                                   clang::NamespaceDecl *ns_decl);
1018 
1019   clang::UsingDecl *CreateUsingDeclaration(clang::DeclContext *current_decl_ctx,
1020                                            OptionalClangModuleID owning_module,
1021                                            clang::NamedDecl *target);
1022 
1023   clang::VarDecl *CreateVariableDeclaration(clang::DeclContext *decl_context,
1024                                             OptionalClangModuleID owning_module,
1025                                             const char *name,
1026                                             clang::QualType type);
1027 
1028   static lldb::opaque_compiler_type_t
1029   GetOpaqueCompilerType(clang::ASTContext *ast, lldb::BasicType basic_type);
1030 
1031   static clang::QualType GetQualType(lldb::opaque_compiler_type_t type) {
1032     if (type)
1033       return clang::QualType::getFromOpaquePtr(type);
1034     return clang::QualType();
1035   }
1036 
1037   static clang::QualType
1038   GetCanonicalQualType(lldb::opaque_compiler_type_t type) {
1039     if (type)
1040       return clang::QualType::getFromOpaquePtr(type).getCanonicalType();
1041     return clang::QualType();
1042   }
1043 
1044   clang::DeclarationName
1045   GetDeclarationName(llvm::StringRef name,
1046                      const CompilerType &function_clang_type);
1047 
1048   clang::LangOptions *GetLangOpts() const {
1049     return m_language_options_up.get();
1050   }
1051   clang::SourceManager *GetSourceMgr() const {
1052     return m_source_manager_up.get();
1053   }
1054 
1055 private:
1056   /// Returns the PrintingPolicy used when generating the internal type names.
1057   /// These type names are mostly used for the formatter selection.
1058   clang::PrintingPolicy GetTypePrintingPolicy();
1059   /// Returns the internal type name for the given NamedDecl using the
1060   /// type printing policy.
1061   std::string GetTypeNameForDecl(const clang::NamedDecl *named_decl);
1062 
1063   const clang::ClassTemplateSpecializationDecl *
1064   GetAsTemplateSpecialization(lldb::opaque_compiler_type_t type);
1065 
1066   // Classes that inherit from TypeSystemClang can see and modify these
1067   std::string m_target_triple;
1068   std::unique_ptr<clang::ASTContext> m_ast_up;
1069   std::unique_ptr<clang::LangOptions> m_language_options_up;
1070   std::unique_ptr<clang::FileManager> m_file_manager_up;
1071   std::unique_ptr<clang::SourceManager> m_source_manager_up;
1072   std::unique_ptr<clang::DiagnosticsEngine> m_diagnostics_engine_up;
1073   std::unique_ptr<clang::DiagnosticConsumer> m_diagnostic_consumer_up;
1074   std::shared_ptr<clang::TargetOptions> m_target_options_rp;
1075   std::unique_ptr<clang::TargetInfo> m_target_info_up;
1076   std::unique_ptr<clang::IdentifierTable> m_identifier_table_up;
1077   std::unique_ptr<clang::SelectorTable> m_selector_table_up;
1078   std::unique_ptr<clang::Builtin::Context> m_builtins_up;
1079   std::unique_ptr<clang::HeaderSearch> m_header_search_up;
1080   std::unique_ptr<clang::ModuleMap> m_module_map_up;
1081   std::unique_ptr<DWARFASTParserClang> m_dwarf_ast_parser_up;
1082 #ifdef LLDB_ENABLE_ALL
1083   std::unique_ptr<PDBASTParser> m_pdb_ast_parser_up;
1084 #endif // LLDB_ENABLE_ALL
1085   std::unique_ptr<clang::MangleContext> m_mangle_ctx_up;
1086   uint32_t m_pointer_byte_size = 0;
1087   bool m_ast_owned = false;
1088   /// A string describing what this TypeSystemClang represents (e.g.,
1089   /// AST for debug information, an expression, some other utility ClangAST).
1090   /// Useful for logging and debugging.
1091   std::string m_display_name;
1092 
1093   typedef llvm::DenseMap<const clang::Decl *, ClangASTMetadata> DeclMetadataMap;
1094   /// Maps Decls to their associated ClangASTMetadata.
1095   DeclMetadataMap m_decl_metadata;
1096 
1097   typedef llvm::DenseMap<const clang::Type *, ClangASTMetadata> TypeMetadataMap;
1098   /// Maps Types to their associated ClangASTMetadata.
1099   TypeMetadataMap m_type_metadata;
1100 
1101   /// The sema associated that is currently used to build this ASTContext.
1102   /// May be null if we are already done parsing this ASTContext or the
1103   /// ASTContext wasn't created by parsing source code.
1104   clang::Sema *m_sema = nullptr;
1105 
1106   // For TypeSystemClang only
1107   TypeSystemClang(const TypeSystemClang &);
1108   const TypeSystemClang &operator=(const TypeSystemClang &);
1109   /// Creates the internal ASTContext.
1110   void CreateASTContext();
1111   void SetTargetTriple(llvm::StringRef target_triple);
1112 };
1113 
1114 /// The TypeSystemClang instance used for the scratch ASTContext in a
1115 /// lldb::Target.
1116 class ScratchTypeSystemClang : public TypeSystemClang {
1117   /// LLVM RTTI support
1118   static char ID;
1119 
1120 public:
1121   ScratchTypeSystemClang(Target &target, llvm::Triple triple);
1122 
1123   ~ScratchTypeSystemClang() override = default;
1124 
1125   void Finalize() override;
1126 
1127   /// The different kinds of isolated ASTs within the scratch TypeSystem.
1128   ///
1129   /// These ASTs are isolated from the main scratch AST and are each
1130   /// dedicated to a special language option/feature that makes the contained
1131   /// AST nodes incompatible with other AST nodes.
1132   enum IsolatedASTKind {
1133     /// The isolated AST for declarations/types from expressions that imported
1134     /// type information from a C++ module. The templates from a C++ module
1135     /// often conflict with the templates we generate from debug information,
1136     /// so we put these types in their own AST.
1137     CppModules
1138   };
1139 
1140   /// Alias for requesting the default scratch TypeSystemClang in GetForTarget.
1141   // This isn't constexpr as gtest/llvm::Optional comparison logic is trying
1142   // to get the address of this for pretty-printing.
1143   static const llvm::NoneType DefaultAST;
1144 
1145   /// Infers the appropriate sub-AST from Clang's LangOptions.
1146   static llvm::Optional<IsolatedASTKind>
1147   InferIsolatedASTKindFromLangOpts(const clang::LangOptions &l) {
1148     // If modules are activated we want the dedicated C++ module AST.
1149     // See IsolatedASTKind::CppModules for more info.
1150     if (l.Modules)
1151       return IsolatedASTKind::CppModules;
1152     return DefaultAST;
1153   }
1154 
1155   /// Returns the scratch TypeSystemClang for the given target.
1156   /// \param target The Target which scratch TypeSystemClang should be returned.
1157   /// \param ast_kind Allows requesting a specific sub-AST instead of the
1158   ///                 default scratch AST. See also `IsolatedASTKind`.
1159   /// \param create_on_demand If the scratch TypeSystemClang instance can be
1160   /// created by this call if it doesn't exist yet. If it doesn't exist yet and
1161   /// this parameter is false, this function returns a nullptr.
1162   /// \return The scratch type system of the target or a nullptr in case an
1163   ///         error occurred.
1164   static TypeSystemClang *
1165   GetForTarget(Target &target,
1166                llvm::Optional<IsolatedASTKind> ast_kind = DefaultAST,
1167                bool create_on_demand = true);
1168 
1169   /// Returns the scratch TypeSystemClang for the given target. The returned
1170   /// TypeSystemClang will be the scratch AST or a sub-AST, depending on which
1171   /// fits best to the passed LangOptions.
1172   /// \param target The Target which scratch TypeSystemClang should be returned.
1173   /// \param lang_opts The LangOptions of a clang ASTContext that the caller
1174   ///                  wants to export type information from. This is used to
1175   ///                  find the best matching sub-AST that will be returned.
1176   static TypeSystemClang *GetForTarget(Target &target,
1177                                        const clang::LangOptions &lang_opts) {
1178     return GetForTarget(target, InferIsolatedASTKindFromLangOpts(lang_opts));
1179   }
1180 
1181   UserExpression *
1182   GetUserExpression(llvm::StringRef expr, llvm::StringRef prefix,
1183                     lldb::LanguageType language,
1184                     Expression::ResultType desired_type,
1185                     const EvaluateExpressionOptions &options,
1186                     ValueObject *ctx_obj) override;
1187 
1188   FunctionCaller *GetFunctionCaller(const CompilerType &return_type,
1189                                     const Address &function_address,
1190                                     const ValueList &arg_value_list,
1191                                     const char *name) override;
1192 
1193   std::unique_ptr<UtilityFunction>
1194   CreateUtilityFunction(std::string text, std::string name) override;
1195 
1196   PersistentExpressionState *GetPersistentExpressionState() override;
1197 
1198   /// Unregisters the given ASTContext as a source from the scratch AST (and
1199   /// all sub-ASTs).
1200   /// \see ClangASTImporter::ForgetSource
1201   void ForgetSource(clang::ASTContext *src_ctx, ClangASTImporter &importer);
1202 
1203   // llvm casting support
1204   bool isA(const void *ClassID) const override {
1205     return ClassID == &ID || TypeSystemClang::isA(ClassID);
1206   }
1207   static bool classof(const TypeSystem *ts) { return ts->isA(&ID); }
1208 
1209 private:
1210   std::unique_ptr<ClangASTSource> CreateASTSource();
1211   /// Returns the requested sub-AST.
1212   /// Will lazily create the sub-AST if it hasn't been created before.
1213   TypeSystemClang &GetIsolatedAST(IsolatedASTKind feature);
1214 
1215   /// The target triple.
1216   /// This was potentially adjusted and might not be identical to the triple
1217   /// of `m_target_wp`.
1218   llvm::Triple m_triple;
1219   lldb::TargetWP m_target_wp;
1220   /// The persistent variables associated with this process for the expression
1221   /// parser.
1222   std::unique_ptr<ClangPersistentVariables> m_persistent_variables;
1223   /// The ExternalASTSource that performs lookups and completes minimally
1224   /// imported types.
1225   std::unique_ptr<ClangASTSource> m_scratch_ast_source_up;
1226 
1227   // FIXME: GCC 5.x doesn't support enum as map keys.
1228   typedef int IsolatedASTKey;
1229 
1230   /// Map from IsolatedASTKind to their actual TypeSystemClang instance.
1231   /// This map is lazily filled with sub-ASTs and should be accessed via
1232   /// `GetSubAST` (which lazily fills this map).
1233   std::unordered_map<IsolatedASTKey, std::unique_ptr<TypeSystemClang>>
1234       m_isolated_asts;
1235 };
1236 
1237 } // namespace lldb_private
1238 
1239 #endif // LLDB_SOURCE_PLUGINS_TYPESYSTEM_CLANG_TYPESYSTEMCLANG_H
1240