ClangExpressionDeclMap.h revision 6916e358c9725b75ed91f31236c147f26c9af10e
1//===-- ClangExpressionDeclMap.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_ClangExpressionDeclMap_h_
11#define liblldb_ClangExpressionDeclMap_h_
12
13// C Includes
14#include <signal.h>
15#include <stdint.h>
16
17// C++ Includes
18#include <vector>
19
20// Other libraries and framework includes
21// Project includes
22#include "llvm/ADT/DenseMap.h"
23#include "lldb/Core/ClangForward.h"
24#include "lldb/Core/Value.h"
25#include "lldb/Expression/ClangExpressionVariable.h"
26#include "lldb/Symbol/TaggedASTType.h"
27#include "lldb/Symbol/SymbolContext.h"
28#include "lldb/Target/ExecutionContext.h"
29
30namespace llvm {
31    class Type;
32    class Value;
33}
34
35namespace lldb_private {
36
37class ClangExpressionVariables;
38class ClangPersistentVariables;
39class Error;
40class Function;
41class NameSearchContext;
42class Variable;
43
44//----------------------------------------------------------------------
45/// @class ClangExpressionDeclMap ClangExpressionDeclMap.h "lldb/Expression/ClangExpressionDeclMap.h"
46/// @brief Manages named entities that are defined in LLDB's debug information.
47///
48/// The Clang parser uses the ClangASTSource as an interface to request named
49/// entities from outside an expression.  The ClangASTSource reports back, listing
50/// all possible objects corresponding to a particular name.  But it in turn
51/// relies on ClangExpressionDeclMap, which performs several important functions.
52///
53/// First, it records what variables and functions were looked up and what Decls
54/// were returned for them.
55///
56/// Second, it constructs a struct on behalf of IRForTarget, recording which
57/// variables should be placed where and relaying this information back so that
58/// IRForTarget can generate context-independent code.
59///
60/// Third, it "materializes" this struct on behalf of the expression command,
61/// finding the current values of each variable and placing them into the
62/// struct so that it can be passed to the JITted version of the IR.
63///
64/// Fourth and finally, it "dematerializes" the struct after the JITted code has
65/// has executed, placing the new values back where it found the old ones.
66//----------------------------------------------------------------------
67class ClangExpressionDeclMap
68{
69public:
70    //------------------------------------------------------------------
71    /// Constructor
72    ///
73    /// Initializes class variabes.
74    ///
75    /// @param[in] exe_ctx
76    ///     The execution context to use when finding types for variables.
77    ///     Also used to find a "scratch" AST context to store result types.
78    //------------------------------------------------------------------
79    ClangExpressionDeclMap(ExecutionContext *exe_ctx);
80
81    //------------------------------------------------------------------
82    /// Destructor
83    //------------------------------------------------------------------
84    ~ClangExpressionDeclMap();
85
86    //------------------------------------------------------------------
87    /// [Used by IRForTarget] Get a new result variable name of the form
88    ///     $n, where n is a natural number starting with 0.
89    ///
90    /// @param[in] name
91    ///     The std::string to place the name into.
92    //------------------------------------------------------------------
93    const ConstString &
94    GetPersistentResultName ();
95
96    clang::NamespaceDecl *
97    AddNamespace (NameSearchContext &context,
98                  const ClangNamespaceDecl &namespace_decl);
99
100    //------------------------------------------------------------------
101    /// [Used by IRForTarget] Add a variable to the list of persistent
102    ///     variables for the process.
103    ///
104    /// @param[in] decl
105    ///     The Clang declaration for the persistent variable, used for
106    ///     lookup during parsing.
107    ///
108    /// @param[in] name
109    ///     The name of the persistent variable, usually $something.
110    ///
111    /// @param[in] type
112    ///     The type of the variable, in the Clang parser's context.
113    ///
114    /// @return
115    ///     True on success; false otherwise.
116    //------------------------------------------------------------------
117    bool AddPersistentVariable (const clang::NamedDecl *decl,
118                                const ConstString &name,
119                                TypeFromParser type);
120
121    //------------------------------------------------------------------
122    /// [Used by IRForTarget] Add a variable to the struct that needs to
123    ///     be materialized each time the expression runs.
124    ///
125    /// @param[in] decl
126    ///     The Clang declaration for the variable.
127    ///
128    /// @param[in] name
129    ///     The name of the variable.
130    ///
131    /// @param[in] value
132    ///     The LLVM IR value for this variable.
133    ///
134    /// @param[in] size
135    ///     The size of the variable in bytes.
136    ///
137    /// @param[in] alignment
138    ///     The required alignment of the variable in bytes.
139    ///
140    /// @return
141    ///     True on success; false otherwise.
142    //------------------------------------------------------------------
143    bool AddValueToStruct (const clang::NamedDecl *decl,
144                           const ConstString &name,
145                           llvm::Value *value,
146                           size_t size,
147                           off_t alignment);
148
149    //------------------------------------------------------------------
150    /// [Used by IRForTarget] Finalize the struct, laying out the position
151    /// of each object in it.
152    ///
153    /// @return
154    ///     True on success; false otherwise.
155    //------------------------------------------------------------------
156    bool DoStructLayout ();
157
158    //------------------------------------------------------------------
159    /// [Used by IRForTarget] Get general information about the laid-out
160    /// struct after DoStructLayout() has been called.
161    ///
162    /// @param[out] num_elements
163    ///     The number of elements in the struct.
164    ///
165    /// @param[out] size
166    ///     The size of the struct, in bytes.
167    ///
168    /// @param[out] alignment
169    ///     The alignment of the struct, in bytes.
170    ///
171    /// @return
172    ///     True if the information could be retrieved; false otherwise.
173    //------------------------------------------------------------------
174    bool GetStructInfo (uint32_t &num_elements,
175                        size_t &size,
176                        off_t &alignment);
177
178    //------------------------------------------------------------------
179    /// [Used by IRForTarget] Get specific information about one field
180    /// of the laid-out struct after DoStructLayout() has been called.
181    ///
182    /// @param[out] decl
183    ///     The parsed Decl for the field, as generated by ClangASTSource
184    ///     on ClangExpressionDeclMap's behalf.  In the case of the result
185    ///     value, this will have the name $__lldb_result even if the
186    ///     result value ends up having the name $1.  This is an
187    ///     implementation detail of IRForTarget.
188    ///
189    /// @param[out] value
190    ///     The IR value for the field (usually a GlobalVariable).  In
191    ///     the case of the result value, this will have the correct
192    ///     name ($1, for instance).  This is an implementation detail
193    ///     of IRForTarget.
194    ///
195    /// @param[out] offset
196    ///     The offset of the field from the beginning of the struct.
197    ///     As long as the struct is aligned according to its required
198    ///     alignment, this offset will align the field correctly.
199    ///
200    /// @param[out] name
201    ///     The name of the field as used in materialization.
202    ///
203    /// @param[in] index
204    ///     The index of the field about which information is requested.
205    ///
206    /// @return
207    ///     True if the information could be retrieved; false otherwise.
208    //------------------------------------------------------------------
209    bool GetStructElement (const clang::NamedDecl *&decl,
210                           llvm::Value *&value,
211                           off_t &offset,
212                           ConstString &name,
213                           uint32_t index);
214
215    //------------------------------------------------------------------
216    /// [Used by IRForTarget] Get information about a function given its
217    /// Decl.
218    ///
219    /// @param[in] decl
220    ///     The parsed Decl for the Function, as generated by ClangASTSource
221    ///     on ClangExpressionDeclMap's behalf.
222    ///
223    /// @param[out] value
224    ///     A pointer to the address where a Value for the function's address
225    ///     can be stored.  IRForTarget typically places a ConstantExpr here.
226    ///
227    /// @param[out] ptr
228    ///     The absolute address of the function in the target.
229    ///
230    /// @return
231    ///     True if the information could be retrieved; false otherwise.
232    //------------------------------------------------------------------
233    bool GetFunctionInfo (const clang::NamedDecl *decl,
234                          llvm::Value**& value,
235                          uint64_t &ptr);
236
237    //------------------------------------------------------------------
238    /// [Used by IRForTarget] Get the address of a function given nothing
239    /// but its name.  Some functions are needed but didn't get Decls made
240    /// during parsing -- specifically, sel_registerName is never called
241    /// in the generated IR but we need to call it nonetheless.
242    ///
243    /// @param[in] name
244    ///     The name of the function.
245    ///
246    /// @param[out] ptr
247    ///     The absolute address of the function in the target.
248    ///
249    /// @return
250    ///     True if the address could be retrieved; false otherwise.
251    //------------------------------------------------------------------
252    bool GetFunctionAddress (const ConstString &name,
253                             uint64_t &ptr);
254
255    //------------------------------------------------------------------
256    /// [Used by CommandObjectExpression] Materialize the entire struct
257    /// at a given address, which should be aligned as specified by
258    /// GetStructInfo().
259    ///
260    /// @param[in] exe_ctx
261    ///     The execution context at which to dump the struct.
262    ///
263    /// @param[in] struct_address
264    ///     The address at which the struct should be written.
265    ///
266    /// @param[in] error
267    ///     An Error to populate with any messages related to
268    ///     materializing the struct.
269    ///
270    /// @return
271    ///     True on success; false otherwise.
272    //------------------------------------------------------------------
273    bool Materialize(ExecutionContext *exe_ctx,
274                     lldb::addr_t &struct_address,
275                     Error &error);
276
277    //------------------------------------------------------------------
278    /// [Used by CommandObjectExpression] Get the "this" pointer
279    /// from a given execution context.
280    ///
281    /// @param[out] object_ptr
282    ///     The this pointer.
283    ///
284    /// @param[in] exe_ctx
285    ///     The execution context at which to dump the struct.
286    ///
287    /// @param[in] error
288    ///     An Error to populate with any messages related to
289    ///     finding the "this" pointer.
290    ///
291    /// @return
292    ///     True on success; false otherwise.
293    //------------------------------------------------------------------
294    bool GetObjectPointer(lldb::addr_t &object_ptr,
295                          ExecutionContext *exe_ctx,
296                          Error &error);
297
298    //------------------------------------------------------------------
299    /// [Used by CommandObjectExpression] Pretty-print a materialized
300    /// struct, which must have been materialized by Materialize(),
301    /// byte for byte on a given stream.
302    ///
303    /// @param[in] exe_ctx
304    ///     The execution context from which to read the struct.
305    ///
306    /// @param[in] s
307    ///     The stream on which to write the pretty-printed output.
308    ///
309    /// @param[in] error
310    ///     An Error to populate with any messages related to
311    ///     pretty-printing the struct.
312    ///
313    /// @return
314    ///     True on success; false otherwise.
315    //------------------------------------------------------------------
316    bool DumpMaterializedStruct(ExecutionContext *exe_ctx,
317                                Stream &s,
318                                Error &error);
319
320    //------------------------------------------------------------------
321    /// [Used by CommandObjectExpression] Deaterialize the entire struct.
322    ///
323    /// @param[in] exe_ctx
324    ///     The execution context from which to read the struct.
325    ///
326    /// @param[out] result
327    ///     A ClangExpressionVariable containing the result of the
328    ///     expression, for potential re-use.
329    ///
330    /// @param[in] error
331    ///     An Error to populate with any messages related to
332    ///     dematerializing the struct.
333    ///
334    /// @return
335    ///     True on success; false otherwise.
336    //------------------------------------------------------------------
337    bool Dematerialize(ExecutionContext *exe_ctx,
338                       ClangExpressionVariable *&result,
339                       Error &error);
340
341    //------------------------------------------------------------------
342    /// [Used by ClangASTSource] Find all entities matching a given name,
343    /// using a NameSearchContext to make Decls for them.
344    ///
345    /// @param[in] context
346    ///     The NameSearchContext that can construct Decls for this name.
347    ///
348    /// @param[in] name
349    ///     The name as a plain C string.  The NameSearchContext contains
350    ///     a DeclarationName for the name so at first the name may seem
351    ///     redundant, but ClangExpressionDeclMap operates in RTTI land so
352    ///     it can't access DeclarationName.
353    ///
354    /// @return
355    ///     True on success; false otherwise.
356    //------------------------------------------------------------------
357    void GetDecls (NameSearchContext &context,
358                   const ConstString &name);
359
360    bool
361    GetLookupsEnabled ()
362    {
363        return m_enable_lookups;
364    }
365
366    void
367    SetLookupsEnabled (bool b)
368    {
369        m_enable_lookups = b;
370    }
371
372private:
373    ClangExpressionVariableStore    m_found_entities;       ///< All entities that were looked up for the parser.
374    ClangExpressionVariableList     m_struct_members;       ///< All entities that need to be placed in the struct.
375
376    ExecutionContext            m_exe_ctx;                  ///< The execution context where this expression was first defined.  It determines types for all the external variables, even if the expression is re-used.
377    SymbolContext               m_sym_ctx;                  ///< [owned by ClangExpressionDeclMap] The symbol context where this expression was first defined.
378    ClangPersistentVariables   *m_persistent_vars;          ///< The list of persistent variables to use when resolving symbols in the expression and when creating new ones (like the result).
379    off_t                       m_struct_alignment;         ///< The alignment of the struct in bytes.
380    size_t                      m_struct_size;              ///< The size of the struct in bytes.
381    bool                        m_struct_laid_out;          ///< True if the struct has been laid out and the layout is valid (that is, no new fields have been added since).
382    bool                        m_enable_lookups;           ///< Set to true during expression evaluation if we have found the first "$__lldb" name.
383    lldb::addr_t                m_allocated_area;           ///< The base of the memory allocated for the struct.  Starts on a potentially unaligned address and may therefore be larger than the struct.
384    lldb::addr_t                m_materialized_location;    ///< The address at which the struct is placed.  Falls inside the allocated area.
385    ConstString                 m_result_name;              ///< The name of the result variable ($1, for example)
386    TypeFromUser                m_object_pointer_type;      ///< The type of the "this" variable, if one exists.
387
388    llvm::DenseMap <const char*, bool>  m_lookedup_types;   ///< Contains each type that has been looked up in the current type lookup stack.
389                                                            ///< m_lookedup_types is used to gate the type search in GetDecls().  If a name is
390                                                            ///< not in it, the following procedure occurs:
391                                                            ///<   1 The name is added to m_lookedup_types.
392                                                            ///<   2 The type is looked up and added, potentially causing more type loookups.
393                                                            ///<   3 The name is removed from m_lookedup_types.
394                                                            ///< There must be no non-fatal error path that permits the type search to complete
395                                                            ///< without removing the name from m_lookedup_types at the end.
396                                                            ///< m_lookedup_type assumes single threadedness.
397
398    //------------------------------------------------------------------
399    /// Given a stack frame, find a variable that matches the given name and
400    /// type.  We need this for expression re-use; we may not always get the
401    /// same lldb::Variable back, and we want the expression to work wherever
402    /// it can.  Returns the variable defined in the tightest scope.
403    ///
404    /// @param[in] frame
405    ///     The stack frame to use as a basis for finding the variable.
406    ///
407    /// @param[in] name
408    ///     The name as a plain C string.
409    ///
410    /// @param[in] type
411    ///     The required type for the variable.  This function may be called
412    ///     during parsing, in which case we don't know its type; hence the
413    ///     default.
414    ///
415    /// @return
416    ///     The LLDB Variable found, or NULL if none was found.
417    //------------------------------------------------------------------
418    Variable *FindVariableInScope(StackFrame &frame,
419                                  const ConstString &name,
420                                  TypeFromUser *type = NULL);
421
422    //------------------------------------------------------------------
423    /// Get the value of a variable in a given execution context and return
424    /// the associated Types if needed.
425    ///
426    /// @param[in] exe_ctx
427    ///     The execution context to look for the variable in.
428    ///
429    /// @param[in] var
430    ///     The variable to evaluate.
431    ///
432    /// @param[in] parser_ast_context
433    ///     The AST context of the parser, to store the found type in.
434    ///
435    /// @param[out] found_type
436    ///     The type of the found value, as it was found in the user process.
437    ///     This is only useful when the variable is being inspected on behalf
438    ///     of the parser, hence the default.
439    ///
440    /// @param[out] parser_type
441    ///     The type of the found value, as it was copied into the parser's
442    ///     AST context.  This is only useful when the variable is being
443    ///     inspected on behalf of the parser, hence the default.
444    ///
445    /// @param[in] decl
446    ///     The Decl to be looked up.
447    ///
448    /// @return
449    ///     The LLDB Value for the variable.
450    //------------------------------------------------------------------
451    Value *GetVariableValue(ExecutionContext &exe_ctx,
452                            Variable *var,
453                            clang::ASTContext *parser_ast_context,
454                            TypeFromUser *found_type = NULL,
455                            TypeFromParser *parser_type = NULL);
456
457    //------------------------------------------------------------------
458    /// Use the NameSearchContext to generate a Decl for the given LLDB
459    /// Variable, and put it in the Tuple list.
460    ///
461    /// @param[in] context
462    ///     The NameSearchContext to use when constructing the Decl.
463    ///
464    /// @param[in] var
465    ///     The LLDB Variable that needs a Decl.
466    //------------------------------------------------------------------
467    void AddOneVariable(NameSearchContext &context,
468                        Variable *var);
469
470    //------------------------------------------------------------------
471    /// Use the NameSearchContext to generate a Decl for the given
472    /// persistent variable, and put it in the Tuple list.
473    ///
474    /// @param[in] context
475    ///     The NameSearchContext to use when constructing the Decl.
476    ///
477    /// @param[in] pvar
478    ///     The persistent variable that needs a Decl.
479    //------------------------------------------------------------------
480    void AddOneVariable(NameSearchContext &context, ClangExpressionVariable *pvar);
481
482    //------------------------------------------------------------------
483    /// Use the NameSearchContext to generate a Decl for the given
484    /// function.  (Functions are not placed in the Tuple list.)  Can
485    /// handle both fully typed functions and generic functions.
486    ///
487    /// @param[in] context
488    ///     The NameSearchContext to use when constructing the Decl.
489    ///
490    /// @param[in] fun
491    ///     The Function that needs to be created.  If non-NULL, this is
492    ///     a fully-typed function.
493    ///
494    /// @param[in] sym
495    ///     The Symbol that corresponds to a function that needs to be
496    ///     created with generic type (unitptr_t foo(...)).
497    //------------------------------------------------------------------
498    void AddOneFunction(NameSearchContext &context, Function *fun, Symbol *sym);
499
500    //------------------------------------------------------------------
501    /// Use the NameSearchContext to generate a Decl for the given
502    /// type.  (Types are not placed in the Tuple list.)
503    ///
504    /// @param[in] context
505    ///     The NameSearchContext to use when constructing the Decl.
506    ///
507    /// @param[in] type
508    ///     The type that needs to be created.
509    ///
510    /// @param[in] add_method
511    ///     True if a method with signature void $__lldb_expr(void*)
512    ///     should be added to the C++ class type passed in
513    //------------------------------------------------------------------
514    void AddOneType(NameSearchContext &context,
515                    TypeFromUser &type,
516                    bool add_method = false);
517
518    //------------------------------------------------------------------
519    /// Actually do the task of materializing or dematerializing the struct.
520    /// Since both tasks are very similar, although ClangExpressionDeclMap
521    /// exposes two functions to the outside, both call DoMaterialize.
522    ///
523    /// @param[in] dematerialize
524    ///     True if the struct is to be dematerialized; false if it is to
525    ///     be materialized.
526    ///
527    /// @param[in] exe_ctx
528    ///     The execution context to use.
529    ///
530    /// @param[out] result
531    ///     If the struct is being dematerialized, a pointer into which the
532    ///     location of the result persistent variable is placed.  If not,
533    ///     NULL.
534    ///
535    /// @param[in] err
536    ///     An Error to populate with any messages related to
537    ///     (de)materializing the struct.
538    ///
539    /// @return
540    ///     True on success; false otherwise.
541    //------------------------------------------------------------------
542    bool DoMaterialize (bool dematerialize,
543                        ExecutionContext *exe_ctx,
544                        ClangExpressionVariable **result,
545                        Error &err);
546
547    //------------------------------------------------------------------
548    /// Actually do the task of materializing or dematerializing a persistent
549    /// variable.
550    ///
551    /// @param[in] dematerialize
552    ///     True if the variable is to be dematerialized; false if it is to
553    ///     be materialized.
554    ///
555    /// @param[in] exe_ctx
556    ///     The execution context to use.
557    ///
558    /// @param[in] name
559    ///     The name of the persistent variable.
560    ///
561    /// @param[in] addr
562    ///     The address at which to materialize the variable.
563    ///
564    /// @param[in] err
565    ///     An Error to populate with any messages related to
566    ///     (de)materializing the persistent variable.
567    ///
568    /// @return
569    ///     True on success; false otherwise.
570    //------------------------------------------------------------------
571    bool DoMaterializeOnePersistentVariable(bool dematerialize,
572                                            ExecutionContext &exe_ctx,
573                                            const ConstString &name,
574                                            lldb::addr_t addr,
575                                            Error &err);
576
577    //------------------------------------------------------------------
578    /// Actually do the task of materializing or dematerializing a
579    /// variable.
580    ///
581    /// @param[in] dematerialize
582    ///     True if the variable is to be dematerialized; false if it is to
583    ///     be materialized.
584    ///
585    /// @param[in] exe_ctx
586    ///     The execution context to use.
587    ///
588    /// @param[in] sym_ctx
589    ///     The symbol context to use (for looking the variable up).
590    ///
591    /// @param[in] name
592    ///     The name of the variable (for looking the variable up).
593    ///
594    /// @param[in] type
595    ///     The required type of the variable (for looking the variable up).
596    ///
597    /// @param[in] addr
598    ///     The address at which to materialize the variable.
599    ///
600    /// @param[in] err
601    ///     An Error to populate with any messages related to
602    ///     (de)materializing the persistent variable.
603    ///
604    /// @return
605    ///     True on success; false otherwise.
606    //------------------------------------------------------------------
607    bool DoMaterializeOneVariable(bool dematerialize,
608                                  ExecutionContext &exe_ctx,
609                                  const SymbolContext &sym_ctx,
610                                  const ConstString &name,
611                                  TypeFromUser type,
612                                  lldb::addr_t addr,
613                                  Error &err);
614};
615
616} // namespace lldb_private
617
618#endif  // liblldb_ClangExpressionDeclMap_h_
619