1 //===-- IRForTarget.h ---------------------------------------------*- C++
4 // The LLVM Compiler Infrastructure
6 // This file is distributed under the University of Illinois Open Source
7 // License. See LICENSE.TXT for details.
9 //===----------------------------------------------------------------------===//
11 #ifndef liblldb_IRForTarget_h_
12 #define liblldb_IRForTarget_h_
14 #include "lldb/Symbol/TaggedASTType.h"
15 #include "lldb/Utility/ConstString.h"
16 #include "lldb/Utility/Status.h"
17 #include "lldb/Utility/Stream.h"
18 #include "lldb/Utility/StreamString.h"
19 #include "lldb/lldb-public.h"
20 #include "llvm/Pass.h"
42 namespace lldb_private {
43 class ClangExpressionDeclMap;
44 class IRExecutionUnit;
48 //----------------------------------------------------------------------
49 /// @class IRForTarget IRForTarget.h "lldb/Expression/IRForTarget.h"
50 /// Transforms the IR for a function to run in the target
52 /// Once an expression has been parsed and converted to IR, it can run in two
53 /// contexts: interpreted by LLDB as a DWARF location expression, or compiled
54 /// by the JIT and inserted into the target process for execution.
56 /// IRForTarget makes the second possible, by applying a series of
57 /// transformations to the IR which make it relocatable. These
58 /// transformations are discussed in more detail next to their relevant
60 //----------------------------------------------------------------------
61 class IRForTarget : public llvm::ModulePass {
63 enum class LookupResult { Success, Fail, Ignore };
65 //------------------------------------------------------------------
68 /// @param[in] decl_map
69 /// The list of externally-referenced variables for the expression,
70 /// for use in looking up globals and allocating the argument
71 /// struct. See the documentation for ClangExpressionDeclMap.
73 /// @param[in] resolve_vars
74 /// True if the external variable references (including persistent
75 /// variables) should be resolved. If not, only external functions
78 /// @param[in] execution_policy
79 /// Determines whether an IR interpreter can be used to statically
80 /// evaluate the expression.
82 /// @param[in] const_result
83 /// This variable is populated with the statically-computed result
84 /// of the function, if it has no side-effects and the result can
85 /// be computed statically.
87 /// @param[in] execution_unit
88 /// The holder for raw data associated with the expression.
90 /// @param[in] error_stream
91 /// If non-NULL, a stream on which errors can be printed.
93 /// @param[in] func_name
94 /// The name of the function to prepare for execution in the target.
95 //------------------------------------------------------------------
96 IRForTarget(lldb_private::ClangExpressionDeclMap *decl_map, bool resolve_vars,
97 lldb_private::IRExecutionUnit &execution_unit,
98 lldb_private::Stream &error_stream,
99 const char *func_name = "$__lldb_expr");
101 //------------------------------------------------------------------
103 //------------------------------------------------------------------
104 ~IRForTarget() override;
106 //------------------------------------------------------------------
107 /// Run this IR transformer on a single module
109 /// Implementation of the llvm::ModulePass::runOnModule() function.
111 /// @param[in] llvm_module
112 /// The module to run on. This module is searched for the function
113 /// $__lldb_expr, and that function is passed to the passes one by
116 /// @param[in] interpreter_error
117 /// An error. If the expression fails to be interpreted, this error
118 /// is set to a reason why.
121 /// True on success; false otherwise
122 //------------------------------------------------------------------
123 bool runOnModule(llvm::Module &llvm_module) override;
125 //------------------------------------------------------------------
128 /// Implementation of the llvm::ModulePass::assignPassManager() function.
129 //------------------------------------------------------------------
130 void assignPassManager(llvm::PMStack &pass_mgr_stack,
131 llvm::PassManagerType pass_mgr_type =
132 llvm::PMT_ModulePassManager) override;
134 //------------------------------------------------------------------
135 /// Returns PMT_ModulePassManager
137 /// Implementation of the llvm::ModulePass::getPotentialPassManagerType()
139 //------------------------------------------------------------------
140 llvm::PassManagerType getPotentialPassManagerType() const override;
143 //------------------------------------------------------------------
144 /// Ensures that the current function's linkage is set to external.
145 /// Otherwise the JIT may not return an address for it.
147 /// @param[in] llvm_function
148 /// The function whose linkage is to be fixed.
151 /// True on success; false otherwise.
152 //------------------------------------------------------------------
153 bool FixFunctionLinkage(llvm::Function &llvm_function);
155 //------------------------------------------------------------------
156 /// A module-level pass to replace all function pointers with their
157 /// integer equivalents.
158 //------------------------------------------------------------------
160 //------------------------------------------------------------------
161 /// The top-level pass implementation
163 /// @param[in] llvm_module
164 /// The module currently being processed.
166 /// @param[in] llvm_function
167 /// The function currently being processed.
170 /// True on success; false otherwise.
171 //------------------------------------------------------------------
172 bool HasSideEffects(llvm::Function &llvm_function);
174 //------------------------------------------------------------------
175 /// A function-level pass to check whether the function has side
177 //------------------------------------------------------------------
179 //------------------------------------------------------------------
180 /// Get the address of a function, and a location to put the complete Value
181 /// of the function if one is available.
183 /// @param[in] function
184 /// The function to find the location of.
187 /// The location of the function in the target.
190 /// The resolved name of the function (matters for intrinsics).
192 /// @param[out] value_ptr
193 /// A variable to put the function's completed Value* in, or NULL
194 /// if the Value* shouldn't be stored anywhere.
198 //------------------------------------------------------------------
199 LookupResult GetFunctionAddress(llvm::Function *function, uint64_t &ptr,
200 lldb_private::ConstString &name,
201 llvm::Constant **&value_ptr);
203 //------------------------------------------------------------------
204 /// A function-level pass to take the generated global value
205 /// $__lldb_expr_result and make it into a persistent variable. Also see
206 /// ASTResultSynthesizer.
207 //------------------------------------------------------------------
209 //------------------------------------------------------------------
210 /// Find the NamedDecl corresponding to a Value. This interface is exposed
211 /// for the IR interpreter.
213 /// @param[in] module
214 /// The module containing metadata to search
216 /// @param[in] global
217 /// The global entity to search for
220 /// The corresponding variable declaration
221 //------------------------------------------------------------------
223 static clang::NamedDecl *DeclForGlobal(const llvm::GlobalValue *global_val,
224 llvm::Module *module);
227 clang::NamedDecl *DeclForGlobal(llvm::GlobalValue *global);
229 //------------------------------------------------------------------
230 /// Set the constant result variable m_const_result to the provided
231 /// constant, assuming it can be evaluated. The result variable will be
232 /// reset to NULL later if the expression has side effects.
234 /// @param[in] initializer
235 /// The constant initializer for the variable.
238 /// The name of the result variable.
241 /// The Clang type of the result variable.
242 //------------------------------------------------------------------
243 void MaybeSetConstantResult(llvm::Constant *initializer,
244 const lldb_private::ConstString &name,
245 lldb_private::TypeFromParser type);
247 //------------------------------------------------------------------
248 /// If the IR represents a cast of a variable, set m_const_result to the
249 /// result of the cast. The result variable will be reset to
250 /// NULL latger if the expression has side effects.
253 /// The Clang type of the result variable.
254 //------------------------------------------------------------------
255 void MaybeSetCastResult(lldb_private::TypeFromParser type);
257 //------------------------------------------------------------------
258 /// The top-level pass implementation
260 /// @param[in] llvm_function
261 /// The function currently being processed.
264 /// True on success; false otherwise
265 //------------------------------------------------------------------
266 bool CreateResultVariable(llvm::Function &llvm_function);
268 //------------------------------------------------------------------
269 /// A module-level pass to find Objective-C constant strings and
270 /// transform them to calls to CFStringCreateWithBytes.
271 //------------------------------------------------------------------
273 //------------------------------------------------------------------
274 /// Rewrite a single Objective-C constant string.
277 /// The constant NSString to be transformed
280 /// The constant C string inside the NSString. This will be
281 /// passed as the bytes argument to CFStringCreateWithBytes.
284 /// True on success; false otherwise
285 //------------------------------------------------------------------
286 bool RewriteObjCConstString(llvm::GlobalVariable *NSStr,
287 llvm::GlobalVariable *CStr);
289 //------------------------------------------------------------------
290 /// The top-level pass implementation
293 /// True on success; false otherwise
294 //------------------------------------------------------------------
295 bool RewriteObjCConstStrings();
297 //------------------------------------------------------------------
298 /// A basic block-level pass to find all Objective-C method calls and
299 /// rewrite them to use sel_registerName instead of statically allocated
300 /// selectors. The reason is that the selectors are created on the
301 /// assumption that the Objective-C runtime will scan the appropriate
302 /// section and prepare them. This doesn't happen when code is copied into
303 /// the target, though, and there's no easy way to induce the runtime to
304 /// scan them. So instead we get our selectors from sel_registerName.
305 //------------------------------------------------------------------
307 //------------------------------------------------------------------
308 /// Replace a single selector reference
310 /// @param[in] selector_load
311 /// The load of the statically-allocated selector.
314 /// True on success; false otherwise
315 //------------------------------------------------------------------
316 bool RewriteObjCSelector(llvm::Instruction *selector_load);
318 //------------------------------------------------------------------
319 /// The top-level pass implementation
321 /// @param[in] basic_block
322 /// The basic block currently being processed.
325 /// True on success; false otherwise
326 //------------------------------------------------------------------
327 bool RewriteObjCSelectors(llvm::BasicBlock &basic_block);
329 //------------------------------------------------------------------
330 /// A basic block-level pass to find all Objective-C class references that
331 /// use the old-style Objective-C runtime and rewrite them to use
332 /// class_getClass instead of statically allocated class references.
333 //------------------------------------------------------------------
335 //------------------------------------------------------------------
336 /// Replace a single old-style class reference
338 /// @param[in] selector_load
339 /// The load of the statically-allocated selector.
342 /// True on success; false otherwise
343 //------------------------------------------------------------------
344 bool RewriteObjCClassReference(llvm::Instruction *class_load);
346 //------------------------------------------------------------------
347 /// The top-level pass implementation
349 /// @param[in] basic_block
350 /// The basic block currently being processed.
353 /// True on success; false otherwise
354 //------------------------------------------------------------------
355 bool RewriteObjCClassReferences(llvm::BasicBlock &basic_block);
357 //------------------------------------------------------------------
358 /// A basic block-level pass to find all newly-declared persistent
359 /// variables and register them with the ClangExprDeclMap. This allows them
360 /// to be materialized and dematerialized like normal external variables.
361 /// Before transformation, these persistent variables look like normal
362 /// locals, so they have an allocation. This pass excises these allocations
363 /// and makes references look like external references where they will be
364 /// resolved -- like all other external references -- by ResolveExternals().
365 //------------------------------------------------------------------
367 //------------------------------------------------------------------
368 /// Handle a single allocation of a persistent variable
370 /// @param[in] persistent_alloc
371 /// The allocation of the persistent variable.
374 /// True on success; false otherwise
375 //------------------------------------------------------------------
376 bool RewritePersistentAlloc(llvm::Instruction *persistent_alloc);
378 //------------------------------------------------------------------
379 /// The top-level pass implementation
381 /// @param[in] basic_block
382 /// The basic block currently being processed.
383 //------------------------------------------------------------------
384 bool RewritePersistentAllocs(llvm::BasicBlock &basic_block);
386 //------------------------------------------------------------------
387 /// A function-level pass to find all external variables and functions
388 /// used in the IR. Each found external variable is added to the struct,
389 /// and each external function is resolved in place, its call replaced with
390 /// a call to a function pointer whose value is the address of the function
391 /// in the target process.
392 //------------------------------------------------------------------
394 //------------------------------------------------------------------
395 /// Write an initializer to a memory array of assumed sufficient size.
398 /// A pointer to the data to write to.
400 /// @param[in] initializer
401 /// The initializer itself.
404 /// True on success; false otherwise
405 //------------------------------------------------------------------
406 bool MaterializeInitializer(uint8_t *data, llvm::Constant *initializer);
408 //------------------------------------------------------------------
409 /// Move an internal variable into the static allocation section.
411 /// @param[in] global_variable
415 /// True on success; false otherwise
416 //------------------------------------------------------------------
417 bool MaterializeInternalVariable(llvm::GlobalVariable *global_variable);
419 //------------------------------------------------------------------
420 /// Handle a single externally-defined variable
426 /// True on success; false otherwise
427 //------------------------------------------------------------------
428 bool MaybeHandleVariable(llvm::Value *value);
430 //------------------------------------------------------------------
431 /// Handle a single externally-defined symbol
433 /// @param[in] symbol
437 /// True on success; false otherwise
438 //------------------------------------------------------------------
439 bool HandleSymbol(llvm::Value *symbol);
441 //------------------------------------------------------------------
442 /// Handle a single externally-defined Objective-C class
444 /// @param[in] classlist_reference
445 /// The reference, usually "01L_OBJC_CLASSLIST_REFERENCES_$_n"
446 /// where n (if present) is an index.
449 /// True on success; false otherwise
450 //------------------------------------------------------------------
451 bool HandleObjCClass(llvm::Value *classlist_reference);
453 //------------------------------------------------------------------
454 /// Handle all the arguments to a function call
457 /// The call instruction.
460 /// True on success; false otherwise
461 //------------------------------------------------------------------
462 bool MaybeHandleCallArguments(llvm::CallInst *call_inst);
464 //------------------------------------------------------------------
465 /// Resolve variable references in calls to external functions
467 /// @param[in] basic_block
468 /// The basic block currently being processed.
471 /// True on success; false otherwise
472 //------------------------------------------------------------------
473 bool ResolveCalls(llvm::BasicBlock &basic_block);
475 //------------------------------------------------------------------
476 /// Remove calls to __cxa_atexit, which should never be generated by
479 /// @param[in] call_inst
480 /// The call instruction.
483 /// True if the scan was successful; false if some operation
485 //------------------------------------------------------------------
486 bool RemoveCXAAtExit(llvm::BasicBlock &basic_block);
488 //------------------------------------------------------------------
489 /// The top-level pass implementation
491 /// @param[in] basic_block
492 /// The function currently being processed.
495 /// True on success; false otherwise
496 //------------------------------------------------------------------
497 bool ResolveExternals(llvm::Function &llvm_function);
499 //------------------------------------------------------------------
500 /// A basic block-level pass to excise guard variables from the code.
501 /// The result for the function is passed through Clang as a static
502 /// variable. Static variables normally have guard variables to ensure that
503 /// they are only initialized once.
504 //------------------------------------------------------------------
506 //------------------------------------------------------------------
507 /// Rewrite a load to a guard variable to return constant 0.
509 /// @param[in] guard_load
510 /// The load instruction to zero out.
511 //------------------------------------------------------------------
512 void TurnGuardLoadIntoZero(llvm::Instruction *guard_load);
514 //------------------------------------------------------------------
515 /// The top-level pass implementation
517 /// @param[in] basic_block
518 /// The basic block currently being processed.
521 /// True on success; false otherwise
522 //------------------------------------------------------------------
523 bool RemoveGuards(llvm::BasicBlock &basic_block);
525 //------------------------------------------------------------------
526 /// A function-level pass to make all external variable references
527 /// point at the correct offsets from the void* passed into the function.
528 /// ClangExpressionDeclMap::DoStructLayout() must be called beforehand, so
529 /// that the offsets are valid.
530 //------------------------------------------------------------------
532 //------------------------------------------------------------------
533 /// The top-level pass implementation
535 /// @param[in] llvm_function
536 /// The function currently being processed.
539 /// True on success; false otherwise
540 //------------------------------------------------------------------
541 bool ReplaceVariables(llvm::Function &llvm_function);
544 bool m_resolve_vars; ///< True if external variable references and persistent
545 ///variable references should be resolved
546 lldb_private::ConstString
547 m_func_name; ///< The name of the function to translate
548 lldb_private::ConstString
549 m_result_name; ///< The name of the result variable ($0, $1, ...)
550 lldb_private::TypeFromParser
551 m_result_type; ///< The type of the result variable.
552 llvm::Module *m_module; ///< The module being processed, or NULL if that has
553 ///not been determined yet.
554 std::unique_ptr<llvm::DataLayout> m_target_data; ///< The target data for the
555 ///module being processed, or
556 ///NULL if there is no
558 lldb_private::ClangExpressionDeclMap
559 *m_decl_map; ///< The DeclMap containing the Decls
560 llvm::Constant *m_CFStringCreateWithBytes; ///< The address of the function
561 ///CFStringCreateWithBytes, cast to
563 /// appropriate function pointer type
564 llvm::Constant *m_sel_registerName; ///< The address of the function
565 ///sel_registerName, cast to the
567 /// function pointer type
568 llvm::Constant *m_objc_getClass; ///< The address of the function
569 ///objc_getClass, cast to the
571 /// function pointer type
573 *m_intptr_ty; ///< The type of an integer large enough to hold a pointer.
575 &m_error_stream; ///< The stream on which errors should be printed
576 lldb_private::IRExecutionUnit &
577 m_execution_unit; ///< The execution unit containing the IR being created.
579 llvm::StoreInst *m_result_store; ///< If non-NULL, the store instruction that
580 ///writes to the result variable. If
581 /// m_has_side_effects is true, this is
583 bool m_result_is_pointer; ///< True if the function's result in the AST is a
584 ///pointer (see comments in
585 /// ASTResultSynthesizer::SynthesizeBodyResult)
587 llvm::GlobalVariable *m_reloc_placeholder; ///< A placeholder that will be
588 ///replaced by a pointer to the
590 /// location of the static allocation.
592 //------------------------------------------------------------------
593 /// UnfoldConstant operates on a constant [Old] which has just been replaced
594 /// with a value [New]. We assume that new_value has been properly placed
595 /// early in the function, in front of the first instruction in the entry
596 /// basic block [FirstEntryInstruction].
598 /// UnfoldConstant reads through the uses of Old and replaces Old in those
599 /// uses with New. Where those uses are constants, the function generates
600 /// new instructions to compute the result of the new, non-constant
601 /// expression and places them before FirstEntryInstruction. These
602 /// instructions replace the constant uses, so UnfoldConstant calls itself
603 /// recursively for those.
605 /// @param[in] llvm_function
606 /// The function currently being processed.
609 /// True on success; false otherwise
610 //------------------------------------------------------------------
612 class FunctionValueCache {
614 typedef std::function<llvm::Value *(llvm::Function *)> Maker;
616 FunctionValueCache(Maker const &maker);
617 ~FunctionValueCache();
618 llvm::Value *GetValue(llvm::Function *function);
622 typedef std::map<llvm::Function *, llvm::Value *> FunctionValueMap;
623 FunctionValueMap m_values;
626 FunctionValueCache m_entry_instruction_finder;
628 static bool UnfoldConstant(llvm::Constant *old_constant,
629 llvm::Function *llvm_function,
630 FunctionValueCache &value_maker,
631 FunctionValueCache &entry_instruction_finder,
632 lldb_private::Stream &error_stream);
634 //------------------------------------------------------------------
635 /// Construct a reference to m_reloc_placeholder with a given type and
636 /// offset. This typically happens after inserting data into
637 /// m_data_allocator.
640 /// The type of the value being loaded.
642 /// @param[in] offset
643 /// The offset of the value from the base of m_data_allocator.
646 /// The Constant for the reference, usually a ConstantExpr.
647 //------------------------------------------------------------------
648 llvm::Constant *BuildRelocation(llvm::Type *type, uint64_t offset);
650 //------------------------------------------------------------------
651 /// Commit the allocation in m_data_allocator and use its final location to
652 /// replace m_reloc_placeholder.
654 /// @param[in] module
655 /// The module that m_data_allocator resides in
658 /// True on success; false otherwise
659 //------------------------------------------------------------------
660 bool CompleteDataAllocation();
663 #endif // liblldb_IRForTarget_h_