1 //===-- IRForTarget.h ---------------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #ifndef liblldb_IRForTarget_h_
11 #define liblldb_IRForTarget_h_
13 #include "lldb/lldb-public.h"
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 "llvm/Pass.h"
41 namespace lldb_private {
42 class ClangExpressionDeclMap;
43 class IRExecutionUnit;
47 //----------------------------------------------------------------------
48 /// @class IRForTarget IRForTarget.h "lldb/Expression/IRForTarget.h"
49 /// @brief Transforms the IR for a function to run in the target
51 /// Once an expression has been parsed and converted to IR, it can run
52 /// in two contexts: interpreted by LLDB as a DWARF location expression,
53 /// or compiled by the JIT and inserted into the target process for
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
64 //------------------------------------------------------------------
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.
72 /// @param[in] resolve_vars
73 /// True if the external variable references (including persistent
74 /// variables) should be resolved. If not, only external functions
77 /// @param[in] execution_policy
78 /// Determines whether an IR interpreter can be used to statically
79 /// evaluate the expression.
81 /// @param[in] const_result
82 /// This variable is populated with the statically-computed result
83 /// of the function, if it has no side-effects and the result can
84 /// be computed statically.
86 /// @param[in] execution_unit
87 /// The holder for raw data associated with the expression.
89 /// @param[in] error_stream
90 /// If non-NULL, a stream on which errors can be printed.
92 /// @param[in] func_name
93 /// The name of the function to prepare for execution in the target.
94 //------------------------------------------------------------------
95 IRForTarget(lldb_private::ClangExpressionDeclMap *decl_map,
97 lldb_private::IRExecutionUnit &execution_unit,
98 lldb_private::Stream *error_stream,
99 const char* func_name = "$__lldb_expr");
101 //------------------------------------------------------------------
103 //------------------------------------------------------------------
104 virtual ~IRForTarget();
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 //------------------------------------------------------------------
124 runOnModule (llvm::Module &llvm_module);
126 //------------------------------------------------------------------
129 /// Implementation of the llvm::ModulePass::assignPassManager()
131 //------------------------------------------------------------------
133 assignPassManager (llvm::PMStack &pass_mgr_stack,
134 llvm::PassManagerType pass_mgr_type = llvm::PMT_ModulePassManager);
136 //------------------------------------------------------------------
137 /// Returns PMT_ModulePassManager
139 /// Implementation of the llvm::ModulePass::getPotentialPassManagerType()
141 //------------------------------------------------------------------
142 virtual llvm::PassManagerType
143 getPotentialPassManagerType() const;
146 //------------------------------------------------------------------
147 /// Ensures that the current function's linkage is set to external.
148 /// Otherwise the JIT may not return an address for it.
150 /// @param[in] llvm_function
151 /// The function whose linkage is to be fixed.
154 /// True on success; false otherwise.
155 //------------------------------------------------------------------
157 FixFunctionLinkage (llvm::Function &llvm_function);
159 //------------------------------------------------------------------
160 /// A module-level pass to replace all function pointers with their
161 /// integer equivalents.
162 //------------------------------------------------------------------
164 //------------------------------------------------------------------
165 /// The top-level pass implementation
167 /// @param[in] llvm_module
168 /// The module currently being processed.
170 /// @param[in] llvm_function
171 /// The function currently being processed.
174 /// True on success; false otherwise.
175 //------------------------------------------------------------------
177 HasSideEffects (llvm::Function &llvm_function);
179 //------------------------------------------------------------------
180 /// A function-level pass to check whether the function has side
182 //------------------------------------------------------------------
184 //------------------------------------------------------------------
185 /// Get the address of a fuction, and a location to put the complete
186 /// Value of the function if one is available.
188 /// @param[in] function
189 /// The function to find the location of.
192 /// The location of the function in the target.
195 /// The resolved name of the function (matters for intrinsics).
197 /// @param[out] value_ptr
198 /// A variable to put the function's completed Value* in, or NULL
199 /// if the Value* shouldn't be stored anywhere.
203 //------------------------------------------------------------------
205 GetFunctionAddress (llvm::Function *function,
207 lldb_private::ConstString &name,
208 llvm::Constant **&value_ptr);
210 //------------------------------------------------------------------
211 /// Build a function pointer given a type and a raw pointer.
214 /// The type of the function pointer to be built.
217 /// The value of the pointer.
221 //------------------------------------------------------------------
223 BuildFunctionPointer (llvm::Type *type,
227 RegisterFunctionMetadata (llvm::LLVMContext &context,
228 llvm::Value *function_ptr,
231 //------------------------------------------------------------------
232 /// The top-level pass implementation
234 /// @param[in] llvm_function
235 /// The function currently being processed.
238 /// True if the function has side effects (or if this cannot
239 /// be determined); false otherwise.
240 //------------------------------------------------------------------
242 ResolveFunctionPointers (llvm::Module &llvm_module);
244 //------------------------------------------------------------------
245 /// A function-level pass to take the generated global value
246 /// $__lldb_expr_result and make it into a persistent variable.
247 /// Also see ASTResultSynthesizer.
248 //------------------------------------------------------------------
250 //------------------------------------------------------------------
251 /// Find the NamedDecl corresponding to a Value. This interface is
252 /// exposed for the IR interpreter.
254 /// @param[in] module
255 /// The module containing metadata to search
257 /// @param[in] global
258 /// The global entity to search for
261 /// The corresponding variable declaration
262 //------------------------------------------------------------------
264 static clang::NamedDecl *
265 DeclForGlobal (const llvm::GlobalValue *global_val, llvm::Module *module);
268 DeclForGlobal (llvm::GlobalValue *global);
270 //------------------------------------------------------------------
271 /// Set the constant result variable m_const_result to the provided
272 /// constant, assuming it can be evaluated. The result variable
273 /// will be reset to NULL later if the expression has side effects.
275 /// @param[in] initializer
276 /// The constant initializer for the variable.
279 /// The name of the result variable.
282 /// The Clang type of the result variable.
283 //------------------------------------------------------------------
285 MaybeSetConstantResult (llvm::Constant *initializer,
286 const lldb_private::ConstString &name,
287 lldb_private::TypeFromParser type);
289 //------------------------------------------------------------------
290 /// If the IR represents a cast of a variable, set m_const_result
291 /// to the result of the cast. The result variable will be reset to
292 /// NULL latger if the expression has side effects.
295 /// The Clang type of the result variable.
296 //------------------------------------------------------------------
298 MaybeSetCastResult (lldb_private::TypeFromParser type);
300 //------------------------------------------------------------------
301 /// The top-level pass implementation
303 /// @param[in] llvm_function
304 /// The function currently being processed.
307 /// True on success; false otherwise
308 //------------------------------------------------------------------
310 CreateResultVariable (llvm::Function &llvm_function);
312 //------------------------------------------------------------------
313 /// A module-level pass to find Objective-C constant strings and
314 /// transform them to calls to CFStringCreateWithBytes.
315 //------------------------------------------------------------------
317 //------------------------------------------------------------------
318 /// Rewrite a single Objective-C constant string.
321 /// The constant NSString to be transformed
324 /// The constant C string inside the NSString. This will be
325 /// passed as the bytes argument to CFStringCreateWithBytes.
328 /// True on success; false otherwise
329 //------------------------------------------------------------------
331 RewriteObjCConstString (llvm::GlobalVariable *NSStr,
332 llvm::GlobalVariable *CStr);
334 //------------------------------------------------------------------
335 /// The top-level pass implementation
338 /// True on success; false otherwise
339 //------------------------------------------------------------------
341 RewriteObjCConstStrings ();
343 //------------------------------------------------------------------
344 /// A basic block-level pass to find all Objective-C method calls and
345 /// rewrite them to use sel_registerName instead of statically allocated
346 /// selectors. The reason is that the selectors are created on the
347 /// assumption that the Objective-C runtime will scan the appropriate
348 /// section and prepare them. This doesn't happen when code is copied
349 /// into the target, though, and there's no easy way to induce the
350 /// runtime to scan them. So instead we get our selectors from
351 /// sel_registerName.
352 //------------------------------------------------------------------
354 //------------------------------------------------------------------
355 /// Replace a single selector reference
357 /// @param[in] selector_load
358 /// The load of the statically-allocated selector.
361 /// True on success; false otherwise
362 //------------------------------------------------------------------
364 RewriteObjCSelector (llvm::Instruction* selector_load);
366 //------------------------------------------------------------------
367 /// The top-level pass implementation
369 /// @param[in] basic_block
370 /// The basic block currently being processed.
373 /// True on success; false otherwise
374 //------------------------------------------------------------------
376 RewriteObjCSelectors (llvm::BasicBlock &basic_block);
378 //------------------------------------------------------------------
379 /// A basic block-level pass to find all newly-declared persistent
380 /// variables and register them with the ClangExprDeclMap. This
381 /// allows them to be materialized and dematerialized like normal
382 /// external variables. Before transformation, these persistent
383 /// variables look like normal locals, so they have an allocation.
384 /// This pass excises these allocations and makes references look
385 /// like external references where they will be resolved -- like all
386 /// other external references -- by ResolveExternals().
387 //------------------------------------------------------------------
389 //------------------------------------------------------------------
390 /// Handle a single allocation of a persistent variable
392 /// @param[in] persistent_alloc
393 /// The allocation of the persistent variable.
396 /// True on success; false otherwise
397 //------------------------------------------------------------------
399 RewritePersistentAlloc (llvm::Instruction *persistent_alloc);
401 //------------------------------------------------------------------
402 /// The top-level pass implementation
404 /// @param[in] basic_block
405 /// The basic block currently being processed.
406 //------------------------------------------------------------------
408 RewritePersistentAllocs (llvm::BasicBlock &basic_block);
410 //------------------------------------------------------------------
411 /// A function-level pass to find all external variables and functions
412 /// used in the IR. Each found external variable is added to the
413 /// struct, and each external function is resolved in place, its call
414 /// replaced with a call to a function pointer whose value is the
415 /// address of the function in the target process.
416 //------------------------------------------------------------------
418 //------------------------------------------------------------------
419 /// Write an initializer to a memory array of assumed sufficient
423 /// A pointer to the data to write to.
425 /// @param[in] initializer
426 /// The initializer itself.
429 /// True on success; false otherwise
430 //------------------------------------------------------------------
432 MaterializeInitializer (uint8_t *data, llvm::Constant *initializer);
434 //------------------------------------------------------------------
435 /// Move an internal variable into the static allocation section.
437 /// @param[in] global_variable
441 /// True on success; false otherwise
442 //------------------------------------------------------------------
444 MaterializeInternalVariable (llvm::GlobalVariable *global_variable);
446 //------------------------------------------------------------------
447 /// Handle a single externally-defined variable
453 /// True on success; false otherwise
454 //------------------------------------------------------------------
456 MaybeHandleVariable (llvm::Value *value);
458 //------------------------------------------------------------------
459 /// Handle a single externally-defined symbol
461 /// @param[in] symbol
465 /// True on success; false otherwise
466 //------------------------------------------------------------------
468 HandleSymbol (llvm::Value *symbol);
470 //------------------------------------------------------------------
471 /// Handle a single externally-defined Objective-C class
473 /// @param[in] classlist_reference
474 /// The reference, usually "01L_OBJC_CLASSLIST_REFERENCES_$_n"
475 /// where n (if present) is an index.
478 /// True on success; false otherwise
479 //------------------------------------------------------------------
481 HandleObjCClass(llvm::Value *classlist_reference);
483 //------------------------------------------------------------------
484 /// Handle all the arguments to a function call
487 /// The call instruction.
490 /// True on success; false otherwise
491 //------------------------------------------------------------------
493 MaybeHandleCallArguments (llvm::CallInst *call_inst);
495 //------------------------------------------------------------------
496 /// Resolve variable references in calls to external functions
498 /// @param[in] basic_block
499 /// The basic block currently being processed.
502 /// True on success; false otherwise
503 //------------------------------------------------------------------
505 ResolveCalls (llvm::BasicBlock &basic_block);
507 //------------------------------------------------------------------
508 /// Remove calls to __cxa_atexit, which should never be generated by
511 /// @param[in] call_inst
512 /// The call instruction.
515 /// True if the scan was successful; false if some operation
517 //------------------------------------------------------------------
519 RemoveCXAAtExit (llvm::BasicBlock &basic_block);
521 //------------------------------------------------------------------
522 /// The top-level pass implementation
524 /// @param[in] basic_block
525 /// The function currently being processed.
528 /// True on success; false otherwise
529 //------------------------------------------------------------------
531 ResolveExternals (llvm::Function &llvm_function);
533 //------------------------------------------------------------------
534 /// A basic block-level pass to excise guard variables from the code.
535 /// The result for the function is passed through Clang as a static
536 /// variable. Static variables normally have guard variables to
537 /// ensure that they are only initialized once.
538 //------------------------------------------------------------------
540 //------------------------------------------------------------------
541 /// Rewrite a load to a guard variable to return constant 0.
543 /// @param[in] guard_load
544 /// The load instruction to zero out.
545 //------------------------------------------------------------------
547 TurnGuardLoadIntoZero(llvm::Instruction* guard_load);
549 //------------------------------------------------------------------
550 /// The top-level pass implementation
552 /// @param[in] basic_block
553 /// The basic block currently being processed.
556 /// True on success; false otherwise
557 //------------------------------------------------------------------
559 RemoveGuards (llvm::BasicBlock &basic_block);
561 //------------------------------------------------------------------
562 /// A module-level pass to allocate all string literals in a separate
563 /// allocation and redirect references to them.
564 //------------------------------------------------------------------
566 //------------------------------------------------------------------
567 /// The top-level pass implementation
570 /// True on success; false otherwise
571 //------------------------------------------------------------------
575 //------------------------------------------------------------------
576 /// A basick block-level pass to find all literals that will be
577 /// allocated as statics by the JIT (in contrast to the Strings,
578 /// which already are statics) and synthesize loads for them.
579 //------------------------------------------------------------------
581 //------------------------------------------------------------------
582 /// The top-level pass implementation
584 /// @param[in] basic_block
585 /// The basic block currently being processed.
588 /// True on success; false otherwise
589 //------------------------------------------------------------------
591 ReplaceStaticLiterals (llvm::BasicBlock &basic_block);
593 //------------------------------------------------------------------
594 /// A function-level pass to make all external variable references
595 /// point at the correct offsets from the void* passed into the
596 /// function. ClangExpressionDeclMap::DoStructLayout() must be called
597 /// beforehand, so that the offsets are valid.
598 //------------------------------------------------------------------
600 //------------------------------------------------------------------
601 /// The top-level pass implementation
603 /// @param[in] llvm_function
604 /// The function currently being processed.
607 /// True on success; false otherwise
608 //------------------------------------------------------------------
610 ReplaceVariables (llvm::Function &llvm_function);
612 //------------------------------------------------------------------
613 /// A module-level pass to remove all global variables from the
614 /// module since it no longer should export or import any symbols.
615 //------------------------------------------------------------------
617 //------------------------------------------------------------------
618 /// The top-level pass implementation
620 /// @param[in] llvm_module
621 /// The module currently being processed.
624 /// True on success; false otherwise
625 //------------------------------------------------------------------
627 StripAllGVs (llvm::Module &llvm_module);
629 class StaticDataAllocator {
631 StaticDataAllocator(lldb_private::IRExecutionUnit &execution_unit);
632 lldb_private::StreamString &GetStream()
634 return m_stream_string;
636 lldb::addr_t Allocate();
638 lldb_private::IRExecutionUnit &m_execution_unit;
639 lldb_private::StreamString m_stream_string;
640 lldb::addr_t m_allocation;
644 bool m_resolve_vars; ///< True if external variable references and persistent variable references should be resolved
645 std::string m_func_name; ///< The name of the function to translate
646 lldb_private::ConstString m_result_name; ///< The name of the result variable ($0, $1, ...)
647 lldb_private::TypeFromParser m_result_type; ///< The type of the result variable.
648 llvm::Module *m_module; ///< The module being processed, or NULL if that has not been determined yet.
649 std::unique_ptr<llvm::DataLayout> m_target_data; ///< The target data for the module being processed, or NULL if there is no module.
650 lldb_private::ClangExpressionDeclMap *m_decl_map; ///< The DeclMap containing the Decls
651 StaticDataAllocator m_data_allocator; ///< The allocator to use for constant strings
652 llvm::Constant *m_CFStringCreateWithBytes; ///< The address of the function CFStringCreateWithBytes, cast to the appropriate function pointer type
653 llvm::Constant *m_sel_registerName; ///< The address of the function sel_registerName, cast to the appropriate function pointer type
654 llvm::IntegerType *m_intptr_ty; ///< The type of an integer large enough to hold a pointer.
655 lldb_private::Stream *m_error_stream; ///< If non-NULL, the stream on which errors should be printed
657 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.
658 bool m_result_is_pointer; ///< True if the function's result in the AST is a pointer (see comments in ASTResultSynthesizer::SynthesizeBodyResult)
660 llvm::GlobalVariable *m_reloc_placeholder; ///< A placeholder that will be replaced by a pointer to the final location of the static allocation.
662 //------------------------------------------------------------------
663 /// UnfoldConstant operates on a constant [Old] which has just been
664 /// replaced with a value [New]. We assume that new_value has
665 /// been properly placed early in the function, in front of the
666 /// first instruction in the entry basic block
667 /// [FirstEntryInstruction].
669 /// UnfoldConstant reads through the uses of Old and replaces Old
670 /// in those uses with New. Where those uses are constants, the
671 /// function generates new instructions to compute the result of the
672 /// new, non-constant expression and places them before
673 /// FirstEntryInstruction. These instructions replace the constant
674 /// uses, so UnfoldConstant calls itself recursively for those.
676 /// @param[in] llvm_function
677 /// The function currently being processed.
680 /// True on success; false otherwise
681 //------------------------------------------------------------------
683 class FunctionValueCache {
685 typedef std::function <llvm::Value *(llvm::Function *)> Maker;
687 FunctionValueCache (Maker const &maker);
688 ~FunctionValueCache ();
689 llvm::Value *GetValue (llvm::Function *function);
692 typedef std::map<llvm::Function *, llvm::Value *> FunctionValueMap;
693 FunctionValueMap m_values;
696 FunctionValueCache m_entry_instruction_finder;
699 UnfoldConstant (llvm::Constant *old_constant,
700 FunctionValueCache &value_maker,
701 FunctionValueCache &entry_instruction_finder);
703 //------------------------------------------------------------------
704 /// Construct a reference to m_reloc_placeholder with a given type
705 /// and offset. This typically happens after inserting data into
706 /// m_data_allocator.
709 /// The type of the value being loaded.
711 /// @param[in] offset
712 /// The offset of the value from the base of m_data_allocator.
715 /// The Constant for the reference, usually a ConstantExpr.
716 //------------------------------------------------------------------
718 BuildRelocation(llvm::Type *type,
721 //------------------------------------------------------------------
722 /// Commit the allocation in m_data_allocator and use its final
723 /// location to replace m_reloc_placeholder.
725 /// @param[in] module
726 /// The module that m_data_allocator resides in
729 /// True on success; false otherwise
730 //------------------------------------------------------------------
732 CompleteDataAllocation ();