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 
45 static std::string PrintValue(const Value *value, bool truncate = false) {
46   std::string s;
47   raw_string_ostream rso(s);
48   value->print(rso);
49   rso.flush();
50   if (truncate)
51     s.resize(s.length() - 1);
52 
53   size_t offset;
54   while ((offset = s.find('\n')) != s.npos)
55     s.erase(offset, 1);
56   while (s[0] == ' ' || s[0] == '\t')
57     s.erase(0, 1);
58 
59   return s;
60 }
61 
62 static std::string PrintType(const Type *type, bool truncate = false) {
63   std::string s;
64   raw_string_ostream rso(s);
65   type->print(rso);
66   rso.flush();
67   if (truncate)
68     s.resize(s.length() - 1);
69   return s;
70 }
71 
72 static bool CanIgnoreCall(const CallInst *call) {
73   const llvm::Function *called_function = call->getCalledFunction();
74 
75   if (!called_function)
76     return false;
77 
78   if (called_function->isIntrinsic()) {
79     switch (called_function->getIntrinsicID()) {
80     default:
81       break;
82     case llvm::Intrinsic::dbg_declare:
83     case llvm::Intrinsic::dbg_value:
84       return true;
85     }
86   }
87 
88   return false;
89 }
90 
91 class InterpreterStackFrame {
92 public:
93   typedef std::map<const Value *, lldb::addr_t> ValueMap;
94 
95   ValueMap m_values;
96   DataLayout &m_target_data;
97   lldb_private::IRExecutionUnit &m_execution_unit;
98   const BasicBlock *m_bb;
99   const BasicBlock *m_prev_bb;
100   BasicBlock::const_iterator m_ii;
101   BasicBlock::const_iterator m_ie;
102 
103   lldb::addr_t m_frame_process_address;
104   size_t m_frame_size;
105   lldb::addr_t m_stack_pointer;
106 
107   lldb::ByteOrder m_byte_order;
108   size_t m_addr_byte_size;
109 
110   InterpreterStackFrame(DataLayout &target_data,
111                         lldb_private::IRExecutionUnit &execution_unit,
112                         lldb::addr_t stack_frame_bottom,
113                         lldb::addr_t stack_frame_top)
114       : m_target_data(target_data), m_execution_unit(execution_unit),
115         m_bb(nullptr), m_prev_bb(nullptr) {
116     m_byte_order = (target_data.isLittleEndian() ? lldb::eByteOrderLittle
117                                                  : lldb::eByteOrderBig);
118     m_addr_byte_size = (target_data.getPointerSize(0));
119 
120     m_frame_process_address = stack_frame_bottom;
121     m_frame_size = stack_frame_top - stack_frame_bottom;
122     m_stack_pointer = stack_frame_top;
123   }
124 
125   ~InterpreterStackFrame() {}
126 
127   void Jump(const BasicBlock *bb) {
128     m_prev_bb = m_bb;
129     m_bb = bb;
130     m_ii = m_bb->begin();
131     m_ie = m_bb->end();
132   }
133 
134   std::string SummarizeValue(const Value *value) {
135     lldb_private::StreamString ss;
136 
137     ss.Printf("%s", PrintValue(value).c_str());
138 
139     ValueMap::iterator i = m_values.find(value);
140 
141     if (i != m_values.end()) {
142       lldb::addr_t addr = i->second;
143 
144       ss.Printf(" 0x%llx", (unsigned long long)addr);
145     }
146 
147     return std::string(ss.GetString());
148   }
149 
150   bool AssignToMatchType(lldb_private::Scalar &scalar, uint64_t u64value,
151                          Type *type) {
152     size_t type_size = m_target_data.getTypeStoreSize(type);
153 
154     if (type_size > 8)
155       return false;
156 
157     if (type_size != 1)
158       type_size = PowerOf2Ceil(type_size);
159 
160     scalar = llvm::APInt(type_size*8, u64value);
161     return true;
162   }
163 
164   bool EvaluateValue(lldb_private::Scalar &scalar, const Value *value,
165                      Module &module) {
166     const Constant *constant = dyn_cast<Constant>(value);
167 
168     if (constant) {
169       APInt value_apint;
170 
171       if (!ResolveConstantValue(value_apint, constant))
172         return false;
173 
174       return AssignToMatchType(scalar, value_apint.getLimitedValue(),
175                                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, u64value, value->getType());
194     }
195 
196     return false;
197   }
198 
199   bool AssignValue(const Value *value, lldb_private::Scalar &scalar,
200                    Module &module) {
201     lldb::addr_t process_address = ResolveValue(value, module);
202 
203     if (process_address == LLDB_INVALID_ADDRESS)
204       return false;
205 
206     lldb_private::Scalar cast_scalar;
207 
208     if (!AssignToMatchType(cast_scalar, scalar.ULongLong(), value->getType()))
209       return false;
210 
211     size_t value_byte_size = m_target_data.getTypeStoreSize(value->getType());
212 
213     lldb_private::DataBufferHeap buf(value_byte_size, 0);
214 
215     lldb_private::Status get_data_error;
216 
217     if (!cast_scalar.GetAsMemoryData(buf.GetBytes(), buf.GetByteSize(),
218                                      m_byte_order, get_data_error))
219       return false;
220 
221     lldb_private::Status write_error;
222 
223     m_execution_unit.WriteMemory(process_address, buf.GetBytes(),
224                                  buf.GetByteSize(), write_error);
225 
226     return write_error.Success();
227   }
228 
229   bool ResolveConstantValue(APInt &value, const Constant *constant) {
230     switch (constant->getValueID()) {
231     default:
232       break;
233     case Value::FunctionVal:
234       if (const Function *constant_func = dyn_cast<Function>(constant)) {
235         lldb_private::ConstString name(constant_func->getName());
236         bool missing_weak = false;
237         lldb::addr_t addr = m_execution_unit.FindSymbol(name, missing_weak);
238         if (addr == LLDB_INVALID_ADDRESS || missing_weak)
239           return false;
240         value = APInt(m_target_data.getPointerSizeInBits(), addr);
241         return true;
242       }
243       break;
244     case Value::ConstantIntVal:
245       if (const ConstantInt *constant_int = dyn_cast<ConstantInt>(constant)) {
246         value = constant_int->getValue();
247         return true;
248       }
249       break;
250     case Value::ConstantFPVal:
251       if (const ConstantFP *constant_fp = dyn_cast<ConstantFP>(constant)) {
252         value = constant_fp->getValueAPF().bitcastToAPInt();
253         return true;
254       }
255       break;
256     case Value::ConstantExprVal:
257       if (const ConstantExpr *constant_expr =
258               dyn_cast<ConstantExpr>(constant)) {
259         switch (constant_expr->getOpcode()) {
260         default:
261           return false;
262         case Instruction::IntToPtr:
263         case Instruction::PtrToInt:
264         case Instruction::BitCast:
265           return ResolveConstantValue(value, constant_expr->getOperand(0));
266         case Instruction::GetElementPtr: {
267           ConstantExpr::const_op_iterator op_cursor = constant_expr->op_begin();
268           ConstantExpr::const_op_iterator op_end = constant_expr->op_end();
269 
270           Constant *base = dyn_cast<Constant>(*op_cursor);
271 
272           if (!base)
273             return false;
274 
275           if (!ResolveConstantValue(value, base))
276             return false;
277 
278           op_cursor++;
279 
280           if (op_cursor == op_end)
281             return true; // no offset to apply!
282 
283           SmallVector<Value *, 8> indices(op_cursor, op_end);
284 
285           Type *src_elem_ty =
286               cast<GEPOperator>(constant_expr)->getSourceElementType();
287           uint64_t offset =
288               m_target_data.getIndexedOffsetInType(src_elem_ty, indices);
289 
290           const bool is_signed = true;
291           value += APInt(value.getBitWidth(), offset, is_signed);
292 
293           return true;
294         }
295         }
296       }
297       break;
298     case Value::ConstantPointerNullVal:
299       if (isa<ConstantPointerNull>(constant)) {
300         value = APInt(m_target_data.getPointerSizeInBits(), 0);
301         return true;
302       }
303       break;
304     }
305     return false;
306   }
307 
308   bool MakeArgument(const Argument *value, uint64_t address) {
309     lldb::addr_t data_address = Malloc(value->getType());
310 
311     if (data_address == LLDB_INVALID_ADDRESS)
312       return false;
313 
314     lldb_private::Status write_error;
315 
316     m_execution_unit.WritePointerToMemory(data_address, address, write_error);
317 
318     if (!write_error.Success()) {
319       lldb_private::Status free_error;
320       m_execution_unit.Free(data_address, free_error);
321       return false;
322     }
323 
324     m_values[value] = data_address;
325 
326     lldb_private::Log *log(
327         lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
328 
329     if (log) {
330       LLDB_LOGF(log, "Made an allocation for argument %s",
331                 PrintValue(value).c_str());
332       LLDB_LOGF(log, "  Data region    : %llx", (unsigned long long)address);
333       LLDB_LOGF(log, "  Ref region     : %llx",
334                 (unsigned long long)data_address);
335     }
336 
337     return true;
338   }
339 
340   bool ResolveConstant(lldb::addr_t process_address, const Constant *constant) {
341     APInt resolved_value;
342 
343     if (!ResolveConstantValue(resolved_value, constant))
344       return false;
345 
346     size_t constant_size = m_target_data.getTypeStoreSize(constant->getType());
347     lldb_private::DataBufferHeap buf(constant_size, 0);
348 
349     lldb_private::Status get_data_error;
350 
351     lldb_private::Scalar resolved_scalar(
352         resolved_value.zextOrTrunc(llvm::NextPowerOf2(constant_size) * 8));
353     if (!resolved_scalar.GetAsMemoryData(buf.GetBytes(), buf.GetByteSize(),
354                                          m_byte_order, get_data_error))
355       return false;
356 
357     lldb_private::Status write_error;
358 
359     m_execution_unit.WriteMemory(process_address, buf.GetBytes(),
360                                  buf.GetByteSize(), write_error);
361 
362     return write_error.Success();
363   }
364 
365   lldb::addr_t Malloc(size_t size, uint8_t byte_alignment) {
366     lldb::addr_t ret = m_stack_pointer;
367 
368     ret -= size;
369     ret -= (ret % byte_alignment);
370 
371     if (ret < m_frame_process_address)
372       return LLDB_INVALID_ADDRESS;
373 
374     m_stack_pointer = ret;
375     return ret;
376   }
377 
378   lldb::addr_t Malloc(llvm::Type *type) {
379     lldb_private::Status alloc_error;
380 
381     return Malloc(m_target_data.getTypeAllocSize(type),
382                   m_target_data.getPrefTypeAlignment(type));
383   }
384 
385   std::string PrintData(lldb::addr_t addr, llvm::Type *type) {
386     size_t length = m_target_data.getTypeStoreSize(type);
387 
388     lldb_private::DataBufferHeap buf(length, 0);
389 
390     lldb_private::Status read_error;
391 
392     m_execution_unit.ReadMemory(buf.GetBytes(), addr, length, read_error);
393 
394     if (!read_error.Success())
395       return std::string("<couldn't read data>");
396 
397     lldb_private::StreamString ss;
398 
399     for (size_t i = 0; i < length; i++) {
400       if ((!(i & 0xf)) && i)
401         ss.Printf("%02hhx - ", buf.GetBytes()[i]);
402       else
403         ss.Printf("%02hhx ", buf.GetBytes()[i]);
404     }
405 
406     return std::string(ss.GetString());
407   }
408 
409   lldb::addr_t ResolveValue(const Value *value, Module &module) {
410     ValueMap::iterator i = m_values.find(value);
411 
412     if (i != m_values.end())
413       return i->second;
414 
415     // Fall back and allocate space [allocation type Alloca]
416 
417     lldb::addr_t data_address = Malloc(value->getType());
418 
419     if (const Constant *constant = dyn_cast<Constant>(value)) {
420       if (!ResolveConstant(data_address, constant)) {
421         lldb_private::Status free_error;
422         m_execution_unit.Free(data_address, free_error);
423         return LLDB_INVALID_ADDRESS;
424       }
425     }
426 
427     m_values[value] = data_address;
428     return data_address;
429   }
430 };
431 
432 static const char *unsupported_opcode_error =
433     "Interpreter doesn't handle one of the expression's opcodes";
434 static const char *unsupported_operand_error =
435     "Interpreter doesn't handle one of the expression's operands";
436 static const char *interpreter_internal_error =
437     "Interpreter encountered an internal error";
438 static const char *bad_value_error =
439     "Interpreter couldn't resolve a value during execution";
440 static const char *memory_allocation_error =
441     "Interpreter couldn't allocate memory";
442 static const char *memory_write_error = "Interpreter couldn't write to memory";
443 static const char *memory_read_error = "Interpreter couldn't read from memory";
444 static const char *infinite_loop_error = "Interpreter ran for too many cycles";
445 static const char *too_many_functions_error =
446     "Interpreter doesn't handle modules with multiple function bodies.";
447 
448 static bool CanResolveConstant(llvm::Constant *constant) {
449   switch (constant->getValueID()) {
450   default:
451     return false;
452   case Value::ConstantIntVal:
453   case Value::ConstantFPVal:
454   case Value::FunctionVal:
455     return true;
456   case Value::ConstantExprVal:
457     if (const ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant)) {
458       switch (constant_expr->getOpcode()) {
459       default:
460         return false;
461       case Instruction::IntToPtr:
462       case Instruction::PtrToInt:
463       case Instruction::BitCast:
464         return CanResolveConstant(constant_expr->getOperand(0));
465       case Instruction::GetElementPtr: {
466         ConstantExpr::const_op_iterator op_cursor = constant_expr->op_begin();
467         Constant *base = dyn_cast<Constant>(*op_cursor);
468         if (!base)
469           return false;
470 
471         return CanResolveConstant(base);
472       }
473       }
474     } else {
475       return false;
476     }
477   case Value::ConstantPointerNullVal:
478     return true;
479   }
480 }
481 
482 bool IRInterpreter::CanInterpret(llvm::Module &module, llvm::Function &function,
483                                  lldb_private::Status &error,
484                                  const bool support_function_calls) {
485   lldb_private::Log *log(
486       lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
487 
488   bool saw_function_with_body = false;
489   for (Function &f : module) {
490     if (f.begin() != f.end()) {
491       if (saw_function_with_body) {
492         LLDB_LOGF(log, "More than one function in the module has a body");
493         error.SetErrorToGenericError();
494         error.SetErrorString(too_many_functions_error);
495         return false;
496       }
497       saw_function_with_body = true;
498     }
499   }
500 
501   for (BasicBlock &bb : function) {
502     for (Instruction &ii : bb) {
503       switch (ii.getOpcode()) {
504       default: {
505         LLDB_LOGF(log, "Unsupported instruction: %s", PrintValue(&ii).c_str());
506         error.SetErrorToGenericError();
507         error.SetErrorString(unsupported_opcode_error);
508         return false;
509       }
510       case Instruction::Add:
511       case Instruction::Alloca:
512       case Instruction::BitCast:
513       case Instruction::Br:
514       case Instruction::PHI:
515         break;
516       case Instruction::Call: {
517         CallInst *call_inst = dyn_cast<CallInst>(&ii);
518 
519         if (!call_inst) {
520           error.SetErrorToGenericError();
521           error.SetErrorString(interpreter_internal_error);
522           return false;
523         }
524 
525         if (!CanIgnoreCall(call_inst) && !support_function_calls) {
526           LLDB_LOGF(log, "Unsupported instruction: %s",
527                     PrintValue(&ii).c_str());
528           error.SetErrorToGenericError();
529           error.SetErrorString(unsupported_opcode_error);
530           return false;
531         }
532       } break;
533       case Instruction::GetElementPtr:
534         break;
535       case Instruction::ICmp: {
536         ICmpInst *icmp_inst = dyn_cast<ICmpInst>(&ii);
537 
538         if (!icmp_inst) {
539           error.SetErrorToGenericError();
540           error.SetErrorString(interpreter_internal_error);
541           return false;
542         }
543 
544         switch (icmp_inst->getPredicate()) {
545         default: {
546           LLDB_LOGF(log, "Unsupported ICmp predicate: %s",
547                     PrintValue(&ii).c_str());
548 
549           error.SetErrorToGenericError();
550           error.SetErrorString(unsupported_opcode_error);
551           return false;
552         }
553         case CmpInst::ICMP_EQ:
554         case CmpInst::ICMP_NE:
555         case CmpInst::ICMP_UGT:
556         case CmpInst::ICMP_UGE:
557         case CmpInst::ICMP_ULT:
558         case CmpInst::ICMP_ULE:
559         case CmpInst::ICMP_SGT:
560         case CmpInst::ICMP_SGE:
561         case CmpInst::ICMP_SLT:
562         case CmpInst::ICMP_SLE:
563           break;
564         }
565       } break;
566       case Instruction::And:
567       case Instruction::AShr:
568       case Instruction::IntToPtr:
569       case Instruction::PtrToInt:
570       case Instruction::Load:
571       case Instruction::LShr:
572       case Instruction::Mul:
573       case Instruction::Or:
574       case Instruction::Ret:
575       case Instruction::SDiv:
576       case Instruction::SExt:
577       case Instruction::Shl:
578       case Instruction::SRem:
579       case Instruction::Store:
580       case Instruction::Sub:
581       case Instruction::Trunc:
582       case Instruction::UDiv:
583       case Instruction::URem:
584       case Instruction::Xor:
585       case Instruction::ZExt:
586         break;
587       }
588 
589       for (unsigned oi = 0, oe = ii.getNumOperands(); oi != oe; ++oi) {
590         Value *operand = ii.getOperand(oi);
591         Type *operand_type = operand->getType();
592 
593         switch (operand_type->getTypeID()) {
594         default:
595           break;
596         case Type::FixedVectorTyID:
597         case Type::ScalableVectorTyID: {
598           LLDB_LOGF(log, "Unsupported operand type: %s",
599                     PrintType(operand_type).c_str());
600           error.SetErrorString(unsupported_operand_error);
601           return false;
602         }
603         }
604 
605         // The IR interpreter currently doesn't know about
606         // 128-bit integers. As they're not that frequent,
607         // we can just fall back to the JIT rather than
608         // choking.
609         if (operand_type->getPrimitiveSizeInBits() > 64) {
610           LLDB_LOGF(log, "Unsupported operand type: %s",
611                     PrintType(operand_type).c_str());
612           error.SetErrorString(unsupported_operand_error);
613           return false;
614         }
615 
616         if (Constant *constant = llvm::dyn_cast<Constant>(operand)) {
617           if (!CanResolveConstant(constant)) {
618             LLDB_LOGF(log, "Unsupported constant: %s",
619                       PrintValue(constant).c_str());
620             error.SetErrorString(unsupported_operand_error);
621             return false;
622           }
623         }
624       }
625     }
626   }
627 
628   return true;
629 }
630 
631 bool IRInterpreter::Interpret(llvm::Module &module, llvm::Function &function,
632                               llvm::ArrayRef<lldb::addr_t> args,
633                               lldb_private::IRExecutionUnit &execution_unit,
634                               lldb_private::Status &error,
635                               lldb::addr_t stack_frame_bottom,
636                               lldb::addr_t stack_frame_top,
637                               lldb_private::ExecutionContext &exe_ctx) {
638   lldb_private::Log *log(
639       lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_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_read_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.SetErrorStringWithFormat("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.SetErrorStringWithFormat("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->getNumArgOperands();
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.SetErrorStringWithFormat("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.SetErrorStringWithFormat("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.SetErrorStringWithFormat("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