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