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