xref: /freebsd/contrib/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionDeclMap.h (revision c66ec88fed842fbaad62c30d510644ceb7bd2d71)
1 //===-- ClangExpressionDeclMap.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_EXPRESSIONPARSER_CLANG_CLANGEXPRESSIONDECLMAP_H
10 #define LLDB_SOURCE_PLUGINS_EXPRESSIONPARSER_CLANG_CLANGEXPRESSIONDECLMAP_H
11 
12 #include <signal.h>
13 #include <stdint.h>
14 
15 #include <vector>
16 
17 #include "ClangASTSource.h"
18 #include "ClangExpressionVariable.h"
19 
20 #include "lldb/Core/Value.h"
21 #include "lldb/Expression/Materializer.h"
22 #include "lldb/Symbol/SymbolContext.h"
23 #include "lldb/Symbol/TaggedASTType.h"
24 #include "lldb/Target/ExecutionContext.h"
25 #include "lldb/lldb-public.h"
26 #include "clang/AST/Decl.h"
27 #include "llvm/ADT/DenseMap.h"
28 
29 namespace lldb_private {
30 
31 class ClangPersistentVariables;
32 
33 /// \class ClangExpressionDeclMap ClangExpressionDeclMap.h
34 /// "lldb/Expression/ClangExpressionDeclMap.h" Manages named entities that are
35 /// defined in LLDB's debug information.
36 ///
37 /// The Clang parser uses the ClangASTSource as an interface to request named
38 /// entities from outside an expression.  The ClangASTSource reports back,
39 /// listing all possible objects corresponding to a particular name.  But it
40 /// in turn relies on ClangExpressionDeclMap, which performs several important
41 /// functions.
42 ///
43 /// First, it records what variables and functions were looked up and what
44 /// Decls were returned for them.
45 ///
46 /// Second, it constructs a struct on behalf of IRForTarget, recording which
47 /// variables should be placed where and relaying this information back so
48 /// that IRForTarget can generate context-independent code.
49 ///
50 /// Third, it "materializes" this struct on behalf of the expression command,
51 /// finding the current values of each variable and placing them into the
52 /// struct so that it can be passed to the JITted version of the IR.
53 ///
54 /// Fourth and finally, it "dematerializes" the struct after the JITted code
55 /// has has executed, placing the new values back where it found the old ones.
56 class ClangExpressionDeclMap : public ClangASTSource {
57 public:
58   /// Constructor
59   ///
60   /// Initializes class variables.
61   ///
62   /// \param[in] keep_result_in_memory
63   ///     If true, inhibits the normal deallocation of the memory for
64   ///     the result persistent variable, and instead marks the variable
65   ///     as persisting.
66   ///
67   /// \param[in] result_delegate
68   ///     If non-NULL, use this delegate to report result values.  This
69   ///     allows the client ClangUserExpression to report a result.
70   ///
71   /// \param[in] target
72   ///     The target to use when parsing.
73   ///
74   /// \param[in] importer
75   ///     The ClangASTImporter to use when parsing.
76   ///
77   /// \param[in] ctx_obj
78   ///     If not empty, then expression is evaluated in context of this object.
79   ///     See the comment to `UserExpression::Evaluate` for details.
80   ClangExpressionDeclMap(
81       bool keep_result_in_memory,
82       Materializer::PersistentVariableDelegate *result_delegate,
83       const lldb::TargetSP &target,
84       const std::shared_ptr<ClangASTImporter> &importer, ValueObject *ctx_obj);
85 
86   /// Destructor
87   ~ClangExpressionDeclMap() override;
88 
89   /// Enable the state needed for parsing and IR transformation.
90   ///
91   /// \param[in] exe_ctx
92   ///     The execution context to use when finding types for variables.
93   ///     Also used to find a "scratch" AST context to store result types.
94   ///
95   /// \param[in] materializer
96   ///     If non-NULL, the materializer to populate with information about
97   ///     the variables to use
98   ///
99   /// \return
100   ///     True if parsing is possible; false if it is unsafe to continue.
101   bool WillParse(ExecutionContext &exe_ctx, Materializer *materializer);
102 
103   void InstallCodeGenerator(clang::ASTConsumer *code_gen);
104 
105   /// Disable the state needed for parsing and IR transformation.
106   void DidParse();
107 
108   /// [Used by IRForTarget] Add a variable to the list of persistent
109   ///     variables for the process.
110   ///
111   /// \param[in] decl
112   ///     The Clang declaration for the persistent variable, used for
113   ///     lookup during parsing.
114   ///
115   /// \param[in] name
116   ///     The name of the persistent variable, usually $something.
117   ///
118   /// \param[in] type
119   ///     The type of the variable, in the Clang parser's context.
120   ///
121   /// \return
122   ///     True on success; false otherwise.
123   bool AddPersistentVariable(const clang::NamedDecl *decl,
124                              ConstString name, TypeFromParser type,
125                              bool is_result, bool is_lvalue);
126 
127   /// [Used by IRForTarget] Add a variable to the struct that needs to
128   ///     be materialized each time the expression runs.
129   ///
130   /// \param[in] decl
131   ///     The Clang declaration for the variable.
132   ///
133   /// \param[in] name
134   ///     The name of the variable.
135   ///
136   /// \param[in] value
137   ///     The LLVM IR value for this variable.
138   ///
139   /// \param[in] size
140   ///     The size of the variable in bytes.
141   ///
142   /// \param[in] alignment
143   ///     The required alignment of the variable in bytes.
144   ///
145   /// \return
146   ///     True on success; false otherwise.
147   bool AddValueToStruct(const clang::NamedDecl *decl, ConstString name,
148                         llvm::Value *value, size_t size,
149                         lldb::offset_t alignment);
150 
151   /// [Used by IRForTarget] Finalize the struct, laying out the position of
152   /// each object in it.
153   ///
154   /// \return
155   ///     True on success; false otherwise.
156   bool DoStructLayout();
157 
158   /// [Used by IRForTarget] Get general information about the laid-out struct
159   /// after DoStructLayout() has been called.
160   ///
161   /// \param[out] num_elements
162   ///     The number of elements in the struct.
163   ///
164   /// \param[out] size
165   ///     The size of the struct, in bytes.
166   ///
167   /// \param[out] alignment
168   ///     The alignment of the struct, in bytes.
169   ///
170   /// \return
171   ///     True if the information could be retrieved; false otherwise.
172   bool GetStructInfo(uint32_t &num_elements, size_t &size,
173                      lldb::offset_t &alignment);
174 
175   /// [Used by IRForTarget] Get specific information about one field of the
176   /// laid-out struct after DoStructLayout() has been called.
177   ///
178   /// \param[out] decl
179   ///     The parsed Decl for the field, as generated by ClangASTSource
180   ///     on ClangExpressionDeclMap's behalf.  In the case of the result
181   ///     value, this will have the name $__lldb_result even if the
182   ///     result value ends up having the name $1.  This is an
183   ///     implementation detail of IRForTarget.
184   ///
185   /// \param[out] value
186   ///     The IR value for the field (usually a GlobalVariable).  In
187   ///     the case of the result value, this will have the correct
188   ///     name ($1, for instance).  This is an implementation detail
189   ///     of IRForTarget.
190   ///
191   /// \param[out] offset
192   ///     The offset of the field from the beginning of the struct.
193   ///     As long as the struct is aligned according to its required
194   ///     alignment, this offset will align the field correctly.
195   ///
196   /// \param[out] name
197   ///     The name of the field as used in materialization.
198   ///
199   /// \param[in] index
200   ///     The index of the field about which information is requested.
201   ///
202   /// \return
203   ///     True if the information could be retrieved; false otherwise.
204   bool GetStructElement(const clang::NamedDecl *&decl, llvm::Value *&value,
205                         lldb::offset_t &offset, ConstString &name,
206                         uint32_t index);
207 
208   /// [Used by IRForTarget] Get information about a function given its Decl.
209   ///
210   /// \param[in] decl
211   ///     The parsed Decl for the Function, as generated by ClangASTSource
212   ///     on ClangExpressionDeclMap's behalf.
213   ///
214   /// \param[out] ptr
215   ///     The absolute address of the function in the target.
216   ///
217   /// \return
218   ///     True if the information could be retrieved; false otherwise.
219   bool GetFunctionInfo(const clang::NamedDecl *decl, uint64_t &ptr);
220 
221   /// [Used by IRForTarget] Get the address of a symbol given nothing but its
222   /// name.
223   ///
224   /// \param[in] target
225   ///     The target to find the symbol in.  If not provided,
226   ///     then the current parsing context's Target.
227   ///
228   /// \param[in] process
229   ///     The process to use.  For Objective-C symbols, the process's
230   ///     Objective-C language runtime may be queried if the process
231   ///     is non-NULL.
232   ///
233   /// \param[in] name
234   ///     The name of the symbol.
235   ///
236   /// \param[in] module
237   ///     The module to limit the search to. This can be NULL
238   ///
239   /// \return
240   ///     Valid load address for the symbol
241   lldb::addr_t GetSymbolAddress(Target &target, Process *process,
242                                 ConstString name, lldb::SymbolType symbol_type,
243                                 Module *module = nullptr);
244 
245   lldb::addr_t GetSymbolAddress(ConstString name,
246                                 lldb::SymbolType symbol_type);
247 
248   struct TargetInfo {
249     lldb::ByteOrder byte_order;
250     size_t address_byte_size;
251 
252     TargetInfo() : byte_order(lldb::eByteOrderInvalid), address_byte_size(0) {}
253 
254     bool IsValid() {
255       return (byte_order != lldb::eByteOrderInvalid && address_byte_size != 0);
256     }
257   };
258   TargetInfo GetTargetInfo();
259 
260   /// [Used by ClangASTSource] Find all entities matching a given name, using
261   /// a NameSearchContext to make Decls for them.
262   ///
263   /// \param[in] context
264   ///     The NameSearchContext that can construct Decls for this name.
265   void FindExternalVisibleDecls(NameSearchContext &context) override;
266 
267   /// Find all entities matching a given name in a given module/namespace,
268   /// using a NameSearchContext to make Decls for them.
269   ///
270   /// \param[in] context
271   ///     The NameSearchContext that can construct Decls for this name.
272   ///
273   /// \param[in] module
274   ///     If non-NULL, the module to query.
275   ///
276   /// \param[in] namespace_decl
277   ///     If valid and module is non-NULL, the parent namespace.
278   void FindExternalVisibleDecls(NameSearchContext &context,
279                                 lldb::ModuleSP module,
280                                 const CompilerDeclContext &namespace_decl);
281 
282 protected:
283   /// Retrieves the declaration with the given name from the storage of
284   /// persistent declarations.
285   ///
286   /// \return
287   ///     A persistent decl with the given name or a nullptr.
288   virtual clang::NamedDecl *GetPersistentDecl(ConstString name);
289 
290 private:
291   ExpressionVariableList
292       m_found_entities; ///< All entities that were looked up for the parser.
293   ExpressionVariableList
294       m_struct_members; ///< All entities that need to be placed in the struct.
295   bool m_keep_result_in_memory; ///< True if result persistent variables
296                                 ///generated by this expression should stay in
297                                 ///memory.
298   Materializer::PersistentVariableDelegate
299       *m_result_delegate; ///< If non-NULL, used to report expression results to
300                           ///ClangUserExpression.
301   ValueObject *m_ctx_obj; ///< If not empty, then expression is
302                           ///evaluated in context of this object.
303                           ///For details see the comment to
304                           ///`UserExpression::Evaluate`.
305 
306   /// The following values should not live beyond parsing
307   class ParserVars {
308   public:
309     ParserVars() {}
310 
311     Target *GetTarget() {
312       if (m_exe_ctx.GetTargetPtr())
313         return m_exe_ctx.GetTargetPtr();
314       else if (m_sym_ctx.target_sp)
315         return m_sym_ctx.target_sp.get();
316       return nullptr;
317     }
318 
319     ExecutionContext m_exe_ctx; ///< The execution context to use when parsing.
320     SymbolContext m_sym_ctx; ///< The symbol context to use in finding variables
321                              ///and types.
322     ClangPersistentVariables *m_persistent_vars =
323         nullptr; ///< The persistent variables for the process.
324     bool m_enable_lookups = false; ///< Set to true during parsing if we have
325                                    ///found the first "$__lldb" name.
326     TargetInfo m_target_info;      ///< Basic information about the target.
327     Materializer *m_materializer = nullptr;   ///< If non-NULL, the materializer
328                                               ///to use when reporting used
329                                               ///variables.
330     clang::ASTConsumer *m_code_gen = nullptr; ///< If non-NULL, a code generator
331                                               ///that receives new top-level
332                                               ///functions.
333   private:
334     ParserVars(const ParserVars &) = delete;
335     const ParserVars &operator=(const ParserVars &) = delete;
336   };
337 
338   std::unique_ptr<ParserVars> m_parser_vars;
339 
340   /// Activate parser-specific variables
341   void EnableParserVars() {
342     if (!m_parser_vars.get())
343       m_parser_vars = std::make_unique<ParserVars>();
344   }
345 
346   /// Deallocate parser-specific variables
347   void DisableParserVars() { m_parser_vars.reset(); }
348 
349   /// The following values contain layout information for the materialized
350   /// struct, but are not specific to a single materialization
351   struct StructVars {
352     StructVars()
353         : m_struct_alignment(0), m_struct_size(0), m_struct_laid_out(false),
354           m_result_name(), m_object_pointer_type(nullptr, nullptr) {}
355 
356     lldb::offset_t
357         m_struct_alignment; ///< The alignment of the struct in bytes.
358     size_t m_struct_size;   ///< The size of the struct in bytes.
359     bool m_struct_laid_out; ///< True if the struct has been laid out and the
360                             ///layout is valid (that is, no new fields have been
361                             ///added since).
362     ConstString
363         m_result_name; ///< The name of the result variable ($1, for example)
364     TypeFromUser m_object_pointer_type; ///< The type of the "this" variable, if
365                                         ///one exists
366   };
367 
368   std::unique_ptr<StructVars> m_struct_vars;
369 
370   /// Activate struct variables
371   void EnableStructVars() {
372     if (!m_struct_vars.get())
373       m_struct_vars.reset(new struct StructVars);
374   }
375 
376   /// Deallocate struct variables
377   void DisableStructVars() { m_struct_vars.reset(); }
378 
379   /// Get this parser's ID for use in extracting parser- and JIT-specific data
380   /// from persistent variables.
381   uint64_t GetParserID() { return (uint64_t) this; }
382 
383   /// Should be called on all copied functions.
384   void MaybeRegisterFunctionBody(clang::FunctionDecl *copied_function_decl);
385 
386   /// Searches the persistent decls of the target for entities with the
387   /// given name.
388   ///
389   /// \param[in] context
390   ///     The NameSearchContext that can construct Decls for this name.
391   ///
392   /// \param[in] name
393   ///     The name of the entities that need to be found.
394   void SearchPersistenDecls(NameSearchContext &context, const ConstString name);
395 
396   /// Handles looking up $__lldb_class which requires special treatment.
397   ///
398   /// \param[in] context
399   ///     The NameSearchContext that can construct Decls for this name.
400   void LookUpLldbClass(NameSearchContext &context);
401 
402   /// Handles looking up $__lldb_objc_class which requires special treatment.
403   ///
404   /// \param[in] context
405   ///     The NameSearchContext that can construct Decls for this name.
406   void LookUpLldbObjCClass(NameSearchContext &context);
407 
408   /// Handles looking up the synthetic namespace that contains our local
409   /// variables for the current frame.
410   ///
411   /// \param[in] sym_ctx
412   ///     The current SymbolContext of this frame.
413   ///
414   /// \param[in] name_context
415   ///     The NameSearchContext that can construct Decls for this name.
416   void LookupLocalVarNamespace(SymbolContext &sym_ctx,
417                                NameSearchContext &name_context);
418 
419   /// Lookup entities in the ClangModulesDeclVendor.
420   /// \param[in] context
421   ///     The NameSearchContext that can construct Decls for this name.
422   ///
423   /// \param[in] name
424   ///     The name of the entities that need to be found.
425   void LookupInModulesDeclVendor(NameSearchContext &context, ConstString name);
426 
427   /// Looks up a local variable.
428   ///
429   /// \param[in] context
430   ///     The NameSearchContext that can construct Decls for this name.
431   ///
432   /// \param[in] name
433   ///     The name of the entities that need to be found.
434   ///
435   /// \param[in] sym_ctx
436   ///     The current SymbolContext of this frame.
437   ///
438   /// \param[in] namespace_decl
439   ///     The parent namespace if there is one.
440   ///
441   /// \return
442   ///    True iff a local variable was found.
443   bool LookupLocalVariable(NameSearchContext &context, ConstString name,
444                            SymbolContext &sym_ctx,
445                            const CompilerDeclContext &namespace_decl);
446 
447   /// Searches for functions in the given SymbolContextList.
448   ///
449   /// \param[in] sc_list
450   ///     The SymbolContextList to search.
451   ///
452   /// \param[in] frame_decl_context
453   ///     The current DeclContext of the current frame.
454   ///
455   /// \return
456   ///     A SymbolContextList with any found functions in the front and
457   ///     any unknown SymbolContexts which are not functions in the back.
458   ///     The SymbolContexts for the functions are ordered by how close they are
459   ///     to the DeclContext for the given frame DeclContext.
460   SymbolContextList SearchFunctionsInSymbolContexts(
461       const SymbolContextList &sc_list,
462       const CompilerDeclContext &frame_decl_context);
463 
464   /// Looks up a function.
465   ///
466   /// \param[in] context
467   ///     The NameSearchContext that can construct Decls for this name.
468   ///
469   /// \param[in] module_sp
470   ///     If non-NULL, the module to query.
471   ///
472   /// \param[in] name
473   ///     The name of the function that should be find.
474   ///
475   /// \param[in] namespace_decl
476   ///     If valid and module is non-NULL, the parent namespace.
477   void LookupFunction(NameSearchContext &context, lldb::ModuleSP module_sp,
478                       ConstString name,
479                       const CompilerDeclContext &namespace_decl);
480 
481   /// Given a target, find a variable that matches the given name and type.
482   ///
483   /// \param[in] target
484   ///     The target to use as a basis for finding the variable.
485   ///
486   /// \param[in] module
487   ///     If non-NULL, the module to search.
488   ///
489   /// \param[in] name
490   ///     The name as a plain C string.
491   ///
492   /// \param[in] namespace_decl
493   ///     If non-NULL and module is non-NULL, the parent namespace.
494   ///
495   /// \return
496   ///     The LLDB Variable found, or NULL if none was found.
497   lldb::VariableSP
498   FindGlobalVariable(Target &target, lldb::ModuleSP &module, ConstString name,
499                      const CompilerDeclContext &namespace_decl);
500 
501   /// Get the value of a variable in a given execution context and return the
502   /// associated Types if needed.
503   ///
504   /// \param[in] var
505   ///     The variable to evaluate.
506   ///
507   /// \param[out] var_location
508   ///     The variable location value to fill in
509   ///
510   /// \param[out] found_type
511   ///     The type of the found value, as it was found in the user process.
512   ///     This is only useful when the variable is being inspected on behalf
513   ///     of the parser, hence the default.
514   ///
515   /// \param[out] parser_type
516   ///     The type of the found value, as it was copied into the parser's
517   ///     AST context.  This is only useful when the variable is being
518   ///     inspected on behalf of the parser, hence the default.
519   ///
520   /// \return
521   ///     Return true if the value was successfully filled in.
522   bool GetVariableValue(lldb::VariableSP &var,
523                         lldb_private::Value &var_location,
524                         TypeFromUser *found_type = nullptr,
525                         TypeFromParser *parser_type = nullptr);
526 
527   /// Use the NameSearchContext to generate a Decl for the given LLDB
528   /// Variable, and put it in the Tuple list.
529   ///
530   /// \param[in] context
531   ///     The NameSearchContext to use when constructing the Decl.
532   ///
533   /// \param[in] var
534   ///     The LLDB Variable that needs a Decl.
535   ///
536   /// \param[in] valobj
537   ///     The LLDB ValueObject for that variable.
538   void AddOneVariable(NameSearchContext &context, lldb::VariableSP var,
539                       lldb::ValueObjectSP valobj);
540 
541   /// Use the NameSearchContext to generate a Decl for the given persistent
542   /// variable, and put it in the list of found entities.
543   ///
544   /// \param[in] context
545   ///     The NameSearchContext to use when constructing the Decl.
546   ///
547   /// \param[in] pvar_sp
548   ///     The persistent variable that needs a Decl.
549   void AddOneVariable(NameSearchContext &context,
550                       lldb::ExpressionVariableSP &pvar_sp);
551 
552   /// Use the NameSearchContext to generate a Decl for the given LLDB symbol
553   /// (treated as a variable), and put it in the list of found entities.
554   void AddOneGenericVariable(NameSearchContext &context, const Symbol &symbol);
555 
556   /// Use the NameSearchContext to generate a Decl for the given function.
557   /// (Functions are not placed in the Tuple list.)  Can handle both fully
558   /// typed functions and generic functions.
559   ///
560   /// \param[in] context
561   ///     The NameSearchContext to use when constructing the Decl.
562   ///
563   /// \param[in] fun
564   ///     The Function that needs to be created.  If non-NULL, this is
565   ///     a fully-typed function.
566   ///
567   /// \param[in] sym
568   ///     The Symbol that corresponds to a function that needs to be
569   ///     created with generic type (unitptr_t foo(...)).
570   void AddOneFunction(NameSearchContext &context, Function *fun, Symbol *sym);
571 
572   /// Use the NameSearchContext to generate a Decl for the given register.
573   ///
574   /// \param[in] context
575   ///     The NameSearchContext to use when constructing the Decl.
576   ///
577   /// \param[in] reg_info
578   ///     The information corresponding to that register.
579   void AddOneRegister(NameSearchContext &context, const RegisterInfo *reg_info);
580 
581   /// Use the NameSearchContext to generate a Decl for the given type.  (Types
582   /// are not placed in the Tuple list.)
583   ///
584   /// \param[in] context
585   ///     The NameSearchContext to use when constructing the Decl.
586   ///
587   /// \param[in] type
588   ///     The type that needs to be created.
589   void AddOneType(NameSearchContext &context, const TypeFromUser &type);
590 
591   /// Adds the class in which the expression is evaluated to the lookup and
592   /// prepares the class to be used as a context for expression evaluation (for
593   /// example, it creates a fake member function that will contain the
594   /// expression LLDB is trying to evaluate).
595   ///
596   /// \param[in] context
597   ///     The NameSearchContext to which the class should be added as a lookup
598   ///     result.
599   ///
600   /// \param[in] type
601   ///     The type of the class that serves as the evaluation context.
602   void AddContextClassType(NameSearchContext &context,
603                            const TypeFromUser &type);
604 
605   /// Move a type out of the current ASTContext into another, but make sure to
606   /// export all components of the type also.
607   ///
608   /// \param[in] target
609   ///     The TypeSystemClang to move to.
610   /// \param[in] source
611   ///     The TypeSystemClang to move from.  This is assumed to be going away.
612   /// \param[in] parser_type
613   ///     The type as it appears in the source context.
614   ///
615   /// \return
616   ///     Returns the moved type, or an empty type if there was a problem.
617   TypeFromUser DeportType(TypeSystemClang &target, TypeSystemClang &source,
618                           TypeFromParser parser_type);
619 
620   TypeSystemClang *GetTypeSystemClang();
621 };
622 
623 } // namespace lldb_private
624 
625 #endif // LLDB_SOURCE_PLUGINS_EXPRESSIONPARSER_CLANG_CLANGEXPRESSIONDECLMAP_H
626