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     } else {
177       lldb::addr_t process_address = ResolveValue(value, module);
178       size_t value_size = m_target_data.getTypeStoreSize(value->getType());
179 
180       lldb_private::DataExtractor value_extractor;
181       lldb_private::Status extract_error;
182 
183       m_execution_unit.GetMemoryData(value_extractor, process_address,
184                                      value_size, extract_error);
185 
186       if (!extract_error.Success())
187         return false;
188 
189       lldb::offset_t offset = 0;
190       if (value_size <= 8) {
191         uint64_t u64value = value_extractor.GetMaxU64(&offset, value_size);
192         return AssignToMatchType(scalar, u64value, value->getType());
193       }
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_initialization_error = "Interpreter couldn't
437 // be initialized";
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 *bad_result_error                 = "Result of expression
448 // is in bad memory";
449 static const char *too_many_functions_error =
450     "Interpreter doesn't handle modules with multiple function bodies.";
451 
452 static bool CanResolveConstant(llvm::Constant *constant) {
453   switch (constant->getValueID()) {
454   default:
455     return false;
456   case Value::ConstantIntVal:
457   case Value::ConstantFPVal:
458   case Value::FunctionVal:
459     return true;
460   case Value::ConstantExprVal:
461     if (const ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant)) {
462       switch (constant_expr->getOpcode()) {
463       default:
464         return false;
465       case Instruction::IntToPtr:
466       case Instruction::PtrToInt:
467       case Instruction::BitCast:
468         return CanResolveConstant(constant_expr->getOperand(0));
469       case Instruction::GetElementPtr: {
470         ConstantExpr::const_op_iterator op_cursor = constant_expr->op_begin();
471         Constant *base = dyn_cast<Constant>(*op_cursor);
472         if (!base)
473           return false;
474 
475         return CanResolveConstant(base);
476       }
477       }
478     } else {
479       return false;
480     }
481   case Value::ConstantPointerNullVal:
482     return true;
483   }
484 }
485 
486 bool IRInterpreter::CanInterpret(llvm::Module &module, llvm::Function &function,
487                                  lldb_private::Status &error,
488                                  const bool support_function_calls) {
489   lldb_private::Log *log(
490       lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
491 
492   bool saw_function_with_body = false;
493   for (Function &f : module) {
494     if (f.begin() != f.end()) {
495       if (saw_function_with_body) {
496         LLDB_LOGF(log, "More than one function in the module has a body");
497         error.SetErrorToGenericError();
498         error.SetErrorString(too_many_functions_error);
499         return false;
500       }
501       saw_function_with_body = true;
502     }
503   }
504 
505   for (BasicBlock &bb : function) {
506     for (Instruction &ii : bb) {
507       switch (ii.getOpcode()) {
508       default: {
509         LLDB_LOGF(log, "Unsupported instruction: %s", PrintValue(&ii).c_str());
510         error.SetErrorToGenericError();
511         error.SetErrorString(unsupported_opcode_error);
512         return false;
513       }
514       case Instruction::Add:
515       case Instruction::Alloca:
516       case Instruction::BitCast:
517       case Instruction::Br:
518       case Instruction::PHI:
519         break;
520       case Instruction::Call: {
521         CallInst *call_inst = dyn_cast<CallInst>(&ii);
522 
523         if (!call_inst) {
524           error.SetErrorToGenericError();
525           error.SetErrorString(interpreter_internal_error);
526           return false;
527         }
528 
529         if (!CanIgnoreCall(call_inst) && !support_function_calls) {
530           LLDB_LOGF(log, "Unsupported instruction: %s",
531                     PrintValue(&ii).c_str());
532           error.SetErrorToGenericError();
533           error.SetErrorString(unsupported_opcode_error);
534           return false;
535         }
536       } break;
537       case Instruction::GetElementPtr:
538         break;
539       case Instruction::ICmp: {
540         ICmpInst *icmp_inst = dyn_cast<ICmpInst>(&ii);
541 
542         if (!icmp_inst) {
543           error.SetErrorToGenericError();
544           error.SetErrorString(interpreter_internal_error);
545           return false;
546         }
547 
548         switch (icmp_inst->getPredicate()) {
549         default: {
550           LLDB_LOGF(log, "Unsupported ICmp predicate: %s",
551                     PrintValue(&ii).c_str());
552 
553           error.SetErrorToGenericError();
554           error.SetErrorString(unsupported_opcode_error);
555           return false;
556         }
557         case CmpInst::ICMP_EQ:
558         case CmpInst::ICMP_NE:
559         case CmpInst::ICMP_UGT:
560         case CmpInst::ICMP_UGE:
561         case CmpInst::ICMP_ULT:
562         case CmpInst::ICMP_ULE:
563         case CmpInst::ICMP_SGT:
564         case CmpInst::ICMP_SGE:
565         case CmpInst::ICMP_SLT:
566         case CmpInst::ICMP_SLE:
567           break;
568         }
569       } break;
570       case Instruction::And:
571       case Instruction::AShr:
572       case Instruction::IntToPtr:
573       case Instruction::PtrToInt:
574       case Instruction::Load:
575       case Instruction::LShr:
576       case Instruction::Mul:
577       case Instruction::Or:
578       case Instruction::Ret:
579       case Instruction::SDiv:
580       case Instruction::SExt:
581       case Instruction::Shl:
582       case Instruction::SRem:
583       case Instruction::Store:
584       case Instruction::Sub:
585       case Instruction::Trunc:
586       case Instruction::UDiv:
587       case Instruction::URem:
588       case Instruction::Xor:
589       case Instruction::ZExt:
590         break;
591       }
592 
593       for (unsigned oi = 0, oe = ii.getNumOperands(); oi != oe; ++oi) {
594         Value *operand = ii.getOperand(oi);
595         Type *operand_type = operand->getType();
596 
597         switch (operand_type->getTypeID()) {
598         default:
599           break;
600         case Type::FixedVectorTyID:
601         case Type::ScalableVectorTyID: {
602           LLDB_LOGF(log, "Unsupported operand type: %s",
603                     PrintType(operand_type).c_str());
604           error.SetErrorString(unsupported_operand_error);
605           return false;
606         }
607         }
608 
609         // The IR interpreter currently doesn't know about
610         // 128-bit integers. As they're not that frequent,
611         // we can just fall back to the JIT rather than
612         // choking.
613         if (operand_type->getPrimitiveSizeInBits() > 64) {
614           LLDB_LOGF(log, "Unsupported operand type: %s",
615                     PrintType(operand_type).c_str());
616           error.SetErrorString(unsupported_operand_error);
617           return false;
618         }
619 
620         if (Constant *constant = llvm::dyn_cast<Constant>(operand)) {
621           if (!CanResolveConstant(constant)) {
622             LLDB_LOGF(log, "Unsupported constant: %s",
623                       PrintValue(constant).c_str());
624             error.SetErrorString(unsupported_operand_error);
625             return false;
626           }
627         }
628       }
629     }
630   }
631 
632   return true;
633 }
634 
635 bool IRInterpreter::Interpret(llvm::Module &module, llvm::Function &function,
636                               llvm::ArrayRef<lldb::addr_t> args,
637                               lldb_private::IRExecutionUnit &execution_unit,
638                               lldb_private::Status &error,
639                               lldb::addr_t stack_frame_bottom,
640                               lldb::addr_t stack_frame_top,
641                               lldb_private::ExecutionContext &exe_ctx) {
642   lldb_private::Log *log(
643       lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
644 
645   if (log) {
646     std::string s;
647     raw_string_ostream oss(s);
648 
649     module.print(oss, nullptr);
650 
651     oss.flush();
652 
653     LLDB_LOGF(log, "Module as passed in to IRInterpreter::Interpret: \n\"%s\"",
654               s.c_str());
655   }
656 
657   DataLayout data_layout(&module);
658 
659   InterpreterStackFrame frame(data_layout, execution_unit, stack_frame_bottom,
660                               stack_frame_top);
661 
662   if (frame.m_frame_process_address == LLDB_INVALID_ADDRESS) {
663     error.SetErrorString("Couldn't allocate stack frame");
664   }
665 
666   int arg_index = 0;
667 
668   for (llvm::Function::arg_iterator ai = function.arg_begin(),
669                                     ae = function.arg_end();
670        ai != ae; ++ai, ++arg_index) {
671     if (args.size() <= static_cast<size_t>(arg_index)) {
672       error.SetErrorString("Not enough arguments passed in to function");
673       return false;
674     }
675 
676     lldb::addr_t ptr = args[arg_index];
677 
678     frame.MakeArgument(&*ai, ptr);
679   }
680 
681   uint32_t num_insts = 0;
682 
683   frame.Jump(&function.front());
684 
685   while (frame.m_ii != frame.m_ie && (++num_insts < 4096)) {
686     const Instruction *inst = &*frame.m_ii;
687 
688     LLDB_LOGF(log, "Interpreting %s", PrintValue(inst).c_str());
689 
690     switch (inst->getOpcode()) {
691     default:
692       break;
693 
694     case Instruction::Add:
695     case Instruction::Sub:
696     case Instruction::Mul:
697     case Instruction::SDiv:
698     case Instruction::UDiv:
699     case Instruction::SRem:
700     case Instruction::URem:
701     case Instruction::Shl:
702     case Instruction::LShr:
703     case Instruction::AShr:
704     case Instruction::And:
705     case Instruction::Or:
706     case Instruction::Xor: {
707       const BinaryOperator *bin_op = dyn_cast<BinaryOperator>(inst);
708 
709       if (!bin_op) {
710         LLDB_LOGF(
711             log,
712             "getOpcode() returns %s, but instruction is not a BinaryOperator",
713             inst->getOpcodeName());
714         error.SetErrorToGenericError();
715         error.SetErrorString(interpreter_internal_error);
716         return false;
717       }
718 
719       Value *lhs = inst->getOperand(0);
720       Value *rhs = inst->getOperand(1);
721 
722       lldb_private::Scalar L;
723       lldb_private::Scalar R;
724 
725       if (!frame.EvaluateValue(L, lhs, module)) {
726         LLDB_LOGF(log, "Couldn't evaluate %s", PrintValue(lhs).c_str());
727         error.SetErrorToGenericError();
728         error.SetErrorString(bad_value_error);
729         return false;
730       }
731 
732       if (!frame.EvaluateValue(R, rhs, module)) {
733         LLDB_LOGF(log, "Couldn't evaluate %s", PrintValue(rhs).c_str());
734         error.SetErrorToGenericError();
735         error.SetErrorString(bad_value_error);
736         return false;
737       }
738 
739       lldb_private::Scalar result;
740 
741       switch (inst->getOpcode()) {
742       default:
743         break;
744       case Instruction::Add:
745         result = L + R;
746         break;
747       case Instruction::Mul:
748         result = L * R;
749         break;
750       case Instruction::Sub:
751         result = L - R;
752         break;
753       case Instruction::SDiv:
754         L.MakeSigned();
755         R.MakeSigned();
756         result = L / R;
757         break;
758       case Instruction::UDiv:
759         L.MakeUnsigned();
760         R.MakeUnsigned();
761         result = L / R;
762         break;
763       case Instruction::SRem:
764         L.MakeSigned();
765         R.MakeSigned();
766         result = L % R;
767         break;
768       case Instruction::URem:
769         L.MakeUnsigned();
770         R.MakeUnsigned();
771         result = L % R;
772         break;
773       case Instruction::Shl:
774         result = L << R;
775         break;
776       case Instruction::AShr:
777         result = L >> R;
778         break;
779       case Instruction::LShr:
780         result = L;
781         result.ShiftRightLogical(R);
782         break;
783       case Instruction::And:
784         result = L & R;
785         break;
786       case Instruction::Or:
787         result = L | R;
788         break;
789       case Instruction::Xor:
790         result = L ^ R;
791         break;
792       }
793 
794       frame.AssignValue(inst, result, module);
795 
796       if (log) {
797         LLDB_LOGF(log, "Interpreted a %s", inst->getOpcodeName());
798         LLDB_LOGF(log, "  L : %s", frame.SummarizeValue(lhs).c_str());
799         LLDB_LOGF(log, "  R : %s", frame.SummarizeValue(rhs).c_str());
800         LLDB_LOGF(log, "  = : %s", frame.SummarizeValue(inst).c_str());
801       }
802     } break;
803     case Instruction::Alloca: {
804       const AllocaInst *alloca_inst = cast<AllocaInst>(inst);
805 
806       if (alloca_inst->isArrayAllocation()) {
807         LLDB_LOGF(log,
808                   "AllocaInsts are not handled if isArrayAllocation() is true");
809         error.SetErrorToGenericError();
810         error.SetErrorString(unsupported_opcode_error);
811         return false;
812       }
813 
814       // The semantics of Alloca are:
815       //   Create a region R of virtual memory of type T, backed by a data
816       //   buffer
817       //   Create a region P of virtual memory of type T*, backed by a data
818       //   buffer
819       //   Write the virtual address of R into P
820 
821       Type *T = alloca_inst->getAllocatedType();
822       Type *Tptr = alloca_inst->getType();
823 
824       lldb::addr_t R = frame.Malloc(T);
825 
826       if (R == LLDB_INVALID_ADDRESS) {
827         LLDB_LOGF(log, "Couldn't allocate memory for an AllocaInst");
828         error.SetErrorToGenericError();
829         error.SetErrorString(memory_allocation_error);
830         return false;
831       }
832 
833       lldb::addr_t P = frame.Malloc(Tptr);
834 
835       if (P == LLDB_INVALID_ADDRESS) {
836         LLDB_LOGF(log,
837                   "Couldn't allocate the result pointer for an AllocaInst");
838         error.SetErrorToGenericError();
839         error.SetErrorString(memory_allocation_error);
840         return false;
841       }
842 
843       lldb_private::Status write_error;
844 
845       execution_unit.WritePointerToMemory(P, R, write_error);
846 
847       if (!write_error.Success()) {
848         LLDB_LOGF(log, "Couldn't write the result pointer for an AllocaInst");
849         error.SetErrorToGenericError();
850         error.SetErrorString(memory_write_error);
851         lldb_private::Status free_error;
852         execution_unit.Free(P, free_error);
853         execution_unit.Free(R, free_error);
854         return false;
855       }
856 
857       frame.m_values[alloca_inst] = P;
858 
859       if (log) {
860         LLDB_LOGF(log, "Interpreted an AllocaInst");
861         LLDB_LOGF(log, "  R : 0x%" PRIx64, R);
862         LLDB_LOGF(log, "  P : 0x%" PRIx64, P);
863       }
864     } break;
865     case Instruction::BitCast:
866     case Instruction::ZExt: {
867       const CastInst *cast_inst = cast<CastInst>(inst);
868 
869       Value *source = cast_inst->getOperand(0);
870 
871       lldb_private::Scalar S;
872 
873       if (!frame.EvaluateValue(S, source, module)) {
874         LLDB_LOGF(log, "Couldn't evaluate %s", PrintValue(source).c_str());
875         error.SetErrorToGenericError();
876         error.SetErrorString(bad_value_error);
877         return false;
878       }
879 
880       frame.AssignValue(inst, S, module);
881     } break;
882     case Instruction::SExt: {
883       const CastInst *cast_inst = cast<CastInst>(inst);
884 
885       Value *source = cast_inst->getOperand(0);
886 
887       lldb_private::Scalar S;
888 
889       if (!frame.EvaluateValue(S, source, module)) {
890         LLDB_LOGF(log, "Couldn't evaluate %s", PrintValue(source).c_str());
891         error.SetErrorToGenericError();
892         error.SetErrorString(bad_value_error);
893         return false;
894       }
895 
896       S.MakeSigned();
897 
898       lldb_private::Scalar S_signextend(S.SLongLong());
899 
900       frame.AssignValue(inst, S_signextend, module);
901     } break;
902     case Instruction::Br: {
903       const BranchInst *br_inst = cast<BranchInst>(inst);
904 
905       if (br_inst->isConditional()) {
906         Value *condition = br_inst->getCondition();
907 
908         lldb_private::Scalar C;
909 
910         if (!frame.EvaluateValue(C, condition, module)) {
911           LLDB_LOGF(log, "Couldn't evaluate %s", PrintValue(condition).c_str());
912           error.SetErrorToGenericError();
913           error.SetErrorString(bad_value_error);
914           return false;
915         }
916 
917         if (!C.IsZero())
918           frame.Jump(br_inst->getSuccessor(0));
919         else
920           frame.Jump(br_inst->getSuccessor(1));
921 
922         if (log) {
923           LLDB_LOGF(log, "Interpreted a BrInst with a condition");
924           LLDB_LOGF(log, "  cond : %s",
925                     frame.SummarizeValue(condition).c_str());
926         }
927       } else {
928         frame.Jump(br_inst->getSuccessor(0));
929 
930         if (log) {
931           LLDB_LOGF(log, "Interpreted a BrInst with no condition");
932         }
933       }
934     }
935       continue;
936     case Instruction::PHI: {
937       const PHINode *phi_inst = cast<PHINode>(inst);
938       if (!frame.m_prev_bb) {
939         LLDB_LOGF(log,
940                   "Encountered PHI node without having jumped from another "
941                   "basic block");
942         error.SetErrorToGenericError();
943         error.SetErrorString(interpreter_internal_error);
944         return false;
945       }
946 
947       Value *value = phi_inst->getIncomingValueForBlock(frame.m_prev_bb);
948       lldb_private::Scalar result;
949       if (!frame.EvaluateValue(result, value, module)) {
950         LLDB_LOGF(log, "Couldn't evaluate %s", PrintValue(value).c_str());
951         error.SetErrorToGenericError();
952         error.SetErrorString(bad_value_error);
953         return false;
954       }
955       frame.AssignValue(inst, result, module);
956 
957       if (log) {
958         LLDB_LOGF(log, "Interpreted a %s", inst->getOpcodeName());
959         LLDB_LOGF(log, "  Incoming value : %s",
960                   frame.SummarizeValue(value).c_str());
961       }
962     } break;
963     case Instruction::GetElementPtr: {
964       const GetElementPtrInst *gep_inst = cast<GetElementPtrInst>(inst);
965 
966       const Value *pointer_operand = gep_inst->getPointerOperand();
967       Type *src_elem_ty = gep_inst->getSourceElementType();
968 
969       lldb_private::Scalar P;
970 
971       if (!frame.EvaluateValue(P, pointer_operand, module)) {
972         LLDB_LOGF(log, "Couldn't evaluate %s",
973                   PrintValue(pointer_operand).c_str());
974         error.SetErrorToGenericError();
975         error.SetErrorString(bad_value_error);
976         return false;
977       }
978 
979       typedef SmallVector<Value *, 8> IndexVector;
980       typedef IndexVector::iterator IndexIterator;
981 
982       SmallVector<Value *, 8> indices(gep_inst->idx_begin(),
983                                       gep_inst->idx_end());
984 
985       SmallVector<Value *, 8> const_indices;
986 
987       for (IndexIterator ii = indices.begin(), ie = indices.end(); ii != ie;
988            ++ii) {
989         ConstantInt *constant_index = dyn_cast<ConstantInt>(*ii);
990 
991         if (!constant_index) {
992           lldb_private::Scalar I;
993 
994           if (!frame.EvaluateValue(I, *ii, module)) {
995             LLDB_LOGF(log, "Couldn't evaluate %s", PrintValue(*ii).c_str());
996             error.SetErrorToGenericError();
997             error.SetErrorString(bad_value_error);
998             return false;
999           }
1000 
1001           LLDB_LOGF(log, "Evaluated constant index %s as %llu",
1002                     PrintValue(*ii).c_str(), I.ULongLong(LLDB_INVALID_ADDRESS));
1003 
1004           constant_index = cast<ConstantInt>(ConstantInt::get(
1005               (*ii)->getType(), I.ULongLong(LLDB_INVALID_ADDRESS)));
1006         }
1007 
1008         const_indices.push_back(constant_index);
1009       }
1010 
1011       uint64_t offset =
1012           data_layout.getIndexedOffsetInType(src_elem_ty, const_indices);
1013 
1014       lldb_private::Scalar Poffset = P + offset;
1015 
1016       frame.AssignValue(inst, Poffset, module);
1017 
1018       if (log) {
1019         LLDB_LOGF(log, "Interpreted a GetElementPtrInst");
1020         LLDB_LOGF(log, "  P       : %s",
1021                   frame.SummarizeValue(pointer_operand).c_str());
1022         LLDB_LOGF(log, "  Poffset : %s", frame.SummarizeValue(inst).c_str());
1023       }
1024     } break;
1025     case Instruction::ICmp: {
1026       const ICmpInst *icmp_inst = cast<ICmpInst>(inst);
1027 
1028       CmpInst::Predicate predicate = icmp_inst->getPredicate();
1029 
1030       Value *lhs = inst->getOperand(0);
1031       Value *rhs = inst->getOperand(1);
1032 
1033       lldb_private::Scalar L;
1034       lldb_private::Scalar R;
1035 
1036       if (!frame.EvaluateValue(L, lhs, module)) {
1037         LLDB_LOGF(log, "Couldn't evaluate %s", PrintValue(lhs).c_str());
1038         error.SetErrorToGenericError();
1039         error.SetErrorString(bad_value_error);
1040         return false;
1041       }
1042 
1043       if (!frame.EvaluateValue(R, rhs, module)) {
1044         LLDB_LOGF(log, "Couldn't evaluate %s", PrintValue(rhs).c_str());
1045         error.SetErrorToGenericError();
1046         error.SetErrorString(bad_value_error);
1047         return false;
1048       }
1049 
1050       lldb_private::Scalar result;
1051 
1052       switch (predicate) {
1053       default:
1054         return false;
1055       case CmpInst::ICMP_EQ:
1056         result = (L == R);
1057         break;
1058       case CmpInst::ICMP_NE:
1059         result = (L != R);
1060         break;
1061       case CmpInst::ICMP_UGT:
1062         L.MakeUnsigned();
1063         R.MakeUnsigned();
1064         result = (L > R);
1065         break;
1066       case CmpInst::ICMP_UGE:
1067         L.MakeUnsigned();
1068         R.MakeUnsigned();
1069         result = (L >= R);
1070         break;
1071       case CmpInst::ICMP_ULT:
1072         L.MakeUnsigned();
1073         R.MakeUnsigned();
1074         result = (L < R);
1075         break;
1076       case CmpInst::ICMP_ULE:
1077         L.MakeUnsigned();
1078         R.MakeUnsigned();
1079         result = (L <= R);
1080         break;
1081       case CmpInst::ICMP_SGT:
1082         L.MakeSigned();
1083         R.MakeSigned();
1084         result = (L > R);
1085         break;
1086       case CmpInst::ICMP_SGE:
1087         L.MakeSigned();
1088         R.MakeSigned();
1089         result = (L >= R);
1090         break;
1091       case CmpInst::ICMP_SLT:
1092         L.MakeSigned();
1093         R.MakeSigned();
1094         result = (L < R);
1095         break;
1096       case CmpInst::ICMP_SLE:
1097         L.MakeSigned();
1098         R.MakeSigned();
1099         result = (L <= R);
1100         break;
1101       }
1102 
1103       frame.AssignValue(inst, result, module);
1104 
1105       if (log) {
1106         LLDB_LOGF(log, "Interpreted an ICmpInst");
1107         LLDB_LOGF(log, "  L : %s", frame.SummarizeValue(lhs).c_str());
1108         LLDB_LOGF(log, "  R : %s", frame.SummarizeValue(rhs).c_str());
1109         LLDB_LOGF(log, "  = : %s", frame.SummarizeValue(inst).c_str());
1110       }
1111     } break;
1112     case Instruction::IntToPtr: {
1113       const IntToPtrInst *int_to_ptr_inst = cast<IntToPtrInst>(inst);
1114 
1115       Value *src_operand = int_to_ptr_inst->getOperand(0);
1116 
1117       lldb_private::Scalar I;
1118 
1119       if (!frame.EvaluateValue(I, src_operand, module)) {
1120         LLDB_LOGF(log, "Couldn't evaluate %s", PrintValue(src_operand).c_str());
1121         error.SetErrorToGenericError();
1122         error.SetErrorString(bad_value_error);
1123         return false;
1124       }
1125 
1126       frame.AssignValue(inst, I, module);
1127 
1128       if (log) {
1129         LLDB_LOGF(log, "Interpreted an IntToPtr");
1130         LLDB_LOGF(log, "  Src : %s", frame.SummarizeValue(src_operand).c_str());
1131         LLDB_LOGF(log, "  =   : %s", frame.SummarizeValue(inst).c_str());
1132       }
1133     } break;
1134     case Instruction::PtrToInt: {
1135       const PtrToIntInst *ptr_to_int_inst = cast<PtrToIntInst>(inst);
1136 
1137       Value *src_operand = ptr_to_int_inst->getOperand(0);
1138 
1139       lldb_private::Scalar I;
1140 
1141       if (!frame.EvaluateValue(I, src_operand, module)) {
1142         LLDB_LOGF(log, "Couldn't evaluate %s", PrintValue(src_operand).c_str());
1143         error.SetErrorToGenericError();
1144         error.SetErrorString(bad_value_error);
1145         return false;
1146       }
1147 
1148       frame.AssignValue(inst, I, module);
1149 
1150       if (log) {
1151         LLDB_LOGF(log, "Interpreted a PtrToInt");
1152         LLDB_LOGF(log, "  Src : %s", frame.SummarizeValue(src_operand).c_str());
1153         LLDB_LOGF(log, "  =   : %s", frame.SummarizeValue(inst).c_str());
1154       }
1155     } break;
1156     case Instruction::Trunc: {
1157       const TruncInst *trunc_inst = cast<TruncInst>(inst);
1158 
1159       Value *src_operand = trunc_inst->getOperand(0);
1160 
1161       lldb_private::Scalar I;
1162 
1163       if (!frame.EvaluateValue(I, src_operand, module)) {
1164         LLDB_LOGF(log, "Couldn't evaluate %s", PrintValue(src_operand).c_str());
1165         error.SetErrorToGenericError();
1166         error.SetErrorString(bad_value_error);
1167         return false;
1168       }
1169 
1170       frame.AssignValue(inst, I, module);
1171 
1172       if (log) {
1173         LLDB_LOGF(log, "Interpreted a Trunc");
1174         LLDB_LOGF(log, "  Src : %s", frame.SummarizeValue(src_operand).c_str());
1175         LLDB_LOGF(log, "  =   : %s", frame.SummarizeValue(inst).c_str());
1176       }
1177     } break;
1178     case Instruction::Load: {
1179       const LoadInst *load_inst = cast<LoadInst>(inst);
1180 
1181       // The semantics of Load are:
1182       //   Create a region D that will contain the loaded data
1183       //   Resolve the region P containing a pointer
1184       //   Dereference P to get the region R that the data should be loaded from
1185       //   Transfer a unit of type type(D) from R to D
1186 
1187       const Value *pointer_operand = load_inst->getPointerOperand();
1188 
1189       Type *pointer_ty = pointer_operand->getType();
1190       PointerType *pointer_ptr_ty = dyn_cast<PointerType>(pointer_ty);
1191       if (!pointer_ptr_ty) {
1192         LLDB_LOGF(log, "getPointerOperand()->getType() is not a PointerType");
1193         error.SetErrorToGenericError();
1194         error.SetErrorString(interpreter_internal_error);
1195         return false;
1196       }
1197       Type *target_ty = pointer_ptr_ty->getElementType();
1198 
1199       lldb::addr_t D = frame.ResolveValue(load_inst, module);
1200       lldb::addr_t P = frame.ResolveValue(pointer_operand, module);
1201 
1202       if (D == LLDB_INVALID_ADDRESS) {
1203         LLDB_LOGF(log, "LoadInst's value doesn't resolve to anything");
1204         error.SetErrorToGenericError();
1205         error.SetErrorString(bad_value_error);
1206         return false;
1207       }
1208 
1209       if (P == LLDB_INVALID_ADDRESS) {
1210         LLDB_LOGF(log, "LoadInst's pointer doesn't resolve to anything");
1211         error.SetErrorToGenericError();
1212         error.SetErrorString(bad_value_error);
1213         return false;
1214       }
1215 
1216       lldb::addr_t R;
1217       lldb_private::Status read_error;
1218       execution_unit.ReadPointerFromMemory(&R, P, read_error);
1219 
1220       if (!read_error.Success()) {
1221         LLDB_LOGF(log, "Couldn't read the address to be loaded for a LoadInst");
1222         error.SetErrorToGenericError();
1223         error.SetErrorString(memory_read_error);
1224         return false;
1225       }
1226 
1227       size_t target_size = data_layout.getTypeStoreSize(target_ty);
1228       lldb_private::DataBufferHeap buffer(target_size, 0);
1229 
1230       read_error.Clear();
1231       execution_unit.ReadMemory(buffer.GetBytes(), R, buffer.GetByteSize(),
1232                                 read_error);
1233       if (!read_error.Success()) {
1234         LLDB_LOGF(log, "Couldn't read from a region on behalf of a LoadInst");
1235         error.SetErrorToGenericError();
1236         error.SetErrorString(memory_read_error);
1237         return false;
1238       }
1239 
1240       lldb_private::Status write_error;
1241       execution_unit.WriteMemory(D, buffer.GetBytes(), buffer.GetByteSize(),
1242                                  write_error);
1243       if (!write_error.Success()) {
1244         LLDB_LOGF(log, "Couldn't write to a region on behalf of a LoadInst");
1245         error.SetErrorToGenericError();
1246         error.SetErrorString(memory_read_error);
1247         return false;
1248       }
1249 
1250       if (log) {
1251         LLDB_LOGF(log, "Interpreted a LoadInst");
1252         LLDB_LOGF(log, "  P : 0x%" PRIx64, P);
1253         LLDB_LOGF(log, "  R : 0x%" PRIx64, R);
1254         LLDB_LOGF(log, "  D : 0x%" PRIx64, D);
1255       }
1256     } break;
1257     case Instruction::Ret: {
1258       return true;
1259     }
1260     case Instruction::Store: {
1261       const StoreInst *store_inst = cast<StoreInst>(inst);
1262 
1263       // The semantics of Store are:
1264       //   Resolve the region D containing the data to be stored
1265       //   Resolve the region P containing a pointer
1266       //   Dereference P to get the region R that the data should be stored in
1267       //   Transfer a unit of type type(D) from D to R
1268 
1269       const Value *value_operand = store_inst->getValueOperand();
1270       const Value *pointer_operand = store_inst->getPointerOperand();
1271 
1272       Type *pointer_ty = pointer_operand->getType();
1273       PointerType *pointer_ptr_ty = dyn_cast<PointerType>(pointer_ty);
1274       if (!pointer_ptr_ty)
1275         return false;
1276       Type *target_ty = pointer_ptr_ty->getElementType();
1277 
1278       lldb::addr_t D = frame.ResolveValue(value_operand, module);
1279       lldb::addr_t P = frame.ResolveValue(pointer_operand, module);
1280 
1281       if (D == LLDB_INVALID_ADDRESS) {
1282         LLDB_LOGF(log, "StoreInst's value doesn't resolve to anything");
1283         error.SetErrorToGenericError();
1284         error.SetErrorString(bad_value_error);
1285         return false;
1286       }
1287 
1288       if (P == LLDB_INVALID_ADDRESS) {
1289         LLDB_LOGF(log, "StoreInst's pointer doesn't resolve to anything");
1290         error.SetErrorToGenericError();
1291         error.SetErrorString(bad_value_error);
1292         return false;
1293       }
1294 
1295       lldb::addr_t R;
1296       lldb_private::Status read_error;
1297       execution_unit.ReadPointerFromMemory(&R, P, read_error);
1298 
1299       if (!read_error.Success()) {
1300         LLDB_LOGF(log, "Couldn't read the address to be loaded for a LoadInst");
1301         error.SetErrorToGenericError();
1302         error.SetErrorString(memory_read_error);
1303         return false;
1304       }
1305 
1306       size_t target_size = data_layout.getTypeStoreSize(target_ty);
1307       lldb_private::DataBufferHeap buffer(target_size, 0);
1308 
1309       read_error.Clear();
1310       execution_unit.ReadMemory(buffer.GetBytes(), D, buffer.GetByteSize(),
1311                                 read_error);
1312       if (!read_error.Success()) {
1313         LLDB_LOGF(log, "Couldn't read from a region on behalf of a StoreInst");
1314         error.SetErrorToGenericError();
1315         error.SetErrorString(memory_read_error);
1316         return false;
1317       }
1318 
1319       lldb_private::Status write_error;
1320       execution_unit.WriteMemory(R, buffer.GetBytes(), buffer.GetByteSize(),
1321                                  write_error);
1322       if (!write_error.Success()) {
1323         LLDB_LOGF(log, "Couldn't write to a region on behalf of a StoreInst");
1324         error.SetErrorToGenericError();
1325         error.SetErrorString(memory_write_error);
1326         return false;
1327       }
1328 
1329       if (log) {
1330         LLDB_LOGF(log, "Interpreted a StoreInst");
1331         LLDB_LOGF(log, "  D : 0x%" PRIx64, D);
1332         LLDB_LOGF(log, "  P : 0x%" PRIx64, P);
1333         LLDB_LOGF(log, "  R : 0x%" PRIx64, R);
1334       }
1335     } break;
1336     case Instruction::Call: {
1337       const CallInst *call_inst = cast<CallInst>(inst);
1338 
1339       if (CanIgnoreCall(call_inst))
1340         break;
1341 
1342       // Get the return type
1343       llvm::Type *returnType = call_inst->getType();
1344       if (returnType == nullptr) {
1345         error.SetErrorToGenericError();
1346         error.SetErrorString("unable to access return type");
1347         return false;
1348       }
1349 
1350       // Work with void, integer and pointer return types
1351       if (!returnType->isVoidTy() && !returnType->isIntegerTy() &&
1352           !returnType->isPointerTy()) {
1353         error.SetErrorToGenericError();
1354         error.SetErrorString("return type is not supported");
1355         return false;
1356       }
1357 
1358       // Check we can actually get a thread
1359       if (exe_ctx.GetThreadPtr() == nullptr) {
1360         error.SetErrorToGenericError();
1361         error.SetErrorStringWithFormat("unable to acquire thread");
1362         return false;
1363       }
1364 
1365       // Make sure we have a valid process
1366       if (!exe_ctx.GetProcessPtr()) {
1367         error.SetErrorToGenericError();
1368         error.SetErrorStringWithFormat("unable to get the process");
1369         return false;
1370       }
1371 
1372       // Find the address of the callee function
1373       lldb_private::Scalar I;
1374       const llvm::Value *val = call_inst->getCalledOperand();
1375 
1376       if (!frame.EvaluateValue(I, val, module)) {
1377         error.SetErrorToGenericError();
1378         error.SetErrorString("unable to get address of function");
1379         return false;
1380       }
1381       lldb_private::Address funcAddr(I.ULongLong(LLDB_INVALID_ADDRESS));
1382 
1383       lldb_private::DiagnosticManager diagnostics;
1384       lldb_private::EvaluateExpressionOptions options;
1385 
1386       // We generally receive a function pointer which we must dereference
1387       llvm::Type *prototype = val->getType();
1388       if (!prototype->isPointerTy()) {
1389         error.SetErrorToGenericError();
1390         error.SetErrorString("call need function pointer");
1391         return false;
1392       }
1393 
1394       // Dereference the function pointer
1395       prototype = prototype->getPointerElementType();
1396       if (!(prototype->isFunctionTy() || prototype->isFunctionVarArg())) {
1397         error.SetErrorToGenericError();
1398         error.SetErrorString("call need function pointer");
1399         return false;
1400       }
1401 
1402       // Find number of arguments
1403       const int numArgs = call_inst->getNumArgOperands();
1404 
1405       // We work with a fixed array of 16 arguments which is our upper limit
1406       static lldb_private::ABI::CallArgument rawArgs[16];
1407       if (numArgs >= 16) {
1408         error.SetErrorToGenericError();
1409         error.SetErrorStringWithFormat("function takes too many arguments");
1410         return false;
1411       }
1412 
1413       // Push all function arguments to the argument list that will be passed
1414       // to the call function thread plan
1415       for (int i = 0; i < numArgs; i++) {
1416         // Get details of this argument
1417         llvm::Value *arg_op = call_inst->getArgOperand(i);
1418         llvm::Type *arg_ty = arg_op->getType();
1419 
1420         // Ensure that this argument is an supported type
1421         if (!arg_ty->isIntegerTy() && !arg_ty->isPointerTy()) {
1422           error.SetErrorToGenericError();
1423           error.SetErrorStringWithFormat("argument %d must be integer type", i);
1424           return false;
1425         }
1426 
1427         // Extract the arguments value
1428         lldb_private::Scalar tmp_op = 0;
1429         if (!frame.EvaluateValue(tmp_op, arg_op, module)) {
1430           error.SetErrorToGenericError();
1431           error.SetErrorStringWithFormat("unable to evaluate argument %d", i);
1432           return false;
1433         }
1434 
1435         // Check if this is a string literal or constant string pointer
1436         if (arg_ty->isPointerTy()) {
1437           lldb::addr_t addr = tmp_op.ULongLong();
1438           size_t dataSize = 0;
1439 
1440           bool Success = execution_unit.GetAllocSize(addr, dataSize);
1441           (void)Success;
1442           assert(Success &&
1443                  "unable to locate host data for transfer to device");
1444           // Create the required buffer
1445           rawArgs[i].size = dataSize;
1446           rawArgs[i].data_up.reset(new uint8_t[dataSize + 1]);
1447 
1448           // Read string from host memory
1449           execution_unit.ReadMemory(rawArgs[i].data_up.get(), addr, dataSize,
1450                                     error);
1451           assert(!error.Fail() &&
1452                  "we have failed to read the string from memory");
1453 
1454           // Add null terminator
1455           rawArgs[i].data_up[dataSize] = '\0';
1456           rawArgs[i].type = lldb_private::ABI::CallArgument::HostPointer;
1457         } else /* if ( arg_ty->isPointerTy() ) */
1458         {
1459           rawArgs[i].type = lldb_private::ABI::CallArgument::TargetValue;
1460           // Get argument size in bytes
1461           rawArgs[i].size = arg_ty->getIntegerBitWidth() / 8;
1462           // Push value into argument list for thread plan
1463           rawArgs[i].value = tmp_op.ULongLong();
1464         }
1465       }
1466 
1467       // Pack the arguments into an llvm::array
1468       llvm::ArrayRef<lldb_private::ABI::CallArgument> args(rawArgs, numArgs);
1469 
1470       // Setup a thread plan to call the target function
1471       lldb::ThreadPlanSP call_plan_sp(
1472           new lldb_private::ThreadPlanCallFunctionUsingABI(
1473               exe_ctx.GetThreadRef(), funcAddr, *prototype, *returnType, args,
1474               options));
1475 
1476       // Check if the plan is valid
1477       lldb_private::StreamString ss;
1478       if (!call_plan_sp || !call_plan_sp->ValidatePlan(&ss)) {
1479         error.SetErrorToGenericError();
1480         error.SetErrorStringWithFormat(
1481             "unable to make ThreadPlanCallFunctionUsingABI for 0x%llx",
1482             I.ULongLong());
1483         return false;
1484       }
1485 
1486       exe_ctx.GetProcessPtr()->SetRunningUserExpression(true);
1487 
1488       // Execute the actual function call thread plan
1489       lldb::ExpressionResults res = exe_ctx.GetProcessRef().RunThreadPlan(
1490           exe_ctx, call_plan_sp, options, diagnostics);
1491 
1492       // Check that the thread plan completed successfully
1493       if (res != lldb::ExpressionResults::eExpressionCompleted) {
1494         error.SetErrorToGenericError();
1495         error.SetErrorStringWithFormat("ThreadPlanCallFunctionUsingABI failed");
1496         return false;
1497       }
1498 
1499       exe_ctx.GetProcessPtr()->SetRunningUserExpression(false);
1500 
1501       // Void return type
1502       if (returnType->isVoidTy()) {
1503         // Cant assign to void types, so we leave the frame untouched
1504       } else
1505           // Integer or pointer return type
1506           if (returnType->isIntegerTy() || returnType->isPointerTy()) {
1507         // Get the encapsulated return value
1508         lldb::ValueObjectSP retVal = call_plan_sp.get()->GetReturnValueObject();
1509 
1510         lldb_private::Scalar returnVal = -1;
1511         lldb_private::ValueObject *vobj = retVal.get();
1512 
1513         // Check if the return value is valid
1514         if (vobj == nullptr || !retVal) {
1515           error.SetErrorToGenericError();
1516           error.SetErrorStringWithFormat("unable to get the return value");
1517           return false;
1518         }
1519 
1520         // Extract the return value as a integer
1521         lldb_private::Value &value = vobj->GetValue();
1522         returnVal = value.GetScalar();
1523 
1524         // Push the return value as the result
1525         frame.AssignValue(inst, returnVal, module);
1526       }
1527     } break;
1528     }
1529 
1530     ++frame.m_ii;
1531   }
1532 
1533   if (num_insts >= 4096) {
1534     error.SetErrorToGenericError();
1535     error.SetErrorString(infinite_loop_error);
1536     return false;
1537   }
1538 
1539   return false;
1540 }
1541