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