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 (bool) m_allocation;
163         }
164 
165         bool IsInvalid ()
166         {
167             return !m_allocation;
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 = 0;
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             case Instruction::ZExt:
998                 break;
999             }
1000         }
1001     }
1002 
1003     return true;
1004 }
1005 
1006 bool
1007 IRInterpreter::runOnFunction (lldb::ClangExpressionVariableSP &result,
1008                               const lldb_private::ConstString &result_name,
1009                               lldb_private::TypeFromParser result_type,
1010                               Function &llvm_function,
1011                               Module &llvm_module,
1012                               lldb_private::Error &err)
1013 {
1014     lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1015 
1016     lldb_private::ClangExpressionDeclMap::TargetInfo target_info = m_decl_map.GetTargetInfo();
1017 
1018     if (!target_info.IsValid())
1019     {
1020         err.SetErrorToGenericError();
1021         err.SetErrorString(interpreter_initialization_error);
1022         return false;
1023     }
1024 
1025     lldb::addr_t alloc_min;
1026     lldb::addr_t alloc_max;
1027 
1028     switch (target_info.address_byte_size)
1029     {
1030     default:
1031         err.SetErrorToGenericError();
1032         err.SetErrorString(interpreter_initialization_error);
1033         return false;
1034     case 4:
1035         alloc_min = 0x00001000llu;
1036         alloc_max = 0x0000ffffllu;
1037         break;
1038     case 8:
1039         alloc_min = 0x0000000000001000llu;
1040         alloc_max = 0x000000000000ffffllu;
1041         break;
1042     }
1043 
1044     TargetData target_data(&llvm_module);
1045     if (target_data.getPointerSize() != target_info.address_byte_size)
1046     {
1047         err.SetErrorToGenericError();
1048         err.SetErrorString(interpreter_initialization_error);
1049         return false;
1050     }
1051     if (target_data.isLittleEndian() != (target_info.byte_order == lldb::eByteOrderLittle))
1052     {
1053         err.SetErrorToGenericError();
1054         err.SetErrorString(interpreter_initialization_error);
1055         return false;
1056     }
1057 
1058     Memory memory(target_data, m_decl_map, alloc_min, alloc_max);
1059     InterpreterStackFrame frame(target_data, memory, m_decl_map);
1060 
1061     uint32_t num_insts = 0;
1062 
1063     frame.Jump(llvm_function.begin());
1064 
1065     while (frame.m_ii != frame.m_ie && (++num_insts < 4096))
1066     {
1067         const Instruction *inst = frame.m_ii;
1068 
1069         if (log)
1070             log->Printf("Interpreting %s", PrintValue(inst).c_str());
1071 
1072         switch (inst->getOpcode())
1073         {
1074         default:
1075             break;
1076         case Instruction::Add:
1077         case Instruction::Sub:
1078         case Instruction::Mul:
1079         case Instruction::SDiv:
1080         case Instruction::UDiv:
1081             {
1082                 const BinaryOperator *bin_op = dyn_cast<BinaryOperator>(inst);
1083 
1084                 if (!bin_op)
1085                 {
1086                     if (log)
1087                         log->Printf("getOpcode() returns %s, but instruction is not a BinaryOperator", inst->getOpcodeName());
1088                     err.SetErrorToGenericError();
1089                     err.SetErrorString(interpreter_internal_error);
1090                     return false;
1091                 }
1092 
1093                 Value *lhs = inst->getOperand(0);
1094                 Value *rhs = inst->getOperand(1);
1095 
1096                 lldb_private::Scalar L;
1097                 lldb_private::Scalar R;
1098 
1099                 if (!frame.EvaluateValue(L, lhs, llvm_module))
1100                 {
1101                     if (log)
1102                         log->Printf("Couldn't evaluate %s", PrintValue(lhs).c_str());
1103                     err.SetErrorToGenericError();
1104                     err.SetErrorString(bad_value_error);
1105                     return false;
1106                 }
1107 
1108                 if (!frame.EvaluateValue(R, rhs, llvm_module))
1109                 {
1110                     if (log)
1111                         log->Printf("Couldn't evaluate %s", PrintValue(rhs).c_str());
1112                     err.SetErrorToGenericError();
1113                     err.SetErrorString(bad_value_error);
1114                     return false;
1115                 }
1116 
1117                 lldb_private::Scalar result;
1118 
1119                 switch (inst->getOpcode())
1120                 {
1121                 default:
1122                     break;
1123                 case Instruction::Add:
1124                     result = L + R;
1125                     break;
1126                 case Instruction::Mul:
1127                     result = L * R;
1128                     break;
1129                 case Instruction::Sub:
1130                     result = L - R;
1131                     break;
1132                 case Instruction::SDiv:
1133                     result = L / R;
1134                     break;
1135                 case Instruction::UDiv:
1136                     result = L.GetRawBits64(0) / R.GetRawBits64(1);
1137                     break;
1138                 }
1139 
1140                 frame.AssignValue(inst, result, llvm_module);
1141 
1142                 if (log)
1143                 {
1144                     log->Printf("Interpreted a %s", inst->getOpcodeName());
1145                     log->Printf("  L : %s", frame.SummarizeValue(lhs).c_str());
1146                     log->Printf("  R : %s", frame.SummarizeValue(rhs).c_str());
1147                     log->Printf("  = : %s", frame.SummarizeValue(inst).c_str());
1148                 }
1149             }
1150             break;
1151         case Instruction::Alloca:
1152             {
1153                 const AllocaInst *alloca_inst = dyn_cast<AllocaInst>(inst);
1154 
1155                 if (!alloca_inst)
1156                 {
1157                     if (log)
1158                         log->Printf("getOpcode() returns Alloca, but instruction is not an AllocaInst");
1159                     err.SetErrorToGenericError();
1160                     err.SetErrorString(interpreter_internal_error);
1161                     return false;
1162                 }
1163 
1164                 if (alloca_inst->isArrayAllocation())
1165                 {
1166                     if (log)
1167                         log->Printf("AllocaInsts are not handled if isArrayAllocation() is true");
1168                     err.SetErrorToGenericError();
1169                     err.SetErrorString(unsupported_opcode_error);
1170                     return false;
1171                 }
1172 
1173                 // The semantics of Alloca are:
1174                 //   Create a region R of virtual memory of type T, backed by a data buffer
1175                 //   Create a region P of virtual memory of type T*, backed by a data buffer
1176                 //   Write the virtual address of R into P
1177 
1178                 Type *T = alloca_inst->getAllocatedType();
1179                 Type *Tptr = alloca_inst->getType();
1180 
1181                 Memory::Region R = memory.Malloc(T);
1182 
1183                 if (R.IsInvalid())
1184                 {
1185                     if (log)
1186                         log->Printf("Couldn't allocate memory for an AllocaInst");
1187                     err.SetErrorToGenericError();
1188                     err.SetErrorString(memory_allocation_error);
1189                     return false;
1190                 }
1191 
1192                 Memory::Region P = memory.Malloc(Tptr);
1193 
1194                 if (P.IsInvalid())
1195                 {
1196                     if (log)
1197                         log->Printf("Couldn't allocate the result pointer for an AllocaInst");
1198                     err.SetErrorToGenericError();
1199                     err.SetErrorString(memory_allocation_error);
1200                     return false;
1201                 }
1202 
1203                 DataEncoderSP P_encoder = memory.GetEncoder(P);
1204 
1205                 if (P_encoder->PutAddress(0, R.m_base) == UINT32_MAX)
1206                 {
1207                     if (log)
1208                         log->Printf("Couldn't write the result pointer for an AllocaInst");
1209                     err.SetErrorToGenericError();
1210                     err.SetErrorString(memory_write_error);
1211                     return false;
1212                 }
1213 
1214                 frame.m_values[alloca_inst] = P;
1215 
1216                 if (log)
1217                 {
1218                     log->Printf("Interpreted an AllocaInst");
1219                     log->Printf("  R : %s", memory.SummarizeRegion(R).c_str());
1220                     log->Printf("  P : %s", frame.SummarizeValue(alloca_inst).c_str());
1221                 }
1222             }
1223             break;
1224         case Instruction::BitCast:
1225         case Instruction::ZExt:
1226             {
1227                 const CastInst *cast_inst = dyn_cast<CastInst>(inst);
1228 
1229                 if (!cast_inst)
1230                 {
1231                     if (log)
1232                         log->Printf("getOpcode() returns %s, but instruction is not a BitCastInst", cast_inst->getOpcodeName());
1233                     err.SetErrorToGenericError();
1234                     err.SetErrorString(interpreter_internal_error);
1235                     return false;
1236                 }
1237 
1238                 Value *source = cast_inst->getOperand(0);
1239 
1240                 lldb_private::Scalar S;
1241 
1242                 if (!frame.EvaluateValue(S, source, llvm_module))
1243                 {
1244                     if (log)
1245                         log->Printf("Couldn't evaluate %s", PrintValue(source).c_str());
1246                     err.SetErrorToGenericError();
1247                     err.SetErrorString(bad_value_error);
1248                     return false;
1249                 }
1250 
1251                 frame.AssignValue(inst, S, llvm_module);
1252             }
1253             break;
1254         case Instruction::Br:
1255             {
1256                 const BranchInst *br_inst = dyn_cast<BranchInst>(inst);
1257 
1258                 if (!br_inst)
1259                 {
1260                     if (log)
1261                         log->Printf("getOpcode() returns Br, but instruction is not a BranchInst");
1262                     err.SetErrorToGenericError();
1263                     err.SetErrorString(interpreter_internal_error);
1264                     return false;
1265                 }
1266 
1267                 if (br_inst->isConditional())
1268                 {
1269                     Value *condition = br_inst->getCondition();
1270 
1271                     lldb_private::Scalar C;
1272 
1273                     if (!frame.EvaluateValue(C, condition, llvm_module))
1274                     {
1275                         if (log)
1276                             log->Printf("Couldn't evaluate %s", PrintValue(condition).c_str());
1277                         err.SetErrorToGenericError();
1278                         err.SetErrorString(bad_value_error);
1279                         return false;
1280                     }
1281 
1282                     if (C.GetRawBits64(0))
1283                         frame.Jump(br_inst->getSuccessor(0));
1284                     else
1285                         frame.Jump(br_inst->getSuccessor(1));
1286 
1287                     if (log)
1288                     {
1289                         log->Printf("Interpreted a BrInst with a condition");
1290                         log->Printf("  cond : %s", frame.SummarizeValue(condition).c_str());
1291                     }
1292                 }
1293                 else
1294                 {
1295                     frame.Jump(br_inst->getSuccessor(0));
1296 
1297                     if (log)
1298                     {
1299                         log->Printf("Interpreted a BrInst with no condition");
1300                     }
1301                 }
1302             }
1303             continue;
1304         case Instruction::GetElementPtr:
1305             {
1306                 const GetElementPtrInst *gep_inst = dyn_cast<GetElementPtrInst>(inst);
1307 
1308                 if (!gep_inst)
1309                 {
1310                     if (log)
1311                         log->Printf("getOpcode() returns GetElementPtr, but instruction is not a GetElementPtrInst");
1312                     err.SetErrorToGenericError();
1313                     err.SetErrorString(interpreter_internal_error);
1314                     return false;
1315                 }
1316 
1317                 const Value *pointer_operand = gep_inst->getPointerOperand();
1318                 Type *pointer_type = pointer_operand->getType();
1319 
1320                 lldb_private::Scalar P;
1321 
1322                 if (!frame.EvaluateValue(P, pointer_operand, llvm_module))
1323                 {
1324                     if (log)
1325                         log->Printf("Couldn't evaluate %s", PrintValue(pointer_operand).c_str());
1326                     err.SetErrorToGenericError();
1327                     err.SetErrorString(bad_value_error);
1328                     return false;
1329                 }
1330 
1331                 typedef SmallVector <Value *, 8> IndexVector;
1332                 typedef IndexVector::iterator IndexIterator;
1333 
1334                 SmallVector <Value *, 8> indices (gep_inst->idx_begin(),
1335                                                   gep_inst->idx_end());
1336 
1337                 SmallVector <Value *, 8> const_indices;
1338 
1339                 for (IndexIterator ii = indices.begin(), ie = indices.end();
1340                      ii != ie;
1341                      ++ii)
1342                 {
1343                     ConstantInt *constant_index = dyn_cast<ConstantInt>(*ii);
1344 
1345                     if (!constant_index)
1346                     {
1347                         lldb_private::Scalar I;
1348 
1349                         if (!frame.EvaluateValue(I, *ii, llvm_module))
1350                         {
1351                             if (log)
1352                                 log->Printf("Couldn't evaluate %s", PrintValue(*ii).c_str());
1353                             err.SetErrorToGenericError();
1354                             err.SetErrorString(bad_value_error);
1355                             return false;
1356                         }
1357 
1358                         if (log)
1359                             log->Printf("Evaluated constant index %s as %llu", PrintValue(*ii).c_str(), I.ULongLong(LLDB_INVALID_ADDRESS));
1360 
1361                         constant_index = cast<ConstantInt>(ConstantInt::get((*ii)->getType(), I.ULongLong(LLDB_INVALID_ADDRESS)));
1362                     }
1363 
1364                     const_indices.push_back(constant_index);
1365                 }
1366 
1367                 uint64_t offset = target_data.getIndexedOffset(pointer_type, const_indices);
1368 
1369                 lldb_private::Scalar Poffset = P + offset;
1370 
1371                 frame.AssignValue(inst, Poffset, llvm_module);
1372 
1373                 if (log)
1374                 {
1375                     log->Printf("Interpreted a GetElementPtrInst");
1376                     log->Printf("  P       : %s", frame.SummarizeValue(pointer_operand).c_str());
1377                     log->Printf("  Poffset : %s", frame.SummarizeValue(inst).c_str());
1378                 }
1379             }
1380             break;
1381         case Instruction::ICmp:
1382             {
1383                 const ICmpInst *icmp_inst = dyn_cast<ICmpInst>(inst);
1384 
1385                 if (!icmp_inst)
1386                 {
1387                     if (log)
1388                         log->Printf("getOpcode() returns ICmp, but instruction is not an ICmpInst");
1389                     err.SetErrorToGenericError();
1390                     err.SetErrorString(interpreter_internal_error);
1391                     return false;
1392                 }
1393 
1394                 CmpInst::Predicate predicate = icmp_inst->getPredicate();
1395 
1396                 Value *lhs = inst->getOperand(0);
1397                 Value *rhs = inst->getOperand(1);
1398 
1399                 lldb_private::Scalar L;
1400                 lldb_private::Scalar R;
1401 
1402                 if (!frame.EvaluateValue(L, lhs, llvm_module))
1403                 {
1404                     if (log)
1405                         log->Printf("Couldn't evaluate %s", PrintValue(lhs).c_str());
1406                     err.SetErrorToGenericError();
1407                     err.SetErrorString(bad_value_error);
1408                     return false;
1409                 }
1410 
1411                 if (!frame.EvaluateValue(R, rhs, llvm_module))
1412                 {
1413                     if (log)
1414                         log->Printf("Couldn't evaluate %s", PrintValue(rhs).c_str());
1415                     err.SetErrorToGenericError();
1416                     err.SetErrorString(bad_value_error);
1417                     return false;
1418                 }
1419 
1420                 lldb_private::Scalar result;
1421 
1422                 switch (predicate)
1423                 {
1424                 default:
1425                     return false;
1426                 case CmpInst::ICMP_EQ:
1427                     result = (L == R);
1428                     break;
1429                 case CmpInst::ICMP_NE:
1430                     result = (L != R);
1431                     break;
1432                 case CmpInst::ICMP_UGT:
1433                     result = (L.GetRawBits64(0) > R.GetRawBits64(0));
1434                     break;
1435                 case CmpInst::ICMP_UGE:
1436                     result = (L.GetRawBits64(0) >= R.GetRawBits64(0));
1437                     break;
1438                 case CmpInst::ICMP_ULT:
1439                     result = (L.GetRawBits64(0) < R.GetRawBits64(0));
1440                     break;
1441                 case CmpInst::ICMP_ULE:
1442                     result = (L.GetRawBits64(0) <= R.GetRawBits64(0));
1443                     break;
1444                 case CmpInst::ICMP_SGT:
1445                     result = (L > R);
1446                     break;
1447                 case CmpInst::ICMP_SGE:
1448                     result = (L >= R);
1449                     break;
1450                 case CmpInst::ICMP_SLT:
1451                     result = (L < R);
1452                     break;
1453                 case CmpInst::ICMP_SLE:
1454                     result = (L <= R);
1455                     break;
1456                 }
1457 
1458                 frame.AssignValue(inst, result, llvm_module);
1459 
1460                 if (log)
1461                 {
1462                     log->Printf("Interpreted an ICmpInst");
1463                     log->Printf("  L : %s", frame.SummarizeValue(lhs).c_str());
1464                     log->Printf("  R : %s", frame.SummarizeValue(rhs).c_str());
1465                     log->Printf("  = : %s", frame.SummarizeValue(inst).c_str());
1466                 }
1467             }
1468             break;
1469         case Instruction::IntToPtr:
1470             {
1471                 const IntToPtrInst *int_to_ptr_inst = dyn_cast<IntToPtrInst>(inst);
1472 
1473                 if (!int_to_ptr_inst)
1474                 {
1475                     if (log)
1476                         log->Printf("getOpcode() returns IntToPtr, but instruction is not an IntToPtrInst");
1477                     err.SetErrorToGenericError();
1478                     err.SetErrorString(interpreter_internal_error);
1479                     return false;
1480                 }
1481 
1482                 Value *src_operand = int_to_ptr_inst->getOperand(0);
1483 
1484                 lldb_private::Scalar I;
1485 
1486                 if (!frame.EvaluateValue(I, src_operand, llvm_module))
1487                 {
1488                     if (log)
1489                         log->Printf("Couldn't evaluate %s", PrintValue(src_operand).c_str());
1490                     err.SetErrorToGenericError();
1491                     err.SetErrorString(bad_value_error);
1492                     return false;
1493                 }
1494 
1495                 frame.AssignValue(inst, I, llvm_module);
1496 
1497                 if (log)
1498                 {
1499                     log->Printf("Interpreted an IntToPtr");
1500                     log->Printf("  Src : %s", frame.SummarizeValue(src_operand).c_str());
1501                     log->Printf("  =   : %s", frame.SummarizeValue(inst).c_str());
1502                 }
1503             }
1504             break;
1505         case Instruction::Load:
1506             {
1507                 const LoadInst *load_inst = dyn_cast<LoadInst>(inst);
1508 
1509                 if (!load_inst)
1510                 {
1511                     if (log)
1512                         log->Printf("getOpcode() returns Load, but instruction is not a LoadInst");
1513                     err.SetErrorToGenericError();
1514                     err.SetErrorString(interpreter_internal_error);
1515                     return false;
1516                 }
1517 
1518                 // The semantics of Load are:
1519                 //   Create a region D that will contain the loaded data
1520                 //   Resolve the region P containing a pointer
1521                 //   Dereference P to get the region R that the data should be loaded from
1522                 //   Transfer a unit of type type(D) from R to D
1523 
1524                 const Value *pointer_operand = load_inst->getPointerOperand();
1525 
1526                 Type *pointer_ty = pointer_operand->getType();
1527                 PointerType *pointer_ptr_ty = dyn_cast<PointerType>(pointer_ty);
1528                 if (!pointer_ptr_ty)
1529                 {
1530                     if (log)
1531                         log->Printf("getPointerOperand()->getType() is not a PointerType");
1532                     err.SetErrorToGenericError();
1533                     err.SetErrorString(interpreter_internal_error);
1534                     return false;
1535                 }
1536                 Type *target_ty = pointer_ptr_ty->getElementType();
1537 
1538                 Memory::Region D = frame.ResolveValue(load_inst, llvm_module);
1539                 Memory::Region P = frame.ResolveValue(pointer_operand, llvm_module);
1540 
1541                 if (D.IsInvalid())
1542                 {
1543                     if (log)
1544                         log->Printf("LoadInst's value doesn't resolve to anything");
1545                     err.SetErrorToGenericError();
1546                     err.SetErrorString(bad_value_error);
1547                     return false;
1548                 }
1549 
1550                 if (P.IsInvalid())
1551                 {
1552                     if (log)
1553                         log->Printf("LoadInst's pointer doesn't resolve to anything");
1554                     err.SetErrorToGenericError();
1555                     err.SetErrorString(bad_value_error);
1556                     return false;
1557                 }
1558 
1559                 DataExtractorSP P_extractor(memory.GetExtractor(P));
1560                 DataEncoderSP D_encoder(memory.GetEncoder(D));
1561 
1562                 uint32_t offset = 0;
1563                 lldb::addr_t pointer = P_extractor->GetAddress(&offset);
1564 
1565                 Memory::Region R = memory.Lookup(pointer, target_ty);
1566 
1567                 if (R.IsValid())
1568                 {
1569                     if (!memory.Read(D_encoder->GetDataStart(), R.m_base, target_data.getTypeStoreSize(target_ty)))
1570                     {
1571                         if (log)
1572                             log->Printf("Couldn't read from a region on behalf of a LoadInst");
1573                         err.SetErrorToGenericError();
1574                         err.SetErrorString(memory_read_error);
1575                         return false;
1576                     }
1577                 }
1578                 else
1579                 {
1580                     if (!memory.ReadFromRawPtr(D_encoder->GetDataStart(), pointer, target_data.getTypeStoreSize(target_ty)))
1581                     {
1582                         if (log)
1583                             log->Printf("Couldn't read from a raw pointer on behalf of a LoadInst");
1584                         err.SetErrorToGenericError();
1585                         err.SetErrorString(memory_read_error);
1586                         return false;
1587                     }
1588                 }
1589 
1590                 if (log)
1591                 {
1592                     log->Printf("Interpreted a LoadInst");
1593                     log->Printf("  P : %s", frame.SummarizeValue(pointer_operand).c_str());
1594                     if (R.IsValid())
1595                         log->Printf("  R : %s", memory.SummarizeRegion(R).c_str());
1596                     else
1597                         log->Printf("  R : raw pointer 0x%llx", (unsigned long long)pointer);
1598                     log->Printf("  D : %s", frame.SummarizeValue(load_inst).c_str());
1599                 }
1600             }
1601             break;
1602         case Instruction::Ret:
1603             {
1604                 if (result_name.IsEmpty())
1605                     return true;
1606 
1607                 GlobalValue *result_value = llvm_module.getNamedValue(result_name.GetCString());
1608 
1609                 if (!frame.ConstructResult(result, result_value, result_name, result_type, llvm_module))
1610                 {
1611                     if (log)
1612                         log->Printf("Couldn't construct the expression's result");
1613                     err.SetErrorToGenericError();
1614                     err.SetErrorString(bad_result_error);
1615                     return false;
1616                 }
1617 
1618                 return true;
1619             }
1620         case Instruction::Store:
1621             {
1622                 const StoreInst *store_inst = dyn_cast<StoreInst>(inst);
1623 
1624                 if (!store_inst)
1625                 {
1626                     if (log)
1627                         log->Printf("getOpcode() returns Store, but instruction is not a StoreInst");
1628                     err.SetErrorToGenericError();
1629                     err.SetErrorString(interpreter_internal_error);
1630                     return false;
1631                 }
1632 
1633                 // The semantics of Store are:
1634                 //   Resolve the region D containing the data to be stored
1635                 //   Resolve the region P containing a pointer
1636                 //   Dereference P to get the region R that the data should be stored in
1637                 //   Transfer a unit of type type(D) from D to R
1638 
1639                 const Value *value_operand = store_inst->getValueOperand();
1640                 const Value *pointer_operand = store_inst->getPointerOperand();
1641 
1642                 Type *pointer_ty = pointer_operand->getType();
1643                 PointerType *pointer_ptr_ty = dyn_cast<PointerType>(pointer_ty);
1644                 if (!pointer_ptr_ty)
1645                     return false;
1646                 Type *target_ty = pointer_ptr_ty->getElementType();
1647 
1648                 Memory::Region D = frame.ResolveValue(value_operand, llvm_module);
1649                 Memory::Region P = frame.ResolveValue(pointer_operand, llvm_module);
1650 
1651                 if (D.IsInvalid())
1652                 {
1653                     if (log)
1654                         log->Printf("StoreInst's value doesn't resolve to anything");
1655                     err.SetErrorToGenericError();
1656                     err.SetErrorString(bad_value_error);
1657                     return false;
1658                 }
1659 
1660                 if (P.IsInvalid())
1661                 {
1662                     if (log)
1663                         log->Printf("StoreInst's pointer doesn't resolve to anything");
1664                     err.SetErrorToGenericError();
1665                     err.SetErrorString(bad_value_error);
1666                     return false;
1667                 }
1668 
1669                 DataExtractorSP P_extractor(memory.GetExtractor(P));
1670                 DataExtractorSP D_extractor(memory.GetExtractor(D));
1671 
1672                 if (!P_extractor || !D_extractor)
1673                     return false;
1674 
1675                 uint32_t offset = 0;
1676                 lldb::addr_t pointer = P_extractor->GetAddress(&offset);
1677 
1678                 Memory::Region R = memory.Lookup(pointer, target_ty);
1679 
1680                 if (R.IsValid())
1681                 {
1682                     if (!memory.Write(R.m_base, D_extractor->GetDataStart(), target_data.getTypeStoreSize(target_ty)))
1683                     {
1684                         if (log)
1685                             log->Printf("Couldn't write to a region on behalf of a LoadInst");
1686                         err.SetErrorToGenericError();
1687                         err.SetErrorString(memory_write_error);
1688                         return false;
1689                     }
1690                 }
1691                 else
1692                 {
1693                     if (!memory.WriteToRawPtr(pointer, D_extractor->GetDataStart(), target_data.getTypeStoreSize(target_ty)))
1694                     {
1695                         if (log)
1696                             log->Printf("Couldn't write to a raw pointer on behalf of a LoadInst");
1697                         err.SetErrorToGenericError();
1698                         err.SetErrorString(memory_write_error);
1699                         return false;
1700                     }
1701                 }
1702 
1703 
1704                 if (log)
1705                 {
1706                     log->Printf("Interpreted a StoreInst");
1707                     log->Printf("  D : %s", frame.SummarizeValue(value_operand).c_str());
1708                     log->Printf("  P : %s", frame.SummarizeValue(pointer_operand).c_str());
1709                     log->Printf("  R : %s", memory.SummarizeRegion(R).c_str());
1710                 }
1711             }
1712             break;
1713         }
1714 
1715         ++frame.m_ii;
1716     }
1717 
1718     if (num_insts >= 4096)
1719     {
1720         err.SetErrorToGenericError();
1721         err.SetErrorString(infinite_loop_error);
1722         return false;
1723     }
1724 
1725     return false;
1726 }
1727