1 //===-- ClangASTContext.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 liblldb_ClangASTContext_h_
10 #define liblldb_ClangASTContext_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/TemplateBase.h"
25 #include "llvm/ADT/APSInt.h"
26 #include "llvm/ADT/SmallVector.h"
27 
28 #include "lldb/Core/ClangForward.h"
29 #include "lldb/Expression/ExpressionVariable.h"
30 #include "lldb/Symbol/CompilerType.h"
31 #include "lldb/Symbol/TypeSystem.h"
32 #include "lldb/Target/Target.h"
33 #include "lldb/Utility/ConstString.h"
34 #include "lldb/Utility/Log.h"
35 #include "lldb/Utility/Logging.h"
36 #include "lldb/lldb-enumerations.h"
37 
38 class DWARFASTParserClang;
39 class PDBASTParser;
40 
41 namespace lldb_private {
42 
43 class Declaration;
44 
45 class ClangASTContext : public TypeSystem {
46   // LLVM RTTI support
47   static char ID;
48 
49 public:
50   typedef void (*CompleteTagDeclCallback)(void *baton, clang::TagDecl *);
51   typedef void (*CompleteObjCInterfaceDeclCallback)(void *baton,
52                                                     clang::ObjCInterfaceDecl *);
53 
54   // llvm casting support
isA(const void * ClassID)55   bool isA(const void *ClassID) const override { return ClassID == &ID; }
classof(const TypeSystem * ts)56   static bool classof(const TypeSystem *ts) { return ts->isA(&ID); }
57 
58   /// Constructs a ClangASTContext with an ASTContext using the given triple.
59   ///
60   /// \param triple The llvm::Triple used for the ASTContext. The triple defines
61   ///               certain characteristics of the ASTContext and its types
62   ///               (e.g., whether certain primitive types exist or what their
63   ///               signedness is).
64   explicit ClangASTContext(llvm::Triple triple);
65 
66   /// Constructs a ClangASTContext that uses an existing ASTContext internally.
67   /// Useful when having an existing ASTContext created by Clang.
68   ///
69   /// \param existing_ctxt An existing ASTContext.
70   explicit ClangASTContext(clang::ASTContext &existing_ctxt);
71 
72   ~ClangASTContext() override;
73 
74   void Finalize() override;
75 
76   // PluginInterface functions
77   ConstString GetPluginName() override;
78 
79   uint32_t GetPluginVersion() override;
80 
81   static ConstString GetPluginNameStatic();
82 
83   static lldb::TypeSystemSP CreateInstance(lldb::LanguageType language,
84                                            Module *module, Target *target);
85 
86   static LanguageSet GetSupportedLanguagesForTypes();
87   static LanguageSet GetSupportedLanguagesForExpressions();
88 
89   static void Initialize();
90 
91   static void Terminate();
92 
93   static ClangASTContext *GetASTContext(clang::ASTContext *ast_ctx);
94 
95   static ClangASTContext *GetScratch(Target &target,
96                                      bool create_on_demand = true) {
97     auto type_system_or_err = target.GetScratchTypeSystemForLanguage(
98         lldb::eLanguageTypeC, create_on_demand);
99     if (auto err = type_system_or_err.takeError()) {
100       LLDB_LOG_ERROR(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_TARGET),
101                      std::move(err), "Couldn't get scratch ClangASTContext");
102       return nullptr;
103     }
104     return llvm::dyn_cast<ClangASTContext>(&type_system_or_err.get());
105   }
106 
107   clang::ASTContext &getASTContext();
108 
109   clang::MangleContext *getMangleContext();
110 
111   std::shared_ptr<clang::TargetOptions> &getTargetOptions();
112 
113   clang::TargetInfo *getTargetInfo();
114 
115   void setSema(clang::Sema *s);
getSema()116   clang::Sema *getSema() { return m_sema; }
117 
118   const char *GetTargetTriple();
119 
120   void SetExternalSource(
121       llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> &ast_source_up);
122 
GetCompleteDecl(clang::Decl * decl)123   bool GetCompleteDecl(clang::Decl *decl) {
124     return ClangASTContext::GetCompleteDecl(&getASTContext(), decl);
125   }
126 
127   static void DumpDeclHiearchy(clang::Decl *decl);
128 
129   static void DumpDeclContextHiearchy(clang::DeclContext *decl_ctx);
130 
131   static bool DeclsAreEquivalent(clang::Decl *lhs_decl, clang::Decl *rhs_decl);
132 
133   static bool GetCompleteDecl(clang::ASTContext *ast, clang::Decl *decl);
134 
135   void SetMetadataAsUserID(const clang::Decl *decl, lldb::user_id_t user_id);
136   void SetMetadataAsUserID(const clang::Type *type, lldb::user_id_t user_id);
137 
138   void SetMetadata(const clang::Decl *object, ClangASTMetadata &meta_data);
139 
140   void SetMetadata(const clang::Type *object, ClangASTMetadata &meta_data);
141   ClangASTMetadata *GetMetadata(const clang::Decl *object);
142   ClangASTMetadata *GetMetadata(const clang::Type *object);
143 
144   // Basic Types
145   CompilerType GetBuiltinTypeForEncodingAndBitSize(lldb::Encoding encoding,
146                                                    size_t bit_size) override;
147 
148   CompilerType GetBasicType(lldb::BasicType type);
149 
150   static lldb::BasicType GetBasicTypeEnumeration(ConstString name);
151 
152   CompilerType
153   GetBuiltinTypeForDWARFEncodingAndBitSize(llvm::StringRef type_name,
154                                            uint32_t dw_ate, uint32_t bit_size);
155 
156   CompilerType GetCStringType(bool is_const);
157 
158   static clang::DeclContext *GetDeclContextForType(clang::QualType type);
159 
160   static clang::DeclContext *GetDeclContextForType(const CompilerType &type);
161 
162   uint32_t GetPointerByteSize() override;
163 
GetTranslationUnitDecl()164   clang::TranslationUnitDecl *GetTranslationUnitDecl() {
165     return getASTContext().getTranslationUnitDecl();
166   }
167 
168   static bool AreTypesSame(CompilerType type1, CompilerType type2,
169                            bool ignore_qualifiers = false);
170 
171   /// Creates a CompilerType form the given QualType with the current
172   /// ClangASTContext instance as the CompilerType's typesystem.
173   /// \param qt The QualType for a type that belongs to the ASTContext of this
174   ///           ClangASTContext.
175   /// \return The CompilerType representing the given QualType. If the
176   ///         QualType's type pointer is a nullptr then the function returns an
177   ///         invalid CompilerType.
GetType(clang::QualType qt)178   CompilerType GetType(clang::QualType qt) {
179     if (qt.getTypePtrOrNull() == nullptr)
180       return CompilerType();
181     // Check that the type actually belongs to this ClangASTContext.
182     assert(qt->getAsTagDecl() == nullptr ||
183            &qt->getAsTagDecl()->getASTContext() == &getASTContext());
184     return CompilerType(this, qt.getAsOpaquePtr());
185   }
186 
187   CompilerType GetTypeForDecl(clang::NamedDecl *decl);
188 
189   CompilerType GetTypeForDecl(clang::TagDecl *decl);
190 
191   CompilerType GetTypeForDecl(clang::ObjCInterfaceDecl *objc_decl);
192 
193   template <typename RecordDeclType>
194   CompilerType
195   GetTypeForIdentifier(ConstString type_name,
196                        clang::DeclContext *decl_context = nullptr) {
197     CompilerType compiler_type;
198 
199     if (type_name.GetLength()) {
200       clang::ASTContext &ast = getASTContext();
201       if (!decl_context)
202         decl_context = ast.getTranslationUnitDecl();
203 
204       clang::IdentifierInfo &myIdent = ast.Idents.get(type_name.GetCString());
205       clang::DeclarationName myName =
206           ast.DeclarationNames.getIdentifier(&myIdent);
207 
208       clang::DeclContext::lookup_result result = decl_context->lookup(myName);
209 
210       if (!result.empty()) {
211         clang::NamedDecl *named_decl = result[0];
212         if (const RecordDeclType *record_decl =
213                 llvm::dyn_cast<RecordDeclType>(named_decl))
214           compiler_type.SetCompilerType(
215               this, clang::QualType(record_decl->getTypeForDecl(), 0)
216                         .getAsOpaquePtr());
217       }
218     }
219 
220     return compiler_type;
221   }
222 
223   CompilerType CreateStructForIdentifier(
224       ConstString type_name,
225       const std::initializer_list<std::pair<const char *, CompilerType>>
226           &type_fields,
227       bool packed = false);
228 
229   CompilerType GetOrCreateStructForIdentifier(
230       ConstString type_name,
231       const std::initializer_list<std::pair<const char *, CompilerType>>
232           &type_fields,
233       bool packed = false);
234 
235   static bool IsOperator(llvm::StringRef name,
236                          clang::OverloadedOperatorKind &op_kind);
237 
238   // Structure, Unions, Classes
239 
240   static clang::AccessSpecifier
241   ConvertAccessTypeToAccessSpecifier(lldb::AccessType access);
242 
243   static clang::AccessSpecifier
244   UnifyAccessSpecifiers(clang::AccessSpecifier lhs, clang::AccessSpecifier rhs);
245 
246   static uint32_t GetNumBaseClasses(const clang::CXXRecordDecl *cxx_record_decl,
247                                     bool omit_empty_base_classes);
248 
249   CompilerType CreateRecordType(clang::DeclContext *decl_ctx,
250                                 lldb::AccessType access_type,
251                                 llvm::StringRef name, int kind,
252                                 lldb::LanguageType language,
253                                 ClangASTMetadata *metadata = nullptr,
254                                 bool exports_symbols = false);
255 
256   class TemplateParameterInfos {
257   public:
IsValid()258     bool IsValid() const {
259       if (args.empty())
260         return false;
261       return args.size() == names.size() &&
262         ((bool)pack_name == (bool)packed_args) &&
263         (!packed_args || !packed_args->packed_args);
264     }
265 
266     llvm::SmallVector<const char *, 2> names;
267     llvm::SmallVector<clang::TemplateArgument, 2> args;
268 
269     const char * pack_name = nullptr;
270     std::unique_ptr<TemplateParameterInfos> packed_args;
271   };
272 
273   clang::FunctionTemplateDecl *
274   CreateFunctionTemplateDecl(clang::DeclContext *decl_ctx,
275                              clang::FunctionDecl *func_decl, const char *name,
276                              const TemplateParameterInfos &infos);
277 
278   void CreateFunctionTemplateSpecializationInfo(
279       clang::FunctionDecl *func_decl, clang::FunctionTemplateDecl *Template,
280       const TemplateParameterInfos &infos);
281 
282   clang::ClassTemplateDecl *
283   CreateClassTemplateDecl(clang::DeclContext *decl_ctx,
284                           lldb::AccessType access_type, const char *class_name,
285                           int kind, const TemplateParameterInfos &infos);
286 
287   clang::TemplateTemplateParmDecl *
288   CreateTemplateTemplateParmDecl(const char *template_name);
289 
290   clang::ClassTemplateSpecializationDecl *CreateClassTemplateSpecializationDecl(
291       clang::DeclContext *decl_ctx,
292       clang::ClassTemplateDecl *class_template_decl, int kind,
293       const TemplateParameterInfos &infos);
294 
295   CompilerType
296   CreateClassTemplateSpecializationType(clang::ClassTemplateSpecializationDecl *
297                                             class_template_specialization_decl);
298 
299   static clang::DeclContext *
300   GetAsDeclContext(clang::FunctionDecl *function_decl);
301 
302   static bool CheckOverloadedOperatorKindParameterCount(
303       bool is_method, clang::OverloadedOperatorKind op_kind,
304       uint32_t num_params);
305 
306   bool FieldIsBitfield(clang::FieldDecl *field, uint32_t &bitfield_bit_size);
307 
308   static bool RecordHasFields(const clang::RecordDecl *record_decl);
309 
310   CompilerType CreateObjCClass(llvm::StringRef name,
311                                clang::DeclContext *decl_ctx, bool isForwardDecl,
312                                bool isInternal,
313                                ClangASTMetadata *metadata = nullptr);
314 
315   bool SetTagTypeKind(clang::QualType type, int kind) const;
316 
317   bool SetDefaultAccessForRecordFields(clang::RecordDecl *record_decl,
318                                        int default_accessibility,
319                                        int *assigned_accessibilities,
320                                        size_t num_assigned_accessibilities);
321 
322   // Returns a mask containing bits from the ClangASTContext::eTypeXXX
323   // enumerations
324 
325   // Namespace Declarations
326 
327   clang::NamespaceDecl *
328   GetUniqueNamespaceDeclaration(const char *name, clang::DeclContext *decl_ctx,
329                                 bool is_inline = false);
330 
331   // Function Types
332 
333   clang::FunctionDecl *
334   CreateFunctionDeclaration(clang::DeclContext *decl_ctx, const char *name,
335                             const CompilerType &function_Type, int storage,
336                             bool is_inline);
337 
338   CompilerType CreateFunctionType(const CompilerType &result_type,
339                                   const CompilerType *args, unsigned num_args,
340                                   bool is_variadic, unsigned type_quals,
341                                   clang::CallingConv cc);
342 
CreateFunctionType(const CompilerType & result_type,const CompilerType * args,unsigned num_args,bool is_variadic,unsigned type_quals)343   CompilerType CreateFunctionType(const CompilerType &result_type,
344                                   const CompilerType *args, unsigned num_args,
345                                   bool is_variadic, unsigned type_quals) {
346     return CreateFunctionType(result_type, args, num_args, is_variadic,
347                               type_quals, clang::CC_C);
348   }
349 
350   clang::ParmVarDecl *CreateParameterDeclaration(clang::DeclContext *decl_ctx,
351                                                  const char *name,
352                                                  const CompilerType &param_type,
353                                                  int storage,
354                                                  bool add_decl=false);
355 
356   void SetFunctionParameters(clang::FunctionDecl *function_decl,
357                              clang::ParmVarDecl **params, unsigned num_params);
358 
359   CompilerType CreateBlockPointerType(const CompilerType &function_type);
360 
361   // Array Types
362 
363   CompilerType CreateArrayType(const CompilerType &element_type,
364                                size_t element_count, bool is_vector);
365 
366   // Enumeration Types
367   CompilerType CreateEnumerationType(const char *name,
368                                      clang::DeclContext *decl_ctx,
369                                      const Declaration &decl,
370                                      const CompilerType &integer_qual_type,
371                                      bool is_scoped);
372 
373   // Integer type functions
374 
375   CompilerType GetIntTypeFromBitSize(size_t bit_size, bool is_signed);
376 
377   CompilerType GetPointerSizedIntType(bool is_signed);
378 
379   // Floating point functions
380 
381   static CompilerType GetFloatTypeFromBitSize(clang::ASTContext *ast,
382                                               size_t bit_size);
383 
384   // TypeSystem methods
385   DWARFASTParser *GetDWARFParser() override;
386   PDBASTParser *GetPDBParser() override;
387 
388   // ClangASTContext callbacks for external source lookups.
389   void CompleteTagDecl(clang::TagDecl *);
390 
391   void CompleteObjCInterfaceDecl(clang::ObjCInterfaceDecl *);
392 
393   bool LayoutRecordType(
394       const clang::RecordDecl *record_decl, uint64_t &size, uint64_t &alignment,
395       llvm::DenseMap<const clang::FieldDecl *, uint64_t> &field_offsets,
396       llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits>
397           &base_offsets,
398       llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits>
399           &vbase_offsets);
400 
401   // CompilerDecl override functions
402   ConstString DeclGetName(void *opaque_decl) override;
403 
404   ConstString DeclGetMangledName(void *opaque_decl) override;
405 
406   CompilerDeclContext DeclGetDeclContext(void *opaque_decl) override;
407 
408   CompilerType DeclGetFunctionReturnType(void *opaque_decl) override;
409 
410   size_t DeclGetFunctionNumArguments(void *opaque_decl) override;
411 
412   CompilerType DeclGetFunctionArgumentType(void *opaque_decl,
413                                            size_t arg_idx) override;
414 
415   CompilerType GetTypeForDecl(void *opaque_decl) override;
416 
417   // CompilerDeclContext override functions
418 
419   /// Creates a CompilerDeclContext from the given DeclContext
420   /// with the current ClangASTContext instance as its typesystem.
421   /// The DeclContext has to come from the ASTContext of this
422   /// ClangASTContext.
423   CompilerDeclContext CreateDeclContext(clang::DeclContext *ctx);
424 
425   std::vector<CompilerDecl>
426   DeclContextFindDeclByName(void *opaque_decl_ctx, ConstString name,
427                             const bool ignore_using_decls) override;
428 
429   ConstString DeclContextGetName(void *opaque_decl_ctx) override;
430 
431   ConstString DeclContextGetScopeQualifiedName(void *opaque_decl_ctx) override;
432 
433   bool DeclContextIsClassMethod(void *opaque_decl_ctx,
434                                 lldb::LanguageType *language_ptr,
435                                 bool *is_instance_method_ptr,
436                                 ConstString *language_object_name_ptr) override;
437 
438   bool DeclContextIsContainedInLookup(void *opaque_decl_ctx,
439                                       void *other_opaque_decl_ctx) override;
440 
441   // Clang specific clang::DeclContext functions
442 
443   static clang::DeclContext *
444   DeclContextGetAsDeclContext(const CompilerDeclContext &dc);
445 
446   static clang::ObjCMethodDecl *
447   DeclContextGetAsObjCMethodDecl(const CompilerDeclContext &dc);
448 
449   static clang::CXXMethodDecl *
450   DeclContextGetAsCXXMethodDecl(const CompilerDeclContext &dc);
451 
452   static clang::FunctionDecl *
453   DeclContextGetAsFunctionDecl(const CompilerDeclContext &dc);
454 
455   static clang::NamespaceDecl *
456   DeclContextGetAsNamespaceDecl(const CompilerDeclContext &dc);
457 
458   static ClangASTMetadata *DeclContextGetMetaData(const CompilerDeclContext &dc,
459                                                   const clang::Decl *object);
460 
461   static clang::ASTContext *
462   DeclContextGetClangASTContext(const CompilerDeclContext &dc);
463 
464   // Tests
465 
466   bool IsArrayType(lldb::opaque_compiler_type_t type,
467                    CompilerType *element_type, uint64_t *size,
468                    bool *is_incomplete) override;
469 
470   bool IsVectorType(lldb::opaque_compiler_type_t type,
471                     CompilerType *element_type, uint64_t *size) override;
472 
473   bool IsAggregateType(lldb::opaque_compiler_type_t type) override;
474 
475   bool IsAnonymousType(lldb::opaque_compiler_type_t type) override;
476 
477   bool IsBeingDefined(lldb::opaque_compiler_type_t type) override;
478 
479   bool IsCharType(lldb::opaque_compiler_type_t type) override;
480 
481   bool IsCompleteType(lldb::opaque_compiler_type_t type) override;
482 
483   bool IsConst(lldb::opaque_compiler_type_t type) override;
484 
485   bool IsCStringType(lldb::opaque_compiler_type_t type,
486                      uint32_t &length) override;
487 
488   static bool IsCXXClassType(const CompilerType &type);
489 
490   bool IsDefined(lldb::opaque_compiler_type_t type) override;
491 
492   bool IsFloatingPointType(lldb::opaque_compiler_type_t type, uint32_t &count,
493                            bool &is_complex) override;
494 
495   bool IsFunctionType(lldb::opaque_compiler_type_t type,
496                       bool *is_variadic_ptr) override;
497 
498   uint32_t IsHomogeneousAggregate(lldb::opaque_compiler_type_t type,
499                                   CompilerType *base_type_ptr) override;
500 
501   size_t
502   GetNumberOfFunctionArguments(lldb::opaque_compiler_type_t type) override;
503 
504   CompilerType GetFunctionArgumentAtIndex(lldb::opaque_compiler_type_t type,
505                                           const size_t index) override;
506 
507   bool IsFunctionPointerType(lldb::opaque_compiler_type_t type) override;
508 
509   bool IsBlockPointerType(lldb::opaque_compiler_type_t type,
510                           CompilerType *function_pointer_type_ptr) override;
511 
512   bool IsIntegerType(lldb::opaque_compiler_type_t type,
513                      bool &is_signed) override;
514 
515   bool IsEnumerationType(lldb::opaque_compiler_type_t type,
516                          bool &is_signed) override;
517 
518   static bool IsObjCClassType(const CompilerType &type);
519 
520   static bool IsObjCClassTypeAndHasIVars(const CompilerType &type,
521                                          bool check_superclass);
522 
523   static bool IsObjCObjectOrInterfaceType(const CompilerType &type);
524 
525   static bool IsObjCObjectPointerType(const CompilerType &type,
526                                       CompilerType *target_type = nullptr);
527 
528   bool IsPolymorphicClass(lldb::opaque_compiler_type_t type) override;
529 
530   static bool IsClassType(lldb::opaque_compiler_type_t type);
531 
532   static bool IsEnumType(lldb::opaque_compiler_type_t type);
533 
534   bool IsPossibleDynamicType(lldb::opaque_compiler_type_t type,
535                              CompilerType *target_type, // Can pass nullptr
536                              bool check_cplusplus, bool check_objc) override;
537 
538   bool IsRuntimeGeneratedType(lldb::opaque_compiler_type_t type) override;
539 
540   bool IsPointerType(lldb::opaque_compiler_type_t type,
541                      CompilerType *pointee_type) override;
542 
543   bool IsPointerOrReferenceType(lldb::opaque_compiler_type_t type,
544                                 CompilerType *pointee_type) override;
545 
546   bool IsReferenceType(lldb::opaque_compiler_type_t type,
547                        CompilerType *pointee_type, bool *is_rvalue) override;
548 
549   bool IsScalarType(lldb::opaque_compiler_type_t type) override;
550 
551   bool IsTypedefType(lldb::opaque_compiler_type_t type) override;
552 
553   bool IsVoidType(lldb::opaque_compiler_type_t type) override;
554 
555   bool CanPassInRegisters(const CompilerType &type) override;
556 
557   bool SupportsLanguage(lldb::LanguageType language) override;
558 
559   static llvm::Optional<std::string> GetCXXClassName(const CompilerType &type);
560 
561   // Type Completion
562 
563   bool GetCompleteType(lldb::opaque_compiler_type_t type) override;
564 
565   // Accessors
566 
567   ConstString GetTypeName(lldb::opaque_compiler_type_t type) override;
568 
569   uint32_t GetTypeInfo(lldb::opaque_compiler_type_t type,
570                        CompilerType *pointee_or_element_compiler_type) override;
571 
572   lldb::LanguageType
573   GetMinimumLanguage(lldb::opaque_compiler_type_t type) override;
574 
575   lldb::TypeClass GetTypeClass(lldb::opaque_compiler_type_t type) override;
576 
577   unsigned GetTypeQualifiers(lldb::opaque_compiler_type_t type) override;
578 
579   // Creating related types
580 
581   // Using the current type, create a new typedef to that type using
582   // "typedef_name" as the name and "decl_ctx" as the decl context.
583   static CompilerType
584   CreateTypedefType(const CompilerType &type, const char *typedef_name,
585                     const CompilerDeclContext &compiler_decl_ctx);
586 
587   CompilerType GetArrayElementType(lldb::opaque_compiler_type_t type,
588                                    uint64_t *stride) override;
589 
590   CompilerType GetArrayType(lldb::opaque_compiler_type_t type,
591                             uint64_t size) override;
592 
593   CompilerType GetCanonicalType(lldb::opaque_compiler_type_t type) override;
594 
595   CompilerType
596   GetFullyUnqualifiedType(lldb::opaque_compiler_type_t type) override;
597 
598   // Returns -1 if this isn't a function of if the function doesn't have a
599   // prototype Returns a value >= 0 if there is a prototype.
600   int GetFunctionArgumentCount(lldb::opaque_compiler_type_t type) override;
601 
602   CompilerType GetFunctionArgumentTypeAtIndex(lldb::opaque_compiler_type_t type,
603                                               size_t idx) override;
604 
605   CompilerType
606   GetFunctionReturnType(lldb::opaque_compiler_type_t type) override;
607 
608   size_t GetNumMemberFunctions(lldb::opaque_compiler_type_t type) override;
609 
610   TypeMemberFunctionImpl
611   GetMemberFunctionAtIndex(lldb::opaque_compiler_type_t type,
612                            size_t idx) override;
613 
614   CompilerType GetNonReferenceType(lldb::opaque_compiler_type_t type) override;
615 
616   CompilerType GetPointeeType(lldb::opaque_compiler_type_t type) override;
617 
618   CompilerType GetPointerType(lldb::opaque_compiler_type_t type) override;
619 
620   CompilerType
621   GetLValueReferenceType(lldb::opaque_compiler_type_t type) override;
622 
623   CompilerType
624   GetRValueReferenceType(lldb::opaque_compiler_type_t type) override;
625 
626   CompilerType GetAtomicType(lldb::opaque_compiler_type_t type) override;
627 
628   CompilerType AddConstModifier(lldb::opaque_compiler_type_t type) override;
629 
630   CompilerType AddVolatileModifier(lldb::opaque_compiler_type_t type) override;
631 
632   CompilerType AddRestrictModifier(lldb::opaque_compiler_type_t type) override;
633 
634   CompilerType CreateTypedef(lldb::opaque_compiler_type_t type,
635                              const char *name,
636                              const CompilerDeclContext &decl_ctx) override;
637 
638   // If the current object represents a typedef type, get the underlying type
639   CompilerType GetTypedefedType(lldb::opaque_compiler_type_t type) override;
640 
641   // Create related types using the current type's AST
642   CompilerType GetBasicTypeFromAST(lldb::BasicType basic_type) override;
643 
644   // Exploring the type
645 
646   const llvm::fltSemantics &GetFloatTypeSemantics(size_t byte_size) override;
647 
GetByteSize(lldb::opaque_compiler_type_t type,ExecutionContextScope * exe_scope)648   llvm::Optional<uint64_t> GetByteSize(lldb::opaque_compiler_type_t type,
649                        ExecutionContextScope *exe_scope) {
650     if (llvm::Optional<uint64_t> bit_size = GetBitSize(type, exe_scope))
651       return (*bit_size + 7) / 8;
652     return llvm::None;
653   }
654 
655   llvm::Optional<uint64_t>
656   GetBitSize(lldb::opaque_compiler_type_t type,
657              ExecutionContextScope *exe_scope) override;
658 
659   lldb::Encoding GetEncoding(lldb::opaque_compiler_type_t type,
660                              uint64_t &count) override;
661 
662   lldb::Format GetFormat(lldb::opaque_compiler_type_t type) override;
663 
664   llvm::Optional<size_t>
665   GetTypeBitAlign(lldb::opaque_compiler_type_t type,
666                   ExecutionContextScope *exe_scope) override;
667 
668   uint32_t GetNumChildren(lldb::opaque_compiler_type_t type,
669                           bool omit_empty_base_classes,
670                           const ExecutionContext *exe_ctx) override;
671 
672   CompilerType GetBuiltinTypeByName(ConstString name) override;
673 
674   lldb::BasicType
675   GetBasicTypeEnumeration(lldb::opaque_compiler_type_t type) override;
676 
677   static lldb::BasicType
678   GetBasicTypeEnumeration(lldb::opaque_compiler_type_t type,
679                           ConstString name);
680 
681   void ForEachEnumerator(
682       lldb::opaque_compiler_type_t type,
683       std::function<bool(const CompilerType &integer_type,
684                          ConstString name,
685                          const llvm::APSInt &value)> const &callback) override;
686 
687   uint32_t GetNumFields(lldb::opaque_compiler_type_t type) override;
688 
689   CompilerType GetFieldAtIndex(lldb::opaque_compiler_type_t type, size_t idx,
690                                std::string &name, uint64_t *bit_offset_ptr,
691                                uint32_t *bitfield_bit_size_ptr,
692                                bool *is_bitfield_ptr) override;
693 
694   uint32_t GetNumDirectBaseClasses(lldb::opaque_compiler_type_t type) override;
695 
696   uint32_t GetNumVirtualBaseClasses(lldb::opaque_compiler_type_t type) override;
697 
698   CompilerType GetDirectBaseClassAtIndex(lldb::opaque_compiler_type_t type,
699                                          size_t idx,
700                                          uint32_t *bit_offset_ptr) override;
701 
702   CompilerType GetVirtualBaseClassAtIndex(lldb::opaque_compiler_type_t type,
703                                           size_t idx,
704                                           uint32_t *bit_offset_ptr) override;
705 
706   static uint32_t GetNumPointeeChildren(clang::QualType type);
707 
708   CompilerType GetChildCompilerTypeAtIndex(
709       lldb::opaque_compiler_type_t type, ExecutionContext *exe_ctx, size_t idx,
710       bool transparent_pointers, bool omit_empty_base_classes,
711       bool ignore_array_bounds, std::string &child_name,
712       uint32_t &child_byte_size, int32_t &child_byte_offset,
713       uint32_t &child_bitfield_bit_size, uint32_t &child_bitfield_bit_offset,
714       bool &child_is_base_class, bool &child_is_deref_of_parent,
715       ValueObject *valobj, uint64_t &language_flags) override;
716 
717   // Lookup a child given a name. This function will match base class names and
718   // member member names in "clang_type" only, not descendants.
719   uint32_t GetIndexOfChildWithName(lldb::opaque_compiler_type_t type,
720                                    const char *name,
721                                    bool omit_empty_base_classes) override;
722 
723   // Lookup a child member given a name. This function will match member names
724   // only and will descend into "clang_type" children in search for the first
725   // member in this class, or any base class that matches "name".
726   // TODO: Return all matches for a given name by returning a
727   // vector<vector<uint32_t>>
728   // so we catch all names that match a given child name, not just the first.
729   size_t
730   GetIndexOfChildMemberWithName(lldb::opaque_compiler_type_t type,
731                                 const char *name, bool omit_empty_base_classes,
732                                 std::vector<uint32_t> &child_indexes) override;
733 
734   size_t GetNumTemplateArguments(lldb::opaque_compiler_type_t type) override;
735 
736   lldb::TemplateArgumentKind
737   GetTemplateArgumentKind(lldb::opaque_compiler_type_t type,
738                           size_t idx) override;
739   CompilerType GetTypeTemplateArgument(lldb::opaque_compiler_type_t type,
740                                        size_t idx) override;
741   llvm::Optional<CompilerType::IntegralTemplateArgument>
742   GetIntegralTemplateArgument(lldb::opaque_compiler_type_t type,
743                               size_t idx) override;
744 
745   CompilerType GetTypeForFormatters(void *type) override;
746 
747 #define LLDB_INVALID_DECL_LEVEL UINT32_MAX
748   // LLDB_INVALID_DECL_LEVEL is returned by CountDeclLevels if child_decl_ctx
749   // could not be found in decl_ctx.
750   uint32_t CountDeclLevels(clang::DeclContext *frame_decl_ctx,
751                            clang::DeclContext *child_decl_ctx,
752                            ConstString *child_name = nullptr,
753                            CompilerType *child_type = nullptr);
754 
755   // Modifying RecordType
756   static clang::FieldDecl *AddFieldToRecordType(const CompilerType &type,
757                                                 llvm::StringRef name,
758                                                 const CompilerType &field_type,
759                                                 lldb::AccessType access,
760                                                 uint32_t bitfield_bit_size);
761 
762   static void BuildIndirectFields(const CompilerType &type);
763 
764   static void SetIsPacked(const CompilerType &type);
765 
766   static clang::VarDecl *AddVariableToRecordType(const CompilerType &type,
767                                                  llvm::StringRef name,
768                                                  const CompilerType &var_type,
769                                                  lldb::AccessType access);
770 
771   clang::CXXMethodDecl *AddMethodToCXXRecordType(
772       lldb::opaque_compiler_type_t type, llvm::StringRef name,
773       const char *mangled_name, const CompilerType &method_type,
774       lldb::AccessType access, bool is_virtual, bool is_static, bool is_inline,
775       bool is_explicit, bool is_attr_used, bool is_artificial);
776 
777   void AddMethodOverridesForCXXRecordType(lldb::opaque_compiler_type_t type);
778 
779   // C++ Base Classes
780   std::unique_ptr<clang::CXXBaseSpecifier>
781   CreateBaseClassSpecifier(lldb::opaque_compiler_type_t type,
782                            lldb::AccessType access, bool is_virtual,
783                            bool base_of_class);
784 
785   bool TransferBaseClasses(
786       lldb::opaque_compiler_type_t type,
787       std::vector<std::unique_ptr<clang::CXXBaseSpecifier>> bases);
788 
789   static bool SetObjCSuperClass(const CompilerType &type,
790                                 const CompilerType &superclass_compiler_type);
791 
792   static bool AddObjCClassProperty(const CompilerType &type,
793                                    const char *property_name,
794                                    const CompilerType &property_compiler_type,
795                                    clang::ObjCIvarDecl *ivar_decl,
796                                    const char *property_setter_name,
797                                    const char *property_getter_name,
798                                    uint32_t property_attributes,
799                                    ClangASTMetadata *metadata);
800 
801   static clang::ObjCMethodDecl *AddMethodToObjCObjectType(
802       const CompilerType &type,
803       const char *name, // the full symbol name as seen in the symbol table
804                         // (lldb::opaque_compiler_type_t type, "-[NString
805                         // stringWithCString:]")
806       const CompilerType &method_compiler_type, lldb::AccessType access,
807       bool is_artificial, bool is_variadic, bool is_objc_direct_call);
808 
809   static bool SetHasExternalStorage(lldb::opaque_compiler_type_t type,
810                                     bool has_extern);
811 
812   // Tag Declarations
813   static bool StartTagDeclarationDefinition(const CompilerType &type);
814 
815   static bool CompleteTagDeclarationDefinition(const CompilerType &type);
816 
817   // Modifying Enumeration types
818   clang::EnumConstantDecl *AddEnumerationValueToEnumerationType(
819       const CompilerType &enum_type, const Declaration &decl, const char *name,
820       int64_t enum_value, uint32_t enum_value_bit_size);
821   clang::EnumConstantDecl *AddEnumerationValueToEnumerationType(
822       const CompilerType &enum_type, const Declaration &decl, const char *name,
823       const llvm::APSInt &value);
824 
825   CompilerType GetEnumerationIntegerType(lldb::opaque_compiler_type_t type);
826 
827   // Pointers & References
828 
829   // Call this function using the class type when you want to make a member
830   // pointer type to pointee_type.
831   static CompilerType CreateMemberPointerType(const CompilerType &type,
832                                               const CompilerType &pointee_type);
833 
834   // Dumping types
835 #ifndef NDEBUG
836   /// Convenience LLVM-style dump method for use in the debugger only.
837   /// In contrast to the other \p Dump() methods this directly invokes
838   /// \p clang::QualType::dump().
839   LLVM_DUMP_METHOD void dump(lldb::opaque_compiler_type_t type) const override;
840 #endif
841 
842   void Dump(Stream &s);
843 
844   /// Dump clang AST types from the symbol file.
845   ///
846   /// \param[in] s
847   ///       A stream to send the dumped AST node(s) to
848   /// \param[in] symbol_name
849   ///       The name of the symbol to dump, if it is empty dump all the symbols
850   void DumpFromSymbolFile(Stream &s, llvm::StringRef symbol_name);
851 
852   void DumpValue(lldb::opaque_compiler_type_t type, ExecutionContext *exe_ctx,
853                  Stream *s, lldb::Format format, const DataExtractor &data,
854                  lldb::offset_t data_offset, size_t data_byte_size,
855                  uint32_t bitfield_bit_size, uint32_t bitfield_bit_offset,
856                  bool show_types, bool show_summary, bool verbose,
857                  uint32_t depth) override;
858 
859   bool DumpTypeValue(lldb::opaque_compiler_type_t type, Stream *s,
860                      lldb::Format format, const DataExtractor &data,
861                      lldb::offset_t data_offset, size_t data_byte_size,
862                      uint32_t bitfield_bit_size, uint32_t bitfield_bit_offset,
863                      ExecutionContextScope *exe_scope) override;
864 
865   void DumpSummary(lldb::opaque_compiler_type_t type, ExecutionContext *exe_ctx,
866                    Stream *s, const DataExtractor &data,
867                    lldb::offset_t data_offset, size_t data_byte_size) override;
868 
869   void DumpTypeDescription(
870       lldb::opaque_compiler_type_t type) override; // Dump to stdout
871 
872   void DumpTypeDescription(lldb::opaque_compiler_type_t type,
873                            Stream *s) override;
874 
875   static void DumpTypeName(const CompilerType &type);
876 
877   static clang::EnumDecl *GetAsEnumDecl(const CompilerType &type);
878 
879   static clang::RecordDecl *GetAsRecordDecl(const CompilerType &type);
880 
881   static clang::TagDecl *GetAsTagDecl(const CompilerType &type);
882 
883   static clang::TypedefNameDecl *GetAsTypedefDecl(const CompilerType &type);
884 
885   static clang::CXXRecordDecl *
886   GetAsCXXRecordDecl(lldb::opaque_compiler_type_t type);
887 
888   static clang::ObjCInterfaceDecl *
889   GetAsObjCInterfaceDecl(const CompilerType &type);
890 
891   clang::ClassTemplateDecl *ParseClassTemplateDecl(
892       clang::DeclContext *decl_ctx, lldb::AccessType access_type,
893       const char *parent_name, int tag_decl_kind,
894       const ClangASTContext::TemplateParameterInfos &template_param_infos);
895 
896   clang::BlockDecl *CreateBlockDeclaration(clang::DeclContext *ctx);
897 
898   clang::UsingDirectiveDecl *
899   CreateUsingDirectiveDeclaration(clang::DeclContext *decl_ctx,
900                                   clang::NamespaceDecl *ns_decl);
901 
902   clang::UsingDecl *CreateUsingDeclaration(clang::DeclContext *current_decl_ctx,
903                                            clang::NamedDecl *target);
904 
905   clang::VarDecl *CreateVariableDeclaration(clang::DeclContext *decl_context,
906                                             const char *name,
907                                             clang::QualType type);
908 
909   static lldb::opaque_compiler_type_t
910   GetOpaqueCompilerType(clang::ASTContext *ast, lldb::BasicType basic_type);
911 
GetQualType(lldb::opaque_compiler_type_t type)912   static clang::QualType GetQualType(lldb::opaque_compiler_type_t type) {
913     if (type)
914       return clang::QualType::getFromOpaquePtr(type);
915     return clang::QualType();
916   }
917 
918   static clang::QualType
GetCanonicalQualType(lldb::opaque_compiler_type_t type)919   GetCanonicalQualType(lldb::opaque_compiler_type_t type) {
920     if (type)
921       return clang::QualType::getFromOpaquePtr(type).getCanonicalType();
922     return clang::QualType();
923   }
924 
925   clang::DeclarationName
926   GetDeclarationName(const char *name, const CompilerType &function_clang_type);
927 
928 private:
929   const clang::ClassTemplateSpecializationDecl *
930   GetAsTemplateSpecialization(lldb::opaque_compiler_type_t type);
931 
932   // Classes that inherit from ClangASTContext can see and modify these
933   std::string m_target_triple;
934   std::unique_ptr<clang::ASTContext> m_ast_up;
935   std::unique_ptr<clang::LangOptions> m_language_options_up;
936   std::unique_ptr<clang::FileManager> m_file_manager_up;
937   std::unique_ptr<clang::SourceManager> m_source_manager_up;
938   std::unique_ptr<clang::DiagnosticsEngine> m_diagnostics_engine_up;
939   std::unique_ptr<clang::DiagnosticConsumer> m_diagnostic_consumer_up;
940   std::shared_ptr<clang::TargetOptions> m_target_options_rp;
941   std::unique_ptr<clang::TargetInfo> m_target_info_up;
942   std::unique_ptr<clang::IdentifierTable> m_identifier_table_up;
943   std::unique_ptr<clang::SelectorTable> m_selector_table_up;
944   std::unique_ptr<clang::Builtin::Context> m_builtins_up;
945   std::unique_ptr<DWARFASTParserClang> m_dwarf_ast_parser_up;
946   std::unique_ptr<PDBASTParser> m_pdb_ast_parser_up;
947   std::unique_ptr<clang::MangleContext> m_mangle_ctx_up;
948   uint32_t m_pointer_byte_size = 0;
949   bool m_ast_owned = false;
950 
951   typedef llvm::DenseMap<const clang::Decl *, ClangASTMetadata> DeclMetadataMap;
952   /// Maps Decls to their associated ClangASTMetadata.
953   DeclMetadataMap m_decl_metadata;
954 
955   typedef llvm::DenseMap<const clang::Type *, ClangASTMetadata> TypeMetadataMap;
956   /// Maps Types to their associated ClangASTMetadata.
957   TypeMetadataMap m_type_metadata;
958 
959   /// The sema associated that is currently used to build this ASTContext.
960   /// May be null if we are already done parsing this ASTContext or the
961   /// ASTContext wasn't created by parsing source code.
962   clang::Sema *m_sema = nullptr;
963 
964   // For ClangASTContext only
965   ClangASTContext(const ClangASTContext &);
966   const ClangASTContext &operator=(const ClangASTContext &);
967   /// Creates the internal ASTContext.
968   void CreateASTContext();
969   void SetTargetTriple(llvm::StringRef target_triple);
970 };
971 
972 class ClangASTContextForExpressions : public ClangASTContext {
973 public:
974   ClangASTContextForExpressions(Target &target, llvm::Triple triple);
975 
976   ~ClangASTContextForExpressions() override = default;
977 
978   void Finalize() override;
979 
980   UserExpression *
981   GetUserExpression(llvm::StringRef expr, llvm::StringRef prefix,
982                     lldb::LanguageType language,
983                     Expression::ResultType desired_type,
984                     const EvaluateExpressionOptions &options,
985                     ValueObject *ctx_obj) override;
986 
987   FunctionCaller *GetFunctionCaller(const CompilerType &return_type,
988                                     const Address &function_address,
989                                     const ValueList &arg_value_list,
990                                     const char *name) override;
991 
992   UtilityFunction *GetUtilityFunction(const char *text,
993                                       const char *name) override;
994 
995   PersistentExpressionState *GetPersistentExpressionState() override;
996 private:
997   lldb::TargetWP m_target_wp;
998   std::unique_ptr<PersistentExpressionState>
999       m_persistent_variables; // These are the persistent variables associated
1000                               // with this process for the expression parser
1001   std::unique_ptr<ClangASTSource> m_scratch_ast_source_up;
1002 };
1003 
1004 } // namespace lldb_private
1005 
1006 #endif // liblldb_ClangASTContext_h_
1007