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