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