LLDB mainline
IRForTarget.h
Go to the documentation of this file.
1//===-- IRForTarget.h ---------------------------------------------*- C++
2//-*-===//
3//
4// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
5// See https://llvm.org/LICENSE.txt for license information.
6// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7//
8//===----------------------------------------------------------------------===//
9
10#ifndef LLDB_SOURCE_PLUGINS_EXPRESSIONPARSER_CLANG_IRFORTARGET_H
11#define LLDB_SOURCE_PLUGINS_EXPRESSIONPARSER_CLANG_IRFORTARGET_H
12
15#include "lldb/Utility/Status.h"
16#include "lldb/Utility/Stream.h"
18#include "lldb/lldb-public.h"
19#include "llvm/IR/DerivedTypes.h"
20#include "llvm/Pass.h"
21
22#include <functional>
23#include <map>
24
25namespace llvm {
26class BasicBlock;
27class CallInst;
28class Constant;
29class ConstantInt;
30class Function;
31class GlobalValue;
32class GlobalVariable;
33class Instruction;
34class Module;
35class StoreInst;
36class DataLayout;
37class Value;
38}
39
40namespace clang {
41class NamedDecl;
42}
43
44namespace lldb_private {
46class IRExecutionUnit;
47class IRMemoryMap;
48}
49
50/// \class IRForTarget IRForTarget.h "lldb/Expression/IRForTarget.h"
51/// Transforms the IR for a function to run in the target
52///
53/// Once an expression has been parsed and converted to IR, it can run in two
54/// contexts: interpreted by LLDB as a DWARF location expression, or compiled
55/// by the JIT and inserted into the target process for 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.
62public:
63 enum class LookupResult { Success, Fail, Ignore };
64
65 /// Constructor
66 ///
67 /// \param[in] decl_map
68 /// The list of externally-referenced variables for the expression,
69 /// for use in looking up globals and allocating the argument
70 /// struct. See the documentation for ClangExpressionDeclMap.
71 ///
72 /// \param[in] resolve_vars
73 /// True if the external variable references (including persistent
74 /// variables) should be resolved. If not, only external functions
75 /// are resolved.
76 ///
77 /// \param[in] execution_unit
78 /// The holder for raw data associated with the expression.
79 ///
80 /// \param[in] error_stream
81 /// If non-NULL, a stream on which errors can be printed.
82 ///
83 /// \param[in] func_name
84 /// The name of the function to prepare for execution in the target.
85 IRForTarget(lldb_private::ClangExpressionDeclMap *decl_map, bool resolve_vars,
86 lldb_private::IRExecutionUnit &execution_unit,
87 lldb_private::Stream &error_stream,
88 lldb_private::ExecutionPolicy execution_policy,
89 const char *func_name = "$__lldb_expr");
90
91 /// Run this IR transformer on a single module
92 ///
93 /// Implementation of the llvm::ModulePass::runOnModule() function.
94 ///
95 /// \param[in] llvm_module
96 /// The module to run on. This module is searched for the function
97 /// $__lldb_expr, and that function is passed to the passes one by
98 /// one.
99 ///
100 /// \return
101 /// True on success; false otherwise
102 bool runOnModule(llvm::Module &llvm_module);
103
104private:
105 /// Ensures that the current function's linkage is set to external.
106 /// Otherwise the JIT may not return an address for it.
107 ///
108 /// \param[in] llvm_function
109 /// The function whose linkage is to be fixed.
110 ///
111 /// \return
112 /// True on success; false otherwise.
113 bool FixFunctionLinkage(llvm::Function &llvm_function);
114
115 /// A function-level pass to take the generated global value
116 /// $__lldb_expr_result and make it into a persistent variable. Also see
117 /// ASTResultSynthesizer.
118
119 /// Find the NamedDecl corresponding to a Value. This interface is exposed
120 /// for the IR interpreter.
121 ///
122 /// \param[in] global_val
123 /// The global entity to search for
124 ///
125 /// \param[in] module
126 /// The module containing metadata to search
127 ///
128 /// \return
129 /// The corresponding variable declaration
130public:
131 static clang::NamedDecl *DeclForGlobal(const llvm::GlobalValue *global_val,
132 llvm::Module *module);
133
134private:
135 clang::NamedDecl *DeclForGlobal(llvm::GlobalValue *global);
136
137 /// The top-level pass implementation
138 ///
139 /// \param[in] llvm_function
140 /// The function currently being processed.
141 ///
142 /// \return
143 /// True on success; false otherwise
144 bool CreateResultVariable(llvm::Function &llvm_function);
145
146 /// A module-level pass to find Objective-C constant strings and
147 /// transform them to calls to CFStringCreateWithBytes.
148
149 /// Rewrite a single Objective-C constant string.
150 ///
151 /// \param[in] NSStr
152 /// The constant NSString to be transformed
153 ///
154 /// \param[in] CStr
155 /// The constant C string inside the NSString. This will be
156 /// passed as the bytes argument to CFStringCreateWithBytes.
157 ///
158 /// \return
159 /// True on success; false otherwise
160 bool RewriteObjCConstString(llvm::GlobalVariable *NSStr,
161 llvm::GlobalVariable *CStr);
162
163 /// The top-level pass implementation
164 ///
165 /// \return
166 /// True on success; false otherwise
168
169 /// A basic block-level pass to find all Objective-C method calls and
170 /// rewrite them to use sel_registerName instead of statically allocated
171 /// selectors. The reason is that the selectors are created on the
172 /// assumption that the Objective-C runtime will scan the appropriate
173 /// section and prepare them. This doesn't happen when code is copied into
174 /// the target, though, and there's no easy way to induce the runtime to
175 /// scan them. So instead we get our selectors from sel_registerName.
176
177 /// Replace a single selector reference
178 ///
179 /// \param[in] selector_load
180 /// The load of the statically-allocated selector.
181 ///
182 /// \return
183 /// True on success; false otherwise
184 bool RewriteObjCSelector(llvm::Instruction *selector_load);
185
186 /// The top-level pass implementation
187 ///
188 /// \param[in] basic_block
189 /// The basic block currently being processed.
190 ///
191 /// \return
192 /// True on success; false otherwise
193 bool RewriteObjCSelectors(llvm::BasicBlock &basic_block);
194
195 /// A basic block-level pass to find all newly-declared persistent
196 /// variables and register them with the ClangExprDeclMap. This allows them
197 /// to be materialized and dematerialized like normal external variables.
198 /// Before transformation, these persistent variables look like normal
199 /// locals, so they have an allocation. This pass excises these allocations
200 /// and makes references look like external references where they will be
201 /// resolved -- like all other external references -- by ResolveExternals().
202
203 /// Handle a single allocation of a persistent variable
204 ///
205 /// \param[in] persistent_alloc
206 /// The allocation of the persistent variable.
207 ///
208 /// \return
209 /// True on success; false otherwise
210 bool RewritePersistentAlloc(llvm::Instruction *persistent_alloc);
211
212 /// The top-level pass implementation
213 ///
214 /// \param[in] basic_block
215 /// The basic block currently being processed.
216 bool RewritePersistentAllocs(llvm::BasicBlock &basic_block);
217
218 /// A function-level pass to find all external variables and functions
219 /// used in the IR. Each found external variable is added to the struct,
220 /// and each external function is resolved in place, its call replaced with
221 /// a call to a function pointer whose value is the address of the function
222 /// in the target process.
223
224 /// Handle a single externally-defined variable
225 ///
226 /// \param[in] value
227 /// The variable.
228 ///
229 /// \return
230 /// True on success; false otherwise
231 bool MaybeHandleVariable(llvm::Value *value);
232
233 /// Handle a single externally-defined symbol
234 ///
235 /// \param[in] symbol
236 /// The symbol.
237 ///
238 /// \return
239 /// True on success; false otherwise
240 bool HandleSymbol(llvm::Value *symbol);
241
242 /// Handle a single externally-defined Objective-C class
243 ///
244 /// \param[in] classlist_reference
245 /// The reference, usually "01L_OBJC_CLASSLIST_REFERENCES_$_n"
246 /// where n (if present) is an index.
247 ///
248 /// \return
249 /// True on success; false otherwise
250 bool HandleObjCClass(llvm::Value *classlist_reference);
251
252 /// Handle all the arguments to a function call
253 ///
254 /// \param[in] call_inst
255 /// The call instruction.
256 ///
257 /// \return
258 /// True on success; false otherwise
259 bool MaybeHandleCallArguments(llvm::CallInst *call_inst);
260
261 /// Resolve variable references in calls to external functions
262 ///
263 /// \param[in] basic_block
264 /// The basic block currently being processed.
265 ///
266 /// \return
267 /// True on success; false otherwise
268 bool ResolveCalls(llvm::BasicBlock &basic_block);
269
270 /// Remove calls to __cxa_atexit, which should never be generated by
271 /// expressions.
272 ///
273 /// \param[in] basic_block
274 /// The basic block currently being processed.
275 ///
276 /// \return
277 /// True if the scan was successful; false if some operation
278 /// failed
279 bool RemoveCXAAtExit(llvm::BasicBlock &basic_block);
280
281 /// The top-level pass implementation
282 ///
283 /// \param[in] llvm_function
284 /// The function currently being processed.
285 ///
286 /// \return
287 /// True on success; false otherwise
288 bool ResolveExternals(llvm::Function &llvm_function);
289
290 /// A basic block-level pass to excise guard variables from the code.
291 /// The result for the function is passed through Clang as a static
292 /// variable. Static variables normally have guard variables to ensure that
293 /// they are only initialized once.
294
295 /// Rewrite a load to a guard variable to return constant 0.
296 ///
297 /// \param[in] guard_load
298 /// The load instruction to zero out.
299 void TurnGuardLoadIntoZero(llvm::Instruction *guard_load);
300
301 /// The top-level pass implementation
302 ///
303 /// \param[in] basic_block
304 /// The basic block currently being processed.
305 ///
306 /// \return
307 /// True on success; false otherwise
308 bool RemoveGuards(llvm::BasicBlock &basic_block);
309
310 /// A function-level pass to make all external variable references
311 /// point at the correct offsets from the void* passed into the function.
312 /// ClangExpressionDeclMap::DoStructLayout() must be called beforehand, so
313 /// that the offsets are valid.
314
315 /// The top-level pass implementation
316 ///
317 /// \param[in] llvm_function
318 /// The function currently being processed.
319 ///
320 /// \return
321 /// True on success; false otherwise
322 bool ReplaceVariables(llvm::Function &llvm_function);
323
324 /// True if external variable references and persistent variable references
325 /// should be resolved
327 /// The name of the function to translate
329 /// The name of the result variable ($0, $1, ...)
331 /// The type of the result variable.
333 /// The module being processed, or NULL if that has not been determined yet.
334 llvm::Module *m_module = nullptr;
335 /// The target data for the module being processed, or nullptr if there is no
336 /// module.
337 const llvm::DataLayout *m_target_data = nullptr;
338 /// The DeclMap containing the Decls
340 /// The address of the function CFStringCreateWithBytes, cast to the
341 /// appropriate function pointer type
342 llvm::FunctionCallee m_CFStringCreateWithBytes;
343 /// The address of the function sel_registerName, cast to the appropriate
344 /// function pointer type.
345 llvm::FunctionCallee m_sel_registerName;
346 /// The type of an integer large enough to hold a pointer.
347 llvm::IntegerType *m_intptr_ty = nullptr;
348 /// The stream on which errors should be printed.
350 /// The execution unit containing the IR being created.
352 /// True if the function's result in the AST is a pointer (see comments in
353 /// ASTResultSynthesizer::SynthesizeBodyResult)
355
357
359 public:
360 typedef std::function<llvm::Value *(llvm::Function *)> Maker;
361
362 FunctionValueCache(Maker const &maker);
364 llvm::Value *GetValue(llvm::Function *function);
365
366 private:
368 typedef std::map<llvm::Function *, llvm::Value *> FunctionValueMap;
370 };
371
373
374 /// UnfoldConstant operates on a constant [Old] which has just been replaced
375 /// with a value [New]. We assume that new_value has been properly placed
376 /// early in the function, in front of the first instruction in the entry
377 /// basic block [FirstEntryInstruction].
378 ///
379 /// UnfoldConstant reads through the uses of Old and replaces Old in those
380 /// uses with New. Where those uses are constants, the function generates
381 /// new instructions to compute the result of the new, non-constant
382 /// expression and places them before FirstEntryInstruction. These
383 /// instructions replace the constant uses, so UnfoldConstant calls itself
384 /// recursively for those.
385 ///
386 /// \return
387 /// True on success; false otherwise
388 static bool UnfoldConstant(llvm::Constant *old_constant,
389 llvm::Function *llvm_function,
390 FunctionValueCache &value_maker,
391 FunctionValueCache &entry_instruction_finder,
392 lldb_private::Stream &error_stream);
393};
394
395#endif // LLDB_SOURCE_PLUGINS_EXPRESSIONPARSER_CLANG_IRFORTARGET_H
FunctionValueCache(Maker const &maker)
llvm::Value * GetValue(llvm::Function *function)
std::function< llvm::Value *(llvm::Function *)> Maker
std::map< llvm::Function *, llvm::Value * > FunctionValueMap
lldb_private::ConstString m_func_name
The name of the function to translate.
IRForTarget(lldb_private::ClangExpressionDeclMap *decl_map, bool resolve_vars, lldb_private::IRExecutionUnit &execution_unit, lldb_private::Stream &error_stream, lldb_private::ExecutionPolicy execution_policy, const char *func_name="$__lldb_expr")
Constructor.
bool MaybeHandleVariable(llvm::Value *value)
A function-level pass to find all external variables and functions used in the IR.
bool FixFunctionLinkage(llvm::Function &llvm_function)
Ensures that the current function's linkage is set to external.
lldb_private::IRExecutionUnit & m_execution_unit
The execution unit containing the IR being created.
bool CreateResultVariable(llvm::Function &llvm_function)
The top-level pass implementation.
llvm::Module * m_module
The module being processed, or NULL if that has not been determined yet.
clang::NamedDecl * DeclForGlobal(llvm::GlobalValue *global)
bool HandleSymbol(llvm::Value *symbol)
Handle a single externally-defined symbol.
bool RewriteObjCConstStrings()
The top-level pass implementation.
bool ResolveCalls(llvm::BasicBlock &basic_block)
Resolve variable references in calls to external functions.
bool m_result_is_pointer
True if the function's result in the AST is a pointer (see comments in ASTResultSynthesizer::Synthesi...
bool RewriteObjCConstString(llvm::GlobalVariable *NSStr, llvm::GlobalVariable *CStr)
A module-level pass to find Objective-C constant strings and transform them to calls to CFStringCreat...
bool RemoveGuards(llvm::BasicBlock &basic_block)
The top-level pass implementation.
lldb_private::Stream & m_error_stream
The stream on which errors should be printed.
bool HandleObjCClass(llvm::Value *classlist_reference)
Handle a single externally-defined Objective-C class.
bool m_resolve_vars
True if external variable references and persistent variable references should be resolved.
static clang::NamedDecl * DeclForGlobal(const llvm::GlobalValue *global_val, llvm::Module *module)
A function-level pass to take the generated global value $__lldb_expr_result and make it into a persi...
lldb_private::TypeFromParser m_result_type
The type of the result variable.
llvm::FunctionCallee m_CFStringCreateWithBytes
The address of the function CFStringCreateWithBytes, cast to the appropriate function pointer type.
bool MaybeHandleCallArguments(llvm::CallInst *call_inst)
Handle all the arguments to a function call.
lldb_private::ExecutionPolicy m_policy
bool runOnModule(llvm::Module &llvm_module)
Run this IR transformer on a single module.
bool RewriteObjCSelectors(llvm::BasicBlock &basic_block)
The top-level pass implementation.
lldb_private::ConstString m_result_name
The name of the result variable ($0, $1, ...)
lldb_private::ClangExpressionDeclMap * m_decl_map
The DeclMap containing the Decls.
bool RemoveCXAAtExit(llvm::BasicBlock &basic_block)
Remove calls to __cxa_atexit, which should never be generated by expressions.
bool RewritePersistentAllocs(llvm::BasicBlock &basic_block)
The top-level pass implementation.
bool RewritePersistentAlloc(llvm::Instruction *persistent_alloc)
A basic block-level pass to find all newly-declared persistent variables and register them with the C...
void TurnGuardLoadIntoZero(llvm::Instruction *guard_load)
A basic block-level pass to excise guard variables from the code.
FunctionValueCache m_entry_instruction_finder
const llvm::DataLayout * m_target_data
The target data for the module being processed, or nullptr if there is no module.
llvm::FunctionCallee m_sel_registerName
The address of the function sel_registerName, cast to the appropriate function pointer type.
llvm::IntegerType * m_intptr_ty
The type of an integer large enough to hold a pointer.
bool RewriteObjCSelector(llvm::Instruction *selector_load)
A basic block-level pass to find all Objective-C method calls and rewrite them to use sel_registerNam...
bool ResolveExternals(llvm::Function &llvm_function)
The top-level pass implementation.
bool ReplaceVariables(llvm::Function &llvm_function)
A function-level pass to make all external variable references point at the correct offsets from the ...
static bool UnfoldConstant(llvm::Constant *old_constant, llvm::Function *llvm_function, FunctionValueCache &value_maker, FunctionValueCache &entry_instruction_finder, lldb_private::Stream &error_stream)
UnfoldConstant operates on a constant [Old] which has just been replaced with a value [New].
"lldb/Expression/ClangExpressionDeclMap.h" Manages named entities that are defined in LLDB's debug in...
A uniqued constant string class.
Definition ConstString.h:40
"lldb/Expression/IRExecutionUnit.h" Contains the IR and, optionally, JIT- compiled code for a module.
Encapsulates memory that may exist in the process but must also be available in the host process.
Definition IRMemoryMap.h:35
A stream class that can stream formatted output to a file.
Definition Stream.h:28
A class that represents a running process on the host machine.
TaggedASTType< 0 > TypeFromParser
ExecutionPolicy
Expression execution policies.