xref: /llvm-project/lldb/source/Expression/DWARFExpression.cpp (revision 4cf1fe240589d3f2a8a8332abf3f71a18bdba027)
1 //===-- DWARFExpression.cpp -----------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "lldb/Expression/DWARFExpression.h"
10 
11 #include <cinttypes>
12 
13 #include <optional>
14 #include <vector>
15 
16 #include "lldb/Core/Module.h"
17 #include "lldb/Core/Value.h"
18 #include "lldb/Core/dwarf.h"
19 #include "lldb/Utility/DataEncoder.h"
20 #include "lldb/Utility/LLDBLog.h"
21 #include "lldb/Utility/Log.h"
22 #include "lldb/Utility/RegisterValue.h"
23 #include "lldb/Utility/Scalar.h"
24 #include "lldb/Utility/StreamString.h"
25 #include "lldb/Utility/VMRange.h"
26 
27 #include "lldb/Host/Host.h"
28 #include "lldb/Utility/Endian.h"
29 
30 #include "lldb/Symbol/Function.h"
31 
32 #include "lldb/Target/ABI.h"
33 #include "lldb/Target/ExecutionContext.h"
34 #include "lldb/Target/Process.h"
35 #include "lldb/Target/RegisterContext.h"
36 #include "lldb/Target/StackFrame.h"
37 #include "lldb/Target/StackID.h"
38 #include "lldb/Target/Target.h"
39 #include "lldb/Target/Thread.h"
40 #include "llvm/DebugInfo/DWARF/DWARFDebugLoc.h"
41 #include "llvm/DebugInfo/DWARF/DWARFExpression.h"
42 
43 #include "Plugins/SymbolFile/DWARF/DWARFUnit.h"
44 
45 using namespace lldb;
46 using namespace lldb_private;
47 using namespace lldb_private::dwarf;
48 using namespace lldb_private::plugin::dwarf;
49 
50 // DWARFExpression constructor
51 DWARFExpression::DWARFExpression() : m_data() {}
52 
53 DWARFExpression::DWARFExpression(const DataExtractor &data) : m_data(data) {}
54 
55 // Destructor
56 DWARFExpression::~DWARFExpression() = default;
57 
58 bool DWARFExpression::IsValid() const { return m_data.GetByteSize() > 0; }
59 
60 void DWARFExpression::UpdateValue(uint64_t const_value,
61                                   lldb::offset_t const_value_byte_size,
62                                   uint8_t addr_byte_size) {
63   if (!const_value_byte_size)
64     return;
65 
66   m_data.SetData(
67       DataBufferSP(new DataBufferHeap(&const_value, const_value_byte_size)));
68   m_data.SetByteOrder(endian::InlHostByteOrder());
69   m_data.SetAddressByteSize(addr_byte_size);
70 }
71 
72 void DWARFExpression::DumpLocation(Stream *s, lldb::DescriptionLevel level,
73                                    ABI *abi) const {
74   auto *MCRegInfo = abi ? &abi->GetMCRegisterInfo() : nullptr;
75   auto GetRegName = [&MCRegInfo](uint64_t DwarfRegNum,
76                                  bool IsEH) -> llvm::StringRef {
77     if (!MCRegInfo)
78       return {};
79     if (std::optional<unsigned> LLVMRegNum =
80             MCRegInfo->getLLVMRegNum(DwarfRegNum, IsEH))
81       if (const char *RegName = MCRegInfo->getName(*LLVMRegNum))
82         return llvm::StringRef(RegName);
83     return {};
84   };
85   llvm::DIDumpOptions DumpOpts;
86   DumpOpts.GetNameForDWARFReg = GetRegName;
87   llvm::DWARFExpression(m_data.GetAsLLVM(), m_data.GetAddressByteSize())
88       .print(s->AsRawOstream(), DumpOpts, nullptr);
89 }
90 
91 RegisterKind DWARFExpression::GetRegisterKind() const { return m_reg_kind; }
92 
93 void DWARFExpression::SetRegisterKind(RegisterKind reg_kind) {
94   m_reg_kind = reg_kind;
95 }
96 
97 static llvm::Error ReadRegisterValueAsScalar(RegisterContext *reg_ctx,
98                                              lldb::RegisterKind reg_kind,
99                                              uint32_t reg_num, Value &value) {
100   if (reg_ctx == nullptr)
101     return llvm::createStringError("no register context in frame");
102 
103   const uint32_t native_reg =
104       reg_ctx->ConvertRegisterKindToRegisterNumber(reg_kind, reg_num);
105   if (native_reg == LLDB_INVALID_REGNUM)
106     return llvm::createStringError(
107         "unable to convert register kind=%u reg_num=%u to a native "
108         "register number",
109         reg_kind, reg_num);
110 
111   const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoAtIndex(native_reg);
112   RegisterValue reg_value;
113   if (reg_ctx->ReadRegister(reg_info, reg_value)) {
114     if (reg_value.GetScalarValue(value.GetScalar())) {
115       value.SetValueType(Value::ValueType::Scalar);
116       value.SetContext(Value::ContextType::RegisterInfo,
117                        const_cast<RegisterInfo *>(reg_info));
118       return llvm::Error::success();
119     }
120 
121     // If we get this error, then we need to implement a value buffer in
122     // the dwarf expression evaluation function...
123     return llvm::createStringError(
124         "register %s can't be converted to a scalar value", reg_info->name);
125   }
126 
127   return llvm::createStringError("register %s is not available",
128                                  reg_info->name);
129 }
130 
131 /// Return the length in bytes of the set of operands for \p op. No guarantees
132 /// are made on the state of \p data after this call.
133 static lldb::offset_t GetOpcodeDataSize(const DataExtractor &data,
134                                         const lldb::offset_t data_offset,
135                                         const LocationAtom op,
136                                         const DWARFUnit *dwarf_cu) {
137   lldb::offset_t offset = data_offset;
138   switch (op) {
139   // Only used in LLVM metadata.
140   case DW_OP_LLVM_fragment:
141   case DW_OP_LLVM_convert:
142   case DW_OP_LLVM_tag_offset:
143   case DW_OP_LLVM_entry_value:
144   case DW_OP_LLVM_implicit_pointer:
145   case DW_OP_LLVM_arg:
146   case DW_OP_LLVM_extract_bits_sext:
147   case DW_OP_LLVM_extract_bits_zext:
148     break;
149   // Vendor extensions:
150   case DW_OP_HP_is_value:
151   case DW_OP_HP_fltconst4:
152   case DW_OP_HP_fltconst8:
153   case DW_OP_HP_mod_range:
154   case DW_OP_HP_unmod_range:
155   case DW_OP_HP_tls:
156   case DW_OP_INTEL_bit_piece:
157   case DW_OP_WASM_location:
158   case DW_OP_WASM_location_int:
159   case DW_OP_APPLE_uninit:
160   case DW_OP_PGI_omp_thread_num:
161   case DW_OP_hi_user:
162     break;
163 
164   case DW_OP_addr:
165   case DW_OP_call_ref: // 0x9a 1 address sized offset of DIE (DWARF3)
166     return data.GetAddressByteSize();
167 
168   // Opcodes with no arguments
169   case DW_OP_deref:                // 0x06
170   case DW_OP_dup:                  // 0x12
171   case DW_OP_drop:                 // 0x13
172   case DW_OP_over:                 // 0x14
173   case DW_OP_swap:                 // 0x16
174   case DW_OP_rot:                  // 0x17
175   case DW_OP_xderef:               // 0x18
176   case DW_OP_abs:                  // 0x19
177   case DW_OP_and:                  // 0x1a
178   case DW_OP_div:                  // 0x1b
179   case DW_OP_minus:                // 0x1c
180   case DW_OP_mod:                  // 0x1d
181   case DW_OP_mul:                  // 0x1e
182   case DW_OP_neg:                  // 0x1f
183   case DW_OP_not:                  // 0x20
184   case DW_OP_or:                   // 0x21
185   case DW_OP_plus:                 // 0x22
186   case DW_OP_shl:                  // 0x24
187   case DW_OP_shr:                  // 0x25
188   case DW_OP_shra:                 // 0x26
189   case DW_OP_xor:                  // 0x27
190   case DW_OP_eq:                   // 0x29
191   case DW_OP_ge:                   // 0x2a
192   case DW_OP_gt:                   // 0x2b
193   case DW_OP_le:                   // 0x2c
194   case DW_OP_lt:                   // 0x2d
195   case DW_OP_ne:                   // 0x2e
196   case DW_OP_lit0:                 // 0x30
197   case DW_OP_lit1:                 // 0x31
198   case DW_OP_lit2:                 // 0x32
199   case DW_OP_lit3:                 // 0x33
200   case DW_OP_lit4:                 // 0x34
201   case DW_OP_lit5:                 // 0x35
202   case DW_OP_lit6:                 // 0x36
203   case DW_OP_lit7:                 // 0x37
204   case DW_OP_lit8:                 // 0x38
205   case DW_OP_lit9:                 // 0x39
206   case DW_OP_lit10:                // 0x3A
207   case DW_OP_lit11:                // 0x3B
208   case DW_OP_lit12:                // 0x3C
209   case DW_OP_lit13:                // 0x3D
210   case DW_OP_lit14:                // 0x3E
211   case DW_OP_lit15:                // 0x3F
212   case DW_OP_lit16:                // 0x40
213   case DW_OP_lit17:                // 0x41
214   case DW_OP_lit18:                // 0x42
215   case DW_OP_lit19:                // 0x43
216   case DW_OP_lit20:                // 0x44
217   case DW_OP_lit21:                // 0x45
218   case DW_OP_lit22:                // 0x46
219   case DW_OP_lit23:                // 0x47
220   case DW_OP_lit24:                // 0x48
221   case DW_OP_lit25:                // 0x49
222   case DW_OP_lit26:                // 0x4A
223   case DW_OP_lit27:                // 0x4B
224   case DW_OP_lit28:                // 0x4C
225   case DW_OP_lit29:                // 0x4D
226   case DW_OP_lit30:                // 0x4E
227   case DW_OP_lit31:                // 0x4f
228   case DW_OP_reg0:                 // 0x50
229   case DW_OP_reg1:                 // 0x51
230   case DW_OP_reg2:                 // 0x52
231   case DW_OP_reg3:                 // 0x53
232   case DW_OP_reg4:                 // 0x54
233   case DW_OP_reg5:                 // 0x55
234   case DW_OP_reg6:                 // 0x56
235   case DW_OP_reg7:                 // 0x57
236   case DW_OP_reg8:                 // 0x58
237   case DW_OP_reg9:                 // 0x59
238   case DW_OP_reg10:                // 0x5A
239   case DW_OP_reg11:                // 0x5B
240   case DW_OP_reg12:                // 0x5C
241   case DW_OP_reg13:                // 0x5D
242   case DW_OP_reg14:                // 0x5E
243   case DW_OP_reg15:                // 0x5F
244   case DW_OP_reg16:                // 0x60
245   case DW_OP_reg17:                // 0x61
246   case DW_OP_reg18:                // 0x62
247   case DW_OP_reg19:                // 0x63
248   case DW_OP_reg20:                // 0x64
249   case DW_OP_reg21:                // 0x65
250   case DW_OP_reg22:                // 0x66
251   case DW_OP_reg23:                // 0x67
252   case DW_OP_reg24:                // 0x68
253   case DW_OP_reg25:                // 0x69
254   case DW_OP_reg26:                // 0x6A
255   case DW_OP_reg27:                // 0x6B
256   case DW_OP_reg28:                // 0x6C
257   case DW_OP_reg29:                // 0x6D
258   case DW_OP_reg30:                // 0x6E
259   case DW_OP_reg31:                // 0x6F
260   case DW_OP_nop:                  // 0x96
261   case DW_OP_push_object_address:  // 0x97 DWARF3
262   case DW_OP_form_tls_address:     // 0x9b DWARF3
263   case DW_OP_call_frame_cfa:       // 0x9c DWARF3
264   case DW_OP_stack_value:          // 0x9f DWARF4
265   case DW_OP_GNU_push_tls_address: // 0xe0 GNU extension
266     return 0;
267 
268   // Opcodes with a single 1 byte arguments
269   case DW_OP_const1u:     // 0x08 1 1-byte constant
270   case DW_OP_const1s:     // 0x09 1 1-byte constant
271   case DW_OP_pick:        // 0x15 1 1-byte stack index
272   case DW_OP_deref_size:  // 0x94 1 1-byte size of data retrieved
273   case DW_OP_xderef_size: // 0x95 1 1-byte size of data retrieved
274   case DW_OP_deref_type:  // 0xa6 1 1-byte constant
275     return 1;
276 
277   // Opcodes with a single 2 byte arguments
278   case DW_OP_const2u: // 0x0a 1 2-byte constant
279   case DW_OP_const2s: // 0x0b 1 2-byte constant
280   case DW_OP_skip:    // 0x2f 1 signed 2-byte constant
281   case DW_OP_bra:     // 0x28 1 signed 2-byte constant
282   case DW_OP_call2:   // 0x98 1 2-byte offset of DIE (DWARF3)
283     return 2;
284 
285   // Opcodes with a single 4 byte arguments
286   case DW_OP_const4u: // 0x0c 1 4-byte constant
287   case DW_OP_const4s: // 0x0d 1 4-byte constant
288   case DW_OP_call4:   // 0x99 1 4-byte offset of DIE (DWARF3)
289     return 4;
290 
291   // Opcodes with a single 8 byte arguments
292   case DW_OP_const8u: // 0x0e 1 8-byte constant
293   case DW_OP_const8s: // 0x0f 1 8-byte constant
294     return 8;
295 
296   // All opcodes that have a single ULEB (signed or unsigned) argument
297   case DW_OP_constu:          // 0x10 1 ULEB128 constant
298   case DW_OP_consts:          // 0x11 1 SLEB128 constant
299   case DW_OP_plus_uconst:     // 0x23 1 ULEB128 addend
300   case DW_OP_breg0:           // 0x70 1 ULEB128 register
301   case DW_OP_breg1:           // 0x71 1 ULEB128 register
302   case DW_OP_breg2:           // 0x72 1 ULEB128 register
303   case DW_OP_breg3:           // 0x73 1 ULEB128 register
304   case DW_OP_breg4:           // 0x74 1 ULEB128 register
305   case DW_OP_breg5:           // 0x75 1 ULEB128 register
306   case DW_OP_breg6:           // 0x76 1 ULEB128 register
307   case DW_OP_breg7:           // 0x77 1 ULEB128 register
308   case DW_OP_breg8:           // 0x78 1 ULEB128 register
309   case DW_OP_breg9:           // 0x79 1 ULEB128 register
310   case DW_OP_breg10:          // 0x7a 1 ULEB128 register
311   case DW_OP_breg11:          // 0x7b 1 ULEB128 register
312   case DW_OP_breg12:          // 0x7c 1 ULEB128 register
313   case DW_OP_breg13:          // 0x7d 1 ULEB128 register
314   case DW_OP_breg14:          // 0x7e 1 ULEB128 register
315   case DW_OP_breg15:          // 0x7f 1 ULEB128 register
316   case DW_OP_breg16:          // 0x80 1 ULEB128 register
317   case DW_OP_breg17:          // 0x81 1 ULEB128 register
318   case DW_OP_breg18:          // 0x82 1 ULEB128 register
319   case DW_OP_breg19:          // 0x83 1 ULEB128 register
320   case DW_OP_breg20:          // 0x84 1 ULEB128 register
321   case DW_OP_breg21:          // 0x85 1 ULEB128 register
322   case DW_OP_breg22:          // 0x86 1 ULEB128 register
323   case DW_OP_breg23:          // 0x87 1 ULEB128 register
324   case DW_OP_breg24:          // 0x88 1 ULEB128 register
325   case DW_OP_breg25:          // 0x89 1 ULEB128 register
326   case DW_OP_breg26:          // 0x8a 1 ULEB128 register
327   case DW_OP_breg27:          // 0x8b 1 ULEB128 register
328   case DW_OP_breg28:          // 0x8c 1 ULEB128 register
329   case DW_OP_breg29:          // 0x8d 1 ULEB128 register
330   case DW_OP_breg30:          // 0x8e 1 ULEB128 register
331   case DW_OP_breg31:          // 0x8f 1 ULEB128 register
332   case DW_OP_regx:            // 0x90 1 ULEB128 register
333   case DW_OP_fbreg:           // 0x91 1 SLEB128 offset
334   case DW_OP_piece:           // 0x93 1 ULEB128 size of piece addressed
335   case DW_OP_convert:         // 0xa8 1 ULEB128 offset
336   case DW_OP_reinterpret:     // 0xa9 1 ULEB128 offset
337   case DW_OP_addrx:           // 0xa1 1 ULEB128 index
338   case DW_OP_constx:          // 0xa2 1 ULEB128 index
339   case DW_OP_xderef_type:     // 0xa7 1 ULEB128 index
340   case DW_OP_GNU_addr_index:  // 0xfb 1 ULEB128 index
341   case DW_OP_GNU_const_index: // 0xfc 1 ULEB128 index
342     data.Skip_LEB128(&offset);
343     return offset - data_offset;
344 
345   // All opcodes that have a 2 ULEB (signed or unsigned) arguments
346   case DW_OP_bregx:       // 0x92 2 ULEB128 register followed by SLEB128 offset
347   case DW_OP_bit_piece:   // 0x9d ULEB128 bit size, ULEB128 bit offset (DWARF3);
348   case DW_OP_regval_type: // 0xa5 ULEB128 + ULEB128
349     data.Skip_LEB128(&offset);
350     data.Skip_LEB128(&offset);
351     return offset - data_offset;
352 
353   case DW_OP_implicit_value: // 0x9e ULEB128 size followed by block of that size
354                              // (DWARF4)
355   {
356     uint64_t block_len = data.Skip_LEB128(&offset);
357     offset += block_len;
358     return offset - data_offset;
359   }
360 
361   case DW_OP_implicit_pointer: // 0xa0 4-byte (or 8-byte for DWARF 64) constant
362                                // + LEB128
363   {
364     data.Skip_LEB128(&offset);
365     return DWARFUnit::GetAddressByteSize(dwarf_cu) + offset - data_offset;
366   }
367 
368   case DW_OP_GNU_entry_value:
369   case DW_OP_entry_value: // 0xa3 ULEB128 size + variable-length block
370   {
371     uint64_t subexpr_len = data.GetULEB128(&offset);
372     return (offset - data_offset) + subexpr_len;
373   }
374 
375   case DW_OP_const_type: // 0xa4 ULEB128 + size + variable-length block
376   {
377     data.Skip_LEB128(&offset);
378     uint8_t length = data.GetU8(&offset);
379     return (offset - data_offset) + length;
380   }
381 
382   case DW_OP_LLVM_user: // 0xe9: ULEB128 + variable length constant
383   {
384     uint64_t constants = data.GetULEB128(&offset);
385     return (offset - data_offset) + constants;
386   }
387   }
388 
389   if (dwarf_cu)
390     return dwarf_cu->GetSymbolFileDWARF().GetVendorDWARFOpcodeSize(
391         data, data_offset, op);
392 
393   return LLDB_INVALID_OFFSET;
394 }
395 
396 llvm::Expected<lldb::addr_t>
397 DWARFExpression::GetLocation_DW_OP_addr(const DWARFUnit *dwarf_cu) const {
398   lldb::offset_t offset = 0;
399   while (m_data.ValidOffset(offset)) {
400     const LocationAtom op = static_cast<LocationAtom>(m_data.GetU8(&offset));
401 
402     if (op == DW_OP_addr)
403       return m_data.GetAddress(&offset);
404 
405     if (op == DW_OP_GNU_addr_index || op == DW_OP_addrx) {
406       const uint64_t index = m_data.GetULEB128(&offset);
407       if (dwarf_cu)
408         return dwarf_cu->ReadAddressFromDebugAddrSection(index);
409       return llvm::createStringError("cannot evaluate %s without a DWARF unit",
410                                      DW_OP_value_to_name(op));
411     }
412 
413     const lldb::offset_t op_arg_size =
414         GetOpcodeDataSize(m_data, offset, op, dwarf_cu);
415     if (op_arg_size == LLDB_INVALID_OFFSET)
416       return llvm::createStringError("cannot get opcode data size for %s",
417                                      DW_OP_value_to_name(op));
418 
419     offset += op_arg_size;
420   }
421 
422   return LLDB_INVALID_ADDRESS;
423 }
424 
425 bool DWARFExpression::Update_DW_OP_addr(const DWARFUnit *dwarf_cu,
426                                         lldb::addr_t file_addr) {
427   lldb::offset_t offset = 0;
428   while (m_data.ValidOffset(offset)) {
429     const LocationAtom op = static_cast<LocationAtom>(m_data.GetU8(&offset));
430 
431     if (op == DW_OP_addr) {
432       const uint32_t addr_byte_size = m_data.GetAddressByteSize();
433       // We have to make a copy of the data as we don't know if this data is
434       // from a read only memory mapped buffer, so we duplicate all of the data
435       // first, then modify it, and if all goes well, we then replace the data
436       // for this expression
437 
438       // Make en encoder that contains a copy of the location expression data
439       // so we can write the address into the buffer using the correct byte
440       // order.
441       DataEncoder encoder(m_data.GetDataStart(), m_data.GetByteSize(),
442                           m_data.GetByteOrder(), addr_byte_size);
443 
444       // Replace the address in the new buffer
445       if (encoder.PutAddress(offset, file_addr) == UINT32_MAX)
446         return false;
447 
448       // All went well, so now we can reset the data using a shared pointer to
449       // the heap data so "m_data" will now correctly manage the heap data.
450       m_data.SetData(encoder.GetDataBuffer());
451       return true;
452     }
453     if (op == DW_OP_addrx) {
454       // Replace DW_OP_addrx with DW_OP_addr, since we can't modify the
455       // read-only debug_addr table.
456       // Subtract one to account for the opcode.
457       llvm::ArrayRef data_before_op = m_data.GetData().take_front(offset - 1);
458 
459       // Read the addrx index to determine how many bytes it needs.
460       const lldb::offset_t old_offset = offset;
461       m_data.GetULEB128(&offset);
462       if (old_offset == offset)
463         return false;
464       llvm::ArrayRef data_after_op = m_data.GetData().drop_front(offset);
465 
466       DataEncoder encoder(m_data.GetByteOrder(), m_data.GetAddressByteSize());
467       encoder.AppendData(data_before_op);
468       encoder.AppendU8(DW_OP_addr);
469       encoder.AppendAddress(file_addr);
470       encoder.AppendData(data_after_op);
471       m_data.SetData(encoder.GetDataBuffer());
472       return true;
473     }
474     const lldb::offset_t op_arg_size =
475         GetOpcodeDataSize(m_data, offset, op, dwarf_cu);
476     if (op_arg_size == LLDB_INVALID_OFFSET)
477       break;
478     offset += op_arg_size;
479   }
480   return false;
481 }
482 
483 bool DWARFExpression::ContainsThreadLocalStorage(
484     const DWARFUnit *dwarf_cu) const {
485   lldb::offset_t offset = 0;
486   while (m_data.ValidOffset(offset)) {
487     const LocationAtom op = static_cast<LocationAtom>(m_data.GetU8(&offset));
488 
489     if (op == DW_OP_form_tls_address || op == DW_OP_GNU_push_tls_address)
490       return true;
491     const lldb::offset_t op_arg_size =
492         GetOpcodeDataSize(m_data, offset, op, dwarf_cu);
493     if (op_arg_size == LLDB_INVALID_OFFSET)
494       return false;
495     offset += op_arg_size;
496   }
497   return false;
498 }
499 bool DWARFExpression::LinkThreadLocalStorage(
500     const DWARFUnit *dwarf_cu,
501     std::function<lldb::addr_t(lldb::addr_t file_addr)> const
502         &link_address_callback) {
503   const uint32_t addr_byte_size = m_data.GetAddressByteSize();
504   // We have to make a copy of the data as we don't know if this data is from a
505   // read only memory mapped buffer, so we duplicate all of the data first,
506   // then modify it, and if all goes well, we then replace the data for this
507   // expression.
508   // Make en encoder that contains a copy of the location expression data so we
509   // can write the address into the buffer using the correct byte order.
510   DataEncoder encoder(m_data.GetDataStart(), m_data.GetByteSize(),
511                       m_data.GetByteOrder(), addr_byte_size);
512 
513   lldb::offset_t offset = 0;
514   lldb::offset_t const_offset = 0;
515   lldb::addr_t const_value = 0;
516   size_t const_byte_size = 0;
517   while (m_data.ValidOffset(offset)) {
518     const LocationAtom op = static_cast<LocationAtom>(m_data.GetU8(&offset));
519 
520     bool decoded_data = false;
521     switch (op) {
522     case DW_OP_const4u:
523       // Remember the const offset in case we later have a
524       // DW_OP_form_tls_address or DW_OP_GNU_push_tls_address
525       const_offset = offset;
526       const_value = m_data.GetU32(&offset);
527       decoded_data = true;
528       const_byte_size = 4;
529       break;
530 
531     case DW_OP_const8u:
532       // Remember the const offset in case we later have a
533       // DW_OP_form_tls_address or DW_OP_GNU_push_tls_address
534       const_offset = offset;
535       const_value = m_data.GetU64(&offset);
536       decoded_data = true;
537       const_byte_size = 8;
538       break;
539 
540     case DW_OP_form_tls_address:
541     case DW_OP_GNU_push_tls_address:
542       // DW_OP_form_tls_address and DW_OP_GNU_push_tls_address must be preceded
543       // by a file address on the stack. We assume that DW_OP_const4u or
544       // DW_OP_const8u is used for these values, and we check that the last
545       // opcode we got before either of these was DW_OP_const4u or
546       // DW_OP_const8u. If so, then we can link the value accordingly. For
547       // Darwin, the value in the DW_OP_const4u or DW_OP_const8u is the file
548       // address of a structure that contains a function pointer, the pthread
549       // key and the offset into the data pointed to by the pthread key. So we
550       // must link this address and also set the module of this expression to
551       // the new_module_sp so we can resolve the file address correctly
552       if (const_byte_size > 0) {
553         lldb::addr_t linked_file_addr = link_address_callback(const_value);
554         if (linked_file_addr == LLDB_INVALID_ADDRESS)
555           return false;
556         // Replace the address in the new buffer
557         if (encoder.PutUnsigned(const_offset, const_byte_size,
558                                 linked_file_addr) == UINT32_MAX)
559           return false;
560       }
561       break;
562 
563     default:
564       const_offset = 0;
565       const_value = 0;
566       const_byte_size = 0;
567       break;
568     }
569 
570     if (!decoded_data) {
571       const lldb::offset_t op_arg_size =
572           GetOpcodeDataSize(m_data, offset, op, dwarf_cu);
573       if (op_arg_size == LLDB_INVALID_OFFSET)
574         return false;
575       else
576         offset += op_arg_size;
577     }
578   }
579 
580   m_data.SetData(encoder.GetDataBuffer());
581   return true;
582 }
583 
584 static llvm::Error Evaluate_DW_OP_entry_value(std::vector<Value> &stack,
585                                               ExecutionContext *exe_ctx,
586                                               RegisterContext *reg_ctx,
587                                               const DataExtractor &opcodes,
588                                               lldb::offset_t &opcode_offset,
589                                               Log *log) {
590   // DW_OP_entry_value(sub-expr) describes the location a variable had upon
591   // function entry: this variable location is presumed to be optimized out at
592   // the current PC value.  The caller of the function may have call site
593   // information that describes an alternate location for the variable (e.g. a
594   // constant literal, or a spilled stack value) in the parent frame.
595   //
596   // Example (this is pseudo-code & pseudo-DWARF, but hopefully illustrative):
597   //
598   //     void child(int &sink, int x) {
599   //       ...
600   //       /* "x" gets optimized out. */
601   //
602   //       /* The location of "x" here is: DW_OP_entry_value($reg2). */
603   //       ++sink;
604   //     }
605   //
606   //     void parent() {
607   //       int sink;
608   //
609   //       /*
610   //        * The callsite information emitted here is:
611   //        *
612   //        * DW_TAG_call_site
613   //        *   DW_AT_return_pc ... (for "child(sink, 123);")
614   //        *   DW_TAG_call_site_parameter (for "sink")
615   //        *     DW_AT_location   ($reg1)
616   //        *     DW_AT_call_value ($SP - 8)
617   //        *   DW_TAG_call_site_parameter (for "x")
618   //        *     DW_AT_location   ($reg2)
619   //        *     DW_AT_call_value ($literal 123)
620   //        *
621   //        * DW_TAG_call_site
622   //        *   DW_AT_return_pc ... (for "child(sink, 456);")
623   //        *   ...
624   //        */
625   //       child(sink, 123);
626   //       child(sink, 456);
627   //     }
628   //
629   // When the program stops at "++sink" within `child`, the debugger determines
630   // the call site by analyzing the return address. Once the call site is found,
631   // the debugger determines which parameter is referenced by DW_OP_entry_value
632   // and evaluates the corresponding location for that parameter in `parent`.
633 
634   // 1. Find the function which pushed the current frame onto the stack.
635   if ((!exe_ctx || !exe_ctx->HasTargetScope()) || !reg_ctx) {
636     return llvm::createStringError("no exe/reg context");
637   }
638 
639   StackFrame *current_frame = exe_ctx->GetFramePtr();
640   Thread *thread = exe_ctx->GetThreadPtr();
641   if (!current_frame || !thread)
642     return llvm::createStringError("no current frame/thread");
643 
644   Target &target = exe_ctx->GetTargetRef();
645   StackFrameSP parent_frame = nullptr;
646   addr_t return_pc = LLDB_INVALID_ADDRESS;
647   uint32_t current_frame_idx = current_frame->GetFrameIndex();
648 
649   for (uint32_t parent_frame_idx = current_frame_idx + 1;;parent_frame_idx++) {
650     parent_frame = thread->GetStackFrameAtIndex(parent_frame_idx);
651     // If this is null, we're at the end of the stack.
652     if (!parent_frame)
653       break;
654 
655     // Record the first valid return address, even if this is an inlined frame,
656     // in order to look up the associated call edge in the first non-inlined
657     // parent frame.
658     if (return_pc == LLDB_INVALID_ADDRESS) {
659       return_pc = parent_frame->GetFrameCodeAddress().GetLoadAddress(&target);
660       LLDB_LOG(log, "immediate ancestor with pc = {0:x}", return_pc);
661     }
662 
663     // If we've found an inlined frame, skip it (these have no call site
664     // parameters).
665     if (parent_frame->IsInlined())
666       continue;
667 
668     // We've found the first non-inlined parent frame.
669     break;
670   }
671   if (!parent_frame || !parent_frame->GetRegisterContext()) {
672     return llvm::createStringError("no parent frame with reg ctx");
673   }
674 
675   Function *parent_func =
676       parent_frame->GetSymbolContext(eSymbolContextFunction).function;
677   if (!parent_func)
678     return llvm::createStringError("no parent function");
679 
680   // 2. Find the call edge in the parent function responsible for creating the
681   //    current activation.
682   Function *current_func =
683       current_frame->GetSymbolContext(eSymbolContextFunction).function;
684   if (!current_func)
685     return llvm::createStringError("no current function");
686 
687   CallEdge *call_edge = nullptr;
688   ModuleList &modlist = target.GetImages();
689   ExecutionContext parent_exe_ctx = *exe_ctx;
690   parent_exe_ctx.SetFrameSP(parent_frame);
691   if (!parent_frame->IsArtificial()) {
692     // If the parent frame is not artificial, the current activation may be
693     // produced by an ambiguous tail call. In this case, refuse to proceed.
694     call_edge = parent_func->GetCallEdgeForReturnAddress(return_pc, target);
695     if (!call_edge) {
696       return llvm::createStringError(
697           llvm::formatv("no call edge for retn-pc = {0:x} in parent frame {1}",
698                         return_pc, parent_func->GetName()));
699     }
700     Function *callee_func = call_edge->GetCallee(modlist, parent_exe_ctx);
701     if (callee_func != current_func) {
702       return llvm::createStringError(
703           "ambiguous call sequence, can't find real parent frame");
704     }
705   } else {
706     // The StackFrameList solver machinery has deduced that an unambiguous tail
707     // call sequence that produced the current activation.  The first edge in
708     // the parent that points to the current function must be valid.
709     for (auto &edge : parent_func->GetTailCallingEdges()) {
710       if (edge->GetCallee(modlist, parent_exe_ctx) == current_func) {
711         call_edge = edge.get();
712         break;
713       }
714     }
715   }
716   if (!call_edge)
717     return llvm::createStringError("no unambiguous edge from parent "
718                                    "to current function");
719 
720   // 3. Attempt to locate the DW_OP_entry_value expression in the set of
721   //    available call site parameters. If found, evaluate the corresponding
722   //    parameter in the context of the parent frame.
723   const uint32_t subexpr_len = opcodes.GetULEB128(&opcode_offset);
724   const void *subexpr_data = opcodes.GetData(&opcode_offset, subexpr_len);
725   if (!subexpr_data)
726     return llvm::createStringError("subexpr could not be read");
727 
728   const CallSiteParameter *matched_param = nullptr;
729   for (const CallSiteParameter &param : call_edge->GetCallSiteParameters()) {
730     DataExtractor param_subexpr_extractor;
731     if (!param.LocationInCallee.GetExpressionData(param_subexpr_extractor))
732       continue;
733     lldb::offset_t param_subexpr_offset = 0;
734     const void *param_subexpr_data =
735         param_subexpr_extractor.GetData(&param_subexpr_offset, subexpr_len);
736     if (!param_subexpr_data ||
737         param_subexpr_extractor.BytesLeft(param_subexpr_offset) != 0)
738       continue;
739 
740     // At this point, the DW_OP_entry_value sub-expression and the callee-side
741     // expression in the call site parameter are known to have the same length.
742     // Check whether they are equal.
743     //
744     // Note that an equality check is sufficient: the contents of the
745     // DW_OP_entry_value subexpression are only used to identify the right call
746     // site parameter in the parent, and do not require any special handling.
747     if (memcmp(subexpr_data, param_subexpr_data, subexpr_len) == 0) {
748       matched_param = &param;
749       break;
750     }
751   }
752   if (!matched_param)
753     return llvm::createStringError("no matching call site param found");
754 
755   // TODO: Add support for DW_OP_push_object_address within a DW_OP_entry_value
756   // subexpresion whenever llvm does.
757   const DWARFExpressionList &param_expr = matched_param->LocationInCaller;
758 
759   llvm::Expected<Value> maybe_result = param_expr.Evaluate(
760       &parent_exe_ctx, parent_frame->GetRegisterContext().get(),
761       LLDB_INVALID_ADDRESS,
762       /*initial_value_ptr=*/nullptr,
763       /*object_address_ptr=*/nullptr);
764   if (!maybe_result) {
765     LLDB_LOG(log,
766              "Evaluate_DW_OP_entry_value: call site param evaluation failed");
767     return maybe_result.takeError();
768   }
769 
770   stack.push_back(*maybe_result);
771   return llvm::Error::success();
772 }
773 
774 namespace {
775 /// The location description kinds described by the DWARF v5
776 /// specification.  Composite locations are handled out-of-band and
777 /// thus aren't part of the enum.
778 enum LocationDescriptionKind {
779   Empty,
780   Memory,
781   Register,
782   Implicit
783   /* Composite*/
784 };
785 /// Adjust value's ValueType according to the kind of location description.
786 void UpdateValueTypeFromLocationDescription(Log *log, const DWARFUnit *dwarf_cu,
787                                             LocationDescriptionKind kind,
788                                             Value *value = nullptr) {
789   // Note that this function is conflating DWARF expressions with
790   // DWARF location descriptions. Perhaps it would be better to define
791   // a wrapper for DWARFExpression::Eval() that deals with DWARF
792   // location descriptions (which consist of one or more DWARF
793   // expressions). But doing this would mean we'd also need factor the
794   // handling of DW_OP_(bit_)piece out of this function.
795   if (dwarf_cu && dwarf_cu->GetVersion() >= 4) {
796     const char *log_msg = "DWARF location description kind: %s";
797     switch (kind) {
798     case Empty:
799       LLDB_LOGF(log, log_msg, "Empty");
800       break;
801     case Memory:
802       LLDB_LOGF(log, log_msg, "Memory");
803       if (value->GetValueType() == Value::ValueType::Scalar)
804         value->SetValueType(Value::ValueType::LoadAddress);
805       break;
806     case Register:
807       LLDB_LOGF(log, log_msg, "Register");
808       value->SetValueType(Value::ValueType::Scalar);
809       break;
810     case Implicit:
811       LLDB_LOGF(log, log_msg, "Implicit");
812       if (value->GetValueType() == Value::ValueType::LoadAddress)
813         value->SetValueType(Value::ValueType::Scalar);
814       break;
815     }
816   }
817 }
818 } // namespace
819 
820 /// Helper function to move common code used to resolve a file address and turn
821 /// into a load address.
822 ///
823 /// \param exe_ctx Pointer to the execution context
824 /// \param module_sp shared_ptr contains the module if we have one
825 /// \param dw_op_type C-style string used to vary the error output
826 /// \param file_addr the file address we are trying to resolve and turn into a
827 ///                  load address
828 /// \param so_addr out parameter, will be set to load address or section offset
829 /// \param check_sectionoffset bool which determines if having a section offset
830 ///                            but not a load address is considerd a success
831 /// \returns std::optional containing the load address if resolving and getting
832 ///          the load address succeed or an empty Optinal otherwise. If
833 ///          check_sectionoffset is true we consider LLDB_INVALID_ADDRESS a
834 ///          success if so_addr.IsSectionOffset() is true.
835 static llvm::Expected<lldb::addr_t>
836 ResolveLoadAddress(ExecutionContext *exe_ctx, lldb::ModuleSP &module_sp,
837                    const char *dw_op_type, lldb::addr_t file_addr,
838                    Address &so_addr, bool check_sectionoffset = false) {
839   if (!module_sp)
840     return llvm::createStringError("need module to resolve file address for %s",
841                                    dw_op_type);
842 
843   if (!module_sp->ResolveFileAddress(file_addr, so_addr))
844     return llvm::createStringError("failed to resolve file address in module");
845 
846   const addr_t load_addr = so_addr.GetLoadAddress(exe_ctx->GetTargetPtr());
847 
848   if (load_addr == LLDB_INVALID_ADDRESS &&
849       (check_sectionoffset && !so_addr.IsSectionOffset()))
850     return llvm::createStringError("failed to resolve load address");
851 
852   return load_addr;
853 }
854 
855 /// Helper function to move common code used to load sized data from a uint8_t
856 /// buffer.
857 ///
858 /// \param addr_bytes uint8_t buffer containg raw data
859 /// \param size_addr_bytes how large is the underlying raw data
860 /// \param byte_order what is the byter order of the underlyig data
861 /// \param size How much of the underlying data we want to use
862 /// \return The underlying data converted into a Scalar
863 static Scalar DerefSizeExtractDataHelper(uint8_t *addr_bytes,
864                                          size_t size_addr_bytes,
865                                          ByteOrder byte_order, size_t size) {
866   DataExtractor addr_data(addr_bytes, size_addr_bytes, byte_order, size);
867 
868   lldb::offset_t addr_data_offset = 0;
869   if (size <= 8)
870     return addr_data.GetMaxU64(&addr_data_offset, size);
871   else
872     return addr_data.GetAddress(&addr_data_offset);
873 }
874 
875 llvm::Expected<Value> DWARFExpression::Evaluate(
876     ExecutionContext *exe_ctx, RegisterContext *reg_ctx,
877     lldb::ModuleSP module_sp, const DataExtractor &opcodes,
878     const DWARFUnit *dwarf_cu, const lldb::RegisterKind reg_kind,
879     const Value *initial_value_ptr, const Value *object_address_ptr) {
880 
881   if (opcodes.GetByteSize() == 0)
882     return llvm::createStringError(
883         "no location, value may have been optimized out");
884   std::vector<Value> stack;
885 
886   Process *process = nullptr;
887   StackFrame *frame = nullptr;
888   Target *target = nullptr;
889 
890   if (exe_ctx) {
891     process = exe_ctx->GetProcessPtr();
892     frame = exe_ctx->GetFramePtr();
893     target = exe_ctx->GetTargetPtr();
894   }
895   if (reg_ctx == nullptr && frame)
896     reg_ctx = frame->GetRegisterContext().get();
897 
898   if (initial_value_ptr)
899     stack.push_back(*initial_value_ptr);
900 
901   lldb::offset_t offset = 0;
902   Value tmp;
903   uint32_t reg_num;
904 
905   /// Insertion point for evaluating multi-piece expression.
906   uint64_t op_piece_offset = 0;
907   Value pieces; // Used for DW_OP_piece
908 
909   Log *log = GetLog(LLDBLog::Expressions);
910   // A generic type is "an integral type that has the size of an address and an
911   // unspecified signedness". For now, just use the signedness of the operand.
912   // TODO: Implement a real typed stack, and store the genericness of the value
913   // there.
914   auto to_generic = [&](auto v) {
915     // TODO: Avoid implicit trunc?
916     // See https://github.com/llvm/llvm-project/issues/112510.
917     bool is_signed = std::is_signed<decltype(v)>::value;
918     return Scalar(llvm::APSInt(llvm::APInt(8 * opcodes.GetAddressByteSize(), v,
919                                            is_signed, /*implicitTrunc=*/true),
920                                !is_signed));
921   };
922 
923   // The default kind is a memory location. This is updated by any
924   // operation that changes this, such as DW_OP_stack_value, and reset
925   // by composition operations like DW_OP_piece.
926   LocationDescriptionKind dwarf4_location_description_kind = Memory;
927 
928   while (opcodes.ValidOffset(offset)) {
929     const lldb::offset_t op_offset = offset;
930     const uint8_t op = opcodes.GetU8(&offset);
931 
932     if (log && log->GetVerbose()) {
933       size_t count = stack.size();
934       LLDB_LOGF(log, "Stack before operation has %" PRIu64 " values:",
935                 (uint64_t)count);
936       for (size_t i = 0; i < count; ++i) {
937         StreamString new_value;
938         new_value.Printf("[%" PRIu64 "]", (uint64_t)i);
939         stack[i].Dump(&new_value);
940         LLDB_LOGF(log, "  %s", new_value.GetData());
941       }
942       LLDB_LOGF(log, "0x%8.8" PRIx64 ": %s", op_offset,
943                 DW_OP_value_to_name(op));
944     }
945 
946     if (std::optional<unsigned> arity =
947             llvm::dwarf::OperationArity(static_cast<LocationAtom>(op))) {
948       if (stack.size() < *arity)
949         return llvm::createStringError(
950             "%s needs at least %d stack entries (stack has %d entries)",
951             DW_OP_value_to_name(op), *arity, stack.size());
952     }
953 
954     switch (op) {
955     // The DW_OP_addr operation has a single operand that encodes a machine
956     // address and whose size is the size of an address on the target machine.
957     case DW_OP_addr:
958       stack.push_back(Scalar(opcodes.GetAddress(&offset)));
959       if (target &&
960           target->GetArchitecture().GetCore() == ArchSpec::eCore_wasm32) {
961         // wasm file sections aren't mapped into memory, therefore addresses can
962         // never point into a file section and are always LoadAddresses.
963         stack.back().SetValueType(Value::ValueType::LoadAddress);
964       } else {
965         stack.back().SetValueType(Value::ValueType::FileAddress);
966       }
967       break;
968 
969     // The DW_OP_addr_sect_offset4 is used for any location expressions in
970     // shared libraries that have a location like:
971     //  DW_OP_addr(0x1000)
972     // If this address resides in a shared library, then this virtual address
973     // won't make sense when it is evaluated in the context of a running
974     // process where shared libraries have been slid. To account for this, this
975     // new address type where we can store the section pointer and a 4 byte
976     // offset.
977     //      case DW_OP_addr_sect_offset4:
978     //          {
979     //              result_type = eResultTypeFileAddress;
980     //              lldb::Section *sect = (lldb::Section
981     //              *)opcodes.GetMaxU64(&offset, sizeof(void *));
982     //              lldb::addr_t sect_offset = opcodes.GetU32(&offset);
983     //
984     //              Address so_addr (sect, sect_offset);
985     //              lldb::addr_t load_addr = so_addr.GetLoadAddress();
986     //              if (load_addr != LLDB_INVALID_ADDRESS)
987     //              {
988     //                  // We successfully resolve a file address to a load
989     //                  // address.
990     //                  stack.push_back(load_addr);
991     //                  break;
992     //              }
993     //              else
994     //              {
995     //                  // We were able
996     //                  if (error_ptr)
997     //                      error_ptr->SetErrorStringWithFormat ("Section %s in
998     //                      %s is not currently loaded.\n",
999     //                      sect->GetName().AsCString(),
1000     //                      sect->GetModule()->GetFileSpec().GetFilename().AsCString());
1001     //                  return false;
1002     //              }
1003     //          }
1004     //          break;
1005 
1006     // OPCODE: DW_OP_deref
1007     // OPERANDS: none
1008     // DESCRIPTION: Pops the top stack entry and treats it as an address.
1009     // The value retrieved from that address is pushed. The size of the data
1010     // retrieved from the dereferenced address is the size of an address on the
1011     // target machine.
1012     case DW_OP_deref: {
1013       if (stack.empty())
1014         return llvm::createStringError(
1015             "expression stack empty for DW_OP_deref");
1016       Value::ValueType value_type = stack.back().GetValueType();
1017       switch (value_type) {
1018       case Value::ValueType::HostAddress: {
1019         void *src = (void *)stack.back().GetScalar().ULongLong();
1020         intptr_t ptr;
1021         ::memcpy(&ptr, src, sizeof(void *));
1022         stack.back().GetScalar() = ptr;
1023         stack.back().ClearContext();
1024       } break;
1025       case Value::ValueType::FileAddress: {
1026         auto file_addr = stack.back().GetScalar().ULongLong(
1027             LLDB_INVALID_ADDRESS);
1028 
1029         Address so_addr;
1030         auto maybe_load_addr = ResolveLoadAddress(
1031             exe_ctx, module_sp, "DW_OP_deref", file_addr, so_addr);
1032 
1033         if (!maybe_load_addr)
1034           return maybe_load_addr.takeError();
1035 
1036         stack.back().GetScalar() = *maybe_load_addr;
1037         // Fall through to load address promotion code below.
1038       }
1039         [[fallthrough]];
1040       case Value::ValueType::Scalar:
1041         // Promote Scalar to LoadAddress and fall through.
1042         stack.back().SetValueType(Value::ValueType::LoadAddress);
1043         [[fallthrough]];
1044       case Value::ValueType::LoadAddress:
1045         if (exe_ctx) {
1046           if (process) {
1047             lldb::addr_t pointer_addr =
1048                 stack.back().GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
1049             Status error;
1050             lldb::addr_t pointer_value =
1051                 process->ReadPointerFromMemory(pointer_addr, error);
1052             if (pointer_value != LLDB_INVALID_ADDRESS) {
1053               if (ABISP abi_sp = process->GetABI())
1054                 pointer_value = abi_sp->FixCodeAddress(pointer_value);
1055               stack.back().GetScalar() = pointer_value;
1056               stack.back().ClearContext();
1057             } else {
1058               return llvm::createStringError(
1059                   "Failed to dereference pointer from 0x%" PRIx64
1060                   " for DW_OP_deref: %s\n",
1061                   pointer_addr, error.AsCString());
1062             }
1063           } else {
1064             return llvm::createStringError("NULL process for DW_OP_deref");
1065           }
1066         } else {
1067           return llvm::createStringError(
1068               "NULL execution context for DW_OP_deref");
1069         }
1070         break;
1071 
1072       case Value::ValueType::Invalid:
1073         return llvm::createStringError("invalid value type for DW_OP_deref");
1074       }
1075 
1076     } break;
1077 
1078     // OPCODE: DW_OP_deref_size
1079     // OPERANDS: 1
1080     //  1 - uint8_t that specifies the size of the data to dereference.
1081     // DESCRIPTION: Behaves like the DW_OP_deref operation: it pops the top
1082     // stack entry and treats it as an address. The value retrieved from that
1083     // address is pushed. In the DW_OP_deref_size operation, however, the size
1084     // in bytes of the data retrieved from the dereferenced address is
1085     // specified by the single operand. This operand is a 1-byte unsigned
1086     // integral constant whose value may not be larger than the size of an
1087     // address on the target machine. The data retrieved is zero extended to
1088     // the size of an address on the target machine before being pushed on the
1089     // expression stack.
1090     case DW_OP_deref_size: {
1091       if (stack.empty()) {
1092         return llvm::createStringError(
1093             "expression stack empty for DW_OP_deref_size");
1094       }
1095       uint8_t size = opcodes.GetU8(&offset);
1096       if (size > 8) {
1097         return llvm::createStringError(
1098             "Invalid address size for DW_OP_deref_size: %d\n", size);
1099       }
1100       Value::ValueType value_type = stack.back().GetValueType();
1101       switch (value_type) {
1102       case Value::ValueType::HostAddress: {
1103         void *src = (void *)stack.back().GetScalar().ULongLong();
1104         intptr_t ptr;
1105         ::memcpy(&ptr, src, sizeof(void *));
1106         // I can't decide whether the size operand should apply to the bytes in
1107         // their
1108         // lldb-host endianness or the target endianness.. I doubt this'll ever
1109         // come up but I'll opt for assuming big endian regardless.
1110         switch (size) {
1111         case 1:
1112           ptr = ptr & 0xff;
1113           break;
1114         case 2:
1115           ptr = ptr & 0xffff;
1116           break;
1117         case 3:
1118           ptr = ptr & 0xffffff;
1119           break;
1120         case 4:
1121           ptr = ptr & 0xffffffff;
1122           break;
1123         // the casts are added to work around the case where intptr_t is a 32
1124         // bit quantity;
1125         // presumably we won't hit the 5..7 cases if (void*) is 32-bits in this
1126         // program.
1127         case 5:
1128           ptr = (intptr_t)ptr & 0xffffffffffULL;
1129           break;
1130         case 6:
1131           ptr = (intptr_t)ptr & 0xffffffffffffULL;
1132           break;
1133         case 7:
1134           ptr = (intptr_t)ptr & 0xffffffffffffffULL;
1135           break;
1136         default:
1137           break;
1138         }
1139         stack.back().GetScalar() = ptr;
1140         stack.back().ClearContext();
1141       } break;
1142       case Value::ValueType::FileAddress: {
1143         auto file_addr =
1144             stack.back().GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
1145         Address so_addr;
1146         auto maybe_load_addr = ResolveLoadAddress(
1147             exe_ctx, module_sp, "DW_OP_deref_size", file_addr, so_addr,
1148             /*check_sectionoffset=*/true);
1149 
1150         if (!maybe_load_addr)
1151           return maybe_load_addr.takeError();
1152 
1153         addr_t load_addr = *maybe_load_addr;
1154 
1155         if (load_addr == LLDB_INVALID_ADDRESS && so_addr.IsSectionOffset()) {
1156           uint8_t addr_bytes[8];
1157           Status error;
1158 
1159           if (target &&
1160               target->ReadMemory(so_addr, &addr_bytes, size, error,
1161                                  /*force_live_memory=*/false) == size) {
1162             ObjectFile *objfile = module_sp->GetObjectFile();
1163 
1164             stack.back().GetScalar() = DerefSizeExtractDataHelper(
1165                 addr_bytes, size, objfile->GetByteOrder(), size);
1166             stack.back().ClearContext();
1167             break;
1168           } else {
1169             return llvm::createStringError(
1170                 "Failed to dereference pointer for DW_OP_deref_size: "
1171                 "%s\n",
1172                 error.AsCString());
1173           }
1174         }
1175         stack.back().GetScalar() = load_addr;
1176         // Fall through to load address promotion code below.
1177       }
1178 
1179         [[fallthrough]];
1180       case Value::ValueType::Scalar:
1181       case Value::ValueType::LoadAddress:
1182         if (exe_ctx) {
1183           if (process) {
1184             lldb::addr_t pointer_addr =
1185                 stack.back().GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
1186             uint8_t addr_bytes[sizeof(lldb::addr_t)];
1187             Status error;
1188             if (process->ReadMemory(pointer_addr, &addr_bytes, size, error) ==
1189                 size) {
1190 
1191               stack.back().GetScalar() =
1192                   DerefSizeExtractDataHelper(addr_bytes, sizeof(addr_bytes),
1193                                              process->GetByteOrder(), size);
1194               stack.back().ClearContext();
1195             } else {
1196               return llvm::createStringError(
1197                   "Failed to dereference pointer from 0x%" PRIx64
1198                   " for DW_OP_deref: %s\n",
1199                   pointer_addr, error.AsCString());
1200             }
1201           } else {
1202 
1203             return llvm::createStringError("NULL process for DW_OP_deref_size");
1204           }
1205         } else {
1206           return llvm::createStringError(
1207               "NULL execution context for DW_OP_deref_size");
1208         }
1209         break;
1210 
1211       case Value::ValueType::Invalid:
1212 
1213         return llvm::createStringError("invalid value for DW_OP_deref_size");
1214       }
1215 
1216     } break;
1217 
1218     // OPCODE: DW_OP_xderef_size
1219     // OPERANDS: 1
1220     //  1 - uint8_t that specifies the size of the data to dereference.
1221     // DESCRIPTION: Behaves like the DW_OP_xderef operation: the entry at
1222     // the top of the stack is treated as an address. The second stack entry is
1223     // treated as an "address space identifier" for those architectures that
1224     // support multiple address spaces. The top two stack elements are popped,
1225     // a data item is retrieved through an implementation-defined address
1226     // calculation and pushed as the new stack top. In the DW_OP_xderef_size
1227     // operation, however, the size in bytes of the data retrieved from the
1228     // dereferenced address is specified by the single operand. This operand is
1229     // a 1-byte unsigned integral constant whose value may not be larger than
1230     // the size of an address on the target machine. The data retrieved is zero
1231     // extended to the size of an address on the target machine before being
1232     // pushed on the expression stack.
1233     case DW_OP_xderef_size:
1234       return llvm::createStringError("unimplemented opcode: DW_OP_xderef_size");
1235     // OPCODE: DW_OP_xderef
1236     // OPERANDS: none
1237     // DESCRIPTION: Provides an extended dereference mechanism. The entry at
1238     // the top of the stack is treated as an address. The second stack entry is
1239     // treated as an "address space identifier" for those architectures that
1240     // support multiple address spaces. The top two stack elements are popped,
1241     // a data item is retrieved through an implementation-defined address
1242     // calculation and pushed as the new stack top. The size of the data
1243     // retrieved from the dereferenced address is the size of an address on the
1244     // target machine.
1245     case DW_OP_xderef:
1246       return llvm::createStringError("unimplemented opcode: DW_OP_xderef");
1247 
1248     // All DW_OP_constXXX opcodes have a single operand as noted below:
1249     //
1250     // Opcode           Operand 1
1251     // DW_OP_const1u    1-byte unsigned integer constant
1252     // DW_OP_const1s    1-byte signed integer constant
1253     // DW_OP_const2u    2-byte unsigned integer constant
1254     // DW_OP_const2s    2-byte signed integer constant
1255     // DW_OP_const4u    4-byte unsigned integer constant
1256     // DW_OP_const4s    4-byte signed integer constant
1257     // DW_OP_const8u    8-byte unsigned integer constant
1258     // DW_OP_const8s    8-byte signed integer constant
1259     // DW_OP_constu     unsigned LEB128 integer constant
1260     // DW_OP_consts     signed LEB128 integer constant
1261     case DW_OP_const1u:
1262       stack.push_back(to_generic(opcodes.GetU8(&offset)));
1263       break;
1264     case DW_OP_const1s:
1265       stack.push_back(to_generic((int8_t)opcodes.GetU8(&offset)));
1266       break;
1267     case DW_OP_const2u:
1268       stack.push_back(to_generic(opcodes.GetU16(&offset)));
1269       break;
1270     case DW_OP_const2s:
1271       stack.push_back(to_generic((int16_t)opcodes.GetU16(&offset)));
1272       break;
1273     case DW_OP_const4u:
1274       stack.push_back(to_generic(opcodes.GetU32(&offset)));
1275       break;
1276     case DW_OP_const4s:
1277       stack.push_back(to_generic((int32_t)opcodes.GetU32(&offset)));
1278       break;
1279     case DW_OP_const8u:
1280       stack.push_back(to_generic(opcodes.GetU64(&offset)));
1281       break;
1282     case DW_OP_const8s:
1283       stack.push_back(to_generic((int64_t)opcodes.GetU64(&offset)));
1284       break;
1285     // These should also use to_generic, but we can't do that due to a
1286     // producer-side bug in llvm. See llvm.org/pr48087.
1287     case DW_OP_constu:
1288       stack.push_back(Scalar(opcodes.GetULEB128(&offset)));
1289       break;
1290     case DW_OP_consts:
1291       stack.push_back(Scalar(opcodes.GetSLEB128(&offset)));
1292       break;
1293 
1294     // OPCODE: DW_OP_dup
1295     // OPERANDS: none
1296     // DESCRIPTION: duplicates the value at the top of the stack
1297     case DW_OP_dup:
1298       if (stack.empty()) {
1299         return llvm::createStringError("expression stack empty for DW_OP_dup");
1300       } else
1301         stack.push_back(stack.back());
1302       break;
1303 
1304     // OPCODE: DW_OP_drop
1305     // OPERANDS: none
1306     // DESCRIPTION: pops the value at the top of the stack
1307     case DW_OP_drop:
1308       if (stack.empty()) {
1309         return llvm::createStringError("expression stack empty for DW_OP_drop");
1310       } else
1311         stack.pop_back();
1312       break;
1313 
1314     // OPCODE: DW_OP_over
1315     // OPERANDS: none
1316     // DESCRIPTION: Duplicates the entry currently second in the stack at
1317     // the top of the stack.
1318     case DW_OP_over:
1319       stack.push_back(stack[stack.size() - 2]);
1320       break;
1321 
1322     // OPCODE: DW_OP_pick
1323     // OPERANDS: uint8_t index into the current stack
1324     // DESCRIPTION: The stack entry with the specified index (0 through 255,
1325     // inclusive) is pushed on the stack
1326     case DW_OP_pick: {
1327       uint8_t pick_idx = opcodes.GetU8(&offset);
1328       if (pick_idx < stack.size())
1329         stack.push_back(stack[stack.size() - 1 - pick_idx]);
1330       else {
1331         return llvm::createStringError(
1332             "Index %u out of range for DW_OP_pick.\n", pick_idx);
1333       }
1334     } break;
1335 
1336     // OPCODE: DW_OP_swap
1337     // OPERANDS: none
1338     // DESCRIPTION: swaps the top two stack entries. The entry at the top
1339     // of the stack becomes the second stack entry, and the second entry
1340     // becomes the top of the stack
1341     case DW_OP_swap:
1342       tmp = stack.back();
1343       stack.back() = stack[stack.size() - 2];
1344       stack[stack.size() - 2] = tmp;
1345       break;
1346 
1347     // OPCODE: DW_OP_rot
1348     // OPERANDS: none
1349     // DESCRIPTION: Rotates the first three stack entries. The entry at
1350     // the top of the stack becomes the third stack entry, the second entry
1351     // becomes the top of the stack, and the third entry becomes the second
1352     // entry.
1353     case DW_OP_rot: {
1354       size_t last_idx = stack.size() - 1;
1355       Value old_top = stack[last_idx];
1356       stack[last_idx] = stack[last_idx - 1];
1357       stack[last_idx - 1] = stack[last_idx - 2];
1358       stack[last_idx - 2] = old_top;
1359     } break;
1360 
1361     // OPCODE: DW_OP_abs
1362     // OPERANDS: none
1363     // DESCRIPTION: pops the top stack entry, interprets it as a signed
1364     // value and pushes its absolute value. If the absolute value can not be
1365     // represented, the result is undefined.
1366     case DW_OP_abs:
1367       if (!stack.back().ResolveValue(exe_ctx).AbsoluteValue()) {
1368         return llvm::createStringError(
1369             "failed to take the absolute value of the first stack item");
1370       }
1371       break;
1372 
1373     // OPCODE: DW_OP_and
1374     // OPERANDS: none
1375     // DESCRIPTION: pops the top two stack values, performs a bitwise and
1376     // operation on the two, and pushes the result.
1377     case DW_OP_and:
1378       tmp = stack.back();
1379       stack.pop_back();
1380       stack.back().ResolveValue(exe_ctx) =
1381           stack.back().ResolveValue(exe_ctx) & tmp.ResolveValue(exe_ctx);
1382       break;
1383 
1384     // OPCODE: DW_OP_div
1385     // OPERANDS: none
1386     // DESCRIPTION: pops the top two stack values, divides the former second
1387     // entry by the former top of the stack using signed division, and pushes
1388     // the result.
1389     case DW_OP_div: {
1390       tmp = stack.back();
1391       if (tmp.ResolveValue(exe_ctx).IsZero())
1392         return llvm::createStringError("divide by zero");
1393 
1394       stack.pop_back();
1395       Scalar divisor, dividend;
1396       divisor = tmp.ResolveValue(exe_ctx);
1397       dividend = stack.back().ResolveValue(exe_ctx);
1398       divisor.MakeSigned();
1399       dividend.MakeSigned();
1400       stack.back() = dividend / divisor;
1401 
1402       if (!stack.back().ResolveValue(exe_ctx).IsValid())
1403         return llvm::createStringError("divide failed");
1404     } break;
1405 
1406     // OPCODE: DW_OP_minus
1407     // OPERANDS: none
1408     // DESCRIPTION: pops the top two stack values, subtracts the former top
1409     // of the stack from the former second entry, and pushes the result.
1410     case DW_OP_minus:
1411       tmp = stack.back();
1412       stack.pop_back();
1413       stack.back().ResolveValue(exe_ctx) =
1414           stack.back().ResolveValue(exe_ctx) - tmp.ResolveValue(exe_ctx);
1415       break;
1416 
1417     // OPCODE: DW_OP_mod
1418     // OPERANDS: none
1419     // DESCRIPTION: pops the top two stack values and pushes the result of
1420     // the calculation: former second stack entry modulo the former top of the
1421     // stack.
1422     case DW_OP_mod:
1423       tmp = stack.back();
1424       stack.pop_back();
1425       stack.back().ResolveValue(exe_ctx) =
1426           stack.back().ResolveValue(exe_ctx) % tmp.ResolveValue(exe_ctx);
1427       break;
1428 
1429     // OPCODE: DW_OP_mul
1430     // OPERANDS: none
1431     // DESCRIPTION: pops the top two stack entries, multiplies them
1432     // together, and pushes the result.
1433     case DW_OP_mul:
1434       tmp = stack.back();
1435       stack.pop_back();
1436       stack.back().ResolveValue(exe_ctx) =
1437           stack.back().ResolveValue(exe_ctx) * tmp.ResolveValue(exe_ctx);
1438       break;
1439 
1440     // OPCODE: DW_OP_neg
1441     // OPERANDS: none
1442     // DESCRIPTION: pops the top stack entry, and pushes its negation.
1443     case DW_OP_neg:
1444       if (!stack.back().ResolveValue(exe_ctx).UnaryNegate())
1445         return llvm::createStringError("unary negate failed");
1446       break;
1447 
1448     // OPCODE: DW_OP_not
1449     // OPERANDS: none
1450     // DESCRIPTION: pops the top stack entry, and pushes its bitwise
1451     // complement
1452     case DW_OP_not:
1453       if (!stack.back().ResolveValue(exe_ctx).OnesComplement())
1454         return llvm::createStringError("logical NOT failed");
1455       break;
1456 
1457     // OPCODE: DW_OP_or
1458     // OPERANDS: none
1459     // DESCRIPTION: pops the top two stack entries, performs a bitwise or
1460     // operation on the two, and pushes the result.
1461     case DW_OP_or:
1462       tmp = stack.back();
1463       stack.pop_back();
1464       stack.back().ResolveValue(exe_ctx) =
1465           stack.back().ResolveValue(exe_ctx) | tmp.ResolveValue(exe_ctx);
1466       break;
1467 
1468     // OPCODE: DW_OP_plus
1469     // OPERANDS: none
1470     // DESCRIPTION: pops the top two stack entries, adds them together, and
1471     // pushes the result.
1472     case DW_OP_plus:
1473       tmp = stack.back();
1474       stack.pop_back();
1475       stack.back().GetScalar() += tmp.GetScalar();
1476       break;
1477 
1478     // OPCODE: DW_OP_plus_uconst
1479     // OPERANDS: none
1480     // DESCRIPTION: pops the top stack entry, adds it to the unsigned LEB128
1481     // constant operand and pushes the result.
1482     case DW_OP_plus_uconst: {
1483       const uint64_t uconst_value = opcodes.GetULEB128(&offset);
1484       // Implicit conversion from a UINT to a Scalar...
1485       stack.back().GetScalar() += uconst_value;
1486       if (!stack.back().GetScalar().IsValid())
1487         return llvm::createStringError("DW_OP_plus_uconst failed");
1488     } break;
1489 
1490     // OPCODE: DW_OP_shl
1491     // OPERANDS: none
1492     // DESCRIPTION:  pops the top two stack entries, shifts the former
1493     // second entry left by the number of bits specified by the former top of
1494     // the stack, and pushes the result.
1495     case DW_OP_shl:
1496       tmp = stack.back();
1497       stack.pop_back();
1498       stack.back().ResolveValue(exe_ctx) <<= tmp.ResolveValue(exe_ctx);
1499       break;
1500 
1501     // OPCODE: DW_OP_shr
1502     // OPERANDS: none
1503     // DESCRIPTION: pops the top two stack entries, shifts the former second
1504     // entry right logically (filling with zero bits) by the number of bits
1505     // specified by the former top of the stack, and pushes the result.
1506     case DW_OP_shr:
1507       tmp = stack.back();
1508       stack.pop_back();
1509       if (!stack.back().ResolveValue(exe_ctx).ShiftRightLogical(
1510               tmp.ResolveValue(exe_ctx)))
1511         return llvm::createStringError("DW_OP_shr failed");
1512       break;
1513 
1514     // OPCODE: DW_OP_shra
1515     // OPERANDS: none
1516     // DESCRIPTION: pops the top two stack entries, shifts the former second
1517     // entry right arithmetically (divide the magnitude by 2, keep the same
1518     // sign for the result) by the number of bits specified by the former top
1519     // of the stack, and pushes the result.
1520     case DW_OP_shra:
1521       tmp = stack.back();
1522       stack.pop_back();
1523       stack.back().ResolveValue(exe_ctx) >>= tmp.ResolveValue(exe_ctx);
1524       break;
1525 
1526     // OPCODE: DW_OP_xor
1527     // OPERANDS: none
1528     // DESCRIPTION: pops the top two stack entries, performs the bitwise
1529     // exclusive-or operation on the two, and pushes the result.
1530     case DW_OP_xor:
1531       tmp = stack.back();
1532       stack.pop_back();
1533       stack.back().ResolveValue(exe_ctx) =
1534           stack.back().ResolveValue(exe_ctx) ^ tmp.ResolveValue(exe_ctx);
1535       break;
1536 
1537     // OPCODE: DW_OP_skip
1538     // OPERANDS: int16_t
1539     // DESCRIPTION:  An unconditional branch. Its single operand is a 2-byte
1540     // signed integer constant. The 2-byte constant is the number of bytes of
1541     // the DWARF expression to skip forward or backward from the current
1542     // operation, beginning after the 2-byte constant.
1543     case DW_OP_skip: {
1544       int16_t skip_offset = (int16_t)opcodes.GetU16(&offset);
1545       lldb::offset_t new_offset = offset + skip_offset;
1546       // New offset can point at the end of the data, in this case we should
1547       // terminate the DWARF expression evaluation (will happen in the loop
1548       // condition).
1549       if (new_offset <= opcodes.GetByteSize())
1550         offset = new_offset;
1551       else {
1552         return llvm::createStringError(llvm::formatv(
1553             "Invalid opcode offset in DW_OP_skip: {0}+({1}) > {2}", offset,
1554             skip_offset, opcodes.GetByteSize()));
1555       }
1556     } break;
1557 
1558     // OPCODE: DW_OP_bra
1559     // OPERANDS: int16_t
1560     // DESCRIPTION: A conditional branch. Its single operand is a 2-byte
1561     // signed integer constant. This operation pops the top of stack. If the
1562     // value popped is not the constant 0, the 2-byte constant operand is the
1563     // number of bytes of the DWARF expression to skip forward or backward from
1564     // the current operation, beginning after the 2-byte constant.
1565     case DW_OP_bra: {
1566       tmp = stack.back();
1567       stack.pop_back();
1568       int16_t bra_offset = (int16_t)opcodes.GetU16(&offset);
1569       Scalar zero(0);
1570       if (tmp.ResolveValue(exe_ctx) != zero) {
1571         lldb::offset_t new_offset = offset + bra_offset;
1572         // New offset can point at the end of the data, in this case we should
1573         // terminate the DWARF expression evaluation (will happen in the loop
1574         // condition).
1575         if (new_offset <= opcodes.GetByteSize())
1576           offset = new_offset;
1577         else {
1578           return llvm::createStringError(llvm::formatv(
1579               "Invalid opcode offset in DW_OP_bra: {0}+({1}) > {2}", offset,
1580               bra_offset, opcodes.GetByteSize()));
1581         }
1582       }
1583     } break;
1584 
1585     // OPCODE: DW_OP_eq
1586     // OPERANDS: none
1587     // DESCRIPTION: pops the top two stack values, compares using the
1588     // equals (==) operator.
1589     // STACK RESULT: push the constant value 1 onto the stack if the result
1590     // of the operation is true or the constant value 0 if the result of the
1591     // operation is false.
1592     case DW_OP_eq:
1593       tmp = stack.back();
1594       stack.pop_back();
1595       stack.back().ResolveValue(exe_ctx) =
1596           stack.back().ResolveValue(exe_ctx) == tmp.ResolveValue(exe_ctx);
1597       break;
1598 
1599     // OPCODE: DW_OP_ge
1600     // OPERANDS: none
1601     // DESCRIPTION: pops the top two stack values, compares using the
1602     // greater than or equal to (>=) operator.
1603     // STACK RESULT: push the constant value 1 onto the stack if the result
1604     // of the operation is true or the constant value 0 if the result of the
1605     // operation is false.
1606     case DW_OP_ge:
1607       tmp = stack.back();
1608       stack.pop_back();
1609       stack.back().ResolveValue(exe_ctx) =
1610           stack.back().ResolveValue(exe_ctx) >= tmp.ResolveValue(exe_ctx);
1611       break;
1612 
1613     // OPCODE: DW_OP_gt
1614     // OPERANDS: none
1615     // DESCRIPTION: pops the top two stack values, compares using the
1616     // greater than (>) operator.
1617     // STACK RESULT: push the constant value 1 onto the stack if the result
1618     // of the operation is true or the constant value 0 if the result of the
1619     // operation is false.
1620     case DW_OP_gt:
1621       tmp = stack.back();
1622       stack.pop_back();
1623       stack.back().ResolveValue(exe_ctx) =
1624           stack.back().ResolveValue(exe_ctx) > tmp.ResolveValue(exe_ctx);
1625       break;
1626 
1627     // OPCODE: DW_OP_le
1628     // OPERANDS: none
1629     // DESCRIPTION: pops the top two stack values, compares using the
1630     // less than or equal to (<=) operator.
1631     // STACK RESULT: push the constant value 1 onto the stack if the result
1632     // of the operation is true or the constant value 0 if the result of the
1633     // operation is false.
1634     case DW_OP_le:
1635       tmp = stack.back();
1636       stack.pop_back();
1637       stack.back().ResolveValue(exe_ctx) =
1638           stack.back().ResolveValue(exe_ctx) <= tmp.ResolveValue(exe_ctx);
1639       break;
1640 
1641     // OPCODE: DW_OP_lt
1642     // OPERANDS: none
1643     // DESCRIPTION: pops the top two stack values, compares using the
1644     // less than (<) operator.
1645     // STACK RESULT: push the constant value 1 onto the stack if the result
1646     // of the operation is true or the constant value 0 if the result of the
1647     // operation is false.
1648     case DW_OP_lt:
1649       tmp = stack.back();
1650       stack.pop_back();
1651       stack.back().ResolveValue(exe_ctx) =
1652           stack.back().ResolveValue(exe_ctx) < tmp.ResolveValue(exe_ctx);
1653       break;
1654 
1655     // OPCODE: DW_OP_ne
1656     // OPERANDS: none
1657     // DESCRIPTION: pops the top two stack values, compares using the
1658     // not equal (!=) operator.
1659     // STACK RESULT: push the constant value 1 onto the stack if the result
1660     // of the operation is true or the constant value 0 if the result of the
1661     // operation is false.
1662     case DW_OP_ne:
1663       tmp = stack.back();
1664       stack.pop_back();
1665       stack.back().ResolveValue(exe_ctx) =
1666           stack.back().ResolveValue(exe_ctx) != tmp.ResolveValue(exe_ctx);
1667       break;
1668 
1669     // OPCODE: DW_OP_litn
1670     // OPERANDS: none
1671     // DESCRIPTION: encode the unsigned literal values from 0 through 31.
1672     // STACK RESULT: push the unsigned literal constant value onto the top
1673     // of the stack.
1674     case DW_OP_lit0:
1675     case DW_OP_lit1:
1676     case DW_OP_lit2:
1677     case DW_OP_lit3:
1678     case DW_OP_lit4:
1679     case DW_OP_lit5:
1680     case DW_OP_lit6:
1681     case DW_OP_lit7:
1682     case DW_OP_lit8:
1683     case DW_OP_lit9:
1684     case DW_OP_lit10:
1685     case DW_OP_lit11:
1686     case DW_OP_lit12:
1687     case DW_OP_lit13:
1688     case DW_OP_lit14:
1689     case DW_OP_lit15:
1690     case DW_OP_lit16:
1691     case DW_OP_lit17:
1692     case DW_OP_lit18:
1693     case DW_OP_lit19:
1694     case DW_OP_lit20:
1695     case DW_OP_lit21:
1696     case DW_OP_lit22:
1697     case DW_OP_lit23:
1698     case DW_OP_lit24:
1699     case DW_OP_lit25:
1700     case DW_OP_lit26:
1701     case DW_OP_lit27:
1702     case DW_OP_lit28:
1703     case DW_OP_lit29:
1704     case DW_OP_lit30:
1705     case DW_OP_lit31:
1706       stack.push_back(to_generic(op - DW_OP_lit0));
1707       break;
1708 
1709     // OPCODE: DW_OP_regN
1710     // OPERANDS: none
1711     // DESCRIPTION: Push the value in register n on the top of the stack.
1712     case DW_OP_reg0:
1713     case DW_OP_reg1:
1714     case DW_OP_reg2:
1715     case DW_OP_reg3:
1716     case DW_OP_reg4:
1717     case DW_OP_reg5:
1718     case DW_OP_reg6:
1719     case DW_OP_reg7:
1720     case DW_OP_reg8:
1721     case DW_OP_reg9:
1722     case DW_OP_reg10:
1723     case DW_OP_reg11:
1724     case DW_OP_reg12:
1725     case DW_OP_reg13:
1726     case DW_OP_reg14:
1727     case DW_OP_reg15:
1728     case DW_OP_reg16:
1729     case DW_OP_reg17:
1730     case DW_OP_reg18:
1731     case DW_OP_reg19:
1732     case DW_OP_reg20:
1733     case DW_OP_reg21:
1734     case DW_OP_reg22:
1735     case DW_OP_reg23:
1736     case DW_OP_reg24:
1737     case DW_OP_reg25:
1738     case DW_OP_reg26:
1739     case DW_OP_reg27:
1740     case DW_OP_reg28:
1741     case DW_OP_reg29:
1742     case DW_OP_reg30:
1743     case DW_OP_reg31: {
1744       dwarf4_location_description_kind = Register;
1745       reg_num = op - DW_OP_reg0;
1746 
1747       if (llvm::Error err =
1748               ReadRegisterValueAsScalar(reg_ctx, reg_kind, reg_num, tmp))
1749         return err;
1750       stack.push_back(tmp);
1751     } break;
1752     // OPCODE: DW_OP_regx
1753     // OPERANDS:
1754     //      ULEB128 literal operand that encodes the register.
1755     // DESCRIPTION: Push the value in register on the top of the stack.
1756     case DW_OP_regx: {
1757       dwarf4_location_description_kind = Register;
1758       reg_num = opcodes.GetULEB128(&offset);
1759       Status read_err;
1760       if (llvm::Error err =
1761               ReadRegisterValueAsScalar(reg_ctx, reg_kind, reg_num, tmp))
1762         return err;
1763       stack.push_back(tmp);
1764     } break;
1765 
1766     // OPCODE: DW_OP_bregN
1767     // OPERANDS:
1768     //      SLEB128 offset from register N
1769     // DESCRIPTION: Value is in memory at the address specified by register
1770     // N plus an offset.
1771     case DW_OP_breg0:
1772     case DW_OP_breg1:
1773     case DW_OP_breg2:
1774     case DW_OP_breg3:
1775     case DW_OP_breg4:
1776     case DW_OP_breg5:
1777     case DW_OP_breg6:
1778     case DW_OP_breg7:
1779     case DW_OP_breg8:
1780     case DW_OP_breg9:
1781     case DW_OP_breg10:
1782     case DW_OP_breg11:
1783     case DW_OP_breg12:
1784     case DW_OP_breg13:
1785     case DW_OP_breg14:
1786     case DW_OP_breg15:
1787     case DW_OP_breg16:
1788     case DW_OP_breg17:
1789     case DW_OP_breg18:
1790     case DW_OP_breg19:
1791     case DW_OP_breg20:
1792     case DW_OP_breg21:
1793     case DW_OP_breg22:
1794     case DW_OP_breg23:
1795     case DW_OP_breg24:
1796     case DW_OP_breg25:
1797     case DW_OP_breg26:
1798     case DW_OP_breg27:
1799     case DW_OP_breg28:
1800     case DW_OP_breg29:
1801     case DW_OP_breg30:
1802     case DW_OP_breg31: {
1803       reg_num = op - DW_OP_breg0;
1804       if (llvm::Error err =
1805               ReadRegisterValueAsScalar(reg_ctx, reg_kind, reg_num, tmp))
1806         return err;
1807 
1808       int64_t breg_offset = opcodes.GetSLEB128(&offset);
1809       tmp.ResolveValue(exe_ctx) += (uint64_t)breg_offset;
1810       tmp.ClearContext();
1811       stack.push_back(tmp);
1812       stack.back().SetValueType(Value::ValueType::LoadAddress);
1813     } break;
1814     // OPCODE: DW_OP_bregx
1815     // OPERANDS: 2
1816     //      ULEB128 literal operand that encodes the register.
1817     //      SLEB128 offset from register N
1818     // DESCRIPTION: Value is in memory at the address specified by register
1819     // N plus an offset.
1820     case DW_OP_bregx: {
1821       reg_num = opcodes.GetULEB128(&offset);
1822       if (llvm::Error err =
1823               ReadRegisterValueAsScalar(reg_ctx, reg_kind, reg_num, tmp))
1824         return err;
1825 
1826       int64_t breg_offset = opcodes.GetSLEB128(&offset);
1827       tmp.ResolveValue(exe_ctx) += (uint64_t)breg_offset;
1828       tmp.ClearContext();
1829       stack.push_back(tmp);
1830       stack.back().SetValueType(Value::ValueType::LoadAddress);
1831     } break;
1832 
1833     case DW_OP_fbreg:
1834       if (exe_ctx) {
1835         if (frame) {
1836           Scalar value;
1837           if (llvm::Error err = frame->GetFrameBaseValue(value))
1838             return err;
1839           int64_t fbreg_offset = opcodes.GetSLEB128(&offset);
1840           value += fbreg_offset;
1841           stack.push_back(value);
1842           stack.back().SetValueType(Value::ValueType::LoadAddress);
1843         } else {
1844           return llvm::createStringError(
1845               "invalid stack frame in context for DW_OP_fbreg opcode");
1846         }
1847       } else {
1848         return llvm::createStringError(
1849             "NULL execution context for DW_OP_fbreg");
1850       }
1851 
1852       break;
1853 
1854     // OPCODE: DW_OP_nop
1855     // OPERANDS: none
1856     // DESCRIPTION: A place holder. It has no effect on the location stack
1857     // or any of its values.
1858     case DW_OP_nop:
1859       break;
1860 
1861     // OPCODE: DW_OP_piece
1862     // OPERANDS: 1
1863     //      ULEB128: byte size of the piece
1864     // DESCRIPTION: The operand describes the size in bytes of the piece of
1865     // the object referenced by the DWARF expression whose result is at the top
1866     // of the stack. If the piece is located in a register, but does not occupy
1867     // the entire register, the placement of the piece within that register is
1868     // defined by the ABI.
1869     //
1870     // Many compilers store a single variable in sets of registers, or store a
1871     // variable partially in memory and partially in registers. DW_OP_piece
1872     // provides a way of describing how large a part of a variable a particular
1873     // DWARF expression refers to.
1874     case DW_OP_piece: {
1875       LocationDescriptionKind piece_locdesc = dwarf4_location_description_kind;
1876       // Reset for the next piece.
1877       dwarf4_location_description_kind = Memory;
1878 
1879       const uint64_t piece_byte_size = opcodes.GetULEB128(&offset);
1880 
1881       if (piece_byte_size > 0) {
1882         Value curr_piece;
1883 
1884         if (stack.empty()) {
1885           UpdateValueTypeFromLocationDescription(
1886               log, dwarf_cu, LocationDescriptionKind::Empty);
1887           // In a multi-piece expression, this means that the current piece is
1888           // not available. Fill with zeros for now by resizing the data and
1889           // appending it
1890           curr_piece.ResizeData(piece_byte_size);
1891           // Note that "0" is not a correct value for the unknown bits.
1892           // It would be better to also return a mask of valid bits together
1893           // with the expression result, so the debugger can print missing
1894           // members as "<optimized out>" or something.
1895           ::memset(curr_piece.GetBuffer().GetBytes(), 0, piece_byte_size);
1896           pieces.AppendDataToHostBuffer(curr_piece);
1897         } else {
1898           Status error;
1899           // Extract the current piece into "curr_piece"
1900           Value curr_piece_source_value(stack.back());
1901           stack.pop_back();
1902           UpdateValueTypeFromLocationDescription(log, dwarf_cu, piece_locdesc,
1903                                                  &curr_piece_source_value);
1904 
1905           const Value::ValueType curr_piece_source_value_type =
1906               curr_piece_source_value.GetValueType();
1907           Scalar &scalar = curr_piece_source_value.GetScalar();
1908           lldb::addr_t addr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1909           switch (curr_piece_source_value_type) {
1910           case Value::ValueType::Invalid:
1911             return llvm::createStringError("invalid value type");
1912           case Value::ValueType::FileAddress:
1913             if (target) {
1914               curr_piece_source_value.ConvertToLoadAddress(module_sp.get(),
1915                                                            target);
1916               addr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1917             } else {
1918               return llvm::createStringError(
1919                   "unable to convert file address 0x%" PRIx64
1920                   " to load address "
1921                   "for DW_OP_piece(%" PRIu64 "): "
1922                   "no target available",
1923                   addr, piece_byte_size);
1924             }
1925             [[fallthrough]];
1926           case Value::ValueType::LoadAddress: {
1927             if (target) {
1928               if (curr_piece.ResizeData(piece_byte_size) == piece_byte_size) {
1929                 if (target->ReadMemory(addr, curr_piece.GetBuffer().GetBytes(),
1930                                        piece_byte_size, error,
1931                                        /*force_live_memory=*/false) !=
1932                     piece_byte_size) {
1933                   const char *addr_type = (curr_piece_source_value_type ==
1934                                            Value::ValueType::LoadAddress)
1935                                               ? "load"
1936                                               : "file";
1937                   return llvm::createStringError(
1938                       "failed to read memory DW_OP_piece(%" PRIu64
1939                       ") from %s address 0x%" PRIx64,
1940                       piece_byte_size, addr_type, addr);
1941                 }
1942               } else {
1943                 return llvm::createStringError(
1944                     "failed to resize the piece memory buffer for "
1945                     "DW_OP_piece(%" PRIu64 ")",
1946                     piece_byte_size);
1947               }
1948             }
1949           } break;
1950           case Value::ValueType::HostAddress: {
1951             return llvm::createStringError(
1952                 "failed to read memory DW_OP_piece(%" PRIu64
1953                 ") from host address 0x%" PRIx64,
1954                 piece_byte_size, addr);
1955           } break;
1956 
1957           case Value::ValueType::Scalar: {
1958             uint32_t bit_size = piece_byte_size * 8;
1959             uint32_t bit_offset = 0;
1960             if (!scalar.ExtractBitfield(
1961                     bit_size, bit_offset)) {
1962               return llvm::createStringError(
1963                   "unable to extract %" PRIu64 " bytes from a %" PRIu64
1964                   " byte scalar value.",
1965                   piece_byte_size,
1966                   (uint64_t)curr_piece_source_value.GetScalar().GetByteSize());
1967             }
1968             // Create curr_piece with bit_size. By default Scalar
1969             // grows to the nearest host integer type.
1970             llvm::APInt fail_value(1, 0, false);
1971             llvm::APInt ap_int = scalar.UInt128(fail_value);
1972             assert(ap_int.getBitWidth() >= bit_size);
1973             llvm::ArrayRef<uint64_t> buf{ap_int.getRawData(),
1974                                          ap_int.getNumWords()};
1975             curr_piece.GetScalar() = Scalar(llvm::APInt(bit_size, buf));
1976           } break;
1977           }
1978 
1979           // Check if this is the first piece?
1980           if (op_piece_offset == 0) {
1981             // This is the first piece, we should push it back onto the stack
1982             // so subsequent pieces will be able to access this piece and add
1983             // to it.
1984             if (pieces.AppendDataToHostBuffer(curr_piece) == 0) {
1985               return llvm::createStringError("failed to append piece data");
1986             }
1987           } else {
1988             // If this is the second or later piece there should be a value on
1989             // the stack.
1990             if (pieces.GetBuffer().GetByteSize() != op_piece_offset) {
1991               return llvm::createStringError(
1992                   "DW_OP_piece for offset %" PRIu64
1993                   " but top of stack is of size %" PRIu64,
1994                   op_piece_offset, pieces.GetBuffer().GetByteSize());
1995             }
1996 
1997             if (pieces.AppendDataToHostBuffer(curr_piece) == 0)
1998               return llvm::createStringError("failed to append piece data");
1999           }
2000         }
2001         op_piece_offset += piece_byte_size;
2002       }
2003     } break;
2004 
2005     case DW_OP_bit_piece: // 0x9d ULEB128 bit size, ULEB128 bit offset (DWARF3);
2006       if (stack.size() < 1) {
2007         UpdateValueTypeFromLocationDescription(log, dwarf_cu,
2008                                                LocationDescriptionKind::Empty);
2009         // Reset for the next piece.
2010         dwarf4_location_description_kind = Memory;
2011         return llvm::createStringError(
2012             "expression stack needs at least 1 item for DW_OP_bit_piece");
2013       } else {
2014         UpdateValueTypeFromLocationDescription(
2015             log, dwarf_cu, dwarf4_location_description_kind, &stack.back());
2016         // Reset for the next piece.
2017         dwarf4_location_description_kind = Memory;
2018         const uint64_t piece_bit_size = opcodes.GetULEB128(&offset);
2019         const uint64_t piece_bit_offset = opcodes.GetULEB128(&offset);
2020         switch (stack.back().GetValueType()) {
2021         case Value::ValueType::Invalid:
2022           return llvm::createStringError(
2023               "unable to extract bit value from invalid value");
2024         case Value::ValueType::Scalar: {
2025           if (!stack.back().GetScalar().ExtractBitfield(piece_bit_size,
2026                                                         piece_bit_offset)) {
2027             return llvm::createStringError(
2028                 "unable to extract %" PRIu64 " bit value with %" PRIu64
2029                 " bit offset from a %" PRIu64 " bit scalar value.",
2030                 piece_bit_size, piece_bit_offset,
2031                 (uint64_t)(stack.back().GetScalar().GetByteSize() * 8));
2032           }
2033         } break;
2034 
2035         case Value::ValueType::FileAddress:
2036         case Value::ValueType::LoadAddress:
2037         case Value::ValueType::HostAddress:
2038           return llvm::createStringError(
2039               "unable to extract DW_OP_bit_piece(bit_size = %" PRIu64
2040               ", bit_offset = %" PRIu64 ") from an address value.",
2041               piece_bit_size, piece_bit_offset);
2042         }
2043       }
2044       break;
2045 
2046     // OPCODE: DW_OP_implicit_value
2047     // OPERANDS: 2
2048     //      ULEB128  size of the value block in bytes
2049     //      uint8_t* block bytes encoding value in target's memory
2050     //      representation
2051     // DESCRIPTION: Value is immediately stored in block in the debug info with
2052     // the memory representation of the target.
2053     case DW_OP_implicit_value: {
2054       dwarf4_location_description_kind = Implicit;
2055 
2056       const uint32_t len = opcodes.GetULEB128(&offset);
2057       const void *data = opcodes.GetData(&offset, len);
2058 
2059       if (!data) {
2060         LLDB_LOG(log, "Evaluate_DW_OP_implicit_value: could not be read data");
2061         return llvm::createStringError("could not evaluate %s",
2062                                        DW_OP_value_to_name(op));
2063       }
2064 
2065       Value result(data, len);
2066       stack.push_back(result);
2067       break;
2068     }
2069 
2070     case DW_OP_implicit_pointer: {
2071       dwarf4_location_description_kind = Implicit;
2072       return llvm::createStringError("Could not evaluate %s.",
2073                                      DW_OP_value_to_name(op));
2074     }
2075 
2076     // OPCODE: DW_OP_push_object_address
2077     // OPERANDS: none
2078     // DESCRIPTION: Pushes the address of the object currently being
2079     // evaluated as part of evaluation of a user presented expression. This
2080     // object may correspond to an independent variable described by its own
2081     // DIE or it may be a component of an array, structure, or class whose
2082     // address has been dynamically determined by an earlier step during user
2083     // expression evaluation.
2084     case DW_OP_push_object_address:
2085       if (object_address_ptr)
2086         stack.push_back(*object_address_ptr);
2087       else {
2088         return llvm::createStringError("DW_OP_push_object_address used without "
2089                                        "specifying an object address");
2090       }
2091       break;
2092 
2093     // OPCODE: DW_OP_call2
2094     // OPERANDS:
2095     //      uint16_t compile unit relative offset of a DIE
2096     // DESCRIPTION: Performs subroutine calls during evaluation
2097     // of a DWARF expression. The operand is the 2-byte unsigned offset of a
2098     // debugging information entry in the current compilation unit.
2099     //
2100     // Operand interpretation is exactly like that for DW_FORM_ref2.
2101     //
2102     // This operation transfers control of DWARF expression evaluation to the
2103     // DW_AT_location attribute of the referenced DIE. If there is no such
2104     // attribute, then there is no effect. Execution of the DWARF expression of
2105     // a DW_AT_location attribute may add to and/or remove from values on the
2106     // stack. Execution returns to the point following the call when the end of
2107     // the attribute is reached. Values on the stack at the time of the call
2108     // may be used as parameters by the called expression and values left on
2109     // the stack by the called expression may be used as return values by prior
2110     // agreement between the calling and called expressions.
2111     case DW_OP_call2:
2112       return llvm::createStringError("unimplemented opcode DW_OP_call2");
2113     // OPCODE: DW_OP_call4
2114     // OPERANDS: 1
2115     //      uint32_t compile unit relative offset of a DIE
2116     // DESCRIPTION: Performs a subroutine call during evaluation of a DWARF
2117     // expression. For DW_OP_call4, the operand is a 4-byte unsigned offset of
2118     // a debugging information entry in  the current compilation unit.
2119     //
2120     // Operand interpretation DW_OP_call4 is exactly like that for
2121     // DW_FORM_ref4.
2122     //
2123     // This operation transfers control of DWARF expression evaluation to the
2124     // DW_AT_location attribute of the referenced DIE. If there is no such
2125     // attribute, then there is no effect. Execution of the DWARF expression of
2126     // a DW_AT_location attribute may add to and/or remove from values on the
2127     // stack. Execution returns to the point following the call when the end of
2128     // the attribute is reached. Values on the stack at the time of the call
2129     // may be used as parameters by the called expression and values left on
2130     // the stack by the called expression may be used as return values by prior
2131     // agreement between the calling and called expressions.
2132     case DW_OP_call4:
2133       return llvm::createStringError("unimplemented opcode DW_OP_call4");
2134 
2135     // OPCODE: DW_OP_stack_value
2136     // OPERANDS: None
2137     // DESCRIPTION: Specifies that the object does not exist in memory but
2138     // rather is a constant value.  The value from the top of the stack is the
2139     // value to be used.  This is the actual object value and not the location.
2140     case DW_OP_stack_value:
2141       dwarf4_location_description_kind = Implicit;
2142       stack.back().SetValueType(Value::ValueType::Scalar);
2143       break;
2144 
2145     // OPCODE: DW_OP_convert
2146     // OPERANDS: 1
2147     //      A ULEB128 that is either a DIE offset of a
2148     //      DW_TAG_base_type or 0 for the generic (pointer-sized) type.
2149     //
2150     // DESCRIPTION: Pop the top stack element, convert it to a
2151     // different type, and push the result.
2152     case DW_OP_convert: {
2153       const uint64_t die_offset = opcodes.GetULEB128(&offset);
2154       uint64_t bit_size;
2155       bool sign;
2156       if (die_offset == 0) {
2157         // The generic type has the size of an address on the target
2158         // machine and an unspecified signedness. Scalar has no
2159         // "unspecified signedness", so we use unsigned types.
2160         if (!module_sp)
2161           return llvm::createStringError("no module");
2162         sign = false;
2163         bit_size = module_sp->GetArchitecture().GetAddressByteSize() * 8;
2164         if (!bit_size)
2165           return llvm::createStringError("unspecified architecture");
2166       } else {
2167         // Retrieve the type DIE that the value is being converted to. This
2168         // offset is compile unit relative so we need to fix it up.
2169         const uint64_t abs_die_offset = die_offset +  dwarf_cu->GetOffset();
2170         // FIXME: the constness has annoying ripple effects.
2171         DWARFDIE die = const_cast<DWARFUnit *>(dwarf_cu)->GetDIE(abs_die_offset);
2172         if (!die)
2173           return llvm::createStringError(
2174               "cannot resolve DW_OP_convert type DIE");
2175         uint64_t encoding =
2176             die.GetAttributeValueAsUnsigned(DW_AT_encoding, DW_ATE_hi_user);
2177         bit_size = die.GetAttributeValueAsUnsigned(DW_AT_byte_size, 0) * 8;
2178         if (!bit_size)
2179           bit_size = die.GetAttributeValueAsUnsigned(DW_AT_bit_size, 0);
2180         if (!bit_size)
2181           return llvm::createStringError(
2182               "unsupported type size in DW_OP_convert");
2183         switch (encoding) {
2184         case DW_ATE_signed:
2185         case DW_ATE_signed_char:
2186           sign = true;
2187           break;
2188         case DW_ATE_unsigned:
2189         case DW_ATE_unsigned_char:
2190           sign = false;
2191           break;
2192         default:
2193           return llvm::createStringError(
2194               "unsupported encoding in DW_OP_convert");
2195         }
2196       }
2197       Scalar &top = stack.back().ResolveValue(exe_ctx);
2198       top.TruncOrExtendTo(bit_size, sign);
2199       break;
2200     }
2201 
2202     // OPCODE: DW_OP_call_frame_cfa
2203     // OPERANDS: None
2204     // DESCRIPTION: Specifies a DWARF expression that pushes the value of
2205     // the canonical frame address consistent with the call frame information
2206     // located in .debug_frame (or in the FDEs of the eh_frame section).
2207     case DW_OP_call_frame_cfa:
2208       if (frame) {
2209         // Note that we don't have to parse FDEs because this DWARF expression
2210         // is commonly evaluated with a valid stack frame.
2211         StackID id = frame->GetStackID();
2212         addr_t cfa = id.GetCallFrameAddress();
2213         if (cfa != LLDB_INVALID_ADDRESS) {
2214           stack.push_back(Scalar(cfa));
2215           stack.back().SetValueType(Value::ValueType::LoadAddress);
2216         } else {
2217           return llvm::createStringError(
2218               "stack frame does not include a canonical "
2219               "frame address for DW_OP_call_frame_cfa "
2220               "opcode");
2221         }
2222       } else {
2223         return llvm::createStringError("unvalid stack frame in context for "
2224                                        "DW_OP_call_frame_cfa opcode");
2225       }
2226       break;
2227 
2228     // OPCODE: DW_OP_form_tls_address (or the old pre-DWARFv3 vendor extension
2229     // opcode, DW_OP_GNU_push_tls_address)
2230     // OPERANDS: none
2231     // DESCRIPTION: Pops a TLS offset from the stack, converts it to
2232     // an address in the current thread's thread-local storage block, and
2233     // pushes it on the stack.
2234     case DW_OP_form_tls_address:
2235     case DW_OP_GNU_push_tls_address: {
2236       if (stack.size() < 1) {
2237         if (op == DW_OP_form_tls_address)
2238           return llvm::createStringError(
2239               "DW_OP_form_tls_address needs an argument");
2240         else
2241           return llvm::createStringError(
2242               "DW_OP_GNU_push_tls_address needs an argument");
2243       }
2244 
2245       if (!exe_ctx || !module_sp)
2246         return llvm::createStringError("no context to evaluate TLS within");
2247 
2248       Thread *thread = exe_ctx->GetThreadPtr();
2249       if (!thread)
2250         return llvm::createStringError("no thread to evaluate TLS within");
2251 
2252       // Lookup the TLS block address for this thread and module.
2253       const addr_t tls_file_addr =
2254           stack.back().GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
2255       const addr_t tls_load_addr =
2256           thread->GetThreadLocalData(module_sp, tls_file_addr);
2257 
2258       if (tls_load_addr == LLDB_INVALID_ADDRESS)
2259         return llvm::createStringError(
2260             "no TLS data currently exists for this thread");
2261 
2262       stack.back().GetScalar() = tls_load_addr;
2263       stack.back().SetValueType(Value::ValueType::LoadAddress);
2264     } break;
2265 
2266     // OPCODE: DW_OP_addrx (DW_OP_GNU_addr_index is the legacy name.)
2267     // OPERANDS: 1
2268     //      ULEB128: index to the .debug_addr section
2269     // DESCRIPTION: Pushes an address to the stack from the .debug_addr
2270     // section with the base address specified by the DW_AT_addr_base attribute
2271     // and the 0 based index is the ULEB128 encoded index.
2272     case DW_OP_addrx:
2273     case DW_OP_GNU_addr_index: {
2274       if (!dwarf_cu)
2275         return llvm::createStringError("DW_OP_GNU_addr_index found without a "
2276                                        "compile unit being specified");
2277       uint64_t index = opcodes.GetULEB128(&offset);
2278       lldb::addr_t value = dwarf_cu->ReadAddressFromDebugAddrSection(index);
2279       stack.push_back(Scalar(value));
2280       if (target &&
2281           target->GetArchitecture().GetCore() == ArchSpec::eCore_wasm32) {
2282         // wasm file sections aren't mapped into memory, therefore addresses can
2283         // never point into a file section and are always LoadAddresses.
2284         stack.back().SetValueType(Value::ValueType::LoadAddress);
2285       } else {
2286         stack.back().SetValueType(Value::ValueType::FileAddress);
2287       }
2288     } break;
2289 
2290     // OPCODE: DW_OP_GNU_const_index
2291     // OPERANDS: 1
2292     //      ULEB128: index to the .debug_addr section
2293     // DESCRIPTION: Pushes an constant with the size of a machine address to
2294     // the stack from the .debug_addr section with the base address specified
2295     // by the DW_AT_addr_base attribute and the 0 based index is the ULEB128
2296     // encoded index.
2297     case DW_OP_GNU_const_index: {
2298       if (!dwarf_cu) {
2299         return llvm::createStringError("DW_OP_GNU_const_index found without a "
2300                                        "compile unit being specified");
2301       }
2302       uint64_t index = opcodes.GetULEB128(&offset);
2303       lldb::addr_t value = dwarf_cu->ReadAddressFromDebugAddrSection(index);
2304       stack.push_back(Scalar(value));
2305     } break;
2306 
2307     case DW_OP_GNU_entry_value:
2308     case DW_OP_entry_value: {
2309       if (llvm::Error err = Evaluate_DW_OP_entry_value(stack, exe_ctx, reg_ctx,
2310                                                        opcodes, offset, log))
2311         return llvm::createStringError(
2312             "could not evaluate DW_OP_entry_value: %s",
2313             llvm::toString(std::move(err)).c_str());
2314       break;
2315     }
2316 
2317     default:
2318       if (dwarf_cu) {
2319         if (dwarf_cu->GetSymbolFileDWARF().ParseVendorDWARFOpcode(
2320                 op, opcodes, offset, stack)) {
2321           break;
2322         }
2323       }
2324       return llvm::createStringError(llvm::formatv(
2325           "Unhandled opcode {0} in DWARFExpression", LocationAtom(op)));
2326     }
2327   }
2328 
2329   if (stack.empty()) {
2330     // Nothing on the stack, check if we created a piece value from DW_OP_piece
2331     // or DW_OP_bit_piece opcodes
2332     if (pieces.GetBuffer().GetByteSize())
2333       return pieces;
2334 
2335     return llvm::createStringError("stack empty after evaluation");
2336   }
2337 
2338   UpdateValueTypeFromLocationDescription(
2339       log, dwarf_cu, dwarf4_location_description_kind, &stack.back());
2340 
2341   if (log && log->GetVerbose()) {
2342     size_t count = stack.size();
2343     LLDB_LOGF(log,
2344               "Stack after operation has %" PRIu64 " values:", (uint64_t)count);
2345     for (size_t i = 0; i < count; ++i) {
2346       StreamString new_value;
2347       new_value.Printf("[%" PRIu64 "]", (uint64_t)i);
2348       stack[i].Dump(&new_value);
2349       LLDB_LOGF(log, "  %s", new_value.GetData());
2350     }
2351   }
2352   return stack.back();
2353 }
2354 
2355 bool DWARFExpression::ParseDWARFLocationList(
2356     const DWARFUnit *dwarf_cu, const DataExtractor &data,
2357     DWARFExpressionList *location_list) {
2358   location_list->Clear();
2359   std::unique_ptr<llvm::DWARFLocationTable> loctable_up =
2360       dwarf_cu->GetLocationTable(data);
2361   Log *log = GetLog(LLDBLog::Expressions);
2362   auto lookup_addr =
2363       [&](uint32_t index) -> std::optional<llvm::object::SectionedAddress> {
2364     addr_t address = dwarf_cu->ReadAddressFromDebugAddrSection(index);
2365     if (address == LLDB_INVALID_ADDRESS)
2366       return std::nullopt;
2367     return llvm::object::SectionedAddress{address};
2368   };
2369   auto process_list = [&](llvm::Expected<llvm::DWARFLocationExpression> loc) {
2370     if (!loc) {
2371       LLDB_LOG_ERROR(log, loc.takeError(), "{0}");
2372       return true;
2373     }
2374     auto buffer_sp =
2375         std::make_shared<DataBufferHeap>(loc->Expr.data(), loc->Expr.size());
2376     DWARFExpression expr = DWARFExpression(DataExtractor(
2377         buffer_sp, data.GetByteOrder(), data.GetAddressByteSize()));
2378     location_list->AddExpression(loc->Range->LowPC, loc->Range->HighPC, expr);
2379     return true;
2380   };
2381   llvm::Error error = loctable_up->visitAbsoluteLocationList(
2382       0, llvm::object::SectionedAddress{dwarf_cu->GetBaseAddress()},
2383       lookup_addr, process_list);
2384   location_list->Sort();
2385   if (error) {
2386     LLDB_LOG_ERROR(log, std::move(error), "{0}");
2387     return false;
2388   }
2389   return true;
2390 }
2391 
2392 bool DWARFExpression::MatchesOperand(
2393     StackFrame &frame, const Instruction::Operand &operand) const {
2394   using namespace OperandMatchers;
2395 
2396   RegisterContextSP reg_ctx_sp = frame.GetRegisterContext();
2397   if (!reg_ctx_sp) {
2398     return false;
2399   }
2400 
2401   DataExtractor opcodes(m_data);
2402 
2403   lldb::offset_t op_offset = 0;
2404   uint8_t opcode = opcodes.GetU8(&op_offset);
2405 
2406   if (opcode == DW_OP_fbreg) {
2407     int64_t offset = opcodes.GetSLEB128(&op_offset);
2408 
2409     DWARFExpressionList *fb_expr = frame.GetFrameBaseExpression(nullptr);
2410     if (!fb_expr) {
2411       return false;
2412     }
2413 
2414     auto recurse = [&frame, fb_expr](const Instruction::Operand &child) {
2415       return fb_expr->MatchesOperand(frame, child);
2416     };
2417 
2418     if (!offset &&
2419         MatchUnaryOp(MatchOpType(Instruction::Operand::Type::Dereference),
2420                      recurse)(operand)) {
2421       return true;
2422     }
2423 
2424     return MatchUnaryOp(
2425         MatchOpType(Instruction::Operand::Type::Dereference),
2426         MatchBinaryOp(MatchOpType(Instruction::Operand::Type::Sum),
2427                       MatchImmOp(offset), recurse))(operand);
2428   }
2429 
2430   bool dereference = false;
2431   const RegisterInfo *reg = nullptr;
2432   int64_t offset = 0;
2433 
2434   if (opcode >= DW_OP_reg0 && opcode <= DW_OP_reg31) {
2435     reg = reg_ctx_sp->GetRegisterInfo(m_reg_kind, opcode - DW_OP_reg0);
2436   } else if (opcode >= DW_OP_breg0 && opcode <= DW_OP_breg31) {
2437     offset = opcodes.GetSLEB128(&op_offset);
2438     reg = reg_ctx_sp->GetRegisterInfo(m_reg_kind, opcode - DW_OP_breg0);
2439   } else if (opcode == DW_OP_regx) {
2440     uint32_t reg_num = static_cast<uint32_t>(opcodes.GetULEB128(&op_offset));
2441     reg = reg_ctx_sp->GetRegisterInfo(m_reg_kind, reg_num);
2442   } else if (opcode == DW_OP_bregx) {
2443     uint32_t reg_num = static_cast<uint32_t>(opcodes.GetULEB128(&op_offset));
2444     offset = opcodes.GetSLEB128(&op_offset);
2445     reg = reg_ctx_sp->GetRegisterInfo(m_reg_kind, reg_num);
2446   } else {
2447     return false;
2448   }
2449 
2450   if (!reg) {
2451     return false;
2452   }
2453 
2454   if (dereference) {
2455     if (!offset &&
2456         MatchUnaryOp(MatchOpType(Instruction::Operand::Type::Dereference),
2457                      MatchRegOp(*reg))(operand)) {
2458       return true;
2459     }
2460 
2461     return MatchUnaryOp(
2462         MatchOpType(Instruction::Operand::Type::Dereference),
2463         MatchBinaryOp(MatchOpType(Instruction::Operand::Type::Sum),
2464                       MatchRegOp(*reg),
2465                       MatchImmOp(offset)))(operand);
2466   } else {
2467     return MatchRegOp(*reg)(operand);
2468   }
2469 }
2470