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