1 //===-- IRInterpreter.cpp ---------------------------------------*- 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 #include "lldb/Expression/IRInterpreter.h"
11 #include "lldb/Core/Module.h"
12 #include "lldb/Core/ModuleSpec.h"
13 #include "lldb/Core/Scalar.h"
14 #include "lldb/Core/ValueObject.h"
15 #include "lldb/Expression/DiagnosticManager.h"
16 #include "lldb/Expression/IRExecutionUnit.h"
17 #include "lldb/Expression/IRMemoryMap.h"
18 #include "lldb/Utility/ConstString.h"
19 #include "lldb/Utility/DataExtractor.h"
20 #include "lldb/Utility/Endian.h"
21 #include "lldb/Utility/Log.h"
22 #include "lldb/Utility/Status.h"
23 #include "lldb/Utility/StreamString.h"
25 #include "lldb/Target/ABI.h"
26 #include "lldb/Target/ExecutionContext.h"
27 #include "lldb/Target/Target.h"
28 #include "lldb/Target/Thread.h"
29 #include "lldb/Target/ThreadPlan.h"
30 #include "lldb/Target/ThreadPlanCallFunctionUsingABI.h"
32 #include "llvm/IR/Constants.h"
33 #include "llvm/IR/DataLayout.h"
34 #include "llvm/IR/Function.h"
35 #include "llvm/IR/Instructions.h"
36 #include "llvm/IR/Intrinsics.h"
37 #include "llvm/IR/LLVMContext.h"
38 #include "llvm/IR/Module.h"
39 #include "llvm/IR/Operator.h"
40 #include "llvm/Support/raw_ostream.h"
46 static std::string PrintValue(const Value *value, bool truncate = false) {
48 raw_string_ostream rso(s);
52 s.resize(s.length() - 1);
55 while ((offset = s.find('\n')) != s.npos)
57 while (s[0] == ' ' || s[0] == '\t')
63 static std::string PrintType(const Type *type, bool truncate = false) {
65 raw_string_ostream rso(s);
69 s.resize(s.length() - 1);
73 static bool CanIgnoreCall(const CallInst *call) {
74 const llvm::Function *called_function = call->getCalledFunction();
79 if (called_function->isIntrinsic()) {
80 switch (called_function->getIntrinsicID()) {
83 case llvm::Intrinsic::dbg_declare:
84 case llvm::Intrinsic::dbg_value:
92 class InterpreterStackFrame {
94 typedef std::map<const Value *, lldb::addr_t> ValueMap;
97 DataLayout &m_target_data;
98 lldb_private::IRExecutionUnit &m_execution_unit;
99 const BasicBlock *m_bb;
100 const BasicBlock *m_prev_bb;
101 BasicBlock::const_iterator m_ii;
102 BasicBlock::const_iterator m_ie;
104 lldb::addr_t m_frame_process_address;
106 lldb::addr_t m_stack_pointer;
108 lldb::ByteOrder m_byte_order;
109 size_t m_addr_byte_size;
111 InterpreterStackFrame(DataLayout &target_data,
112 lldb_private::IRExecutionUnit &execution_unit,
113 lldb::addr_t stack_frame_bottom,
114 lldb::addr_t stack_frame_top)
115 : m_target_data(target_data), m_execution_unit(execution_unit),
116 m_bb(nullptr), m_prev_bb(nullptr) {
117 m_byte_order = (target_data.isLittleEndian() ? lldb::eByteOrderLittle
118 : lldb::eByteOrderBig);
119 m_addr_byte_size = (target_data.getPointerSize(0));
121 m_frame_process_address = stack_frame_bottom;
122 m_frame_size = stack_frame_top - stack_frame_bottom;
123 m_stack_pointer = stack_frame_top;
126 ~InterpreterStackFrame() {}
128 void Jump(const BasicBlock *bb) {
131 m_ii = m_bb->begin();
135 std::string SummarizeValue(const Value *value) {
136 lldb_private::StreamString ss;
138 ss.Printf("%s", PrintValue(value).c_str());
140 ValueMap::iterator i = m_values.find(value);
142 if (i != m_values.end()) {
143 lldb::addr_t addr = i->second;
145 ss.Printf(" 0x%llx", (unsigned long long)addr);
148 return ss.GetString();
151 bool AssignToMatchType(lldb_private::Scalar &scalar, uint64_t u64value,
153 size_t type_size = m_target_data.getTypeStoreSize(type);
160 scalar = llvm::APInt(type_size*8, u64value);
169 bool EvaluateValue(lldb_private::Scalar &scalar, const Value *value,
171 const Constant *constant = dyn_cast<Constant>(value);
176 if (!ResolveConstantValue(value_apint, constant))
179 return AssignToMatchType(scalar, value_apint.getLimitedValue(),
182 lldb::addr_t process_address = ResolveValue(value, module);
183 size_t value_size = m_target_data.getTypeStoreSize(value->getType());
185 lldb_private::DataExtractor value_extractor;
186 lldb_private::Status extract_error;
188 m_execution_unit.GetMemoryData(value_extractor, process_address,
189 value_size, extract_error);
191 if (!extract_error.Success())
194 lldb::offset_t offset = 0;
195 if (value_size == 1 || value_size == 2 || value_size == 4 ||
197 uint64_t u64value = value_extractor.GetMaxU64(&offset, value_size);
198 return AssignToMatchType(scalar, u64value, value->getType());
205 bool AssignValue(const Value *value, lldb_private::Scalar &scalar,
207 lldb::addr_t process_address = ResolveValue(value, module);
209 if (process_address == LLDB_INVALID_ADDRESS)
212 lldb_private::Scalar cast_scalar;
214 if (!AssignToMatchType(cast_scalar, scalar.ULongLong(), value->getType()))
217 size_t value_byte_size = m_target_data.getTypeStoreSize(value->getType());
219 lldb_private::DataBufferHeap buf(value_byte_size, 0);
221 lldb_private::Status get_data_error;
223 if (!cast_scalar.GetAsMemoryData(buf.GetBytes(), buf.GetByteSize(),
224 m_byte_order, get_data_error))
227 lldb_private::Status write_error;
229 m_execution_unit.WriteMemory(process_address, buf.GetBytes(),
230 buf.GetByteSize(), write_error);
232 return write_error.Success();
235 bool ResolveConstantValue(APInt &value, const Constant *constant) {
236 switch (constant->getValueID()) {
239 case Value::FunctionVal:
240 if (const Function *constant_func = dyn_cast<Function>(constant)) {
241 lldb_private::ConstString name(constant_func->getName());
242 lldb::addr_t addr = m_execution_unit.FindSymbol(name);
243 if (addr == LLDB_INVALID_ADDRESS)
245 value = APInt(m_target_data.getPointerSizeInBits(), addr);
249 case Value::ConstantIntVal:
250 if (const ConstantInt *constant_int = dyn_cast<ConstantInt>(constant)) {
251 value = constant_int->getValue();
255 case Value::ConstantFPVal:
256 if (const ConstantFP *constant_fp = dyn_cast<ConstantFP>(constant)) {
257 value = constant_fp->getValueAPF().bitcastToAPInt();
261 case Value::ConstantExprVal:
262 if (const ConstantExpr *constant_expr =
263 dyn_cast<ConstantExpr>(constant)) {
264 switch (constant_expr->getOpcode()) {
267 case Instruction::IntToPtr:
268 case Instruction::PtrToInt:
269 case Instruction::BitCast:
270 return ResolveConstantValue(value, constant_expr->getOperand(0));
271 case Instruction::GetElementPtr: {
272 ConstantExpr::const_op_iterator op_cursor = constant_expr->op_begin();
273 ConstantExpr::const_op_iterator op_end = constant_expr->op_end();
275 Constant *base = dyn_cast<Constant>(*op_cursor);
280 if (!ResolveConstantValue(value, base))
285 if (op_cursor == op_end)
286 return true; // no offset to apply!
288 SmallVector<Value *, 8> indices(op_cursor, op_end);
291 cast<GEPOperator>(constant_expr)->getSourceElementType();
293 m_target_data.getIndexedOffsetInType(src_elem_ty, indices);
295 const bool is_signed = true;
296 value += APInt(value.getBitWidth(), offset, is_signed);
303 case Value::ConstantPointerNullVal:
304 if (isa<ConstantPointerNull>(constant)) {
305 value = APInt(m_target_data.getPointerSizeInBits(), 0);
313 bool MakeArgument(const Argument *value, uint64_t address) {
314 lldb::addr_t data_address = Malloc(value->getType());
316 if (data_address == LLDB_INVALID_ADDRESS)
319 lldb_private::Status write_error;
321 m_execution_unit.WritePointerToMemory(data_address, address, write_error);
323 if (!write_error.Success()) {
324 lldb_private::Status free_error;
325 m_execution_unit.Free(data_address, free_error);
329 m_values[value] = data_address;
331 lldb_private::Log *log(
332 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
335 log->Printf("Made an allocation for argument %s",
336 PrintValue(value).c_str());
337 log->Printf(" Data region : %llx", (unsigned long long)address);
338 log->Printf(" Ref region : %llx", (unsigned long long)data_address);
344 bool ResolveConstant(lldb::addr_t process_address, const Constant *constant) {
345 APInt resolved_value;
347 if (!ResolveConstantValue(resolved_value, constant))
350 size_t constant_size = m_target_data.getTypeStoreSize(constant->getType());
351 lldb_private::DataBufferHeap buf(constant_size, 0);
353 lldb_private::Status get_data_error;
355 lldb_private::Scalar resolved_scalar(
356 resolved_value.zextOrTrunc(llvm::NextPowerOf2(constant_size) * 8));
357 if (!resolved_scalar.GetAsMemoryData(buf.GetBytes(), buf.GetByteSize(),
358 m_byte_order, get_data_error))
361 lldb_private::Status write_error;
363 m_execution_unit.WriteMemory(process_address, buf.GetBytes(),
364 buf.GetByteSize(), write_error);
366 return write_error.Success();
369 lldb::addr_t Malloc(size_t size, uint8_t byte_alignment) {
370 lldb::addr_t ret = m_stack_pointer;
373 ret -= (ret % byte_alignment);
375 if (ret < m_frame_process_address)
376 return LLDB_INVALID_ADDRESS;
378 m_stack_pointer = ret;
382 lldb::addr_t Malloc(llvm::Type *type) {
383 lldb_private::Status alloc_error;
385 return Malloc(m_target_data.getTypeAllocSize(type),
386 m_target_data.getPrefTypeAlignment(type));
389 std::string PrintData(lldb::addr_t addr, llvm::Type *type) {
390 size_t length = m_target_data.getTypeStoreSize(type);
392 lldb_private::DataBufferHeap buf(length, 0);
394 lldb_private::Status read_error;
396 m_execution_unit.ReadMemory(buf.GetBytes(), addr, length, read_error);
398 if (!read_error.Success())
399 return std::string("<couldn't read data>");
401 lldb_private::StreamString ss;
403 for (size_t i = 0; i < length; i++) {
404 if ((!(i & 0xf)) && i)
405 ss.Printf("%02hhx - ", buf.GetBytes()[i]);
407 ss.Printf("%02hhx ", buf.GetBytes()[i]);
410 return ss.GetString();
413 lldb::addr_t ResolveValue(const Value *value, Module &module) {
414 ValueMap::iterator i = m_values.find(value);
416 if (i != m_values.end())
419 // Fall back and allocate space [allocation type Alloca]
421 lldb::addr_t data_address = Malloc(value->getType());
423 if (const Constant *constant = dyn_cast<Constant>(value)) {
424 if (!ResolveConstant(data_address, constant)) {
425 lldb_private::Status free_error;
426 m_execution_unit.Free(data_address, free_error);
427 return LLDB_INVALID_ADDRESS;
431 m_values[value] = data_address;
436 static const char *unsupported_opcode_error =
437 "Interpreter doesn't handle one of the expression's opcodes";
438 static const char *unsupported_operand_error =
439 "Interpreter doesn't handle one of the expression's operands";
440 // static const char *interpreter_initialization_error = "Interpreter couldn't
442 static const char *interpreter_internal_error =
443 "Interpreter encountered an internal error";
444 static const char *bad_value_error =
445 "Interpreter couldn't resolve a value during execution";
446 static const char *memory_allocation_error =
447 "Interpreter couldn't allocate memory";
448 static const char *memory_write_error = "Interpreter couldn't write to memory";
449 static const char *memory_read_error = "Interpreter couldn't read from memory";
450 static const char *infinite_loop_error = "Interpreter ran for too many cycles";
451 // static const char *bad_result_error = "Result of expression
452 // is in bad memory";
453 static const char *too_many_functions_error =
454 "Interpreter doesn't handle modules with multiple function bodies.";
456 static bool CanResolveConstant(llvm::Constant *constant) {
457 switch (constant->getValueID()) {
460 case Value::ConstantIntVal:
461 case Value::ConstantFPVal:
462 case Value::FunctionVal:
464 case Value::ConstantExprVal:
465 if (const ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant)) {
466 switch (constant_expr->getOpcode()) {
469 case Instruction::IntToPtr:
470 case Instruction::PtrToInt:
471 case Instruction::BitCast:
472 return CanResolveConstant(constant_expr->getOperand(0));
473 case Instruction::GetElementPtr: {
474 ConstantExpr::const_op_iterator op_cursor = constant_expr->op_begin();
475 Constant *base = dyn_cast<Constant>(*op_cursor);
479 return CanResolveConstant(base);
485 case Value::ConstantPointerNullVal:
490 bool IRInterpreter::CanInterpret(llvm::Module &module, llvm::Function &function,
491 lldb_private::Status &error,
492 const bool support_function_calls) {
493 lldb_private::Log *log(
494 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
496 bool saw_function_with_body = false;
498 for (Module::iterator fi = module.begin(), fe = module.end(); fi != fe;
500 if (fi->begin() != fi->end()) {
501 if (saw_function_with_body) {
503 log->Printf("More than one function in the module has a body");
504 error.SetErrorToGenericError();
505 error.SetErrorString(too_many_functions_error);
508 saw_function_with_body = true;
512 for (Function::iterator bbi = function.begin(), bbe = function.end();
514 for (BasicBlock::iterator ii = bbi->begin(), ie = bbi->end(); ii != ie;
516 switch (ii->getOpcode()) {
519 log->Printf("Unsupported instruction: %s", PrintValue(&*ii).c_str());
520 error.SetErrorToGenericError();
521 error.SetErrorString(unsupported_opcode_error);
524 case Instruction::Add:
525 case Instruction::Alloca:
526 case Instruction::BitCast:
527 case Instruction::Br:
528 case Instruction::PHI:
530 case Instruction::Call: {
531 CallInst *call_inst = dyn_cast<CallInst>(ii);
534 error.SetErrorToGenericError();
535 error.SetErrorString(interpreter_internal_error);
539 if (!CanIgnoreCall(call_inst) && !support_function_calls) {
541 log->Printf("Unsupported instruction: %s",
542 PrintValue(&*ii).c_str());
543 error.SetErrorToGenericError();
544 error.SetErrorString(unsupported_opcode_error);
548 case Instruction::GetElementPtr:
550 case Instruction::ICmp: {
551 ICmpInst *icmp_inst = dyn_cast<ICmpInst>(ii);
554 error.SetErrorToGenericError();
555 error.SetErrorString(interpreter_internal_error);
559 switch (icmp_inst->getPredicate()) {
562 log->Printf("Unsupported ICmp predicate: %s",
563 PrintValue(&*ii).c_str());
565 error.SetErrorToGenericError();
566 error.SetErrorString(unsupported_opcode_error);
569 case CmpInst::ICMP_EQ:
570 case CmpInst::ICMP_NE:
571 case CmpInst::ICMP_UGT:
572 case CmpInst::ICMP_UGE:
573 case CmpInst::ICMP_ULT:
574 case CmpInst::ICMP_ULE:
575 case CmpInst::ICMP_SGT:
576 case CmpInst::ICMP_SGE:
577 case CmpInst::ICMP_SLT:
578 case CmpInst::ICMP_SLE:
582 case Instruction::And:
583 case Instruction::AShr:
584 case Instruction::IntToPtr:
585 case Instruction::PtrToInt:
586 case Instruction::Load:
587 case Instruction::LShr:
588 case Instruction::Mul:
589 case Instruction::Or:
590 case Instruction::Ret:
591 case Instruction::SDiv:
592 case Instruction::SExt:
593 case Instruction::Shl:
594 case Instruction::SRem:
595 case Instruction::Store:
596 case Instruction::Sub:
597 case Instruction::Trunc:
598 case Instruction::UDiv:
599 case Instruction::URem:
600 case Instruction::Xor:
601 case Instruction::ZExt:
605 for (int oi = 0, oe = ii->getNumOperands(); oi != oe; ++oi) {
606 Value *operand = ii->getOperand(oi);
607 Type *operand_type = operand->getType();
609 switch (operand_type->getTypeID()) {
612 case Type::VectorTyID: {
614 log->Printf("Unsupported operand type: %s",
615 PrintType(operand_type).c_str());
616 error.SetErrorString(unsupported_operand_error);
621 if (Constant *constant = llvm::dyn_cast<Constant>(operand)) {
622 if (!CanResolveConstant(constant)) {
624 log->Printf("Unsupported constant: %s",
625 PrintValue(constant).c_str());
626 error.SetErrorString(unsupported_operand_error);
637 bool IRInterpreter::Interpret(llvm::Module &module, llvm::Function &function,
638 llvm::ArrayRef<lldb::addr_t> args,
639 lldb_private::IRExecutionUnit &execution_unit,
640 lldb_private::Status &error,
641 lldb::addr_t stack_frame_bottom,
642 lldb::addr_t stack_frame_top,
643 lldb_private::ExecutionContext &exe_ctx) {
644 lldb_private::Log *log(
645 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
649 raw_string_ostream oss(s);
651 module.print(oss, NULL);
655 log->Printf("Module as passed in to IRInterpreter::Interpret: \n\"%s\"",
659 DataLayout data_layout(&module);
661 InterpreterStackFrame frame(data_layout, execution_unit, stack_frame_bottom,
664 if (frame.m_frame_process_address == LLDB_INVALID_ADDRESS) {
665 error.SetErrorString("Couldn't allocate stack frame");
670 for (llvm::Function::arg_iterator ai = function.arg_begin(),
671 ae = function.arg_end();
672 ai != ae; ++ai, ++arg_index) {
673 if (args.size() <= static_cast<size_t>(arg_index)) {
674 error.SetErrorString("Not enough arguments passed in to function");
678 lldb::addr_t ptr = args[arg_index];
680 frame.MakeArgument(&*ai, ptr);
683 uint32_t num_insts = 0;
685 frame.Jump(&function.front());
687 while (frame.m_ii != frame.m_ie && (++num_insts < 4096)) {
688 const Instruction *inst = &*frame.m_ii;
691 log->Printf("Interpreting %s", PrintValue(inst).c_str());
693 switch (inst->getOpcode()) {
697 case Instruction::Add:
698 case Instruction::Sub:
699 case Instruction::Mul:
700 case Instruction::SDiv:
701 case Instruction::UDiv:
702 case Instruction::SRem:
703 case Instruction::URem:
704 case Instruction::Shl:
705 case Instruction::LShr:
706 case Instruction::AShr:
707 case Instruction::And:
708 case Instruction::Or:
709 case Instruction::Xor: {
710 const BinaryOperator *bin_op = dyn_cast<BinaryOperator>(inst);
715 "getOpcode() returns %s, but instruction is not a BinaryOperator",
716 inst->getOpcodeName());
717 error.SetErrorToGenericError();
718 error.SetErrorString(interpreter_internal_error);
722 Value *lhs = inst->getOperand(0);
723 Value *rhs = inst->getOperand(1);
725 lldb_private::Scalar L;
726 lldb_private::Scalar R;
728 if (!frame.EvaluateValue(L, lhs, module)) {
730 log->Printf("Couldn't evaluate %s", PrintValue(lhs).c_str());
731 error.SetErrorToGenericError();
732 error.SetErrorString(bad_value_error);
736 if (!frame.EvaluateValue(R, rhs, module)) {
738 log->Printf("Couldn't evaluate %s", PrintValue(rhs).c_str());
739 error.SetErrorToGenericError();
740 error.SetErrorString(bad_value_error);
744 lldb_private::Scalar result;
746 switch (inst->getOpcode()) {
749 case Instruction::Add:
752 case Instruction::Mul:
755 case Instruction::Sub:
758 case Instruction::SDiv:
763 case Instruction::UDiv:
768 case Instruction::SRem:
773 case Instruction::URem:
778 case Instruction::Shl:
781 case Instruction::AShr:
784 case Instruction::LShr:
786 result.ShiftRightLogical(R);
788 case Instruction::And:
791 case Instruction::Or:
794 case Instruction::Xor:
799 frame.AssignValue(inst, result, module);
802 log->Printf("Interpreted a %s", inst->getOpcodeName());
803 log->Printf(" L : %s", frame.SummarizeValue(lhs).c_str());
804 log->Printf(" R : %s", frame.SummarizeValue(rhs).c_str());
805 log->Printf(" = : %s", frame.SummarizeValue(inst).c_str());
808 case Instruction::Alloca: {
809 const AllocaInst *alloca_inst = dyn_cast<AllocaInst>(inst);
813 log->Printf("getOpcode() returns Alloca, but instruction is not an "
815 error.SetErrorToGenericError();
816 error.SetErrorString(interpreter_internal_error);
820 if (alloca_inst->isArrayAllocation()) {
823 "AllocaInsts are not handled if isArrayAllocation() is true");
824 error.SetErrorToGenericError();
825 error.SetErrorString(unsupported_opcode_error);
829 // The semantics of Alloca are:
830 // Create a region R of virtual memory of type T, backed by a data
832 // Create a region P of virtual memory of type T*, backed by a data
834 // Write the virtual address of R into P
836 Type *T = alloca_inst->getAllocatedType();
837 Type *Tptr = alloca_inst->getType();
839 lldb::addr_t R = frame.Malloc(T);
841 if (R == LLDB_INVALID_ADDRESS) {
843 log->Printf("Couldn't allocate memory for an AllocaInst");
844 error.SetErrorToGenericError();
845 error.SetErrorString(memory_allocation_error);
849 lldb::addr_t P = frame.Malloc(Tptr);
851 if (P == LLDB_INVALID_ADDRESS) {
853 log->Printf("Couldn't allocate the result pointer for an AllocaInst");
854 error.SetErrorToGenericError();
855 error.SetErrorString(memory_allocation_error);
859 lldb_private::Status write_error;
861 execution_unit.WritePointerToMemory(P, R, write_error);
863 if (!write_error.Success()) {
865 log->Printf("Couldn't write the result pointer for an AllocaInst");
866 error.SetErrorToGenericError();
867 error.SetErrorString(memory_write_error);
868 lldb_private::Status free_error;
869 execution_unit.Free(P, free_error);
870 execution_unit.Free(R, free_error);
874 frame.m_values[alloca_inst] = P;
877 log->Printf("Interpreted an AllocaInst");
878 log->Printf(" R : 0x%" PRIx64, R);
879 log->Printf(" P : 0x%" PRIx64, P);
882 case Instruction::BitCast:
883 case Instruction::ZExt: {
884 const CastInst *cast_inst = dyn_cast<CastInst>(inst);
889 "getOpcode() returns %s, but instruction is not a BitCastInst",
890 cast_inst->getOpcodeName());
891 error.SetErrorToGenericError();
892 error.SetErrorString(interpreter_internal_error);
896 Value *source = cast_inst->getOperand(0);
898 lldb_private::Scalar S;
900 if (!frame.EvaluateValue(S, source, module)) {
902 log->Printf("Couldn't evaluate %s", PrintValue(source).c_str());
903 error.SetErrorToGenericError();
904 error.SetErrorString(bad_value_error);
908 frame.AssignValue(inst, S, module);
910 case Instruction::SExt: {
911 const CastInst *cast_inst = dyn_cast<CastInst>(inst);
916 "getOpcode() returns %s, but instruction is not a BitCastInst",
917 cast_inst->getOpcodeName());
918 error.SetErrorToGenericError();
919 error.SetErrorString(interpreter_internal_error);
923 Value *source = cast_inst->getOperand(0);
925 lldb_private::Scalar S;
927 if (!frame.EvaluateValue(S, source, module)) {
929 log->Printf("Couldn't evaluate %s", PrintValue(source).c_str());
930 error.SetErrorToGenericError();
931 error.SetErrorString(bad_value_error);
937 lldb_private::Scalar S_signextend(S.SLongLong());
939 frame.AssignValue(inst, S_signextend, module);
941 case Instruction::Br: {
942 const BranchInst *br_inst = dyn_cast<BranchInst>(inst);
947 "getOpcode() returns Br, but instruction is not a BranchInst");
948 error.SetErrorToGenericError();
949 error.SetErrorString(interpreter_internal_error);
953 if (br_inst->isConditional()) {
954 Value *condition = br_inst->getCondition();
956 lldb_private::Scalar C;
958 if (!frame.EvaluateValue(C, condition, module)) {
960 log->Printf("Couldn't evaluate %s", PrintValue(condition).c_str());
961 error.SetErrorToGenericError();
962 error.SetErrorString(bad_value_error);
967 frame.Jump(br_inst->getSuccessor(0));
969 frame.Jump(br_inst->getSuccessor(1));
972 log->Printf("Interpreted a BrInst with a condition");
973 log->Printf(" cond : %s", frame.SummarizeValue(condition).c_str());
976 frame.Jump(br_inst->getSuccessor(0));
979 log->Printf("Interpreted a BrInst with no condition");
984 case Instruction::PHI: {
985 const PHINode *phi_inst = dyn_cast<PHINode>(inst);
990 "getOpcode() returns PHI, but instruction is not a PHINode");
991 error.SetErrorToGenericError();
992 error.SetErrorString(interpreter_internal_error);
995 if (!frame.m_prev_bb) {
997 log->Printf("Encountered PHI node without having jumped from another "
999 error.SetErrorToGenericError();
1000 error.SetErrorString(interpreter_internal_error);
1004 Value *value = phi_inst->getIncomingValueForBlock(frame.m_prev_bb);
1005 lldb_private::Scalar result;
1006 if (!frame.EvaluateValue(result, value, module)) {
1008 log->Printf("Couldn't evaluate %s", PrintValue(value).c_str());
1009 error.SetErrorToGenericError();
1010 error.SetErrorString(bad_value_error);
1013 frame.AssignValue(inst, result, module);
1016 log->Printf("Interpreted a %s", inst->getOpcodeName());
1017 log->Printf(" Incoming value : %s",
1018 frame.SummarizeValue(value).c_str());
1021 case Instruction::GetElementPtr: {
1022 const GetElementPtrInst *gep_inst = dyn_cast<GetElementPtrInst>(inst);
1026 log->Printf("getOpcode() returns GetElementPtr, but instruction is "
1027 "not a GetElementPtrInst");
1028 error.SetErrorToGenericError();
1029 error.SetErrorString(interpreter_internal_error);
1033 const Value *pointer_operand = gep_inst->getPointerOperand();
1034 Type *src_elem_ty = gep_inst->getSourceElementType();
1036 lldb_private::Scalar P;
1038 if (!frame.EvaluateValue(P, pointer_operand, module)) {
1040 log->Printf("Couldn't evaluate %s",
1041 PrintValue(pointer_operand).c_str());
1042 error.SetErrorToGenericError();
1043 error.SetErrorString(bad_value_error);
1047 typedef SmallVector<Value *, 8> IndexVector;
1048 typedef IndexVector::iterator IndexIterator;
1050 SmallVector<Value *, 8> indices(gep_inst->idx_begin(),
1051 gep_inst->idx_end());
1053 SmallVector<Value *, 8> const_indices;
1055 for (IndexIterator ii = indices.begin(), ie = indices.end(); ii != ie;
1057 ConstantInt *constant_index = dyn_cast<ConstantInt>(*ii);
1059 if (!constant_index) {
1060 lldb_private::Scalar I;
1062 if (!frame.EvaluateValue(I, *ii, module)) {
1064 log->Printf("Couldn't evaluate %s", PrintValue(*ii).c_str());
1065 error.SetErrorToGenericError();
1066 error.SetErrorString(bad_value_error);
1071 log->Printf("Evaluated constant index %s as %llu",
1072 PrintValue(*ii).c_str(),
1073 I.ULongLong(LLDB_INVALID_ADDRESS));
1075 constant_index = cast<ConstantInt>(ConstantInt::get(
1076 (*ii)->getType(), I.ULongLong(LLDB_INVALID_ADDRESS)));
1079 const_indices.push_back(constant_index);
1083 data_layout.getIndexedOffsetInType(src_elem_ty, const_indices);
1085 lldb_private::Scalar Poffset = P + offset;
1087 frame.AssignValue(inst, Poffset, module);
1090 log->Printf("Interpreted a GetElementPtrInst");
1091 log->Printf(" P : %s",
1092 frame.SummarizeValue(pointer_operand).c_str());
1093 log->Printf(" Poffset : %s", frame.SummarizeValue(inst).c_str());
1096 case Instruction::ICmp: {
1097 const ICmpInst *icmp_inst = dyn_cast<ICmpInst>(inst);
1102 "getOpcode() returns ICmp, but instruction is not an ICmpInst");
1103 error.SetErrorToGenericError();
1104 error.SetErrorString(interpreter_internal_error);
1108 CmpInst::Predicate predicate = icmp_inst->getPredicate();
1110 Value *lhs = inst->getOperand(0);
1111 Value *rhs = inst->getOperand(1);
1113 lldb_private::Scalar L;
1114 lldb_private::Scalar R;
1116 if (!frame.EvaluateValue(L, lhs, module)) {
1118 log->Printf("Couldn't evaluate %s", PrintValue(lhs).c_str());
1119 error.SetErrorToGenericError();
1120 error.SetErrorString(bad_value_error);
1124 if (!frame.EvaluateValue(R, rhs, module)) {
1126 log->Printf("Couldn't evaluate %s", PrintValue(rhs).c_str());
1127 error.SetErrorToGenericError();
1128 error.SetErrorString(bad_value_error);
1132 lldb_private::Scalar result;
1134 switch (predicate) {
1137 case CmpInst::ICMP_EQ:
1140 case CmpInst::ICMP_NE:
1143 case CmpInst::ICMP_UGT:
1148 case CmpInst::ICMP_UGE:
1153 case CmpInst::ICMP_ULT:
1158 case CmpInst::ICMP_ULE:
1163 case CmpInst::ICMP_SGT:
1168 case CmpInst::ICMP_SGE:
1173 case CmpInst::ICMP_SLT:
1178 case CmpInst::ICMP_SLE:
1185 frame.AssignValue(inst, result, module);
1188 log->Printf("Interpreted an ICmpInst");
1189 log->Printf(" L : %s", frame.SummarizeValue(lhs).c_str());
1190 log->Printf(" R : %s", frame.SummarizeValue(rhs).c_str());
1191 log->Printf(" = : %s", frame.SummarizeValue(inst).c_str());
1194 case Instruction::IntToPtr: {
1195 const IntToPtrInst *int_to_ptr_inst = dyn_cast<IntToPtrInst>(inst);
1197 if (!int_to_ptr_inst) {
1199 log->Printf("getOpcode() returns IntToPtr, but instruction is not an "
1201 error.SetErrorToGenericError();
1202 error.SetErrorString(interpreter_internal_error);
1206 Value *src_operand = int_to_ptr_inst->getOperand(0);
1208 lldb_private::Scalar I;
1210 if (!frame.EvaluateValue(I, src_operand, module)) {
1212 log->Printf("Couldn't evaluate %s", PrintValue(src_operand).c_str());
1213 error.SetErrorToGenericError();
1214 error.SetErrorString(bad_value_error);
1218 frame.AssignValue(inst, I, module);
1221 log->Printf("Interpreted an IntToPtr");
1222 log->Printf(" Src : %s", frame.SummarizeValue(src_operand).c_str());
1223 log->Printf(" = : %s", frame.SummarizeValue(inst).c_str());
1226 case Instruction::PtrToInt: {
1227 const PtrToIntInst *ptr_to_int_inst = dyn_cast<PtrToIntInst>(inst);
1229 if (!ptr_to_int_inst) {
1231 log->Printf("getOpcode() returns PtrToInt, but instruction is not an "
1233 error.SetErrorToGenericError();
1234 error.SetErrorString(interpreter_internal_error);
1238 Value *src_operand = ptr_to_int_inst->getOperand(0);
1240 lldb_private::Scalar I;
1242 if (!frame.EvaluateValue(I, src_operand, module)) {
1244 log->Printf("Couldn't evaluate %s", PrintValue(src_operand).c_str());
1245 error.SetErrorToGenericError();
1246 error.SetErrorString(bad_value_error);
1250 frame.AssignValue(inst, I, module);
1253 log->Printf("Interpreted a PtrToInt");
1254 log->Printf(" Src : %s", frame.SummarizeValue(src_operand).c_str());
1255 log->Printf(" = : %s", frame.SummarizeValue(inst).c_str());
1258 case Instruction::Trunc: {
1259 const TruncInst *trunc_inst = dyn_cast<TruncInst>(inst);
1264 "getOpcode() returns Trunc, but instruction is not a TruncInst");
1265 error.SetErrorToGenericError();
1266 error.SetErrorString(interpreter_internal_error);
1270 Value *src_operand = trunc_inst->getOperand(0);
1272 lldb_private::Scalar I;
1274 if (!frame.EvaluateValue(I, src_operand, module)) {
1276 log->Printf("Couldn't evaluate %s", PrintValue(src_operand).c_str());
1277 error.SetErrorToGenericError();
1278 error.SetErrorString(bad_value_error);
1282 frame.AssignValue(inst, I, module);
1285 log->Printf("Interpreted a Trunc");
1286 log->Printf(" Src : %s", frame.SummarizeValue(src_operand).c_str());
1287 log->Printf(" = : %s", frame.SummarizeValue(inst).c_str());
1290 case Instruction::Load: {
1291 const LoadInst *load_inst = dyn_cast<LoadInst>(inst);
1296 "getOpcode() returns Load, but instruction is not a LoadInst");
1297 error.SetErrorToGenericError();
1298 error.SetErrorString(interpreter_internal_error);
1302 // The semantics of Load are:
1303 // Create a region D that will contain the loaded data
1304 // Resolve the region P containing a pointer
1305 // Dereference P to get the region R that the data should be loaded from
1306 // Transfer a unit of type type(D) from R to D
1308 const Value *pointer_operand = load_inst->getPointerOperand();
1310 Type *pointer_ty = pointer_operand->getType();
1311 PointerType *pointer_ptr_ty = dyn_cast<PointerType>(pointer_ty);
1312 if (!pointer_ptr_ty) {
1314 log->Printf("getPointerOperand()->getType() is not a PointerType");
1315 error.SetErrorToGenericError();
1316 error.SetErrorString(interpreter_internal_error);
1319 Type *target_ty = pointer_ptr_ty->getElementType();
1321 lldb::addr_t D = frame.ResolveValue(load_inst, module);
1322 lldb::addr_t P = frame.ResolveValue(pointer_operand, module);
1324 if (D == LLDB_INVALID_ADDRESS) {
1326 log->Printf("LoadInst's value doesn't resolve to anything");
1327 error.SetErrorToGenericError();
1328 error.SetErrorString(bad_value_error);
1332 if (P == LLDB_INVALID_ADDRESS) {
1334 log->Printf("LoadInst's pointer doesn't resolve to anything");
1335 error.SetErrorToGenericError();
1336 error.SetErrorString(bad_value_error);
1341 lldb_private::Status read_error;
1342 execution_unit.ReadPointerFromMemory(&R, P, read_error);
1344 if (!read_error.Success()) {
1346 log->Printf("Couldn't read the address to be loaded for a LoadInst");
1347 error.SetErrorToGenericError();
1348 error.SetErrorString(memory_read_error);
1352 size_t target_size = data_layout.getTypeStoreSize(target_ty);
1353 lldb_private::DataBufferHeap buffer(target_size, 0);
1356 execution_unit.ReadMemory(buffer.GetBytes(), R, buffer.GetByteSize(),
1358 if (!read_error.Success()) {
1360 log->Printf("Couldn't read from a region on behalf of a LoadInst");
1361 error.SetErrorToGenericError();
1362 error.SetErrorString(memory_read_error);
1366 lldb_private::Status write_error;
1367 execution_unit.WriteMemory(D, buffer.GetBytes(), buffer.GetByteSize(),
1369 if (!write_error.Success()) {
1371 log->Printf("Couldn't write to a region on behalf of a LoadInst");
1372 error.SetErrorToGenericError();
1373 error.SetErrorString(memory_read_error);
1378 log->Printf("Interpreted a LoadInst");
1379 log->Printf(" P : 0x%" PRIx64, P);
1380 log->Printf(" R : 0x%" PRIx64, R);
1381 log->Printf(" D : 0x%" PRIx64, D);
1384 case Instruction::Ret: {
1387 case Instruction::Store: {
1388 const StoreInst *store_inst = dyn_cast<StoreInst>(inst);
1393 "getOpcode() returns Store, but instruction is not a StoreInst");
1394 error.SetErrorToGenericError();
1395 error.SetErrorString(interpreter_internal_error);
1399 // The semantics of Store are:
1400 // Resolve the region D containing the data to be stored
1401 // Resolve the region P containing a pointer
1402 // Dereference P to get the region R that the data should be stored in
1403 // Transfer a unit of type type(D) from D to R
1405 const Value *value_operand = store_inst->getValueOperand();
1406 const Value *pointer_operand = store_inst->getPointerOperand();
1408 Type *pointer_ty = pointer_operand->getType();
1409 PointerType *pointer_ptr_ty = dyn_cast<PointerType>(pointer_ty);
1410 if (!pointer_ptr_ty)
1412 Type *target_ty = pointer_ptr_ty->getElementType();
1414 lldb::addr_t D = frame.ResolveValue(value_operand, module);
1415 lldb::addr_t P = frame.ResolveValue(pointer_operand, module);
1417 if (D == LLDB_INVALID_ADDRESS) {
1419 log->Printf("StoreInst's value doesn't resolve to anything");
1420 error.SetErrorToGenericError();
1421 error.SetErrorString(bad_value_error);
1425 if (P == LLDB_INVALID_ADDRESS) {
1427 log->Printf("StoreInst's pointer doesn't resolve to anything");
1428 error.SetErrorToGenericError();
1429 error.SetErrorString(bad_value_error);
1434 lldb_private::Status read_error;
1435 execution_unit.ReadPointerFromMemory(&R, P, read_error);
1437 if (!read_error.Success()) {
1439 log->Printf("Couldn't read the address to be loaded for a LoadInst");
1440 error.SetErrorToGenericError();
1441 error.SetErrorString(memory_read_error);
1445 size_t target_size = data_layout.getTypeStoreSize(target_ty);
1446 lldb_private::DataBufferHeap buffer(target_size, 0);
1449 execution_unit.ReadMemory(buffer.GetBytes(), D, buffer.GetByteSize(),
1451 if (!read_error.Success()) {
1453 log->Printf("Couldn't read from a region on behalf of a StoreInst");
1454 error.SetErrorToGenericError();
1455 error.SetErrorString(memory_read_error);
1459 lldb_private::Status write_error;
1460 execution_unit.WriteMemory(R, buffer.GetBytes(), buffer.GetByteSize(),
1462 if (!write_error.Success()) {
1464 log->Printf("Couldn't write to a region on behalf of a StoreInst");
1465 error.SetErrorToGenericError();
1466 error.SetErrorString(memory_write_error);
1471 log->Printf("Interpreted a StoreInst");
1472 log->Printf(" D : 0x%" PRIx64, D);
1473 log->Printf(" P : 0x%" PRIx64, P);
1474 log->Printf(" R : 0x%" PRIx64, R);
1477 case Instruction::Call: {
1478 const CallInst *call_inst = dyn_cast<CallInst>(inst);
1483 "getOpcode() returns %s, but instruction is not a CallInst",
1484 inst->getOpcodeName());
1485 error.SetErrorToGenericError();
1486 error.SetErrorString(interpreter_internal_error);
1490 if (CanIgnoreCall(call_inst))
1493 // Get the return type
1494 llvm::Type *returnType = call_inst->getType();
1495 if (returnType == nullptr) {
1496 error.SetErrorToGenericError();
1497 error.SetErrorString("unable to access return type");
1501 // Work with void, integer and pointer return types
1502 if (!returnType->isVoidTy() && !returnType->isIntegerTy() &&
1503 !returnType->isPointerTy()) {
1504 error.SetErrorToGenericError();
1505 error.SetErrorString("return type is not supported");
1509 // Check we can actually get a thread
1510 if (exe_ctx.GetThreadPtr() == nullptr) {
1511 error.SetErrorToGenericError();
1512 error.SetErrorStringWithFormat("unable to acquire thread");
1516 // Make sure we have a valid process
1517 if (!exe_ctx.GetProcessPtr()) {
1518 error.SetErrorToGenericError();
1519 error.SetErrorStringWithFormat("unable to get the process");
1523 // Find the address of the callee function
1524 lldb_private::Scalar I;
1525 const llvm::Value *val = call_inst->getCalledValue();
1527 if (!frame.EvaluateValue(I, val, module)) {
1528 error.SetErrorToGenericError();
1529 error.SetErrorString("unable to get address of function");
1532 lldb_private::Address funcAddr(I.ULongLong(LLDB_INVALID_ADDRESS));
1534 lldb_private::DiagnosticManager diagnostics;
1535 lldb_private::EvaluateExpressionOptions options;
1537 // We generally receive a function pointer which we must dereference
1538 llvm::Type *prototype = val->getType();
1539 if (!prototype->isPointerTy()) {
1540 error.SetErrorToGenericError();
1541 error.SetErrorString("call need function pointer");
1545 // Dereference the function pointer
1546 prototype = prototype->getPointerElementType();
1547 if (!(prototype->isFunctionTy() || prototype->isFunctionVarArg())) {
1548 error.SetErrorToGenericError();
1549 error.SetErrorString("call need function pointer");
1553 // Find number of arguments
1554 const int numArgs = call_inst->getNumArgOperands();
1556 // We work with a fixed array of 16 arguments which is our upper limit
1557 static lldb_private::ABI::CallArgument rawArgs[16];
1558 if (numArgs >= 16) {
1559 error.SetErrorToGenericError();
1560 error.SetErrorStringWithFormat("function takes too many arguments");
1564 // Push all function arguments to the argument list that will be passed
1565 // to the call function thread plan
1566 for (int i = 0; i < numArgs; i++) {
1567 // Get details of this argument
1568 llvm::Value *arg_op = call_inst->getArgOperand(i);
1569 llvm::Type *arg_ty = arg_op->getType();
1571 // Ensure that this argument is an supported type
1572 if (!arg_ty->isIntegerTy() && !arg_ty->isPointerTy()) {
1573 error.SetErrorToGenericError();
1574 error.SetErrorStringWithFormat("argument %d must be integer type", i);
1578 // Extract the arguments value
1579 lldb_private::Scalar tmp_op = 0;
1580 if (!frame.EvaluateValue(tmp_op, arg_op, module)) {
1581 error.SetErrorToGenericError();
1582 error.SetErrorStringWithFormat("unable to evaluate argument %d", i);
1586 // Check if this is a string literal or constant string pointer
1587 if (arg_ty->isPointerTy()) {
1588 // Pointer to just one type
1589 assert(arg_ty->getNumContainedTypes() == 1);
1591 lldb::addr_t addr = tmp_op.ULongLong();
1592 size_t dataSize = 0;
1594 bool Success = execution_unit.GetAllocSize(addr, dataSize);
1597 "unable to locate host data for transfer to device");
1598 // Create the required buffer
1599 rawArgs[i].size = dataSize;
1600 rawArgs[i].data_ap.reset(new uint8_t[dataSize + 1]);
1602 // Read string from host memory
1603 execution_unit.ReadMemory(rawArgs[i].data_ap.get(), addr, dataSize,
1605 assert(!error.Fail() &&
1606 "we have failed to read the string from memory");
1608 // Add null terminator
1609 rawArgs[i].data_ap[dataSize] = '\0';
1610 rawArgs[i].type = lldb_private::ABI::CallArgument::HostPointer;
1611 } else /* if ( arg_ty->isPointerTy() ) */
1613 rawArgs[i].type = lldb_private::ABI::CallArgument::TargetValue;
1614 // Get argument size in bytes
1615 rawArgs[i].size = arg_ty->getIntegerBitWidth() / 8;
1616 // Push value into argument list for thread plan
1617 rawArgs[i].value = tmp_op.ULongLong();
1621 // Pack the arguments into an llvm::array
1622 llvm::ArrayRef<lldb_private::ABI::CallArgument> args(rawArgs, numArgs);
1624 // Setup a thread plan to call the target function
1625 lldb::ThreadPlanSP call_plan_sp(
1626 new lldb_private::ThreadPlanCallFunctionUsingABI(
1627 exe_ctx.GetThreadRef(), funcAddr, *prototype, *returnType, args,
1630 // Check if the plan is valid
1631 lldb_private::StreamString ss;
1632 if (!call_plan_sp || !call_plan_sp->ValidatePlan(&ss)) {
1633 error.SetErrorToGenericError();
1634 error.SetErrorStringWithFormat(
1635 "unable to make ThreadPlanCallFunctionUsingABI for 0x%llx",
1640 exe_ctx.GetProcessPtr()->SetRunningUserExpression(true);
1642 // Execute the actual function call thread plan
1643 lldb::ExpressionResults res = exe_ctx.GetProcessRef().RunThreadPlan(
1644 exe_ctx, call_plan_sp, options, diagnostics);
1646 // Check that the thread plan completed successfully
1647 if (res != lldb::ExpressionResults::eExpressionCompleted) {
1648 error.SetErrorToGenericError();
1649 error.SetErrorStringWithFormat("ThreadPlanCallFunctionUsingABI failed");
1653 exe_ctx.GetProcessPtr()->SetRunningUserExpression(false);
1656 if (returnType->isVoidTy()) {
1657 // Cant assign to void types, so we leave the frame untouched
1659 // Integer or pointer return type
1660 if (returnType->isIntegerTy() || returnType->isPointerTy()) {
1661 // Get the encapsulated return value
1662 lldb::ValueObjectSP retVal = call_plan_sp.get()->GetReturnValueObject();
1664 lldb_private::Scalar returnVal = -1;
1665 lldb_private::ValueObject *vobj = retVal.get();
1667 // Check if the return value is valid
1668 if (vobj == nullptr || retVal.empty()) {
1669 error.SetErrorToGenericError();
1670 error.SetErrorStringWithFormat("unable to get the return value");
1674 // Extract the return value as a integer
1675 lldb_private::Value &value = vobj->GetValue();
1676 returnVal = value.GetScalar();
1678 // Push the return value as the result
1679 frame.AssignValue(inst, returnVal, module);
1687 if (num_insts >= 4096) {
1688 error.SetErrorToGenericError();
1689 error.SetErrorString(infinite_loop_error);