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