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/ConstString.h"
12 #include "lldb/Core/DataExtractor.h"
13 #include "lldb/Core/Error.h"
14 #include "lldb/Core/Log.h"
15 #include "lldb/Core/Module.h"
16 #include "lldb/Core/ModuleSpec.h"
17 #include "lldb/Core/Scalar.h"
18 #include "lldb/Core/StreamString.h"
19 #include "lldb/Core/ValueObject.h"
20 #include "lldb/Expression/DiagnosticManager.h"
21 #include "lldb/Expression/IRExecutionUnit.h"
22 #include "lldb/Expression/IRMemoryMap.h"
23 #include "lldb/Host/Endian.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);
157 scalar = (uint8_t)u64value;
160 scalar = (uint16_t)u64value;
163 scalar = (uint32_t)u64value;
166 scalar = (uint64_t)u64value;
175 bool EvaluateValue(lldb_private::Scalar &scalar, const Value *value,
177 const Constant *constant = dyn_cast<Constant>(value);
182 if (!ResolveConstantValue(value_apint, constant))
185 return AssignToMatchType(scalar, value_apint.getLimitedValue(),
188 lldb::addr_t process_address = ResolveValue(value, module);
189 size_t value_size = m_target_data.getTypeStoreSize(value->getType());
191 lldb_private::DataExtractor value_extractor;
192 lldb_private::Error extract_error;
194 m_execution_unit.GetMemoryData(value_extractor, process_address,
195 value_size, extract_error);
197 if (!extract_error.Success())
200 lldb::offset_t offset = 0;
201 if (value_size == 1 || value_size == 2 || value_size == 4 ||
203 uint64_t u64value = value_extractor.GetMaxU64(&offset, value_size);
204 return AssignToMatchType(scalar, u64value, value->getType());
211 bool AssignValue(const Value *value, lldb_private::Scalar &scalar,
213 lldb::addr_t process_address = ResolveValue(value, module);
215 if (process_address == LLDB_INVALID_ADDRESS)
218 lldb_private::Scalar cast_scalar;
220 if (!AssignToMatchType(cast_scalar, scalar.ULongLong(), value->getType()))
223 size_t value_byte_size = m_target_data.getTypeStoreSize(value->getType());
225 lldb_private::DataBufferHeap buf(value_byte_size, 0);
227 lldb_private::Error get_data_error;
229 if (!cast_scalar.GetAsMemoryData(buf.GetBytes(), buf.GetByteSize(),
230 m_byte_order, get_data_error))
233 lldb_private::Error write_error;
235 m_execution_unit.WriteMemory(process_address, buf.GetBytes(),
236 buf.GetByteSize(), write_error);
238 return write_error.Success();
241 bool ResolveConstantValue(APInt &value, const Constant *constant) {
242 switch (constant->getValueID()) {
245 case Value::FunctionVal:
246 if (const Function *constant_func = dyn_cast<Function>(constant)) {
247 lldb_private::ConstString name(constant_func->getName());
248 lldb::addr_t addr = m_execution_unit.FindSymbol(name);
249 if (addr == LLDB_INVALID_ADDRESS)
251 value = APInt(m_target_data.getPointerSizeInBits(), addr);
255 case Value::ConstantIntVal:
256 if (const ConstantInt *constant_int = dyn_cast<ConstantInt>(constant)) {
257 value = constant_int->getValue();
261 case Value::ConstantFPVal:
262 if (const ConstantFP *constant_fp = dyn_cast<ConstantFP>(constant)) {
263 value = constant_fp->getValueAPF().bitcastToAPInt();
267 case Value::ConstantExprVal:
268 if (const ConstantExpr *constant_expr =
269 dyn_cast<ConstantExpr>(constant)) {
270 switch (constant_expr->getOpcode()) {
273 case Instruction::IntToPtr:
274 case Instruction::PtrToInt:
275 case Instruction::BitCast:
276 return ResolveConstantValue(value, constant_expr->getOperand(0));
277 case Instruction::GetElementPtr: {
278 ConstantExpr::const_op_iterator op_cursor = constant_expr->op_begin();
279 ConstantExpr::const_op_iterator op_end = constant_expr->op_end();
281 Constant *base = dyn_cast<Constant>(*op_cursor);
286 if (!ResolveConstantValue(value, base))
291 if (op_cursor == op_end)
292 return true; // no offset to apply!
294 SmallVector<Value *, 8> indices(op_cursor, op_end);
297 cast<GEPOperator>(constant_expr)->getSourceElementType();
299 m_target_data.getIndexedOffsetInType(src_elem_ty, indices);
301 const bool is_signed = true;
302 value += APInt(value.getBitWidth(), offset, is_signed);
309 case Value::ConstantPointerNullVal:
310 if (isa<ConstantPointerNull>(constant)) {
311 value = APInt(m_target_data.getPointerSizeInBits(), 0);
319 bool MakeArgument(const Argument *value, uint64_t address) {
320 lldb::addr_t data_address = Malloc(value->getType());
322 if (data_address == LLDB_INVALID_ADDRESS)
325 lldb_private::Error write_error;
327 m_execution_unit.WritePointerToMemory(data_address, address, write_error);
329 if (!write_error.Success()) {
330 lldb_private::Error free_error;
331 m_execution_unit.Free(data_address, free_error);
335 m_values[value] = data_address;
337 lldb_private::Log *log(
338 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
341 log->Printf("Made an allocation for argument %s",
342 PrintValue(value).c_str());
343 log->Printf(" Data region : %llx", (unsigned long long)address);
344 log->Printf(" Ref region : %llx", (unsigned long long)data_address);
350 bool ResolveConstant(lldb::addr_t process_address, const Constant *constant) {
351 APInt resolved_value;
353 if (!ResolveConstantValue(resolved_value, constant))
356 size_t constant_size = m_target_data.getTypeStoreSize(constant->getType());
357 lldb_private::DataBufferHeap buf(constant_size, 0);
359 lldb_private::Error get_data_error;
361 lldb_private::Scalar resolved_scalar(
362 resolved_value.zextOrTrunc(llvm::NextPowerOf2(constant_size) * 8));
363 if (!resolved_scalar.GetAsMemoryData(buf.GetBytes(), buf.GetByteSize(),
364 m_byte_order, get_data_error))
367 lldb_private::Error write_error;
369 m_execution_unit.WriteMemory(process_address, buf.GetBytes(),
370 buf.GetByteSize(), write_error);
372 return write_error.Success();
375 lldb::addr_t Malloc(size_t size, uint8_t byte_alignment) {
376 lldb::addr_t ret = m_stack_pointer;
379 ret -= (ret % byte_alignment);
381 if (ret < m_frame_process_address)
382 return LLDB_INVALID_ADDRESS;
384 m_stack_pointer = ret;
388 lldb::addr_t MallocPointer() {
389 return Malloc(m_target_data.getPointerSize(),
390 m_target_data.getPointerPrefAlignment());
393 lldb::addr_t Malloc(llvm::Type *type) {
394 lldb_private::Error alloc_error;
396 return Malloc(m_target_data.getTypeAllocSize(type),
397 m_target_data.getPrefTypeAlignment(type));
400 std::string PrintData(lldb::addr_t addr, llvm::Type *type) {
401 size_t length = m_target_data.getTypeStoreSize(type);
403 lldb_private::DataBufferHeap buf(length, 0);
405 lldb_private::Error read_error;
407 m_execution_unit.ReadMemory(buf.GetBytes(), addr, length, read_error);
409 if (!read_error.Success())
410 return std::string("<couldn't read data>");
412 lldb_private::StreamString ss;
414 for (size_t i = 0; i < length; i++) {
415 if ((!(i & 0xf)) && i)
416 ss.Printf("%02hhx - ", buf.GetBytes()[i]);
418 ss.Printf("%02hhx ", buf.GetBytes()[i]);
421 return ss.GetString();
424 lldb::addr_t ResolveValue(const Value *value, Module &module) {
425 ValueMap::iterator i = m_values.find(value);
427 if (i != m_values.end())
430 // Fall back and allocate space [allocation type Alloca]
432 lldb::addr_t data_address = Malloc(value->getType());
434 if (const Constant *constant = dyn_cast<Constant>(value)) {
435 if (!ResolveConstant(data_address, constant)) {
436 lldb_private::Error free_error;
437 m_execution_unit.Free(data_address, free_error);
438 return LLDB_INVALID_ADDRESS;
442 m_values[value] = data_address;
447 static const char *unsupported_opcode_error =
448 "Interpreter doesn't handle one of the expression's opcodes";
449 static const char *unsupported_operand_error =
450 "Interpreter doesn't handle one of the expression's operands";
451 // static const char *interpreter_initialization_error = "Interpreter couldn't
453 static const char *interpreter_internal_error =
454 "Interpreter encountered an internal error";
455 static const char *bad_value_error =
456 "Interpreter couldn't resolve a value during execution";
457 static const char *memory_allocation_error =
458 "Interpreter couldn't allocate memory";
459 static const char *memory_write_error = "Interpreter couldn't write to memory";
460 static const char *memory_read_error = "Interpreter couldn't read from memory";
461 static const char *infinite_loop_error = "Interpreter ran for too many cycles";
462 // static const char *bad_result_error = "Result of expression
463 // is in bad memory";
464 static const char *too_many_functions_error =
465 "Interpreter doesn't handle modules with multiple function bodies.";
467 static bool CanResolveConstant(llvm::Constant *constant) {
468 switch (constant->getValueID()) {
471 case Value::ConstantIntVal:
472 case Value::ConstantFPVal:
473 case Value::FunctionVal:
475 case Value::ConstantExprVal:
476 if (const ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant)) {
477 switch (constant_expr->getOpcode()) {
480 case Instruction::IntToPtr:
481 case Instruction::PtrToInt:
482 case Instruction::BitCast:
483 return CanResolveConstant(constant_expr->getOperand(0));
484 case Instruction::GetElementPtr: {
485 ConstantExpr::const_op_iterator op_cursor = constant_expr->op_begin();
486 Constant *base = dyn_cast<Constant>(*op_cursor);
490 return CanResolveConstant(base);
496 case Value::ConstantPointerNullVal:
501 bool IRInterpreter::CanInterpret(llvm::Module &module, llvm::Function &function,
502 lldb_private::Error &error,
503 const bool support_function_calls) {
504 lldb_private::Log *log(
505 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
507 bool saw_function_with_body = false;
509 for (Module::iterator fi = module.begin(), fe = module.end(); fi != fe;
511 if (fi->begin() != fi->end()) {
512 if (saw_function_with_body) {
514 log->Printf("More than one function in the module has a body");
515 error.SetErrorToGenericError();
516 error.SetErrorString(too_many_functions_error);
519 saw_function_with_body = true;
523 for (Function::iterator bbi = function.begin(), bbe = function.end();
525 for (BasicBlock::iterator ii = bbi->begin(), ie = bbi->end(); ii != ie;
527 switch (ii->getOpcode()) {
530 log->Printf("Unsupported instruction: %s", PrintValue(&*ii).c_str());
531 error.SetErrorToGenericError();
532 error.SetErrorString(unsupported_opcode_error);
535 case Instruction::Add:
536 case Instruction::Alloca:
537 case Instruction::BitCast:
538 case Instruction::Br:
539 case Instruction::PHI:
541 case Instruction::Call: {
542 CallInst *call_inst = dyn_cast<CallInst>(ii);
545 error.SetErrorToGenericError();
546 error.SetErrorString(interpreter_internal_error);
550 if (!CanIgnoreCall(call_inst) && !support_function_calls) {
552 log->Printf("Unsupported instruction: %s",
553 PrintValue(&*ii).c_str());
554 error.SetErrorToGenericError();
555 error.SetErrorString(unsupported_opcode_error);
559 case Instruction::GetElementPtr:
561 case Instruction::ICmp: {
562 ICmpInst *icmp_inst = dyn_cast<ICmpInst>(ii);
565 error.SetErrorToGenericError();
566 error.SetErrorString(interpreter_internal_error);
570 switch (icmp_inst->getPredicate()) {
573 log->Printf("Unsupported ICmp predicate: %s",
574 PrintValue(&*ii).c_str());
576 error.SetErrorToGenericError();
577 error.SetErrorString(unsupported_opcode_error);
580 case CmpInst::ICMP_EQ:
581 case CmpInst::ICMP_NE:
582 case CmpInst::ICMP_UGT:
583 case CmpInst::ICMP_UGE:
584 case CmpInst::ICMP_ULT:
585 case CmpInst::ICMP_ULE:
586 case CmpInst::ICMP_SGT:
587 case CmpInst::ICMP_SGE:
588 case CmpInst::ICMP_SLT:
589 case CmpInst::ICMP_SLE:
593 case Instruction::And:
594 case Instruction::AShr:
595 case Instruction::IntToPtr:
596 case Instruction::PtrToInt:
597 case Instruction::Load:
598 case Instruction::LShr:
599 case Instruction::Mul:
600 case Instruction::Or:
601 case Instruction::Ret:
602 case Instruction::SDiv:
603 case Instruction::SExt:
604 case Instruction::Shl:
605 case Instruction::SRem:
606 case Instruction::Store:
607 case Instruction::Sub:
608 case Instruction::Trunc:
609 case Instruction::UDiv:
610 case Instruction::URem:
611 case Instruction::Xor:
612 case Instruction::ZExt:
616 for (int oi = 0, oe = ii->getNumOperands(); oi != oe; ++oi) {
617 Value *operand = ii->getOperand(oi);
618 Type *operand_type = operand->getType();
620 switch (operand_type->getTypeID()) {
623 case Type::VectorTyID: {
625 log->Printf("Unsupported operand type: %s",
626 PrintType(operand_type).c_str());
627 error.SetErrorString(unsupported_operand_error);
632 if (Constant *constant = llvm::dyn_cast<Constant>(operand)) {
633 if (!CanResolveConstant(constant)) {
635 log->Printf("Unsupported constant: %s",
636 PrintValue(constant).c_str());
637 error.SetErrorString(unsupported_operand_error);
648 bool IRInterpreter::Interpret(llvm::Module &module, llvm::Function &function,
649 llvm::ArrayRef<lldb::addr_t> args,
650 lldb_private::IRExecutionUnit &execution_unit,
651 lldb_private::Error &error,
652 lldb::addr_t stack_frame_bottom,
653 lldb::addr_t stack_frame_top,
654 lldb_private::ExecutionContext &exe_ctx) {
655 lldb_private::Log *log(
656 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
660 raw_string_ostream oss(s);
662 module.print(oss, NULL);
666 log->Printf("Module as passed in to IRInterpreter::Interpret: \n\"%s\"",
670 DataLayout data_layout(&module);
672 InterpreterStackFrame frame(data_layout, execution_unit, stack_frame_bottom,
675 if (frame.m_frame_process_address == LLDB_INVALID_ADDRESS) {
676 error.SetErrorString("Couldn't allocate stack frame");
681 for (llvm::Function::arg_iterator ai = function.arg_begin(),
682 ae = function.arg_end();
683 ai != ae; ++ai, ++arg_index) {
684 if (args.size() <= static_cast<size_t>(arg_index)) {
685 error.SetErrorString("Not enough arguments passed in to function");
689 lldb::addr_t ptr = args[arg_index];
691 frame.MakeArgument(&*ai, ptr);
694 uint32_t num_insts = 0;
696 frame.Jump(&function.front());
698 while (frame.m_ii != frame.m_ie && (++num_insts < 4096)) {
699 const Instruction *inst = &*frame.m_ii;
702 log->Printf("Interpreting %s", PrintValue(inst).c_str());
704 switch (inst->getOpcode()) {
708 case Instruction::Add:
709 case Instruction::Sub:
710 case Instruction::Mul:
711 case Instruction::SDiv:
712 case Instruction::UDiv:
713 case Instruction::SRem:
714 case Instruction::URem:
715 case Instruction::Shl:
716 case Instruction::LShr:
717 case Instruction::AShr:
718 case Instruction::And:
719 case Instruction::Or:
720 case Instruction::Xor: {
721 const BinaryOperator *bin_op = dyn_cast<BinaryOperator>(inst);
726 "getOpcode() returns %s, but instruction is not a BinaryOperator",
727 inst->getOpcodeName());
728 error.SetErrorToGenericError();
729 error.SetErrorString(interpreter_internal_error);
733 Value *lhs = inst->getOperand(0);
734 Value *rhs = inst->getOperand(1);
736 lldb_private::Scalar L;
737 lldb_private::Scalar R;
739 if (!frame.EvaluateValue(L, lhs, module)) {
741 log->Printf("Couldn't evaluate %s", PrintValue(lhs).c_str());
742 error.SetErrorToGenericError();
743 error.SetErrorString(bad_value_error);
747 if (!frame.EvaluateValue(R, rhs, module)) {
749 log->Printf("Couldn't evaluate %s", PrintValue(rhs).c_str());
750 error.SetErrorToGenericError();
751 error.SetErrorString(bad_value_error);
755 lldb_private::Scalar result;
757 switch (inst->getOpcode()) {
760 case Instruction::Add:
763 case Instruction::Mul:
766 case Instruction::Sub:
769 case Instruction::SDiv:
774 case Instruction::UDiv:
779 case Instruction::SRem:
784 case Instruction::URem:
789 case Instruction::Shl:
792 case Instruction::AShr:
795 case Instruction::LShr:
797 result.ShiftRightLogical(R);
799 case Instruction::And:
802 case Instruction::Or:
805 case Instruction::Xor:
810 frame.AssignValue(inst, result, module);
813 log->Printf("Interpreted a %s", inst->getOpcodeName());
814 log->Printf(" L : %s", frame.SummarizeValue(lhs).c_str());
815 log->Printf(" R : %s", frame.SummarizeValue(rhs).c_str());
816 log->Printf(" = : %s", frame.SummarizeValue(inst).c_str());
819 case Instruction::Alloca: {
820 const AllocaInst *alloca_inst = dyn_cast<AllocaInst>(inst);
824 log->Printf("getOpcode() returns Alloca, but instruction is not an "
826 error.SetErrorToGenericError();
827 error.SetErrorString(interpreter_internal_error);
831 if (alloca_inst->isArrayAllocation()) {
834 "AllocaInsts are not handled if isArrayAllocation() is true");
835 error.SetErrorToGenericError();
836 error.SetErrorString(unsupported_opcode_error);
840 // The semantics of Alloca are:
841 // Create a region R of virtual memory of type T, backed by a data
843 // Create a region P of virtual memory of type T*, backed by a data
845 // Write the virtual address of R into P
847 Type *T = alloca_inst->getAllocatedType();
848 Type *Tptr = alloca_inst->getType();
850 lldb::addr_t R = frame.Malloc(T);
852 if (R == LLDB_INVALID_ADDRESS) {
854 log->Printf("Couldn't allocate memory for an AllocaInst");
855 error.SetErrorToGenericError();
856 error.SetErrorString(memory_allocation_error);
860 lldb::addr_t P = frame.Malloc(Tptr);
862 if (P == LLDB_INVALID_ADDRESS) {
864 log->Printf("Couldn't allocate the result pointer for an AllocaInst");
865 error.SetErrorToGenericError();
866 error.SetErrorString(memory_allocation_error);
870 lldb_private::Error write_error;
872 execution_unit.WritePointerToMemory(P, R, write_error);
874 if (!write_error.Success()) {
876 log->Printf("Couldn't write the result pointer for an AllocaInst");
877 error.SetErrorToGenericError();
878 error.SetErrorString(memory_write_error);
879 lldb_private::Error free_error;
880 execution_unit.Free(P, free_error);
881 execution_unit.Free(R, free_error);
885 frame.m_values[alloca_inst] = P;
888 log->Printf("Interpreted an AllocaInst");
889 log->Printf(" R : 0x%" PRIx64, R);
890 log->Printf(" P : 0x%" PRIx64, P);
893 case Instruction::BitCast:
894 case Instruction::ZExt: {
895 const CastInst *cast_inst = dyn_cast<CastInst>(inst);
900 "getOpcode() returns %s, but instruction is not a BitCastInst",
901 cast_inst->getOpcodeName());
902 error.SetErrorToGenericError();
903 error.SetErrorString(interpreter_internal_error);
907 Value *source = cast_inst->getOperand(0);
909 lldb_private::Scalar S;
911 if (!frame.EvaluateValue(S, source, module)) {
913 log->Printf("Couldn't evaluate %s", PrintValue(source).c_str());
914 error.SetErrorToGenericError();
915 error.SetErrorString(bad_value_error);
919 frame.AssignValue(inst, S, module);
921 case Instruction::SExt: {
922 const CastInst *cast_inst = dyn_cast<CastInst>(inst);
927 "getOpcode() returns %s, but instruction is not a BitCastInst",
928 cast_inst->getOpcodeName());
929 error.SetErrorToGenericError();
930 error.SetErrorString(interpreter_internal_error);
934 Value *source = cast_inst->getOperand(0);
936 lldb_private::Scalar S;
938 if (!frame.EvaluateValue(S, source, module)) {
940 log->Printf("Couldn't evaluate %s", PrintValue(source).c_str());
941 error.SetErrorToGenericError();
942 error.SetErrorString(bad_value_error);
948 lldb_private::Scalar S_signextend(S.SLongLong());
950 frame.AssignValue(inst, S_signextend, module);
952 case Instruction::Br: {
953 const BranchInst *br_inst = dyn_cast<BranchInst>(inst);
958 "getOpcode() returns Br, but instruction is not a BranchInst");
959 error.SetErrorToGenericError();
960 error.SetErrorString(interpreter_internal_error);
964 if (br_inst->isConditional()) {
965 Value *condition = br_inst->getCondition();
967 lldb_private::Scalar C;
969 if (!frame.EvaluateValue(C, condition, module)) {
971 log->Printf("Couldn't evaluate %s", PrintValue(condition).c_str());
972 error.SetErrorToGenericError();
973 error.SetErrorString(bad_value_error);
978 frame.Jump(br_inst->getSuccessor(0));
980 frame.Jump(br_inst->getSuccessor(1));
983 log->Printf("Interpreted a BrInst with a condition");
984 log->Printf(" cond : %s", frame.SummarizeValue(condition).c_str());
987 frame.Jump(br_inst->getSuccessor(0));
990 log->Printf("Interpreted a BrInst with no condition");
995 case Instruction::PHI: {
996 const PHINode *phi_inst = dyn_cast<PHINode>(inst);
1001 "getOpcode() returns PHI, but instruction is not a PHINode");
1002 error.SetErrorToGenericError();
1003 error.SetErrorString(interpreter_internal_error);
1006 if (!frame.m_prev_bb) {
1008 log->Printf("Encountered PHI node without having jumped from another "
1010 error.SetErrorToGenericError();
1011 error.SetErrorString(interpreter_internal_error);
1015 Value *value = phi_inst->getIncomingValueForBlock(frame.m_prev_bb);
1016 lldb_private::Scalar result;
1017 if (!frame.EvaluateValue(result, value, module)) {
1019 log->Printf("Couldn't evaluate %s", PrintValue(value).c_str());
1020 error.SetErrorToGenericError();
1021 error.SetErrorString(bad_value_error);
1024 frame.AssignValue(inst, result, module);
1027 log->Printf("Interpreted a %s", inst->getOpcodeName());
1028 log->Printf(" Incoming value : %s",
1029 frame.SummarizeValue(value).c_str());
1032 case Instruction::GetElementPtr: {
1033 const GetElementPtrInst *gep_inst = dyn_cast<GetElementPtrInst>(inst);
1037 log->Printf("getOpcode() returns GetElementPtr, but instruction is "
1038 "not a GetElementPtrInst");
1039 error.SetErrorToGenericError();
1040 error.SetErrorString(interpreter_internal_error);
1044 const Value *pointer_operand = gep_inst->getPointerOperand();
1045 Type *src_elem_ty = gep_inst->getSourceElementType();
1047 lldb_private::Scalar P;
1049 if (!frame.EvaluateValue(P, pointer_operand, module)) {
1051 log->Printf("Couldn't evaluate %s",
1052 PrintValue(pointer_operand).c_str());
1053 error.SetErrorToGenericError();
1054 error.SetErrorString(bad_value_error);
1058 typedef SmallVector<Value *, 8> IndexVector;
1059 typedef IndexVector::iterator IndexIterator;
1061 SmallVector<Value *, 8> indices(gep_inst->idx_begin(),
1062 gep_inst->idx_end());
1064 SmallVector<Value *, 8> const_indices;
1066 for (IndexIterator ii = indices.begin(), ie = indices.end(); ii != ie;
1068 ConstantInt *constant_index = dyn_cast<ConstantInt>(*ii);
1070 if (!constant_index) {
1071 lldb_private::Scalar I;
1073 if (!frame.EvaluateValue(I, *ii, module)) {
1075 log->Printf("Couldn't evaluate %s", PrintValue(*ii).c_str());
1076 error.SetErrorToGenericError();
1077 error.SetErrorString(bad_value_error);
1082 log->Printf("Evaluated constant index %s as %llu",
1083 PrintValue(*ii).c_str(),
1084 I.ULongLong(LLDB_INVALID_ADDRESS));
1086 constant_index = cast<ConstantInt>(ConstantInt::get(
1087 (*ii)->getType(), I.ULongLong(LLDB_INVALID_ADDRESS)));
1090 const_indices.push_back(constant_index);
1094 data_layout.getIndexedOffsetInType(src_elem_ty, const_indices);
1096 lldb_private::Scalar Poffset = P + offset;
1098 frame.AssignValue(inst, Poffset, module);
1101 log->Printf("Interpreted a GetElementPtrInst");
1102 log->Printf(" P : %s",
1103 frame.SummarizeValue(pointer_operand).c_str());
1104 log->Printf(" Poffset : %s", frame.SummarizeValue(inst).c_str());
1107 case Instruction::ICmp: {
1108 const ICmpInst *icmp_inst = dyn_cast<ICmpInst>(inst);
1113 "getOpcode() returns ICmp, but instruction is not an ICmpInst");
1114 error.SetErrorToGenericError();
1115 error.SetErrorString(interpreter_internal_error);
1119 CmpInst::Predicate predicate = icmp_inst->getPredicate();
1121 Value *lhs = inst->getOperand(0);
1122 Value *rhs = inst->getOperand(1);
1124 lldb_private::Scalar L;
1125 lldb_private::Scalar R;
1127 if (!frame.EvaluateValue(L, lhs, module)) {
1129 log->Printf("Couldn't evaluate %s", PrintValue(lhs).c_str());
1130 error.SetErrorToGenericError();
1131 error.SetErrorString(bad_value_error);
1135 if (!frame.EvaluateValue(R, rhs, module)) {
1137 log->Printf("Couldn't evaluate %s", PrintValue(rhs).c_str());
1138 error.SetErrorToGenericError();
1139 error.SetErrorString(bad_value_error);
1143 lldb_private::Scalar result;
1145 switch (predicate) {
1148 case CmpInst::ICMP_EQ:
1151 case CmpInst::ICMP_NE:
1154 case CmpInst::ICMP_UGT:
1159 case CmpInst::ICMP_UGE:
1164 case CmpInst::ICMP_ULT:
1169 case CmpInst::ICMP_ULE:
1174 case CmpInst::ICMP_SGT:
1179 case CmpInst::ICMP_SGE:
1184 case CmpInst::ICMP_SLT:
1189 case CmpInst::ICMP_SLE:
1196 frame.AssignValue(inst, result, module);
1199 log->Printf("Interpreted an ICmpInst");
1200 log->Printf(" L : %s", frame.SummarizeValue(lhs).c_str());
1201 log->Printf(" R : %s", frame.SummarizeValue(rhs).c_str());
1202 log->Printf(" = : %s", frame.SummarizeValue(inst).c_str());
1205 case Instruction::IntToPtr: {
1206 const IntToPtrInst *int_to_ptr_inst = dyn_cast<IntToPtrInst>(inst);
1208 if (!int_to_ptr_inst) {
1210 log->Printf("getOpcode() returns IntToPtr, but instruction is not an "
1212 error.SetErrorToGenericError();
1213 error.SetErrorString(interpreter_internal_error);
1217 Value *src_operand = int_to_ptr_inst->getOperand(0);
1219 lldb_private::Scalar I;
1221 if (!frame.EvaluateValue(I, src_operand, module)) {
1223 log->Printf("Couldn't evaluate %s", PrintValue(src_operand).c_str());
1224 error.SetErrorToGenericError();
1225 error.SetErrorString(bad_value_error);
1229 frame.AssignValue(inst, I, module);
1232 log->Printf("Interpreted an IntToPtr");
1233 log->Printf(" Src : %s", frame.SummarizeValue(src_operand).c_str());
1234 log->Printf(" = : %s", frame.SummarizeValue(inst).c_str());
1237 case Instruction::PtrToInt: {
1238 const PtrToIntInst *ptr_to_int_inst = dyn_cast<PtrToIntInst>(inst);
1240 if (!ptr_to_int_inst) {
1242 log->Printf("getOpcode() returns PtrToInt, but instruction is not an "
1244 error.SetErrorToGenericError();
1245 error.SetErrorString(interpreter_internal_error);
1249 Value *src_operand = ptr_to_int_inst->getOperand(0);
1251 lldb_private::Scalar I;
1253 if (!frame.EvaluateValue(I, src_operand, module)) {
1255 log->Printf("Couldn't evaluate %s", PrintValue(src_operand).c_str());
1256 error.SetErrorToGenericError();
1257 error.SetErrorString(bad_value_error);
1261 frame.AssignValue(inst, I, module);
1264 log->Printf("Interpreted a PtrToInt");
1265 log->Printf(" Src : %s", frame.SummarizeValue(src_operand).c_str());
1266 log->Printf(" = : %s", frame.SummarizeValue(inst).c_str());
1269 case Instruction::Trunc: {
1270 const TruncInst *trunc_inst = dyn_cast<TruncInst>(inst);
1275 "getOpcode() returns Trunc, but instruction is not a TruncInst");
1276 error.SetErrorToGenericError();
1277 error.SetErrorString(interpreter_internal_error);
1281 Value *src_operand = trunc_inst->getOperand(0);
1283 lldb_private::Scalar I;
1285 if (!frame.EvaluateValue(I, src_operand, module)) {
1287 log->Printf("Couldn't evaluate %s", PrintValue(src_operand).c_str());
1288 error.SetErrorToGenericError();
1289 error.SetErrorString(bad_value_error);
1293 frame.AssignValue(inst, I, module);
1296 log->Printf("Interpreted a Trunc");
1297 log->Printf(" Src : %s", frame.SummarizeValue(src_operand).c_str());
1298 log->Printf(" = : %s", frame.SummarizeValue(inst).c_str());
1301 case Instruction::Load: {
1302 const LoadInst *load_inst = dyn_cast<LoadInst>(inst);
1307 "getOpcode() returns Load, but instruction is not a LoadInst");
1308 error.SetErrorToGenericError();
1309 error.SetErrorString(interpreter_internal_error);
1313 // The semantics of Load are:
1314 // Create a region D that will contain the loaded data
1315 // Resolve the region P containing a pointer
1316 // Dereference P to get the region R that the data should be loaded from
1317 // Transfer a unit of type type(D) from R to D
1319 const Value *pointer_operand = load_inst->getPointerOperand();
1321 Type *pointer_ty = pointer_operand->getType();
1322 PointerType *pointer_ptr_ty = dyn_cast<PointerType>(pointer_ty);
1323 if (!pointer_ptr_ty) {
1325 log->Printf("getPointerOperand()->getType() is not a PointerType");
1326 error.SetErrorToGenericError();
1327 error.SetErrorString(interpreter_internal_error);
1330 Type *target_ty = pointer_ptr_ty->getElementType();
1332 lldb::addr_t D = frame.ResolveValue(load_inst, module);
1333 lldb::addr_t P = frame.ResolveValue(pointer_operand, module);
1335 if (D == LLDB_INVALID_ADDRESS) {
1337 log->Printf("LoadInst's value doesn't resolve to anything");
1338 error.SetErrorToGenericError();
1339 error.SetErrorString(bad_value_error);
1343 if (P == LLDB_INVALID_ADDRESS) {
1345 log->Printf("LoadInst's pointer doesn't resolve to anything");
1346 error.SetErrorToGenericError();
1347 error.SetErrorString(bad_value_error);
1352 lldb_private::Error read_error;
1353 execution_unit.ReadPointerFromMemory(&R, P, read_error);
1355 if (!read_error.Success()) {
1357 log->Printf("Couldn't read the address to be loaded for a LoadInst");
1358 error.SetErrorToGenericError();
1359 error.SetErrorString(memory_read_error);
1363 size_t target_size = data_layout.getTypeStoreSize(target_ty);
1364 lldb_private::DataBufferHeap buffer(target_size, 0);
1367 execution_unit.ReadMemory(buffer.GetBytes(), R, buffer.GetByteSize(),
1369 if (!read_error.Success()) {
1371 log->Printf("Couldn't read from a region on behalf of a LoadInst");
1372 error.SetErrorToGenericError();
1373 error.SetErrorString(memory_read_error);
1377 lldb_private::Error write_error;
1378 execution_unit.WriteMemory(D, buffer.GetBytes(), buffer.GetByteSize(),
1380 if (!write_error.Success()) {
1382 log->Printf("Couldn't write to a region on behalf of a LoadInst");
1383 error.SetErrorToGenericError();
1384 error.SetErrorString(memory_read_error);
1389 log->Printf("Interpreted a LoadInst");
1390 log->Printf(" P : 0x%" PRIx64, P);
1391 log->Printf(" R : 0x%" PRIx64, R);
1392 log->Printf(" D : 0x%" PRIx64, D);
1395 case Instruction::Ret: {
1398 case Instruction::Store: {
1399 const StoreInst *store_inst = dyn_cast<StoreInst>(inst);
1404 "getOpcode() returns Store, but instruction is not a StoreInst");
1405 error.SetErrorToGenericError();
1406 error.SetErrorString(interpreter_internal_error);
1410 // The semantics of Store are:
1411 // Resolve the region D containing the data to be stored
1412 // Resolve the region P containing a pointer
1413 // Dereference P to get the region R that the data should be stored in
1414 // Transfer a unit of type type(D) from D to R
1416 const Value *value_operand = store_inst->getValueOperand();
1417 const Value *pointer_operand = store_inst->getPointerOperand();
1419 Type *pointer_ty = pointer_operand->getType();
1420 PointerType *pointer_ptr_ty = dyn_cast<PointerType>(pointer_ty);
1421 if (!pointer_ptr_ty)
1423 Type *target_ty = pointer_ptr_ty->getElementType();
1425 lldb::addr_t D = frame.ResolveValue(value_operand, module);
1426 lldb::addr_t P = frame.ResolveValue(pointer_operand, module);
1428 if (D == LLDB_INVALID_ADDRESS) {
1430 log->Printf("StoreInst's value doesn't resolve to anything");
1431 error.SetErrorToGenericError();
1432 error.SetErrorString(bad_value_error);
1436 if (P == LLDB_INVALID_ADDRESS) {
1438 log->Printf("StoreInst's pointer doesn't resolve to anything");
1439 error.SetErrorToGenericError();
1440 error.SetErrorString(bad_value_error);
1445 lldb_private::Error read_error;
1446 execution_unit.ReadPointerFromMemory(&R, P, read_error);
1448 if (!read_error.Success()) {
1450 log->Printf("Couldn't read the address to be loaded for a LoadInst");
1451 error.SetErrorToGenericError();
1452 error.SetErrorString(memory_read_error);
1456 size_t target_size = data_layout.getTypeStoreSize(target_ty);
1457 lldb_private::DataBufferHeap buffer(target_size, 0);
1460 execution_unit.ReadMemory(buffer.GetBytes(), D, buffer.GetByteSize(),
1462 if (!read_error.Success()) {
1464 log->Printf("Couldn't read from a region on behalf of a StoreInst");
1465 error.SetErrorToGenericError();
1466 error.SetErrorString(memory_read_error);
1470 lldb_private::Error write_error;
1471 execution_unit.WriteMemory(R, buffer.GetBytes(), buffer.GetByteSize(),
1473 if (!write_error.Success()) {
1475 log->Printf("Couldn't write to a region on behalf of a StoreInst");
1476 error.SetErrorToGenericError();
1477 error.SetErrorString(memory_write_error);
1482 log->Printf("Interpreted a StoreInst");
1483 log->Printf(" D : 0x%" PRIx64, D);
1484 log->Printf(" P : 0x%" PRIx64, P);
1485 log->Printf(" R : 0x%" PRIx64, R);
1488 case Instruction::Call: {
1489 const CallInst *call_inst = dyn_cast<CallInst>(inst);
1494 "getOpcode() returns %s, but instruction is not a CallInst",
1495 inst->getOpcodeName());
1496 error.SetErrorToGenericError();
1497 error.SetErrorString(interpreter_internal_error);
1501 if (CanIgnoreCall(call_inst))
1504 // Get the return type
1505 llvm::Type *returnType = call_inst->getType();
1506 if (returnType == nullptr) {
1507 error.SetErrorToGenericError();
1508 error.SetErrorString("unable to access return type");
1512 // Work with void, integer and pointer return types
1513 if (!returnType->isVoidTy() && !returnType->isIntegerTy() &&
1514 !returnType->isPointerTy()) {
1515 error.SetErrorToGenericError();
1516 error.SetErrorString("return type is not supported");
1520 // Check we can actually get a thread
1521 if (exe_ctx.GetThreadPtr() == nullptr) {
1522 error.SetErrorToGenericError();
1523 error.SetErrorStringWithFormat("unable to acquire thread");
1527 // Make sure we have a valid process
1528 if (!exe_ctx.GetProcessPtr()) {
1529 error.SetErrorToGenericError();
1530 error.SetErrorStringWithFormat("unable to get the process");
1534 // Find the address of the callee function
1535 lldb_private::Scalar I;
1536 const llvm::Value *val = call_inst->getCalledValue();
1538 if (!frame.EvaluateValue(I, val, module)) {
1539 error.SetErrorToGenericError();
1540 error.SetErrorString("unable to get address of function");
1543 lldb_private::Address funcAddr(I.ULongLong(LLDB_INVALID_ADDRESS));
1545 lldb_private::DiagnosticManager diagnostics;
1546 lldb_private::EvaluateExpressionOptions options;
1548 // We generally receive a function pointer which we must dereference
1549 llvm::Type *prototype = val->getType();
1550 if (!prototype->isPointerTy()) {
1551 error.SetErrorToGenericError();
1552 error.SetErrorString("call need function pointer");
1556 // Dereference the function pointer
1557 prototype = prototype->getPointerElementType();
1558 if (!(prototype->isFunctionTy() || prototype->isFunctionVarArg())) {
1559 error.SetErrorToGenericError();
1560 error.SetErrorString("call need function pointer");
1564 // Find number of arguments
1565 const int numArgs = call_inst->getNumArgOperands();
1567 // We work with a fixed array of 16 arguments which is our upper limit
1568 static lldb_private::ABI::CallArgument rawArgs[16];
1569 if (numArgs >= 16) {
1570 error.SetErrorToGenericError();
1571 error.SetErrorStringWithFormat("function takes too many arguments");
1575 // Push all function arguments to the argument list that will
1576 // be passed to the call function thread plan
1577 for (int i = 0; i < numArgs; i++) {
1578 // Get details of this argument
1579 llvm::Value *arg_op = call_inst->getArgOperand(i);
1580 llvm::Type *arg_ty = arg_op->getType();
1582 // Ensure that this argument is an supported type
1583 if (!arg_ty->isIntegerTy() && !arg_ty->isPointerTy()) {
1584 error.SetErrorToGenericError();
1585 error.SetErrorStringWithFormat("argument %d must be integer type", i);
1589 // Extract the arguments value
1590 lldb_private::Scalar tmp_op = 0;
1591 if (!frame.EvaluateValue(tmp_op, arg_op, module)) {
1592 error.SetErrorToGenericError();
1593 error.SetErrorStringWithFormat("unable to evaluate argument %d", i);
1597 // Check if this is a string literal or constant string pointer
1598 if (arg_ty->isPointerTy()) {
1599 // Pointer to just one type
1600 assert(arg_ty->getNumContainedTypes() == 1);
1602 lldb::addr_t addr = tmp_op.ULongLong();
1603 size_t dataSize = 0;
1605 bool Success = execution_unit.GetAllocSize(addr, dataSize);
1608 "unable to locate host data for transfer to device");
1609 // Create the required buffer
1610 rawArgs[i].size = dataSize;
1611 rawArgs[i].data_ap.reset(new uint8_t[dataSize + 1]);
1613 // Read string from host memory
1614 execution_unit.ReadMemory(rawArgs[i].data_ap.get(), addr, dataSize,
1616 assert(!error.Fail() &&
1617 "we have failed to read the string from memory");
1619 // Add null terminator
1620 rawArgs[i].data_ap[dataSize] = '\0';
1621 rawArgs[i].type = lldb_private::ABI::CallArgument::HostPointer;
1622 } else /* if ( arg_ty->isPointerTy() ) */
1624 rawArgs[i].type = lldb_private::ABI::CallArgument::TargetValue;
1625 // Get argument size in bytes
1626 rawArgs[i].size = arg_ty->getIntegerBitWidth() / 8;
1627 // Push value into argument list for thread plan
1628 rawArgs[i].value = tmp_op.ULongLong();
1632 // Pack the arguments into an llvm::array
1633 llvm::ArrayRef<lldb_private::ABI::CallArgument> args(rawArgs, numArgs);
1635 // Setup a thread plan to call the target function
1636 lldb::ThreadPlanSP call_plan_sp(
1637 new lldb_private::ThreadPlanCallFunctionUsingABI(
1638 exe_ctx.GetThreadRef(), funcAddr, *prototype, *returnType, args,
1641 // Check if the plan is valid
1642 lldb_private::StreamString ss;
1643 if (!call_plan_sp || !call_plan_sp->ValidatePlan(&ss)) {
1644 error.SetErrorToGenericError();
1645 error.SetErrorStringWithFormat(
1646 "unable to make ThreadPlanCallFunctionUsingABI for 0x%llx",
1651 exe_ctx.GetProcessPtr()->SetRunningUserExpression(true);
1653 // Execute the actual function call thread plan
1654 lldb::ExpressionResults res = exe_ctx.GetProcessRef().RunThreadPlan(
1655 exe_ctx, call_plan_sp, options, diagnostics);
1657 // Check that the thread plan completed successfully
1658 if (res != lldb::ExpressionResults::eExpressionCompleted) {
1659 error.SetErrorToGenericError();
1660 error.SetErrorStringWithFormat("ThreadPlanCallFunctionUsingABI failed");
1664 exe_ctx.GetProcessPtr()->SetRunningUserExpression(false);
1667 if (returnType->isVoidTy()) {
1668 // Cant assign to void types, so we leave the frame untouched
1670 // Integer or pointer return type
1671 if (returnType->isIntegerTy() || returnType->isPointerTy()) {
1672 // Get the encapsulated return value
1673 lldb::ValueObjectSP retVal = call_plan_sp.get()->GetReturnValueObject();
1675 lldb_private::Scalar returnVal = -1;
1676 lldb_private::ValueObject *vobj = retVal.get();
1678 // Check if the return value is valid
1679 if (vobj == nullptr || retVal.empty()) {
1680 error.SetErrorToGenericError();
1681 error.SetErrorStringWithFormat("unable to get the return value");
1685 // Extract the return value as a integer
1686 lldb_private::Value &value = vobj->GetValue();
1687 returnVal = value.GetScalar();
1689 // Push the return value as the result
1690 frame.AssignValue(inst, returnVal, module);
1698 if (num_insts >= 4096) {
1699 error.SetErrorToGenericError();
1700 error.SetErrorString(infinite_loop_error);