IRForTarget.h revision 9b6898f3ec1dedbe1dfc8bd7cd1d82a5b10e1bb0
1//===-- IRForTarget.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_IRForTarget_h_
11#define liblldb_IRForTarget_h_
12
13#include "lldb/lldb-public.h"
14#include "lldb/Core/ConstString.h"
15#include "lldb/Core/Stream.h"
16#include "lldb/Symbol/TaggedASTType.h"
17#include "llvm/Pass.h"
18
19namespace llvm {
20    class BasicBlock;
21    class CallInst;
22    class Constant;
23    class ConstantInt;
24    class Function;
25    class GlobalValue;
26    class GlobalVariable;
27    class Instruction;
28    class Module;
29    class StoreInst;
30    class Type;
31    class Value;
32}
33
34namespace lldb_private {
35    class ClangExpressionDeclMap;
36}
37
38//----------------------------------------------------------------------
39/// @class IRForTarget IRForTarget.h "lldb/Expression/IRForTarget.h"
40/// @brief Transforms the IR for a function to run in the target
41///
42/// Once an expression has been parsed and converted to IR, it can run
43/// in two contexts: interpreted by LLDB as a DWARF location expression,
44/// or compiled by the JIT and inserted into the target process for
45/// execution.
46///
47/// IRForTarget makes the second possible, by applying a series of
48/// transformations to the IR which make it relocatable.  These
49/// transformations are discussed in more detail next to their relevant
50/// functions.
51//----------------------------------------------------------------------
52class IRForTarget : public llvm::ModulePass
53{
54public:
55    class StaticDataAllocator {
56    public:
57        StaticDataAllocator();
58        virtual ~StaticDataAllocator();
59        virtual lldb_private::StreamString &GetStream() = 0;
60        virtual lldb::addr_t Allocate() = 0;
61    };
62
63    //------------------------------------------------------------------
64    /// Constructor
65    ///
66    /// @param[in] decl_map
67    ///     The list of externally-referenced variables for the expression,
68    ///     for use in looking up globals and allocating the argument
69    ///     struct.  See the documentation for ClangExpressionDeclMap.
70    ///
71    /// @param[in] resolve_vars
72    ///     True if the external variable references (including persistent
73    ///     variables) should be resolved.  If not, only external functions
74    ///     are resolved.
75    ///
76    /// @param[in] const_result
77    ///     This variable is populated with the statically-computed result
78    ///     of the function, if it has no side-effects and the result can
79    ///     be computed statically.
80    ///
81    /// @param[in] data_allocator
82    ///     If non-NULL, the static data allocator to use for literal strings.
83    ///
84    /// @param[in] error_stream
85    ///     If non-NULL, a stream on which errors can be printed.
86    ///
87    /// @param[in] func_name
88    ///     The name of the function to prepare for execution in the target.
89    //------------------------------------------------------------------
90    IRForTarget(lldb_private::ClangExpressionDeclMap *decl_map,
91                bool resolve_vars,
92                lldb::ClangExpressionVariableSP &const_result,
93                StaticDataAllocator *data_allocator,
94                lldb_private::Stream *error_stream,
95                const char* func_name = "$__lldb_expr");
96
97    //------------------------------------------------------------------
98    /// Destructor
99    //------------------------------------------------------------------
100    virtual ~IRForTarget();
101
102    //------------------------------------------------------------------
103    /// Run this IR transformer on a single module
104    ///
105    /// Implementation of the llvm::ModulePass::runOnModule() function.
106    ///
107    /// @param[in] llvm_module
108    ///     The module to run on.  This module is searched for the function
109    ///     $__lldb_expr, and that function is passed to the passes one by
110    ///     one.
111    ///
112    /// @return
113    ///     True on success; false otherwise
114    //------------------------------------------------------------------
115    virtual bool
116    runOnModule (llvm::Module &llvm_module);
117
118    //------------------------------------------------------------------
119    /// Interface stub
120    ///
121    /// Implementation of the llvm::ModulePass::assignPassManager()
122    /// function.
123    //------------------------------------------------------------------
124    virtual void
125    assignPassManager (llvm::PMStack &pass_mgr_stack,
126                       llvm::PassManagerType pass_mgr_type = llvm::PMT_ModulePassManager);
127
128    //------------------------------------------------------------------
129    /// Returns PMT_ModulePassManager
130    ///
131    /// Implementation of the llvm::ModulePass::getPotentialPassManagerType()
132    /// function.
133    //------------------------------------------------------------------
134    virtual llvm::PassManagerType
135    getPotentialPassManagerType() const;
136
137private:
138    //------------------------------------------------------------------
139    /// Ensures that the current function's linkage is set to external.
140    /// Otherwise the JIT may not return an address for it.
141    ///
142    /// @param[in] llvm_function
143    ///     The function whose linkage is to be fixed.
144    ///
145    /// @return
146    ///     True on success; false otherwise.
147    //------------------------------------------------------------------
148    bool
149    FixFunctionLinkage (llvm::Function &llvm_function);
150
151    //------------------------------------------------------------------
152    /// A function-level pass to check whether the function has side
153    /// effects.
154    //------------------------------------------------------------------
155
156    //------------------------------------------------------------------
157    /// The top-level pass implementation
158    ///
159    /// @param[in] llvm_function
160    ///     The function currently being processed.
161    ///
162    /// @return
163    ///     True if the function has side effects (or if this cannot
164    ///     be determined); false otherwise.
165    //------------------------------------------------------------------
166    bool
167    HasSideEffects (llvm::Function &llvm_function);
168
169    //------------------------------------------------------------------
170    /// A function-level pass to take the generated global value
171    /// $__lldb_expr_result and make it into a persistent variable.
172    /// Also see ASTResultSynthesizer.
173    //------------------------------------------------------------------
174
175    //------------------------------------------------------------------
176    /// Set the constant result variable m_const_result to the provided
177    /// constant, assuming it can be evaluated.  The result variable
178    /// will be reset to NULL later if the expression has side effects.
179    ///
180    /// @param[in] global
181    ///     The global entity to search for
182    ///
183    /// @return
184    ///     The corresponding variable declaration
185    //------------------------------------------------------------------
186    clang::NamedDecl *
187    DeclForGlobal (llvm::GlobalValue *global);
188
189    //------------------------------------------------------------------
190    /// Set the constant result variable m_const_result to the provided
191    /// constant, assuming it can be evaluated.  The result variable
192    /// will be reset to NULL later if the expression has side effects.
193    ///
194    /// @param[in] initializer
195    ///     The constant initializer for the variable.
196    ///
197    /// @param[in] name
198    ///     The name of the result variable.
199    ///
200    /// @param[in] type
201    ///     The Clang type of the result variable.
202    //------------------------------------------------------------------
203    void
204    MaybeSetConstantResult (llvm::Constant *initializer,
205                            const lldb_private::ConstString &name,
206                            lldb_private::TypeFromParser type);
207
208    //------------------------------------------------------------------
209    /// If the IR represents a cast of a variable, set m_const_result
210    /// to the result of the cast.  The result variable will be reset to
211    /// NULL latger if the expression has side effects.
212    ///
213    /// @param[in] type
214    ///     The Clang type of the result variable.
215    //------------------------------------------------------------------
216    void
217    MaybeSetCastResult (lldb_private::TypeFromParser type);
218
219    //------------------------------------------------------------------
220    /// The top-level pass implementation
221    ///
222    /// @param[in] llvm_function
223    ///     The function currently being processed.
224    ///
225    /// @return
226    ///     True on success; false otherwise
227    //------------------------------------------------------------------
228    bool
229    CreateResultVariable (llvm::Function &llvm_function);
230
231    //------------------------------------------------------------------
232    /// A function-level pass to find Objective-C constant strings and
233    /// transform them to calls to CFStringCreateWithBytes.
234    //------------------------------------------------------------------
235
236    //------------------------------------------------------------------
237    /// Rewrite a single Objective-C constant string.
238    ///
239    /// @param[in] NSStr
240    ///     The constant NSString to be transformed
241    ///
242    /// @param[in] CStr
243    ///     The constant C string inside the NSString.  This will be
244    ///     passed as the bytes argument to CFStringCreateWithBytes.
245    ///
246    /// @param[in] FirstEntryInstruction
247    ///     An instruction early in the execution of the function.
248    ///     When this function synthesizes a call to
249    ///     CFStringCreateWithBytes, it places the call before this
250    ///     instruction.  The instruction should come before all
251    ///     uses of the NSString.
252    ///
253    /// @return
254    ///     True on success; false otherwise
255    //------------------------------------------------------------------
256    bool
257    RewriteObjCConstString (llvm::GlobalVariable *NSStr,
258                            llvm::GlobalVariable *CStr,
259                            llvm::Instruction *FirstEntryInstruction);
260
261    //------------------------------------------------------------------
262    /// The top-level pass implementation
263    ///
264    /// @param[in] llvm_function
265    ///     The function currently being processed.
266    ///
267    /// @return
268    ///     True on success; false otherwise
269    //------------------------------------------------------------------
270    bool
271    RewriteObjCConstStrings (llvm::Function &llvm_function);
272
273    //------------------------------------------------------------------
274    /// A basic block-level pass to find all Objective-C method calls and
275    /// rewrite them to use sel_registerName instead of statically allocated
276    /// selectors.  The reason is that the selectors are created on the
277    /// assumption that the Objective-C runtime will scan the appropriate
278    /// section and prepare them.  This doesn't happen when code is copied
279    /// into the target, though, and there's no easy way to induce the
280    /// runtime to scan them.  So instead we get our selectors from
281    /// sel_registerName.
282    //------------------------------------------------------------------
283
284    //------------------------------------------------------------------
285    /// Replace a single selector reference
286    ///
287    /// @param[in] selector_load
288    ///     The load of the statically-allocated selector.
289    ///
290    /// @return
291    ///     True on success; false otherwise
292    //------------------------------------------------------------------
293    bool
294    RewriteObjCSelector (llvm::Instruction* selector_load);
295
296    //------------------------------------------------------------------
297    /// The top-level pass implementation
298    ///
299    /// @param[in] basic_block
300    ///     The basic block currently being processed.
301    ///
302    /// @return
303    ///     True on success; false otherwise
304    //------------------------------------------------------------------
305    bool
306    RewriteObjCSelectors (llvm::BasicBlock &basic_block);
307
308    //------------------------------------------------------------------
309    /// A basic block-level pass to find all newly-declared persistent
310    /// variables and register them with the ClangExprDeclMap.  This
311    /// allows them to be materialized and dematerialized like normal
312    /// external variables.  Before transformation, these persistent
313    /// variables look like normal locals, so they have an allocation.
314    /// This pass excises these allocations and makes references look
315    /// like external references where they will be resolved -- like all
316    /// other external references -- by ResolveExternals().
317    //------------------------------------------------------------------
318
319    //------------------------------------------------------------------
320    /// Handle a single allocation of a persistent variable
321    ///
322    /// @param[in] persistent_alloc
323    ///     The allocation of the persistent variable.
324    ///
325    /// @return
326    ///     True on success; false otherwise
327    //------------------------------------------------------------------
328    bool
329    RewritePersistentAlloc (llvm::Instruction *persistent_alloc);
330
331    //------------------------------------------------------------------
332    /// The top-level pass implementation
333    ///
334    /// @param[in] basic_block
335    ///     The basic block currently being processed.
336    //------------------------------------------------------------------
337    bool
338    RewritePersistentAllocs (llvm::BasicBlock &basic_block);
339
340    //------------------------------------------------------------------
341    /// A function-level pass to find all external variables and functions
342    /// used in the IR.  Each found external variable is added to the
343    /// struct, and each external function is resolved in place, its call
344    /// replaced with a call to a function pointer whose value is the
345    /// address of the function in the target process.
346    //------------------------------------------------------------------
347
348    //------------------------------------------------------------------
349    /// Handle a single externally-defined variable
350    ///
351    /// @param[in] value
352    ///     The variable.
353    ///
354    /// @return
355    ///     True on success; false otherwise
356    //------------------------------------------------------------------
357    bool
358    MaybeHandleVariable (llvm::Value *value);
359
360    //------------------------------------------------------------------
361    /// Handle a single externally-defined symbol
362    ///
363    /// @param[in] symbol
364    ///     The symbol.
365    ///
366    /// @return
367    ///     True on success; false otherwise
368    //------------------------------------------------------------------
369    bool
370    HandleSymbol (llvm::Value *symbol);
371
372    //------------------------------------------------------------------
373    /// Handle all the arguments to a function call
374    ///
375    /// @param[in] C
376    ///     The call instruction.
377    ///
378    /// @return
379    ///     True on success; false otherwise
380    //------------------------------------------------------------------
381    bool
382    MaybeHandleCallArguments (llvm::CallInst *call_inst);
383
384    //------------------------------------------------------------------
385    /// Handle a single external function call
386    ///
387    /// @param[in] C
388    ///     The call instruction.
389    ///
390    /// @return
391    ///     True on success; false otherwise
392    //------------------------------------------------------------------
393    bool
394    MaybeHandleCall (llvm::CallInst *C);
395
396    //------------------------------------------------------------------
397    /// Resolve calls to external functions
398    ///
399    /// @param[in] basic_block
400    ///     The basic block currently being processed.
401    ///
402    /// @return
403    ///     True on success; false otherwise
404    //------------------------------------------------------------------
405    bool
406    ResolveCalls (llvm::BasicBlock &basic_block);
407
408    //------------------------------------------------------------------
409    /// The top-level pass implementation
410    ///
411    /// @param[in] basic_block
412    ///     The function currently being processed.
413    ///
414    /// @return
415    ///     True on success; false otherwise
416    //------------------------------------------------------------------
417    bool
418    ResolveExternals (llvm::Function &llvm_function);
419
420    //------------------------------------------------------------------
421    /// A basic block-level pass to excise guard variables from the code.
422    /// The result for the function is passed through Clang as a static
423    /// variable.  Static variables normally have guard variables to
424    /// ensure that they are only initialized once.
425    //------------------------------------------------------------------
426
427    //------------------------------------------------------------------
428    /// Rewrite a load to a guard variable to return constant 0.
429    ///
430    /// @param[in] guard_load
431    ///     The load instruction to zero out.
432    //------------------------------------------------------------------
433    void
434    TurnGuardLoadIntoZero(llvm::Instruction* guard_load);
435
436    //------------------------------------------------------------------
437    /// The top-level pass implementation
438    ///
439    /// @param[in] basic_block
440    ///     The basic block currently being processed.
441    ///
442    /// @return
443    ///     True on success; false otherwise
444    //------------------------------------------------------------------
445    bool
446    RemoveGuards (llvm::BasicBlock &basic_block);
447
448    //------------------------------------------------------------------
449    /// A module-level pass to allocate all string literals in a separate
450    /// allocation and redirect references to them.
451    //------------------------------------------------------------------
452
453    //------------------------------------------------------------------
454    /// The top-level pass implementation
455    ///
456    /// @return
457    ///     True on success; false otherwise
458    //------------------------------------------------------------------
459    bool
460    ReplaceStrings ();
461
462    //------------------------------------------------------------------
463    /// A basick block-level pass to find all literals that will be
464    /// allocated as statics by the JIT (in contrast to the Strings,
465    /// which already are statics) and synthesize loads for them.
466    //------------------------------------------------------------------
467
468    //------------------------------------------------------------------
469    /// The top-level pass implementation
470    ///
471    /// @param[in] basic_block
472    ///     The basic block currently being processed.
473    ///
474    /// @return
475    ///     True on success; false otherwise
476    //------------------------------------------------------------------
477    bool
478    ReplaceStaticLiterals (llvm::BasicBlock &basic_block);
479
480    //------------------------------------------------------------------
481    /// A function-level pass to make all external variable references
482    /// point at the correct offsets from the void* passed into the
483    /// function.  ClangExpressionDeclMap::DoStructLayout() must be called
484    /// beforehand, so that the offsets are valid.
485    //------------------------------------------------------------------
486
487    //------------------------------------------------------------------
488    /// The top-level pass implementation
489    ///
490    /// @param[in] llvm_function
491    ///     The function currently being processed.
492    ///
493    /// @return
494    ///     True on success; false otherwise
495    //------------------------------------------------------------------
496    bool
497    ReplaceVariables (llvm::Function &llvm_function);
498
499    /// Flags
500    bool                                    m_resolve_vars;             ///< True if external variable references and persistent variable references should be resolved
501    std::string                             m_func_name;                ///< The name of the function to translate
502    lldb_private::ConstString               m_result_name;              ///< The name of the result variable ($0, $1, ...)
503    llvm::Module                           *m_module;                   ///< The module being processed, or NULL if that has not been determined yet.
504    lldb_private::ClangExpressionDeclMap   *m_decl_map;                 ///< The DeclMap containing the Decls
505    StaticDataAllocator                    *m_data_allocator;           ///< If non-NULL, the allocator to use for constant strings
506    llvm::Constant                         *m_CFStringCreateWithBytes;  ///< The address of the function CFStringCreateWithBytes, cast to the appropriate function pointer type
507    llvm::Constant                         *m_sel_registerName;         ///< The address of the function sel_registerName, cast to the appropriate function pointer type
508    lldb::ClangExpressionVariableSP        &m_const_result;             ///< This value should be set to the return value of the expression if it is constant and the expression has no side effects
509    lldb_private::Stream                   *m_error_stream;             ///< If non-NULL, the stream on which errors should be printed
510
511    bool                                    m_has_side_effects;         ///< True if the function's result cannot be simply determined statically
512    llvm::StoreInst                        *m_result_store;             ///< If non-NULL, the store instruction that writes to the result variable.  If m_has_side_effects is true, this is NULL.
513    bool                                    m_result_is_pointer;        ///< True if the function's result in the AST is a pointer (see comments in ASTResultSynthesizer::SynthesizeBodyResult)
514
515    llvm::GlobalVariable                   *m_reloc_placeholder;        ///< A placeholder that will be replaced by a pointer to the final location of the static allocation.
516
517    //------------------------------------------------------------------
518    /// UnfoldConstant operates on a constant [Old] which has just been
519    /// replaced with a value [New].  We assume that new_value has
520    /// been properly placed early in the function, in front of the
521    /// first instruction in the entry basic block
522    /// [FirstEntryInstruction].
523    ///
524    /// UnfoldConstant reads through the uses of Old and replaces Old
525    /// in those uses with New.  Where those uses are constants, the
526    /// function generates new instructions to compute the result of the
527    /// new, non-constant expression and places them before
528    /// FirstEntryInstruction.  These instructions replace the constant
529    /// uses, so UnfoldConstant calls itself recursively for those.
530    ///
531    /// @param[in] llvm_function
532    ///     The function currently being processed.
533    ///
534    /// @return
535    ///     True on success; false otherwise
536    //------------------------------------------------------------------
537    static bool
538    UnfoldConstant (llvm::Constant *old_constant,
539                    llvm::Value *new_constant,
540                    llvm::Instruction *first_entry_inst);
541
542    //------------------------------------------------------------------
543    /// Construct a reference to m_reloc_placeholder with a given type
544    /// and offset.  This typically happens after inserting data into
545    /// m_data_allocator.
546    ///
547    /// @param[in] type
548    ///     The type of the value being loaded.
549    ///
550    /// @param[in] offset
551    ///     The offset of the value from the base of m_data_allocator.
552    ///
553    /// @return
554    ///     The Constant for the reference, usually a ConstantExpr.
555    //------------------------------------------------------------------
556    llvm::Constant *
557    BuildRelocation(llvm::Type *type,
558                    uint64_t offset);
559
560    //------------------------------------------------------------------
561    /// Commit the allocation in m_data_allocator and use its final
562    /// location to replace m_reloc_placeholder.
563    ///
564    /// @param[in] module
565    ///     The module that m_data_allocator resides in
566    ///
567    /// @return
568    ///     True on success; false otherwise
569    //------------------------------------------------------------------
570    bool
571    CompleteDataAllocation ();
572
573};
574
575#endif
576