ClangExpressionDeclMap.h revision 8de27c761a22187ef63fb60000894be163e7285f
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    //------------------------------------------------------------------
97    /// [Used by IRForTarget] Add a variable to the list of persistent
98    ///     variables for the process.
99    ///
100    /// @param[in] decl
101    ///     The Clang declaration for the persistent variable, used for
102    ///     lookup during parsing.
103    ///
104    /// @param[in] name
105    ///     The name of the persistent variable, usually $something.
106    ///
107    /// @param[in] type
108    ///     The type of the variable, in the Clang parser's context.
109    ///
110    /// @return
111    ///     True on success; false otherwise.
112    //------------------------------------------------------------------
113    bool AddPersistentVariable (const clang::NamedDecl *decl,
114                                const ConstString &name,
115                                TypeFromParser type);
116
117    //------------------------------------------------------------------
118    /// [Used by IRForTarget] Add a variable to the struct that needs to
119    ///     be materialized each time the expression runs.
120    ///
121    /// @param[in] decl
122    ///     The Clang declaration for the variable.
123    ///
124    /// @param[in] name
125    ///     The name of the variable.
126    ///
127    /// @param[in] value
128    ///     The LLVM IR value for this variable.
129    ///
130    /// @param[in] size
131    ///     The size of the variable in bytes.
132    ///
133    /// @param[in] alignment
134    ///     The required alignment of the variable in bytes.
135    ///
136    /// @return
137    ///     True on success; false otherwise.
138    //------------------------------------------------------------------
139    bool AddValueToStruct (const clang::NamedDecl *decl,
140                           const ConstString &name,
141                           llvm::Value *value,
142                           size_t size,
143                           off_t alignment);
144
145    //------------------------------------------------------------------
146    /// [Used by IRForTarget] Finalize the struct, laying out the position
147    /// of each object in it.
148    ///
149    /// @return
150    ///     True on success; false otherwise.
151    //------------------------------------------------------------------
152    bool DoStructLayout ();
153
154    //------------------------------------------------------------------
155    /// [Used by IRForTarget] Get general information about the laid-out
156    /// struct after DoStructLayout() has been called.
157    ///
158    /// @param[out] num_elements
159    ///     The number of elements in the struct.
160    ///
161    /// @param[out] size
162    ///     The size of the struct, in bytes.
163    ///
164    /// @param[out] alignment
165    ///     The alignment of the struct, in bytes.
166    ///
167    /// @return
168    ///     True if the information could be retrieved; false otherwise.
169    //------------------------------------------------------------------
170    bool GetStructInfo (uint32_t &num_elements,
171                        size_t &size,
172                        off_t &alignment);
173
174    //------------------------------------------------------------------
175    /// [Used by IRForTarget] Get specific information about one field
176    /// of the 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    //------------------------------------------------------------------
205    bool GetStructElement (const clang::NamedDecl *&decl,
206                           llvm::Value *&value,
207                           off_t &offset,
208                           ConstString &name,
209                           uint32_t index);
210
211    //------------------------------------------------------------------
212    /// [Used by IRForTarget] Get information about a function given its
213    /// Decl.
214    ///
215    /// @param[in] decl
216    ///     The parsed Decl for the Function, as generated by ClangASTSource
217    ///     on ClangExpressionDeclMap's behalf.
218    ///
219    /// @param[out] value
220    ///     A pointer to the address where a Value for the function's address
221    ///     can be stored.  IRForTarget typically places a ConstantExpr here.
222    ///
223    /// @param[out] ptr
224    ///     The absolute address of the function in the target.
225    ///
226    /// @return
227    ///     True if the information could be retrieved; false otherwise.
228    //------------------------------------------------------------------
229    bool GetFunctionInfo (const clang::NamedDecl *decl,
230                          llvm::Value**& value,
231                          uint64_t &ptr);
232
233    //------------------------------------------------------------------
234    /// [Used by IRForTarget] Get the address of a function given nothing
235    /// but its name.  Some functions are needed but didn't get Decls made
236    /// during parsing -- specifically, sel_registerName is never called
237    /// in the generated IR but we need to call it nonetheless.
238    ///
239    /// @param[in] name
240    ///     The name of the function.
241    ///
242    /// @param[out] ptr
243    ///     The absolute address of the function in the target.
244    ///
245    /// @return
246    ///     True if the address could be retrieved; false otherwise.
247    //------------------------------------------------------------------
248    bool GetFunctionAddress (const ConstString &name,
249                             uint64_t &ptr);
250
251    //------------------------------------------------------------------
252    /// [Used by CommandObjectExpression] Materialize the entire struct
253    /// at a given address, which should be aligned as specified by
254    /// GetStructInfo().
255    ///
256    /// @param[in] exe_ctx
257    ///     The execution context at which to dump the struct.
258    ///
259    /// @param[in] struct_address
260    ///     The address at which the struct should be written.
261    ///
262    /// @param[in] error
263    ///     An Error to populate with any messages related to
264    ///     materializing the struct.
265    ///
266    /// @return
267    ///     True on success; false otherwise.
268    //------------------------------------------------------------------
269    bool Materialize(ExecutionContext *exe_ctx,
270                     lldb::addr_t &struct_address,
271                     Error &error);
272
273    //------------------------------------------------------------------
274    /// [Used by CommandObjectExpression] Get the "this" pointer
275    /// from a given execution context.
276    ///
277    /// @param[out] object_ptr
278    ///     The this pointer.
279    ///
280    /// @param[in] exe_ctx
281    ///     The execution context at which to dump the struct.
282    ///
283    /// @param[in] error
284    ///     An Error to populate with any messages related to
285    ///     finding the "this" pointer.
286    ///
287    /// @return
288    ///     True on success; false otherwise.
289    //------------------------------------------------------------------
290    bool GetObjectPointer(lldb::addr_t &object_ptr,
291                          ExecutionContext *exe_ctx,
292                          Error &error);
293
294    //------------------------------------------------------------------
295    /// [Used by CommandObjectExpression] Pretty-print a materialized
296    /// struct, which must have been materialized by Materialize(),
297    /// byte for byte on a given stream.
298    ///
299    /// @param[in] exe_ctx
300    ///     The execution context from which to read the struct.
301    ///
302    /// @param[in] s
303    ///     The stream on which to write the pretty-printed output.
304    ///
305    /// @param[in] error
306    ///     An Error to populate with any messages related to
307    ///     pretty-printing the struct.
308    ///
309    /// @return
310    ///     True on success; false otherwise.
311    //------------------------------------------------------------------
312    bool DumpMaterializedStruct(ExecutionContext *exe_ctx,
313                                Stream &s,
314                                Error &error);
315
316    //------------------------------------------------------------------
317    /// [Used by CommandObjectExpression] Deaterialize the entire struct.
318    ///
319    /// @param[in] exe_ctx
320    ///     The execution context from which to read the struct.
321    ///
322    /// @param[out] result
323    ///     A ClangExpressionVariable containing the result of the
324    ///     expression, for potential re-use.
325    ///
326    /// @param[in] error
327    ///     An Error to populate with any messages related to
328    ///     dematerializing the struct.
329    ///
330    /// @return
331    ///     True on success; false otherwise.
332    //------------------------------------------------------------------
333    bool Dematerialize(ExecutionContext *exe_ctx,
334                       ClangExpressionVariable *&result,
335                       Error &error);
336
337    //------------------------------------------------------------------
338    /// [Used by ClangASTSource] Find all entities matching a given name,
339    /// using a NameSearchContext to make Decls for them.
340    ///
341    /// @param[in] context
342    ///     The NameSearchContext that can construct Decls for this name.
343    ///
344    /// @param[in] name
345    ///     The name as a plain C string.  The NameSearchContext contains
346    ///     a DeclarationName for the name so at first the name may seem
347    ///     redundant, but ClangExpressionDeclMap operates in RTTI land so
348    ///     it can't access DeclarationName.
349    ///
350    /// @return
351    ///     True on success; false otherwise.
352    //------------------------------------------------------------------
353    void GetDecls (NameSearchContext &context,
354                   const ConstString &name);
355
356    bool
357    GetLookupsEnabled ()
358    {
359        return m_enable_lookups;
360    }
361
362    void
363    SetLookupsEnabled (bool b)
364    {
365        m_enable_lookups = b;
366    }
367
368private:
369    ClangExpressionVariableStore    m_found_entities;       ///< All entities that were looked up for the parser.
370    ClangExpressionVariableList     m_struct_members;       ///< All entities that need to be placed in the struct.
371
372    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.
373    SymbolContext               m_sym_ctx;                  ///< [owned by ClangExpressionDeclMap] The symbol context where this expression was first defined.
374    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).
375    off_t                       m_struct_alignment;         ///< The alignment of the struct in bytes.
376    size_t                      m_struct_size;              ///< The size of the struct in bytes.
377    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).
378    bool                        m_enable_lookups;           ///< Set to true during expression evaluation if we have found the first "$__lldb" name.
379    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.
380    lldb::addr_t                m_materialized_location;    ///< The address at which the struct is placed.  Falls inside the allocated area.
381    ConstString                 m_result_name;              ///< The name of the result variable ($1, for example)
382    TypeFromUser                m_object_pointer_type;      ///< The type of the "this" variable, if one exists.
383
384    llvm::DenseMap <const char*, bool>  m_lookedup_types;   ///< Contains each type that has been looked up in the current type lookup stack.
385                                                            ///< m_lookedup_types is used to gate the type search in GetDecls().  If a name is
386                                                            ///< not in it, the following procedure occurs:
387                                                            ///<   1 The name is added to m_lookedup_types.
388                                                            ///<   2 The type is looked up and added, potentially causing more type loookups.
389                                                            ///<   3 The name is removed from m_lookedup_types.
390                                                            ///< There must be no non-fatal error path that permits the type search to complete
391                                                            ///< without removing the name from m_lookedup_types at the end.
392                                                            ///< m_lookedup_type assumes single threadedness.
393
394    //------------------------------------------------------------------
395    /// Given a stack frame, find a variable that matches the given name and
396    /// type.  We need this for expression re-use; we may not always get the
397    /// same lldb::Variable back, and we want the expression to work wherever
398    /// it can.  Returns the variable defined in the tightest scope.
399    ///
400    /// @param[in] frame
401    ///     The stack frame to use as a basis for finding the variable.
402    ///
403    /// @param[in] name
404    ///     The name as a plain C string.
405    ///
406    /// @param[in] type
407    ///     The required type for the variable.  This function may be called
408    ///     during parsing, in which case we don't know its type; hence the
409    ///     default.
410    ///
411    /// @return
412    ///     The LLDB Variable found, or NULL if none was found.
413    //------------------------------------------------------------------
414    Variable *FindVariableInScope(StackFrame &frame,
415                                  const ConstString &name,
416                                  TypeFromUser *type = NULL);
417
418    //------------------------------------------------------------------
419    /// Get the value of a variable in a given execution context and return
420    /// the associated Types if needed.
421    ///
422    /// @param[in] exe_ctx
423    ///     The execution context to look for the variable in.
424    ///
425    /// @param[in] var
426    ///     The variable to evaluate.
427    ///
428    /// @param[in] parser_ast_context
429    ///     The AST context of the parser, to store the found type in.
430    ///
431    /// @param[out] found_type
432    ///     The type of the found value, as it was found in the user process.
433    ///     This is only useful when the variable is being inspected on behalf
434    ///     of the parser, hence the default.
435    ///
436    /// @param[out] parser_type
437    ///     The type of the found value, as it was copied into the parser's
438    ///     AST context.  This is only useful when the variable is being
439    ///     inspected on behalf of the parser, hence the default.
440    ///
441    /// @param[in] decl
442    ///     The Decl to be looked up.
443    ///
444    /// @return
445    ///     The LLDB Value for the variable.
446    //------------------------------------------------------------------
447    Value *GetVariableValue(ExecutionContext &exe_ctx,
448                            Variable *var,
449                            clang::ASTContext *parser_ast_context,
450                            TypeFromUser *found_type = NULL,
451                            TypeFromParser *parser_type = NULL);
452
453    //------------------------------------------------------------------
454    /// Use the NameSearchContext to generate a Decl for the given LLDB
455    /// Variable, and put it in the Tuple list.
456    ///
457    /// @param[in] context
458    ///     The NameSearchContext to use when constructing the Decl.
459    ///
460    /// @param[in] var
461    ///     The LLDB Variable that needs a Decl.
462    //------------------------------------------------------------------
463    void AddOneVariable(NameSearchContext &context,
464                        Variable *var);
465
466    //------------------------------------------------------------------
467    /// Use the NameSearchContext to generate a Decl for the given
468    /// persistent variable, and put it in the Tuple list.
469    ///
470    /// @param[in] context
471    ///     The NameSearchContext to use when constructing the Decl.
472    ///
473    /// @param[in] pvar
474    ///     The persistent variable that needs a Decl.
475    //------------------------------------------------------------------
476    void AddOneVariable(NameSearchContext &context, ClangExpressionVariable *pvar);
477
478    //------------------------------------------------------------------
479    /// Use the NameSearchContext to generate a Decl for the given
480    /// function.  (Functions are not placed in the Tuple list.)  Can
481    /// handle both fully typed functions and generic functions.
482    ///
483    /// @param[in] context
484    ///     The NameSearchContext to use when constructing the Decl.
485    ///
486    /// @param[in] fun
487    ///     The Function that needs to be created.  If non-NULL, this is
488    ///     a fully-typed function.
489    ///
490    /// @param[in] sym
491    ///     The Symbol that corresponds to a function that needs to be
492    ///     created with generic type (unitptr_t foo(...)).
493    //------------------------------------------------------------------
494    void AddOneFunction(NameSearchContext &context, Function *fun, Symbol *sym);
495
496    //------------------------------------------------------------------
497    /// Use the NameSearchContext to generate a Decl for the given
498    /// type.  (Types are not placed in the Tuple list.)
499    ///
500    /// @param[in] context
501    ///     The NameSearchContext to use when constructing the Decl.
502    ///
503    /// @param[in] type
504    ///     The type that needs to be created.
505    ///
506    /// @param[in] add_method
507    ///     True if a method with signature void $__lldb_expr(void*)
508    ///     should be added to the C++ class type passed in
509    //------------------------------------------------------------------
510    void AddOneType(NameSearchContext &context,
511                    TypeFromUser &type,
512                    bool add_method = false);
513
514    //------------------------------------------------------------------
515    /// Actually do the task of materializing or dematerializing the struct.
516    /// Since both tasks are very similar, although ClangExpressionDeclMap
517    /// exposes two functions to the outside, both call DoMaterialize.
518    ///
519    /// @param[in] dematerialize
520    ///     True if the struct is to be dematerialized; false if it is to
521    ///     be materialized.
522    ///
523    /// @param[in] exe_ctx
524    ///     The execution context to use.
525    ///
526    /// @param[out] result
527    ///     If the struct is being dematerialized, a pointer into which the
528    ///     location of the result persistent variable is placed.  If not,
529    ///     NULL.
530    ///
531    /// @param[in] err
532    ///     An Error to populate with any messages related to
533    ///     (de)materializing the struct.
534    ///
535    /// @return
536    ///     True on success; false otherwise.
537    //------------------------------------------------------------------
538    bool DoMaterialize (bool dematerialize,
539                        ExecutionContext *exe_ctx,
540                        ClangExpressionVariable **result,
541                        Error &err);
542
543    //------------------------------------------------------------------
544    /// Actually do the task of materializing or dematerializing a persistent
545    /// variable.
546    ///
547    /// @param[in] dematerialize
548    ///     True if the variable is to be dematerialized; false if it is to
549    ///     be materialized.
550    ///
551    /// @param[in] exe_ctx
552    ///     The execution context to use.
553    ///
554    /// @param[in] name
555    ///     The name of the persistent variable.
556    ///
557    /// @param[in] addr
558    ///     The address at which to materialize the variable.
559    ///
560    /// @param[in] err
561    ///     An Error to populate with any messages related to
562    ///     (de)materializing the persistent variable.
563    ///
564    /// @return
565    ///     True on success; false otherwise.
566    //------------------------------------------------------------------
567    bool DoMaterializeOnePersistentVariable(bool dematerialize,
568                                            ExecutionContext &exe_ctx,
569                                            const ConstString &name,
570                                            lldb::addr_t addr,
571                                            Error &err);
572
573    //------------------------------------------------------------------
574    /// Actually do the task of materializing or dematerializing a
575    /// variable.
576    ///
577    /// @param[in] dematerialize
578    ///     True if the variable is to be dematerialized; false if it is to
579    ///     be materialized.
580    ///
581    /// @param[in] exe_ctx
582    ///     The execution context to use.
583    ///
584    /// @param[in] sym_ctx
585    ///     The symbol context to use (for looking the variable up).
586    ///
587    /// @param[in] name
588    ///     The name of the variable (for looking the variable up).
589    ///
590    /// @param[in] type
591    ///     The required type of the variable (for looking the variable up).
592    ///
593    /// @param[in] addr
594    ///     The address at which to materialize the variable.
595    ///
596    /// @param[in] err
597    ///     An Error to populate with any messages related to
598    ///     (de)materializing the persistent variable.
599    ///
600    /// @return
601    ///     True on success; false otherwise.
602    //------------------------------------------------------------------
603    bool DoMaterializeOneVariable(bool dematerialize,
604                                  ExecutionContext &exe_ctx,
605                                  const SymbolContext &sym_ctx,
606                                  const ConstString &name,
607                                  TypeFromUser type,
608                                  lldb::addr_t addr,
609                                  Error &err);
610};
611
612} // namespace lldb_private
613
614#endif  // liblldb_ClangExpressionDeclMap_h_
615