ClangUserExpression.h revision e6ea5fe8e76b028a0565bc01543bc15f8c120e8a
1//===-- ClangUserExpression.h -----------------------------------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#ifndef liblldb_ClangUserExpression_h_
11#define liblldb_ClangUserExpression_h_
12
13// C Includes
14// C++ Includes
15#include <string>
16#include <map>
17#include <memory>
18#include <vector>
19
20// Other libraries and framework includes
21// Project includes
22
23#include "lldb/lldb-forward.h"
24#include "lldb/lldb-private.h"
25#include "lldb/Core/ClangForward.h"
26#include "lldb/Expression/ClangExpression.h"
27#include "lldb/Expression/ClangExpressionVariable.h"
28#include "lldb/Expression/IRForTarget.h"
29#include "lldb/Expression/ProcessDataAllocator.h"
30#include "lldb/Symbol/TaggedASTType.h"
31#include "lldb/Target/Process.h"
32
33#include "llvm/ExecutionEngine/JITMemoryManager.h"
34
35namespace lldb_private
36{
37
38//----------------------------------------------------------------------
39/// @class ClangUserExpression ClangUserExpression.h "lldb/Expression/ClangUserExpression.h"
40/// @brief Encapsulates a single expression for use with Clang
41///
42/// LLDB uses expressions for various purposes, notably to call functions
43/// and as a backend for the expr command.  ClangUserExpression encapsulates
44/// the objects needed to parse and interpret or JIT an expression.  It
45/// uses the Clang parser to produce LLVM IR from the expression.
46//----------------------------------------------------------------------
47class ClangUserExpression : public ClangExpression
48{
49public:
50    typedef lldb::SharedPtr<ClangUserExpression>::Type ClangUserExpressionSP;
51
52    //------------------------------------------------------------------
53    /// Constructor
54    ///
55    /// @param[in] expr
56    ///     The expression to parse.
57    ///
58    /// @param[in] expr_prefix
59    ///     If non-NULL, a C string containing translation-unit level
60    ///     definitions to be included when the expression is parsed.
61    ///
62    /// @param[in] language
63    ///     If not eLanguageTypeUnknown, a language to use when parsing
64    ///     the expression.  Currently restricted to those languages
65    ///     supported by Clang.
66    //------------------------------------------------------------------
67    ClangUserExpression (const char *expr,
68                         const char *expr_prefix,
69                         lldb::LanguageType language);
70
71    //------------------------------------------------------------------
72    /// Destructor
73    //------------------------------------------------------------------
74    virtual
75    ~ClangUserExpression ();
76
77    //------------------------------------------------------------------
78    /// Parse the expression
79    ///
80    /// @param[in] error_stream
81    ///     A stream to print parse errors and warnings to.
82    ///
83    /// @param[in] exe_ctx
84    ///     The execution context to use when looking up entities that
85    ///     are needed for parsing (locations of functions, types of
86    ///     variables, persistent variables, etc.)
87    ///
88    /// @param[in] desired_type
89    ///     The type that the expression should be coerced to.  If NULL,
90    ///     inferred from the expression itself.
91    ///
92    /// @param[in] execution_policy
93    ///     Determines whether interpretation is possible or mandatory.
94    ///
95    /// @param[in] keep_result_in_memory
96    ///     True if the resulting persistent variable should reside in
97    ///     target memory, if applicable.
98    ///
99    /// @return
100    ///     True on success (no errors); false otherwise.
101    //------------------------------------------------------------------
102    bool
103    Parse (Stream &error_stream,
104           ExecutionContext &exe_ctx,
105           TypeFromUser desired_type,
106           lldb_private::ExecutionPolicy execution_policy,
107           bool keep_result_in_memory);
108
109    //------------------------------------------------------------------
110    /// Execute the parsed expression
111    ///
112    /// @param[in] error_stream
113    ///     A stream to print errors to.
114    ///
115    /// @param[in] exe_ctx
116    ///     The execution context to use when looking up entities that
117    ///     are needed for parsing (locations of variables, etc.)
118    ///
119    /// @param[in] discard_on_error
120    ///     If true, and the execution stops before completion, we unwind the
121    ///     function call, and return the program state to what it was before the
122    ///     execution.  If false, we leave the program in the stopped state.
123    ///
124    /// @param[in] shared_ptr_to_me
125    ///     This is a shared pointer to this ClangUserExpression.  This is
126    ///     needed because Execute can push a thread plan that will hold onto
127    ///     the ClangUserExpression for an unbounded period of time.  So you
128    ///     need to give the thread plan a reference to this object that can
129    ///     keep it alive.
130    ///
131    /// @param[in] result
132    ///     A pointer to direct at the persistent variable in which the
133    ///     expression's result is stored.
134    ///
135    /// @return
136    ///     A Process::Execution results value.
137    //------------------------------------------------------------------
138    ExecutionResults
139    Execute (Stream &error_stream,
140             ExecutionContext &exe_ctx,
141             bool discard_on_error,
142             ClangUserExpressionSP &shared_ptr_to_me,
143             lldb::ClangExpressionVariableSP &result);
144
145    ThreadPlan *
146    GetThreadPlanToExecuteJITExpression (Stream &error_stream,
147                                         ExecutionContext &exe_ctx);
148
149    //------------------------------------------------------------------
150    /// Apply the side effects of the function to program state.
151    ///
152    /// @param[in] error_stream
153    ///     A stream to print errors to.
154    ///
155    /// @param[in] exe_ctx
156    ///     The execution context to use when looking up entities that
157    ///     are needed for parsing (locations of variables, etc.)
158    ///
159    /// @param[in] result
160    ///     A pointer to direct at the persistent variable in which the
161    ///     expression's result is stored.
162    ///
163    /// @param[in] function_stack_pointer
164    ///     A pointer to the base of the function's stack frame.  This
165    ///     is used to determine whether the expession result resides in
166    ///     memory that will still be valid, or whether it needs to be
167    ///     treated as homeless for the purpose of future expressions.
168    ///
169    /// @return
170    ///     A Process::Execution results value.
171    //------------------------------------------------------------------
172    bool
173    FinalizeJITExecution (Stream &error_stream,
174                          ExecutionContext &exe_ctx,
175                          lldb::ClangExpressionVariableSP &result,
176                          lldb::addr_t function_stack_pointer = LLDB_INVALID_ADDRESS);
177
178    //------------------------------------------------------------------
179    /// Return the string that the parser should parse.  Must be a full
180    /// translation unit.
181    //------------------------------------------------------------------
182    const char *
183    Text ()
184    {
185        return m_transformed_text.c_str();
186    }
187
188    //------------------------------------------------------------------
189    /// Return the string that the user typed.
190    //------------------------------------------------------------------
191    const char *
192    GetUserText ()
193    {
194        return m_expr_text.c_str();
195    }
196
197    //------------------------------------------------------------------
198    /// Return the function name that should be used for executing the
199    /// expression.  Text() should contain the definition of this
200    /// function.
201    //------------------------------------------------------------------
202    const char *
203    FunctionName ()
204    {
205        return "$__lldb_expr";
206    }
207
208    //------------------------------------------------------------------
209    /// Return the language that should be used when parsing.  To use
210    /// the default, return eLanguageTypeUnknown.
211    //------------------------------------------------------------------
212    virtual lldb::LanguageType
213    Language ()
214    {
215        return m_language;
216    }
217
218    //------------------------------------------------------------------
219    /// Return the object that the parser should use when resolving external
220    /// values.  May be NULL if everything should be self-contained.
221    //------------------------------------------------------------------
222    ClangExpressionDeclMap *
223    DeclMap ()
224    {
225        return m_expr_decl_map.get();
226    }
227
228    //------------------------------------------------------------------
229    /// Return the object that the parser should use when registering
230    /// local variables.  May be NULL if the Expression doesn't care.
231    //------------------------------------------------------------------
232    ClangExpressionVariableList *
233    LocalVariables ()
234    {
235        return m_local_variables.get();
236    }
237
238    //------------------------------------------------------------------
239    /// Return the object that the parser should allow to access ASTs.
240    /// May be NULL if the ASTs do not need to be transformed.
241    ///
242    /// @param[in] passthrough
243    ///     The ASTConsumer that the returned transformer should send
244    ///     the ASTs to after transformation.
245    //------------------------------------------------------------------
246    clang::ASTConsumer *
247    ASTTransformer (clang::ASTConsumer *passthrough);
248
249    //------------------------------------------------------------------
250    /// Return true if validation code should be inserted into the
251    /// expression.
252    //------------------------------------------------------------------
253    bool
254    NeedsValidation ()
255    {
256        return true;
257    }
258
259    //------------------------------------------------------------------
260    /// Return true if external variables in the expression should be
261    /// resolved.
262    //------------------------------------------------------------------
263    bool
264    NeedsVariableResolution ()
265    {
266        return true;
267    }
268
269    //------------------------------------------------------------------
270    /// Evaluate one expression and return its result.
271    ///
272    /// @param[in] exe_ctx
273    ///     The execution context to use when evaluating the expression.
274    ///
275    /// @param[in] execution_policy
276    ///     Determines whether or not to try using the IR interpreter to
277    ///     avoid running the expression on the parser.
278    ///
279    /// @param[in] language
280    ///     If not eLanguageTypeUnknown, a language to use when parsing
281    ///     the expression.  Currently restricted to those languages
282    ///     supported by Clang.
283    ///
284    /// @param[in] discard_on_error
285    ///     True if the thread's state should be restored in the case
286    ///     of an error.
287    ///
288    /// @param[in] expr_cstr
289    ///     A C string containing the expression to be evaluated.
290    ///
291    /// @param[in] expr_prefix
292    ///     If non-NULL, a C string containing translation-unit level
293    ///     definitions to be included when the expression is parsed.
294    ///
295    /// @param[in/out] result_valobj_sp
296    ///      If execution is successful, the result valobj is placed here.
297    ///
298    /// @result
299    ///      A Process::ExecutionResults value.  eExecutionCompleted for success.
300    //------------------------------------------------------------------
301    static ExecutionResults
302    Evaluate (ExecutionContext &exe_ctx,
303              lldb_private::ExecutionPolicy execution_policy,
304              lldb::LanguageType language,
305              bool discard_on_error,
306              const char *expr_cstr,
307              const char *expr_prefix,
308              lldb::ValueObjectSP &result_valobj_sp);
309
310    static ExecutionResults
311    EvaluateWithError (ExecutionContext &exe_ctx,
312                       lldb_private::ExecutionPolicy execution_policy,
313                       lldb::LanguageType language,
314                       bool discard_on_error,
315                       const char *expr_cstr,
316                       const char *expr_prefix,
317                       lldb::ValueObjectSP &result_valobj_sp,
318                       Error &error);
319
320    static const Error::ValueType kNoResult = 0x1001; ///< ValueObject::GetError() returns this if there is no result from the expression.
321private:
322    //------------------------------------------------------------------
323    /// Populate m_cplusplus and m_objetivec based on the environment.
324    //------------------------------------------------------------------
325
326    void
327    ScanContext (ExecutionContext &exe_ctx,
328                 lldb_private::Error &err);
329
330    bool
331    PrepareToExecuteJITExpression (Stream &error_stream,
332                                   ExecutionContext &exe_ctx,
333                                   lldb::addr_t &struct_address,
334                                   lldb::addr_t &object_ptr,
335                                   lldb::addr_t &cmd_ptr);
336
337    bool
338    EvaluatedStatically ()
339    {
340        return m_evaluated_statically;
341    }
342
343    std::string                                 m_expr_text;            ///< The text of the expression, as typed by the user
344    std::string                                 m_expr_prefix;          ///< The text of the translation-level definitions, as provided by the user
345    lldb::LanguageType                          m_language;             ///< The language to use when parsing (eLanguageTypeUnknown means use defaults)
346    bool                                        m_allow_cxx;            ///< True if the language allows C++.
347    bool                                        m_allow_objc;           ///< True if the language allows Objective-C.
348    std::string                                 m_transformed_text;     ///< The text of the expression, as send to the parser
349    TypeFromUser                                m_desired_type;         ///< The type to coerce the expression's result to.  If NULL, inferred from the expression.
350
351    std::auto_ptr<ClangExpressionDeclMap>       m_expr_decl_map;        ///< The map to use when parsing and materializing the expression.
352    std::auto_ptr<ClangExpressionVariableList>  m_local_variables;      ///< The local expression variables, if the expression is DWARF.
353    std::auto_ptr<ProcessDataAllocator>         m_data_allocator;       ///< The allocator that the parser uses to place strings for use by JIT-compiled code.
354
355    std::auto_ptr<ASTResultSynthesizer>         m_result_synthesizer;   ///< The result synthesizer, if one is needed.
356
357    bool                                        m_cplusplus;            ///< True if the expression is compiled as a C++ member function (true if it was parsed when exe_ctx was in a C++ method).
358    bool                                        m_objectivec;           ///< True if the expression is compiled as an Objective-C method (true if it was parsed when exe_ctx was in an Objective-C method).
359    bool                                        m_static_method;        ///< True if the expression is compiled as a static (or class) method (currently true if it was parsed when exe_ctx was in an Objective-C class method).
360    bool                                        m_needs_object_ptr;     ///< True if "this" or "self" must be looked up and passed in.  False if the expression doesn't really use them and they can be NULL.
361    bool                                        m_const_object;         ///< True if "this" is const.
362    Target                                     *m_target;               ///< The target for storing persistent data like types and variables.
363
364    bool                                        m_evaluated_statically; ///< True if the expression could be evaluated statically; false otherwise.
365    lldb::ClangExpressionVariableSP             m_const_result;         ///< The statically-computed result of the expression.  NULL if it could not be computed statically or the expression has side effects.
366};
367
368} // namespace lldb_private
369
370#endif  // liblldb_ClangUserExpression_h_
371