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