1 //===-- IRInterpreter.cpp -------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "lldb/Expression/IRInterpreter.h"
10 #include "lldb/Core/Module.h"
11 #include "lldb/Core/ModuleSpec.h"
12 #include "lldb/Core/ValueObject.h"
13 #include "lldb/Expression/DiagnosticManager.h"
14 #include "lldb/Expression/IRExecutionUnit.h"
15 #include "lldb/Expression/IRMemoryMap.h"
16 #include "lldb/Utility/ConstString.h"
17 #include "lldb/Utility/DataExtractor.h"
18 #include "lldb/Utility/Endian.h"
19 #include "lldb/Utility/Log.h"
20 #include "lldb/Utility/Scalar.h"
21 #include "lldb/Utility/Status.h"
22 #include "lldb/Utility/StreamString.h"
23 
24 #include "lldb/Target/ABI.h"
25 #include "lldb/Target/ExecutionContext.h"
26 #include "lldb/Target/Target.h"
27 #include "lldb/Target/Thread.h"
28 #include "lldb/Target/ThreadPlan.h"
29 #include "lldb/Target/ThreadPlanCallFunctionUsingABI.h"
30 
31 #include "llvm/IR/Constants.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/Function.h"
34 #include "llvm/IR/Instructions.h"
35 #include "llvm/IR/Intrinsics.h"
36 #include "llvm/IR/LLVMContext.h"
37 #include "llvm/IR/Module.h"
38 #include "llvm/IR/Operator.h"
39 #include "llvm/Support/raw_ostream.h"
40 
41 #include <map>
42 
43 using namespace llvm;
44 using lldb_private::LLDBLog;
45 
46 static std::string PrintValue(const Value *value, bool truncate = false) {
47   std::string s;
48   raw_string_ostream rso(s);
49   value->print(rso);
50   rso.flush();
51   if (truncate)
52     s.resize(s.length() - 1);
53 
54   size_t offset;
55   while ((offset = s.find('\n')) != s.npos)
56     s.erase(offset, 1);
57   while (s[0] == ' ' || s[0] == '\t')
58     s.erase(0, 1);
59 
60   return s;
61 }
62 
63 static std::string PrintType(const Type *type, bool truncate = false) {
64   std::string s;
65   raw_string_ostream rso(s);
66   type->print(rso);
67   rso.flush();
68   if (truncate)
69     s.resize(s.length() - 1);
70   return s;
71 }
72 
73 static bool CanIgnoreCall(const CallInst *call) {
74   const llvm::Function *called_function = call->getCalledFunction();
75 
76   if (!called_function)
77     return false;
78 
79   if (called_function->isIntrinsic()) {
80     switch (called_function->getIntrinsicID()) {
81     default:
82       break;
83     case llvm::Intrinsic::dbg_declare:
84     case llvm::Intrinsic::dbg_value:
85       return true;
86     }
87   }
88 
89   return false;
90 }
91 
92 class InterpreterStackFrame {
93 public:
94   typedef std::map<const Value *, lldb::addr_t> ValueMap;
95 
96   ValueMap m_values;
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;
103 
104   lldb::addr_t m_frame_process_address;
105   size_t m_frame_size;
106   lldb::addr_t m_stack_pointer;
107 
108   lldb::ByteOrder m_byte_order;
109   size_t m_addr_byte_size;
110 
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));
120 
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;
124   }
125 
126   ~InterpreterStackFrame() = default;
127 
128   void Jump(const BasicBlock *bb) {
129     m_prev_bb = m_bb;
130     m_bb = bb;
131     m_ii = m_bb->begin();
132     m_ie = m_bb->end();
133   }
134 
135   std::string SummarizeValue(const Value *value) {
136     lldb_private::StreamString ss;
137 
138     ss.Printf("%s", PrintValue(value).c_str());
139 
140     ValueMap::iterator i = m_values.find(value);
141 
142     if (i != m_values.end()) {
143       lldb::addr_t addr = i->second;
144 
145       ss.Printf(" 0x%llx", (unsigned long long)addr);
146     }
147 
148     return std::string(ss.GetString());
149   }
150 
151   bool AssignToMatchType(lldb_private::Scalar &scalar, llvm::APInt value,
152                          Type *type) {
153     size_t type_size = m_target_data.getTypeStoreSize(type);
154 
155     if (type_size > 8)
156       return false;
157 
158     if (type_size != 1)
159       type_size = PowerOf2Ceil(type_size);
160 
161     scalar = value.zextOrTrunc(type_size * 8);
162     return true;
163   }
164 
165   bool EvaluateValue(lldb_private::Scalar &scalar, const Value *value,
166                      Module &module) {
167     const Constant *constant = dyn_cast<Constant>(value);
168 
169     if (constant) {
170       APInt value_apint;
171 
172       if (!ResolveConstantValue(value_apint, constant))
173         return false;
174 
175       return AssignToMatchType(scalar, value_apint, value->getType());
176     }
177 
178     lldb::addr_t process_address = ResolveValue(value, module);
179     size_t value_size = m_target_data.getTypeStoreSize(value->getType());
180 
181     lldb_private::DataExtractor value_extractor;
182     lldb_private::Status extract_error;
183 
184     m_execution_unit.GetMemoryData(value_extractor, process_address,
185                                    value_size, extract_error);
186 
187     if (!extract_error.Success())
188       return false;
189 
190     lldb::offset_t offset = 0;
191     if (value_size <= 8) {
192       uint64_t u64value = value_extractor.GetMaxU64(&offset, value_size);
193       return AssignToMatchType(scalar, llvm::APInt(64, u64value),
194                                value->getType());
195     }
196 
197     return false;
198   }
199 
200   bool AssignValue(const Value *value, lldb_private::Scalar scalar,
201                    Module &module) {
202     lldb::addr_t process_address = ResolveValue(value, module);
203 
204     if (process_address == LLDB_INVALID_ADDRESS)
205       return false;
206 
207     lldb_private::Scalar cast_scalar;
208 
209     scalar.MakeUnsigned();
210     if (!AssignToMatchType(cast_scalar, scalar.UInt128(llvm::APInt()),
211                            value->getType()))
212       return false;
213 
214     size_t value_byte_size = m_target_data.getTypeStoreSize(value->getType());
215 
216     lldb_private::DataBufferHeap buf(value_byte_size, 0);
217 
218     lldb_private::Status get_data_error;
219 
220     if (!cast_scalar.GetAsMemoryData(buf.GetBytes(), buf.GetByteSize(),
221                                      m_byte_order, get_data_error))
222       return false;
223 
224     lldb_private::Status write_error;
225 
226     m_execution_unit.WriteMemory(process_address, buf.GetBytes(),
227                                  buf.GetByteSize(), write_error);
228 
229     return write_error.Success();
230   }
231 
232   bool ResolveConstantValue(APInt &value, const Constant *constant) {
233     switch (constant->getValueID()) {
234     default:
235       break;
236     case Value::FunctionVal:
237       if (const Function *constant_func = dyn_cast<Function>(constant)) {
238         lldb_private::ConstString name(constant_func->getName());
239         bool missing_weak = false;
240         lldb::addr_t addr = m_execution_unit.FindSymbol(name, missing_weak);
241         if (addr == LLDB_INVALID_ADDRESS || missing_weak)
242           return false;
243         value = APInt(m_target_data.getPointerSizeInBits(), addr);
244         return true;
245       }
246       break;
247     case Value::ConstantIntVal:
248       if (const ConstantInt *constant_int = dyn_cast<ConstantInt>(constant)) {
249         value = constant_int->getValue();
250         return true;
251       }
252       break;
253     case Value::ConstantFPVal:
254       if (const ConstantFP *constant_fp = dyn_cast<ConstantFP>(constant)) {
255         value = constant_fp->getValueAPF().bitcastToAPInt();
256         return true;
257       }
258       break;
259     case Value::ConstantExprVal:
260       if (const ConstantExpr *constant_expr =
261               dyn_cast<ConstantExpr>(constant)) {
262         switch (constant_expr->getOpcode()) {
263         default:
264           return false;
265         case Instruction::IntToPtr:
266         case Instruction::PtrToInt:
267         case Instruction::BitCast:
268           return ResolveConstantValue(value, constant_expr->getOperand(0));
269         case Instruction::GetElementPtr: {
270           ConstantExpr::const_op_iterator op_cursor = constant_expr->op_begin();
271           ConstantExpr::const_op_iterator op_end = constant_expr->op_end();
272 
273           Constant *base = dyn_cast<Constant>(*op_cursor);
274 
275           if (!base)
276             return false;
277 
278           if (!ResolveConstantValue(value, base))
279             return false;
280 
281           op_cursor++;
282 
283           if (op_cursor == op_end)
284             return true; // no offset to apply!
285 
286           SmallVector<Value *, 8> indices(op_cursor, op_end);
287 
288           Type *src_elem_ty =
289               cast<GEPOperator>(constant_expr)->getSourceElementType();
290           uint64_t offset =
291               m_target_data.getIndexedOffsetInType(src_elem_ty, indices);
292 
293           const bool is_signed = true;
294           value += APInt(value.getBitWidth(), offset, is_signed);
295 
296           return true;
297         }
298         }
299       }
300       break;
301     case Value::ConstantPointerNullVal:
302       if (isa<ConstantPointerNull>(constant)) {
303         value = APInt(m_target_data.getPointerSizeInBits(), 0);
304         return true;
305       }
306       break;
307     }
308     return false;
309   }
310 
311   bool MakeArgument(const Argument *value, uint64_t address) {
312     lldb::addr_t data_address = Malloc(value->getType());
313 
314     if (data_address == LLDB_INVALID_ADDRESS)
315       return false;
316 
317     lldb_private::Status write_error;
318 
319     m_execution_unit.WritePointerToMemory(data_address, address, write_error);
320 
321     if (!write_error.Success()) {
322       lldb_private::Status free_error;
323       m_execution_unit.Free(data_address, free_error);
324       return false;
325     }
326 
327     m_values[value] = data_address;
328 
329     lldb_private::Log *log(GetLog(LLDBLog::Expressions));
330 
331     if (log) {
332       LLDB_LOGF(log, "Made an allocation for argument %s",
333                 PrintValue(value).c_str());
334       LLDB_LOGF(log, "  Data region    : %llx", (unsigned long long)address);
335       LLDB_LOGF(log, "  Ref region     : %llx",
336                 (unsigned long long)data_address);
337     }
338 
339     return true;
340   }
341 
342   bool ResolveConstant(lldb::addr_t process_address, const Constant *constant) {
343     APInt resolved_value;
344 
345     if (!ResolveConstantValue(resolved_value, constant))
346       return false;
347 
348     size_t constant_size = m_target_data.getTypeStoreSize(constant->getType());
349     lldb_private::DataBufferHeap buf(constant_size, 0);
350 
351     lldb_private::Status get_data_error;
352 
353     lldb_private::Scalar resolved_scalar(
354         resolved_value.zextOrTrunc(llvm::NextPowerOf2(constant_size) * 8));
355     if (!resolved_scalar.GetAsMemoryData(buf.GetBytes(), buf.GetByteSize(),
356                                          m_byte_order, get_data_error))
357       return false;
358 
359     lldb_private::Status write_error;
360 
361     m_execution_unit.WriteMemory(process_address, buf.GetBytes(),
362                                  buf.GetByteSize(), write_error);
363 
364     return write_error.Success();
365   }
366 
367   lldb::addr_t Malloc(size_t size, uint8_t byte_alignment) {
368     lldb::addr_t ret = m_stack_pointer;
369 
370     ret -= size;
371     ret -= (ret % byte_alignment);
372 
373     if (ret < m_frame_process_address)
374       return LLDB_INVALID_ADDRESS;
375 
376     m_stack_pointer = ret;
377     return ret;
378   }
379 
380   lldb::addr_t Malloc(llvm::Type *type) {
381     lldb_private::Status alloc_error;
382 
383     return Malloc(m_target_data.getTypeAllocSize(type),
384                   m_target_data.getPrefTypeAlignment(type));
385   }
386 
387   std::string PrintData(lldb::addr_t addr, llvm::Type *type) {
388     size_t length = m_target_data.getTypeStoreSize(type);
389 
390     lldb_private::DataBufferHeap buf(length, 0);
391 
392     lldb_private::Status read_error;
393 
394     m_execution_unit.ReadMemory(buf.GetBytes(), addr, length, read_error);
395 
396     if (!read_error.Success())
397       return std::string("<couldn't read data>");
398 
399     lldb_private::StreamString ss;
400 
401     for (size_t i = 0; i < length; i++) {
402       if ((!(i & 0xf)) && i)
403         ss.Printf("%02hhx - ", buf.GetBytes()[i]);
404       else
405         ss.Printf("%02hhx ", buf.GetBytes()[i]);
406     }
407 
408     return std::string(ss.GetString());
409   }
410 
411   lldb::addr_t ResolveValue(const Value *value, Module &module) {
412     ValueMap::iterator i = m_values.find(value);
413 
414     if (i != m_values.end())
415       return i->second;
416 
417     // Fall back and allocate space [allocation type Alloca]
418 
419     lldb::addr_t data_address = Malloc(value->getType());
420 
421     if (const Constant *constant = dyn_cast<Constant>(value)) {
422       if (!ResolveConstant(data_address, constant)) {
423         lldb_private::Status free_error;
424         m_execution_unit.Free(data_address, free_error);
425         return LLDB_INVALID_ADDRESS;
426       }
427     }
428 
429     m_values[value] = data_address;
430     return data_address;
431   }
432 };
433 
434 static const char *unsupported_opcode_error =
435     "Interpreter doesn't handle one of the expression's opcodes";
436 static const char *unsupported_operand_error =
437     "Interpreter doesn't handle one of the expression's operands";
438 static const char *interpreter_internal_error =
439     "Interpreter encountered an internal error";
440 static const char *bad_value_error =
441     "Interpreter couldn't resolve a value during execution";
442 static const char *memory_allocation_error =
443     "Interpreter couldn't allocate memory";
444 static const char *memory_write_error = "Interpreter couldn't write to memory";
445 static const char *memory_read_error = "Interpreter couldn't read from memory";
446 static const char *infinite_loop_error = "Interpreter ran for too many cycles";
447 static const char *too_many_functions_error =
448     "Interpreter doesn't handle modules with multiple function bodies.";
449 
450 static bool CanResolveConstant(llvm::Constant *constant) {
451   switch (constant->getValueID()) {
452   default:
453     return false;
454   case Value::ConstantIntVal:
455   case Value::ConstantFPVal:
456   case Value::FunctionVal:
457     return true;
458   case Value::ConstantExprVal:
459     if (const ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant)) {
460       switch (constant_expr->getOpcode()) {
461       default:
462         return false;
463       case Instruction::IntToPtr:
464       case Instruction::PtrToInt:
465       case Instruction::BitCast:
466         return CanResolveConstant(constant_expr->getOperand(0));
467       case Instruction::GetElementPtr: {
468         ConstantExpr::const_op_iterator op_cursor = constant_expr->op_begin();
469         Constant *base = dyn_cast<Constant>(*op_cursor);
470         if (!base)
471           return false;
472 
473         return CanResolveConstant(base);
474       }
475       }
476     } else {
477       return false;
478     }
479   case Value::ConstantPointerNullVal:
480     return true;
481   }
482 }
483 
484 bool IRInterpreter::CanInterpret(llvm::Module &module, llvm::Function &function,
485                                  lldb_private::Status &error,
486                                  const bool support_function_calls) {
487   lldb_private::Log *log(GetLog(LLDBLog::Expressions));
488 
489   bool saw_function_with_body = false;
490   for (Function &f : module) {
491     if (f.begin() != f.end()) {
492       if (saw_function_with_body) {
493         LLDB_LOGF(log, "More than one function in the module has a body");
494         error.SetErrorToGenericError();
495         error.SetErrorString(too_many_functions_error);
496         return false;
497       }
498       saw_function_with_body = true;
499     }
500   }
501 
502   for (BasicBlock &bb : function) {
503     for (Instruction &ii : bb) {
504       switch (ii.getOpcode()) {
505       default: {
506         LLDB_LOGF(log, "Unsupported instruction: %s", PrintValue(&ii).c_str());
507         error.SetErrorToGenericError();
508         error.SetErrorString(unsupported_opcode_error);
509         return false;
510       }
511       case Instruction::Add:
512       case Instruction::Alloca:
513       case Instruction::BitCast:
514       case Instruction::Br:
515       case Instruction::PHI:
516         break;
517       case Instruction::Call: {
518         CallInst *call_inst = dyn_cast<CallInst>(&ii);
519 
520         if (!call_inst) {
521           error.SetErrorToGenericError();
522           error.SetErrorString(interpreter_internal_error);
523           return false;
524         }
525 
526         if (!CanIgnoreCall(call_inst) && !support_function_calls) {
527           LLDB_LOGF(log, "Unsupported instruction: %s",
528                     PrintValue(&ii).c_str());
529           error.SetErrorToGenericError();
530           error.SetErrorString(unsupported_opcode_error);
531           return false;
532         }
533       } break;
534       case Instruction::GetElementPtr:
535         break;
536       case Instruction::ICmp: {
537         ICmpInst *icmp_inst = dyn_cast<ICmpInst>(&ii);
538 
539         if (!icmp_inst) {
540           error.SetErrorToGenericError();
541           error.SetErrorString(interpreter_internal_error);
542           return false;
543         }
544 
545         switch (icmp_inst->getPredicate()) {
546         default: {
547           LLDB_LOGF(log, "Unsupported ICmp predicate: %s",
548                     PrintValue(&ii).c_str());
549 
550           error.SetErrorToGenericError();
551           error.SetErrorString(unsupported_opcode_error);
552           return false;
553         }
554         case CmpInst::ICMP_EQ:
555         case CmpInst::ICMP_NE:
556         case CmpInst::ICMP_UGT:
557         case CmpInst::ICMP_UGE:
558         case CmpInst::ICMP_ULT:
559         case CmpInst::ICMP_ULE:
560         case CmpInst::ICMP_SGT:
561         case CmpInst::ICMP_SGE:
562         case CmpInst::ICMP_SLT:
563         case CmpInst::ICMP_SLE:
564           break;
565         }
566       } break;
567       case Instruction::And:
568       case Instruction::AShr:
569       case Instruction::IntToPtr:
570       case Instruction::PtrToInt:
571       case Instruction::Load:
572       case Instruction::LShr:
573       case Instruction::Mul:
574       case Instruction::Or:
575       case Instruction::Ret:
576       case Instruction::SDiv:
577       case Instruction::SExt:
578       case Instruction::Shl:
579       case Instruction::SRem:
580       case Instruction::Store:
581       case Instruction::Sub:
582       case Instruction::Trunc:
583       case Instruction::UDiv:
584       case Instruction::URem:
585       case Instruction::Xor:
586       case Instruction::ZExt:
587         break;
588       }
589 
590       for (unsigned oi = 0, oe = ii.getNumOperands(); oi != oe; ++oi) {
591         Value *operand = ii.getOperand(oi);
592         Type *operand_type = operand->getType();
593 
594         switch (operand_type->getTypeID()) {
595         default:
596           break;
597         case Type::FixedVectorTyID:
598         case Type::ScalableVectorTyID: {
599           LLDB_LOGF(log, "Unsupported operand type: %s",
600                     PrintType(operand_type).c_str());
601           error.SetErrorString(unsupported_operand_error);
602           return false;
603         }
604         }
605 
606         // The IR interpreter currently doesn't know about
607         // 128-bit integers. As they're not that frequent,
608         // we can just fall back to the JIT rather than
609         // choking.
610         if (operand_type->getPrimitiveSizeInBits() > 64) {
611           LLDB_LOGF(log, "Unsupported operand type: %s",
612                     PrintType(operand_type).c_str());
613           error.SetErrorString(unsupported_operand_error);
614           return false;
615         }
616 
617         if (Constant *constant = llvm::dyn_cast<Constant>(operand)) {
618           if (!CanResolveConstant(constant)) {
619             LLDB_LOGF(log, "Unsupported constant: %s",
620                       PrintValue(constant).c_str());
621             error.SetErrorString(unsupported_operand_error);
622             return false;
623           }
624         }
625       }
626     }
627   }
628 
629   return true;
630 }
631 
632 bool IRInterpreter::Interpret(llvm::Module &module, llvm::Function &function,
633                               llvm::ArrayRef<lldb::addr_t> args,
634                               lldb_private::IRExecutionUnit &execution_unit,
635                               lldb_private::Status &error,
636                               lldb::addr_t stack_frame_bottom,
637                               lldb::addr_t stack_frame_top,
638                               lldb_private::ExecutionContext &exe_ctx) {
639   lldb_private::Log *log(GetLog(LLDBLog::Expressions));
640 
641   if (log) {
642     std::string s;
643     raw_string_ostream oss(s);
644 
645     module.print(oss, nullptr);
646 
647     oss.flush();
648 
649     LLDB_LOGF(log, "Module as passed in to IRInterpreter::Interpret: \n\"%s\"",
650               s.c_str());
651   }
652 
653   DataLayout data_layout(&module);
654 
655   InterpreterStackFrame frame(data_layout, execution_unit, stack_frame_bottom,
656                               stack_frame_top);
657 
658   if (frame.m_frame_process_address == LLDB_INVALID_ADDRESS) {
659     error.SetErrorString("Couldn't allocate stack frame");
660   }
661 
662   int arg_index = 0;
663 
664   for (llvm::Function::arg_iterator ai = function.arg_begin(),
665                                     ae = function.arg_end();
666        ai != ae; ++ai, ++arg_index) {
667     if (args.size() <= static_cast<size_t>(arg_index)) {
668       error.SetErrorString("Not enough arguments passed in to function");
669       return false;
670     }
671 
672     lldb::addr_t ptr = args[arg_index];
673 
674     frame.MakeArgument(&*ai, ptr);
675   }
676 
677   uint32_t num_insts = 0;
678 
679   frame.Jump(&function.front());
680 
681   while (frame.m_ii != frame.m_ie && (++num_insts < 4096)) {
682     const Instruction *inst = &*frame.m_ii;
683 
684     LLDB_LOGF(log, "Interpreting %s", PrintValue(inst).c_str());
685 
686     switch (inst->getOpcode()) {
687     default:
688       break;
689 
690     case Instruction::Add:
691     case Instruction::Sub:
692     case Instruction::Mul:
693     case Instruction::SDiv:
694     case Instruction::UDiv:
695     case Instruction::SRem:
696     case Instruction::URem:
697     case Instruction::Shl:
698     case Instruction::LShr:
699     case Instruction::AShr:
700     case Instruction::And:
701     case Instruction::Or:
702     case Instruction::Xor: {
703       const BinaryOperator *bin_op = dyn_cast<BinaryOperator>(inst);
704 
705       if (!bin_op) {
706         LLDB_LOGF(
707             log,
708             "getOpcode() returns %s, but instruction is not a BinaryOperator",
709             inst->getOpcodeName());
710         error.SetErrorToGenericError();
711         error.SetErrorString(interpreter_internal_error);
712         return false;
713       }
714 
715       Value *lhs = inst->getOperand(0);
716       Value *rhs = inst->getOperand(1);
717 
718       lldb_private::Scalar L;
719       lldb_private::Scalar R;
720 
721       if (!frame.EvaluateValue(L, lhs, module)) {
722         LLDB_LOGF(log, "Couldn't evaluate %s", PrintValue(lhs).c_str());
723         error.SetErrorToGenericError();
724         error.SetErrorString(bad_value_error);
725         return false;
726       }
727 
728       if (!frame.EvaluateValue(R, rhs, module)) {
729         LLDB_LOGF(log, "Couldn't evaluate %s", PrintValue(rhs).c_str());
730         error.SetErrorToGenericError();
731         error.SetErrorString(bad_value_error);
732         return false;
733       }
734 
735       lldb_private::Scalar result;
736 
737       switch (inst->getOpcode()) {
738       default:
739         break;
740       case Instruction::Add:
741         result = L + R;
742         break;
743       case Instruction::Mul:
744         result = L * R;
745         break;
746       case Instruction::Sub:
747         result = L - R;
748         break;
749       case Instruction::SDiv:
750         L.MakeSigned();
751         R.MakeSigned();
752         result = L / R;
753         break;
754       case Instruction::UDiv:
755         L.MakeUnsigned();
756         R.MakeUnsigned();
757         result = L / R;
758         break;
759       case Instruction::SRem:
760         L.MakeSigned();
761         R.MakeSigned();
762         result = L % R;
763         break;
764       case Instruction::URem:
765         L.MakeUnsigned();
766         R.MakeUnsigned();
767         result = L % R;
768         break;
769       case Instruction::Shl:
770         result = L << R;
771         break;
772       case Instruction::AShr:
773         result = L >> R;
774         break;
775       case Instruction::LShr:
776         result = L;
777         result.ShiftRightLogical(R);
778         break;
779       case Instruction::And:
780         result = L & R;
781         break;
782       case Instruction::Or:
783         result = L | R;
784         break;
785       case Instruction::Xor:
786         result = L ^ R;
787         break;
788       }
789 
790       frame.AssignValue(inst, result, module);
791 
792       if (log) {
793         LLDB_LOGF(log, "Interpreted a %s", inst->getOpcodeName());
794         LLDB_LOGF(log, "  L : %s", frame.SummarizeValue(lhs).c_str());
795         LLDB_LOGF(log, "  R : %s", frame.SummarizeValue(rhs).c_str());
796         LLDB_LOGF(log, "  = : %s", frame.SummarizeValue(inst).c_str());
797       }
798     } break;
799     case Instruction::Alloca: {
800       const AllocaInst *alloca_inst = cast<AllocaInst>(inst);
801 
802       if (alloca_inst->isArrayAllocation()) {
803         LLDB_LOGF(log,
804                   "AllocaInsts are not handled if isArrayAllocation() is true");
805         error.SetErrorToGenericError();
806         error.SetErrorString(unsupported_opcode_error);
807         return false;
808       }
809 
810       // The semantics of Alloca are:
811       //   Create a region R of virtual memory of type T, backed by a data
812       //   buffer
813       //   Create a region P of virtual memory of type T*, backed by a data
814       //   buffer
815       //   Write the virtual address of R into P
816 
817       Type *T = alloca_inst->getAllocatedType();
818       Type *Tptr = alloca_inst->getType();
819 
820       lldb::addr_t R = frame.Malloc(T);
821 
822       if (R == LLDB_INVALID_ADDRESS) {
823         LLDB_LOGF(log, "Couldn't allocate memory for an AllocaInst");
824         error.SetErrorToGenericError();
825         error.SetErrorString(memory_allocation_error);
826         return false;
827       }
828 
829       lldb::addr_t P = frame.Malloc(Tptr);
830 
831       if (P == LLDB_INVALID_ADDRESS) {
832         LLDB_LOGF(log,
833                   "Couldn't allocate the result pointer for an AllocaInst");
834         error.SetErrorToGenericError();
835         error.SetErrorString(memory_allocation_error);
836         return false;
837       }
838 
839       lldb_private::Status write_error;
840 
841       execution_unit.WritePointerToMemory(P, R, write_error);
842 
843       if (!write_error.Success()) {
844         LLDB_LOGF(log, "Couldn't write the result pointer for an AllocaInst");
845         error.SetErrorToGenericError();
846         error.SetErrorString(memory_write_error);
847         lldb_private::Status free_error;
848         execution_unit.Free(P, free_error);
849         execution_unit.Free(R, free_error);
850         return false;
851       }
852 
853       frame.m_values[alloca_inst] = P;
854 
855       if (log) {
856         LLDB_LOGF(log, "Interpreted an AllocaInst");
857         LLDB_LOGF(log, "  R : 0x%" PRIx64, R);
858         LLDB_LOGF(log, "  P : 0x%" PRIx64, P);
859       }
860     } break;
861     case Instruction::BitCast:
862     case Instruction::ZExt: {
863       const CastInst *cast_inst = cast<CastInst>(inst);
864 
865       Value *source = cast_inst->getOperand(0);
866 
867       lldb_private::Scalar S;
868 
869       if (!frame.EvaluateValue(S, source, module)) {
870         LLDB_LOGF(log, "Couldn't evaluate %s", PrintValue(source).c_str());
871         error.SetErrorToGenericError();
872         error.SetErrorString(bad_value_error);
873         return false;
874       }
875 
876       frame.AssignValue(inst, S, module);
877     } break;
878     case Instruction::SExt: {
879       const CastInst *cast_inst = cast<CastInst>(inst);
880 
881       Value *source = cast_inst->getOperand(0);
882 
883       lldb_private::Scalar S;
884 
885       if (!frame.EvaluateValue(S, source, module)) {
886         LLDB_LOGF(log, "Couldn't evaluate %s", PrintValue(source).c_str());
887         error.SetErrorToGenericError();
888         error.SetErrorString(bad_value_error);
889         return false;
890       }
891 
892       S.MakeSigned();
893 
894       lldb_private::Scalar S_signextend(S.SLongLong());
895 
896       frame.AssignValue(inst, S_signextend, module);
897     } break;
898     case Instruction::Br: {
899       const BranchInst *br_inst = cast<BranchInst>(inst);
900 
901       if (br_inst->isConditional()) {
902         Value *condition = br_inst->getCondition();
903 
904         lldb_private::Scalar C;
905 
906         if (!frame.EvaluateValue(C, condition, module)) {
907           LLDB_LOGF(log, "Couldn't evaluate %s", PrintValue(condition).c_str());
908           error.SetErrorToGenericError();
909           error.SetErrorString(bad_value_error);
910           return false;
911         }
912 
913         if (!C.IsZero())
914           frame.Jump(br_inst->getSuccessor(0));
915         else
916           frame.Jump(br_inst->getSuccessor(1));
917 
918         if (log) {
919           LLDB_LOGF(log, "Interpreted a BrInst with a condition");
920           LLDB_LOGF(log, "  cond : %s",
921                     frame.SummarizeValue(condition).c_str());
922         }
923       } else {
924         frame.Jump(br_inst->getSuccessor(0));
925 
926         if (log) {
927           LLDB_LOGF(log, "Interpreted a BrInst with no condition");
928         }
929       }
930     }
931       continue;
932     case Instruction::PHI: {
933       const PHINode *phi_inst = cast<PHINode>(inst);
934       if (!frame.m_prev_bb) {
935         LLDB_LOGF(log,
936                   "Encountered PHI node without having jumped from another "
937                   "basic block");
938         error.SetErrorToGenericError();
939         error.SetErrorString(interpreter_internal_error);
940         return false;
941       }
942 
943       Value *value = phi_inst->getIncomingValueForBlock(frame.m_prev_bb);
944       lldb_private::Scalar result;
945       if (!frame.EvaluateValue(result, value, module)) {
946         LLDB_LOGF(log, "Couldn't evaluate %s", PrintValue(value).c_str());
947         error.SetErrorToGenericError();
948         error.SetErrorString(bad_value_error);
949         return false;
950       }
951       frame.AssignValue(inst, result, module);
952 
953       if (log) {
954         LLDB_LOGF(log, "Interpreted a %s", inst->getOpcodeName());
955         LLDB_LOGF(log, "  Incoming value : %s",
956                   frame.SummarizeValue(value).c_str());
957       }
958     } break;
959     case Instruction::GetElementPtr: {
960       const GetElementPtrInst *gep_inst = cast<GetElementPtrInst>(inst);
961 
962       const Value *pointer_operand = gep_inst->getPointerOperand();
963       Type *src_elem_ty = gep_inst->getSourceElementType();
964 
965       lldb_private::Scalar P;
966 
967       if (!frame.EvaluateValue(P, pointer_operand, module)) {
968         LLDB_LOGF(log, "Couldn't evaluate %s",
969                   PrintValue(pointer_operand).c_str());
970         error.SetErrorToGenericError();
971         error.SetErrorString(bad_value_error);
972         return false;
973       }
974 
975       typedef SmallVector<Value *, 8> IndexVector;
976       typedef IndexVector::iterator IndexIterator;
977 
978       SmallVector<Value *, 8> indices(gep_inst->idx_begin(),
979                                       gep_inst->idx_end());
980 
981       SmallVector<Value *, 8> const_indices;
982 
983       for (IndexIterator ii = indices.begin(), ie = indices.end(); ii != ie;
984            ++ii) {
985         ConstantInt *constant_index = dyn_cast<ConstantInt>(*ii);
986 
987         if (!constant_index) {
988           lldb_private::Scalar I;
989 
990           if (!frame.EvaluateValue(I, *ii, module)) {
991             LLDB_LOGF(log, "Couldn't evaluate %s", PrintValue(*ii).c_str());
992             error.SetErrorToGenericError();
993             error.SetErrorString(bad_value_error);
994             return false;
995           }
996 
997           LLDB_LOGF(log, "Evaluated constant index %s as %llu",
998                     PrintValue(*ii).c_str(), I.ULongLong(LLDB_INVALID_ADDRESS));
999 
1000           constant_index = cast<ConstantInt>(ConstantInt::get(
1001               (*ii)->getType(), I.ULongLong(LLDB_INVALID_ADDRESS)));
1002         }
1003 
1004         const_indices.push_back(constant_index);
1005       }
1006 
1007       uint64_t offset =
1008           data_layout.getIndexedOffsetInType(src_elem_ty, const_indices);
1009 
1010       lldb_private::Scalar Poffset = P + offset;
1011 
1012       frame.AssignValue(inst, Poffset, module);
1013 
1014       if (log) {
1015         LLDB_LOGF(log, "Interpreted a GetElementPtrInst");
1016         LLDB_LOGF(log, "  P       : %s",
1017                   frame.SummarizeValue(pointer_operand).c_str());
1018         LLDB_LOGF(log, "  Poffset : %s", frame.SummarizeValue(inst).c_str());
1019       }
1020     } break;
1021     case Instruction::ICmp: {
1022       const ICmpInst *icmp_inst = cast<ICmpInst>(inst);
1023 
1024       CmpInst::Predicate predicate = icmp_inst->getPredicate();
1025 
1026       Value *lhs = inst->getOperand(0);
1027       Value *rhs = inst->getOperand(1);
1028 
1029       lldb_private::Scalar L;
1030       lldb_private::Scalar R;
1031 
1032       if (!frame.EvaluateValue(L, lhs, module)) {
1033         LLDB_LOGF(log, "Couldn't evaluate %s", PrintValue(lhs).c_str());
1034         error.SetErrorToGenericError();
1035         error.SetErrorString(bad_value_error);
1036         return false;
1037       }
1038 
1039       if (!frame.EvaluateValue(R, rhs, module)) {
1040         LLDB_LOGF(log, "Couldn't evaluate %s", PrintValue(rhs).c_str());
1041         error.SetErrorToGenericError();
1042         error.SetErrorString(bad_value_error);
1043         return false;
1044       }
1045 
1046       lldb_private::Scalar result;
1047 
1048       switch (predicate) {
1049       default:
1050         return false;
1051       case CmpInst::ICMP_EQ:
1052         result = (L == R);
1053         break;
1054       case CmpInst::ICMP_NE:
1055         result = (L != R);
1056         break;
1057       case CmpInst::ICMP_UGT:
1058         L.MakeUnsigned();
1059         R.MakeUnsigned();
1060         result = (L > R);
1061         break;
1062       case CmpInst::ICMP_UGE:
1063         L.MakeUnsigned();
1064         R.MakeUnsigned();
1065         result = (L >= R);
1066         break;
1067       case CmpInst::ICMP_ULT:
1068         L.MakeUnsigned();
1069         R.MakeUnsigned();
1070         result = (L < R);
1071         break;
1072       case CmpInst::ICMP_ULE:
1073         L.MakeUnsigned();
1074         R.MakeUnsigned();
1075         result = (L <= R);
1076         break;
1077       case CmpInst::ICMP_SGT:
1078         L.MakeSigned();
1079         R.MakeSigned();
1080         result = (L > R);
1081         break;
1082       case CmpInst::ICMP_SGE:
1083         L.MakeSigned();
1084         R.MakeSigned();
1085         result = (L >= R);
1086         break;
1087       case CmpInst::ICMP_SLT:
1088         L.MakeSigned();
1089         R.MakeSigned();
1090         result = (L < R);
1091         break;
1092       case CmpInst::ICMP_SLE:
1093         L.MakeSigned();
1094         R.MakeSigned();
1095         result = (L <= R);
1096         break;
1097       }
1098 
1099       frame.AssignValue(inst, result, module);
1100 
1101       if (log) {
1102         LLDB_LOGF(log, "Interpreted an ICmpInst");
1103         LLDB_LOGF(log, "  L : %s", frame.SummarizeValue(lhs).c_str());
1104         LLDB_LOGF(log, "  R : %s", frame.SummarizeValue(rhs).c_str());
1105         LLDB_LOGF(log, "  = : %s", frame.SummarizeValue(inst).c_str());
1106       }
1107     } break;
1108     case Instruction::IntToPtr: {
1109       const IntToPtrInst *int_to_ptr_inst = cast<IntToPtrInst>(inst);
1110 
1111       Value *src_operand = int_to_ptr_inst->getOperand(0);
1112 
1113       lldb_private::Scalar I;
1114 
1115       if (!frame.EvaluateValue(I, src_operand, module)) {
1116         LLDB_LOGF(log, "Couldn't evaluate %s", PrintValue(src_operand).c_str());
1117         error.SetErrorToGenericError();
1118         error.SetErrorString(bad_value_error);
1119         return false;
1120       }
1121 
1122       frame.AssignValue(inst, I, module);
1123 
1124       if (log) {
1125         LLDB_LOGF(log, "Interpreted an IntToPtr");
1126         LLDB_LOGF(log, "  Src : %s", frame.SummarizeValue(src_operand).c_str());
1127         LLDB_LOGF(log, "  =   : %s", frame.SummarizeValue(inst).c_str());
1128       }
1129     } break;
1130     case Instruction::PtrToInt: {
1131       const PtrToIntInst *ptr_to_int_inst = cast<PtrToIntInst>(inst);
1132 
1133       Value *src_operand = ptr_to_int_inst->getOperand(0);
1134 
1135       lldb_private::Scalar I;
1136 
1137       if (!frame.EvaluateValue(I, src_operand, module)) {
1138         LLDB_LOGF(log, "Couldn't evaluate %s", PrintValue(src_operand).c_str());
1139         error.SetErrorToGenericError();
1140         error.SetErrorString(bad_value_error);
1141         return false;
1142       }
1143 
1144       frame.AssignValue(inst, I, module);
1145 
1146       if (log) {
1147         LLDB_LOGF(log, "Interpreted a PtrToInt");
1148         LLDB_LOGF(log, "  Src : %s", frame.SummarizeValue(src_operand).c_str());
1149         LLDB_LOGF(log, "  =   : %s", frame.SummarizeValue(inst).c_str());
1150       }
1151     } break;
1152     case Instruction::Trunc: {
1153       const TruncInst *trunc_inst = cast<TruncInst>(inst);
1154 
1155       Value *src_operand = trunc_inst->getOperand(0);
1156 
1157       lldb_private::Scalar I;
1158 
1159       if (!frame.EvaluateValue(I, src_operand, module)) {
1160         LLDB_LOGF(log, "Couldn't evaluate %s", PrintValue(src_operand).c_str());
1161         error.SetErrorToGenericError();
1162         error.SetErrorString(bad_value_error);
1163         return false;
1164       }
1165 
1166       frame.AssignValue(inst, I, module);
1167 
1168       if (log) {
1169         LLDB_LOGF(log, "Interpreted a Trunc");
1170         LLDB_LOGF(log, "  Src : %s", frame.SummarizeValue(src_operand).c_str());
1171         LLDB_LOGF(log, "  =   : %s", frame.SummarizeValue(inst).c_str());
1172       }
1173     } break;
1174     case Instruction::Load: {
1175       const LoadInst *load_inst = cast<LoadInst>(inst);
1176 
1177       // The semantics of Load are:
1178       //   Create a region D that will contain the loaded data
1179       //   Resolve the region P containing a pointer
1180       //   Dereference P to get the region R that the data should be loaded from
1181       //   Transfer a unit of type type(D) from R to D
1182 
1183       const Value *pointer_operand = load_inst->getPointerOperand();
1184 
1185       Type *pointer_ty = pointer_operand->getType();
1186       PointerType *pointer_ptr_ty = dyn_cast<PointerType>(pointer_ty);
1187       if (!pointer_ptr_ty) {
1188         LLDB_LOGF(log, "getPointerOperand()->getType() is not a PointerType");
1189         error.SetErrorToGenericError();
1190         error.SetErrorString(interpreter_internal_error);
1191         return false;
1192       }
1193       Type *target_ty = pointer_ptr_ty->getElementType();
1194 
1195       lldb::addr_t D = frame.ResolveValue(load_inst, module);
1196       lldb::addr_t P = frame.ResolveValue(pointer_operand, module);
1197 
1198       if (D == LLDB_INVALID_ADDRESS) {
1199         LLDB_LOGF(log, "LoadInst's value doesn't resolve to anything");
1200         error.SetErrorToGenericError();
1201         error.SetErrorString(bad_value_error);
1202         return false;
1203       }
1204 
1205       if (P == LLDB_INVALID_ADDRESS) {
1206         LLDB_LOGF(log, "LoadInst's pointer doesn't resolve to anything");
1207         error.SetErrorToGenericError();
1208         error.SetErrorString(bad_value_error);
1209         return false;
1210       }
1211 
1212       lldb::addr_t R;
1213       lldb_private::Status read_error;
1214       execution_unit.ReadPointerFromMemory(&R, P, read_error);
1215 
1216       if (!read_error.Success()) {
1217         LLDB_LOGF(log, "Couldn't read the address to be loaded for a LoadInst");
1218         error.SetErrorToGenericError();
1219         error.SetErrorString(memory_read_error);
1220         return false;
1221       }
1222 
1223       size_t target_size = data_layout.getTypeStoreSize(target_ty);
1224       lldb_private::DataBufferHeap buffer(target_size, 0);
1225 
1226       read_error.Clear();
1227       execution_unit.ReadMemory(buffer.GetBytes(), R, buffer.GetByteSize(),
1228                                 read_error);
1229       if (!read_error.Success()) {
1230         LLDB_LOGF(log, "Couldn't read from a region on behalf of a LoadInst");
1231         error.SetErrorToGenericError();
1232         error.SetErrorString(memory_read_error);
1233         return false;
1234       }
1235 
1236       lldb_private::Status write_error;
1237       execution_unit.WriteMemory(D, buffer.GetBytes(), buffer.GetByteSize(),
1238                                  write_error);
1239       if (!write_error.Success()) {
1240         LLDB_LOGF(log, "Couldn't write to a region on behalf of a LoadInst");
1241         error.SetErrorToGenericError();
1242         error.SetErrorString(memory_write_error);
1243         return false;
1244       }
1245 
1246       if (log) {
1247         LLDB_LOGF(log, "Interpreted a LoadInst");
1248         LLDB_LOGF(log, "  P : 0x%" PRIx64, P);
1249         LLDB_LOGF(log, "  R : 0x%" PRIx64, R);
1250         LLDB_LOGF(log, "  D : 0x%" PRIx64, D);
1251       }
1252     } break;
1253     case Instruction::Ret: {
1254       return true;
1255     }
1256     case Instruction::Store: {
1257       const StoreInst *store_inst = cast<StoreInst>(inst);
1258 
1259       // The semantics of Store are:
1260       //   Resolve the region D containing the data to be stored
1261       //   Resolve the region P containing a pointer
1262       //   Dereference P to get the region R that the data should be stored in
1263       //   Transfer a unit of type type(D) from D to R
1264 
1265       const Value *value_operand = store_inst->getValueOperand();
1266       const Value *pointer_operand = store_inst->getPointerOperand();
1267 
1268       Type *pointer_ty = pointer_operand->getType();
1269       PointerType *pointer_ptr_ty = dyn_cast<PointerType>(pointer_ty);
1270       if (!pointer_ptr_ty)
1271         return false;
1272       Type *target_ty = pointer_ptr_ty->getElementType();
1273 
1274       lldb::addr_t D = frame.ResolveValue(value_operand, module);
1275       lldb::addr_t P = frame.ResolveValue(pointer_operand, module);
1276 
1277       if (D == LLDB_INVALID_ADDRESS) {
1278         LLDB_LOGF(log, "StoreInst's value doesn't resolve to anything");
1279         error.SetErrorToGenericError();
1280         error.SetErrorString(bad_value_error);
1281         return false;
1282       }
1283 
1284       if (P == LLDB_INVALID_ADDRESS) {
1285         LLDB_LOGF(log, "StoreInst's pointer doesn't resolve to anything");
1286         error.SetErrorToGenericError();
1287         error.SetErrorString(bad_value_error);
1288         return false;
1289       }
1290 
1291       lldb::addr_t R;
1292       lldb_private::Status read_error;
1293       execution_unit.ReadPointerFromMemory(&R, P, read_error);
1294 
1295       if (!read_error.Success()) {
1296         LLDB_LOGF(log, "Couldn't read the address to be loaded for a LoadInst");
1297         error.SetErrorToGenericError();
1298         error.SetErrorString(memory_read_error);
1299         return false;
1300       }
1301 
1302       size_t target_size = data_layout.getTypeStoreSize(target_ty);
1303       lldb_private::DataBufferHeap buffer(target_size, 0);
1304 
1305       read_error.Clear();
1306       execution_unit.ReadMemory(buffer.GetBytes(), D, buffer.GetByteSize(),
1307                                 read_error);
1308       if (!read_error.Success()) {
1309         LLDB_LOGF(log, "Couldn't read from a region on behalf of a StoreInst");
1310         error.SetErrorToGenericError();
1311         error.SetErrorString(memory_read_error);
1312         return false;
1313       }
1314 
1315       lldb_private::Status write_error;
1316       execution_unit.WriteMemory(R, buffer.GetBytes(), buffer.GetByteSize(),
1317                                  write_error);
1318       if (!write_error.Success()) {
1319         LLDB_LOGF(log, "Couldn't write to a region on behalf of a StoreInst");
1320         error.SetErrorToGenericError();
1321         error.SetErrorString(memory_write_error);
1322         return false;
1323       }
1324 
1325       if (log) {
1326         LLDB_LOGF(log, "Interpreted a StoreInst");
1327         LLDB_LOGF(log, "  D : 0x%" PRIx64, D);
1328         LLDB_LOGF(log, "  P : 0x%" PRIx64, P);
1329         LLDB_LOGF(log, "  R : 0x%" PRIx64, R);
1330       }
1331     } break;
1332     case Instruction::Call: {
1333       const CallInst *call_inst = cast<CallInst>(inst);
1334 
1335       if (CanIgnoreCall(call_inst))
1336         break;
1337 
1338       // Get the return type
1339       llvm::Type *returnType = call_inst->getType();
1340       if (returnType == nullptr) {
1341         error.SetErrorToGenericError();
1342         error.SetErrorString("unable to access return type");
1343         return false;
1344       }
1345 
1346       // Work with void, integer and pointer return types
1347       if (!returnType->isVoidTy() && !returnType->isIntegerTy() &&
1348           !returnType->isPointerTy()) {
1349         error.SetErrorToGenericError();
1350         error.SetErrorString("return type is not supported");
1351         return false;
1352       }
1353 
1354       // Check we can actually get a thread
1355       if (exe_ctx.GetThreadPtr() == nullptr) {
1356         error.SetErrorToGenericError();
1357         error.SetErrorString("unable to acquire thread");
1358         return false;
1359       }
1360 
1361       // Make sure we have a valid process
1362       if (!exe_ctx.GetProcessPtr()) {
1363         error.SetErrorToGenericError();
1364         error.SetErrorString("unable to get the process");
1365         return false;
1366       }
1367 
1368       // Find the address of the callee function
1369       lldb_private::Scalar I;
1370       const llvm::Value *val = call_inst->getCalledOperand();
1371 
1372       if (!frame.EvaluateValue(I, val, module)) {
1373         error.SetErrorToGenericError();
1374         error.SetErrorString("unable to get address of function");
1375         return false;
1376       }
1377       lldb_private::Address funcAddr(I.ULongLong(LLDB_INVALID_ADDRESS));
1378 
1379       lldb_private::DiagnosticManager diagnostics;
1380       lldb_private::EvaluateExpressionOptions options;
1381 
1382       // We generally receive a function pointer which we must dereference
1383       llvm::Type *prototype = val->getType();
1384       if (!prototype->isPointerTy()) {
1385         error.SetErrorToGenericError();
1386         error.SetErrorString("call need function pointer");
1387         return false;
1388       }
1389 
1390       // Dereference the function pointer
1391       prototype = prototype->getPointerElementType();
1392       if (!(prototype->isFunctionTy() || prototype->isFunctionVarArg())) {
1393         error.SetErrorToGenericError();
1394         error.SetErrorString("call need function pointer");
1395         return false;
1396       }
1397 
1398       // Find number of arguments
1399       const int numArgs = call_inst->arg_size();
1400 
1401       // We work with a fixed array of 16 arguments which is our upper limit
1402       static lldb_private::ABI::CallArgument rawArgs[16];
1403       if (numArgs >= 16) {
1404         error.SetErrorToGenericError();
1405         error.SetErrorString("function takes too many arguments");
1406         return false;
1407       }
1408 
1409       // Push all function arguments to the argument list that will be passed
1410       // to the call function thread plan
1411       for (int i = 0; i < numArgs; i++) {
1412         // Get details of this argument
1413         llvm::Value *arg_op = call_inst->getArgOperand(i);
1414         llvm::Type *arg_ty = arg_op->getType();
1415 
1416         // Ensure that this argument is an supported type
1417         if (!arg_ty->isIntegerTy() && !arg_ty->isPointerTy()) {
1418           error.SetErrorToGenericError();
1419           error.SetErrorStringWithFormat("argument %d must be integer type", i);
1420           return false;
1421         }
1422 
1423         // Extract the arguments value
1424         lldb_private::Scalar tmp_op = 0;
1425         if (!frame.EvaluateValue(tmp_op, arg_op, module)) {
1426           error.SetErrorToGenericError();
1427           error.SetErrorStringWithFormat("unable to evaluate argument %d", i);
1428           return false;
1429         }
1430 
1431         // Check if this is a string literal or constant string pointer
1432         if (arg_ty->isPointerTy()) {
1433           lldb::addr_t addr = tmp_op.ULongLong();
1434           size_t dataSize = 0;
1435 
1436           bool Success = execution_unit.GetAllocSize(addr, dataSize);
1437           (void)Success;
1438           assert(Success &&
1439                  "unable to locate host data for transfer to device");
1440           // Create the required buffer
1441           rawArgs[i].size = dataSize;
1442           rawArgs[i].data_up.reset(new uint8_t[dataSize + 1]);
1443 
1444           // Read string from host memory
1445           execution_unit.ReadMemory(rawArgs[i].data_up.get(), addr, dataSize,
1446                                     error);
1447           assert(!error.Fail() &&
1448                  "we have failed to read the string from memory");
1449 
1450           // Add null terminator
1451           rawArgs[i].data_up[dataSize] = '\0';
1452           rawArgs[i].type = lldb_private::ABI::CallArgument::HostPointer;
1453         } else /* if ( arg_ty->isPointerTy() ) */
1454         {
1455           rawArgs[i].type = lldb_private::ABI::CallArgument::TargetValue;
1456           // Get argument size in bytes
1457           rawArgs[i].size = arg_ty->getIntegerBitWidth() / 8;
1458           // Push value into argument list for thread plan
1459           rawArgs[i].value = tmp_op.ULongLong();
1460         }
1461       }
1462 
1463       // Pack the arguments into an llvm::array
1464       llvm::ArrayRef<lldb_private::ABI::CallArgument> args(rawArgs, numArgs);
1465 
1466       // Setup a thread plan to call the target function
1467       lldb::ThreadPlanSP call_plan_sp(
1468           new lldb_private::ThreadPlanCallFunctionUsingABI(
1469               exe_ctx.GetThreadRef(), funcAddr, *prototype, *returnType, args,
1470               options));
1471 
1472       // Check if the plan is valid
1473       lldb_private::StreamString ss;
1474       if (!call_plan_sp || !call_plan_sp->ValidatePlan(&ss)) {
1475         error.SetErrorToGenericError();
1476         error.SetErrorStringWithFormat(
1477             "unable to make ThreadPlanCallFunctionUsingABI for 0x%llx",
1478             I.ULongLong());
1479         return false;
1480       }
1481 
1482       exe_ctx.GetProcessPtr()->SetRunningUserExpression(true);
1483 
1484       // Execute the actual function call thread plan
1485       lldb::ExpressionResults res = exe_ctx.GetProcessRef().RunThreadPlan(
1486           exe_ctx, call_plan_sp, options, diagnostics);
1487 
1488       // Check that the thread plan completed successfully
1489       if (res != lldb::ExpressionResults::eExpressionCompleted) {
1490         error.SetErrorToGenericError();
1491         error.SetErrorString("ThreadPlanCallFunctionUsingABI failed");
1492         return false;
1493       }
1494 
1495       exe_ctx.GetProcessPtr()->SetRunningUserExpression(false);
1496 
1497       // Void return type
1498       if (returnType->isVoidTy()) {
1499         // Cant assign to void types, so we leave the frame untouched
1500       } else
1501           // Integer or pointer return type
1502           if (returnType->isIntegerTy() || returnType->isPointerTy()) {
1503         // Get the encapsulated return value
1504         lldb::ValueObjectSP retVal = call_plan_sp.get()->GetReturnValueObject();
1505 
1506         lldb_private::Scalar returnVal = -1;
1507         lldb_private::ValueObject *vobj = retVal.get();
1508 
1509         // Check if the return value is valid
1510         if (vobj == nullptr || !retVal) {
1511           error.SetErrorToGenericError();
1512           error.SetErrorString("unable to get the return value");
1513           return false;
1514         }
1515 
1516         // Extract the return value as a integer
1517         lldb_private::Value &value = vobj->GetValue();
1518         returnVal = value.GetScalar();
1519 
1520         // Push the return value as the result
1521         frame.AssignValue(inst, returnVal, module);
1522       }
1523     } break;
1524     }
1525 
1526     ++frame.m_ii;
1527   }
1528 
1529   if (num_insts >= 4096) {
1530     error.SetErrorToGenericError();
1531     error.SetErrorString(infinite_loop_error);
1532     return false;
1533   }
1534 
1535   return false;
1536 }
1537