ABISysV_ppc.cpp revision 360784
1//===-- ABISysV_ppc.cpp -----------------------------------------*- C++ -*-===//
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 "ABISysV_ppc.h"
10
11#include "llvm/ADT/STLExtras.h"
12#include "llvm/ADT/Triple.h"
13
14#include "lldb/Core/Module.h"
15#include "lldb/Core/PluginManager.h"
16#include "lldb/Core/Value.h"
17#include "lldb/Core/ValueObjectConstResult.h"
18#include "lldb/Core/ValueObjectMemory.h"
19#include "lldb/Core/ValueObjectRegister.h"
20#include "lldb/Symbol/UnwindPlan.h"
21#include "lldb/Target/Process.h"
22#include "lldb/Target/RegisterContext.h"
23#include "lldb/Target/StackFrame.h"
24#include "lldb/Target/Target.h"
25#include "lldb/Target/Thread.h"
26#include "lldb/Utility/ConstString.h"
27#include "lldb/Utility/DataExtractor.h"
28#include "lldb/Utility/Log.h"
29#include "lldb/Utility/RegisterValue.h"
30#include "lldb/Utility/Status.h"
31
32using namespace lldb;
33using namespace lldb_private;
34
35enum dwarf_regnums {
36  dwarf_r0 = 0,
37  dwarf_r1,
38  dwarf_r2,
39  dwarf_r3,
40  dwarf_r4,
41  dwarf_r5,
42  dwarf_r6,
43  dwarf_r7,
44  dwarf_r8,
45  dwarf_r9,
46  dwarf_r10,
47  dwarf_r11,
48  dwarf_r12,
49  dwarf_r13,
50  dwarf_r14,
51  dwarf_r15,
52  dwarf_r16,
53  dwarf_r17,
54  dwarf_r18,
55  dwarf_r19,
56  dwarf_r20,
57  dwarf_r21,
58  dwarf_r22,
59  dwarf_r23,
60  dwarf_r24,
61  dwarf_r25,
62  dwarf_r26,
63  dwarf_r27,
64  dwarf_r28,
65  dwarf_r29,
66  dwarf_r30,
67  dwarf_r31,
68  dwarf_f0,
69  dwarf_f1,
70  dwarf_f2,
71  dwarf_f3,
72  dwarf_f4,
73  dwarf_f5,
74  dwarf_f6,
75  dwarf_f7,
76  dwarf_f8,
77  dwarf_f9,
78  dwarf_f10,
79  dwarf_f11,
80  dwarf_f12,
81  dwarf_f13,
82  dwarf_f14,
83  dwarf_f15,
84  dwarf_f16,
85  dwarf_f17,
86  dwarf_f18,
87  dwarf_f19,
88  dwarf_f20,
89  dwarf_f21,
90  dwarf_f22,
91  dwarf_f23,
92  dwarf_f24,
93  dwarf_f25,
94  dwarf_f26,
95  dwarf_f27,
96  dwarf_f28,
97  dwarf_f29,
98  dwarf_f30,
99  dwarf_f31,
100  dwarf_cr,
101  dwarf_fpscr,
102  dwarf_xer = 101,
103  dwarf_lr = 108,
104  dwarf_ctr,
105  dwarf_pc,
106  dwarf_cfa,
107};
108
109// Note that the size and offset will be updated by platform-specific classes.
110#define DEFINE_GPR(reg, alt, kind1, kind2, kind3, kind4)                       \
111  {                                                                            \
112    #reg, alt, 8, 0, eEncodingUint, eFormatHex, {kind1, kind2, kind3, kind4 }, \
113                                                 nullptr, nullptr, nullptr, 0  \
114  }
115
116static const RegisterInfo g_register_infos[] = {
117    // General purpose registers.             eh_frame,                 DWARF,
118    // Generic,    Process Plugin
119    DEFINE_GPR(r0, nullptr, dwarf_r0, dwarf_r0, LLDB_INVALID_REGNUM,
120               LLDB_INVALID_REGNUM),
121    DEFINE_GPR(r1, "sp", dwarf_r1, dwarf_r1, LLDB_REGNUM_GENERIC_SP,
122               LLDB_INVALID_REGNUM),
123    DEFINE_GPR(r2, nullptr, dwarf_r2, dwarf_r2, LLDB_INVALID_REGNUM,
124               LLDB_INVALID_REGNUM),
125    DEFINE_GPR(r3, "arg1", dwarf_r3, dwarf_r3, LLDB_REGNUM_GENERIC_ARG1,
126               LLDB_INVALID_REGNUM),
127    DEFINE_GPR(r4, "arg2", dwarf_r4, dwarf_r4, LLDB_REGNUM_GENERIC_ARG2,
128               LLDB_INVALID_REGNUM),
129    DEFINE_GPR(r5, "arg3", dwarf_r5, dwarf_r5, LLDB_REGNUM_GENERIC_ARG3,
130               LLDB_INVALID_REGNUM),
131    DEFINE_GPR(r6, "arg4", dwarf_r6, dwarf_r6, LLDB_REGNUM_GENERIC_ARG4,
132               LLDB_INVALID_REGNUM),
133    DEFINE_GPR(r7, "arg5", dwarf_r7, dwarf_r7, LLDB_REGNUM_GENERIC_ARG5,
134               LLDB_INVALID_REGNUM),
135    DEFINE_GPR(r8, "arg6", dwarf_r8, dwarf_r8, LLDB_REGNUM_GENERIC_ARG6,
136               LLDB_INVALID_REGNUM),
137    DEFINE_GPR(r9, "arg7", dwarf_r9, dwarf_r9, LLDB_REGNUM_GENERIC_ARG7,
138               LLDB_INVALID_REGNUM),
139    DEFINE_GPR(r10, "arg8", dwarf_r10, dwarf_r10, LLDB_REGNUM_GENERIC_ARG8,
140               LLDB_INVALID_REGNUM),
141    DEFINE_GPR(r11, nullptr, dwarf_r11, dwarf_r11, LLDB_INVALID_REGNUM,
142               LLDB_INVALID_REGNUM),
143    DEFINE_GPR(r12, nullptr, dwarf_r12, dwarf_r12, LLDB_INVALID_REGNUM,
144               LLDB_INVALID_REGNUM),
145    DEFINE_GPR(r13, nullptr, dwarf_r13, dwarf_r13, LLDB_INVALID_REGNUM,
146               LLDB_INVALID_REGNUM),
147    DEFINE_GPR(r14, nullptr, dwarf_r14, dwarf_r14, LLDB_INVALID_REGNUM,
148               LLDB_INVALID_REGNUM),
149    DEFINE_GPR(r15, nullptr, dwarf_r15, dwarf_r15, LLDB_INVALID_REGNUM,
150               LLDB_INVALID_REGNUM),
151    DEFINE_GPR(r16, nullptr, dwarf_r16, dwarf_r16, LLDB_INVALID_REGNUM,
152               LLDB_INVALID_REGNUM),
153    DEFINE_GPR(r17, nullptr, dwarf_r17, dwarf_r17, LLDB_INVALID_REGNUM,
154               LLDB_INVALID_REGNUM),
155    DEFINE_GPR(r18, nullptr, dwarf_r18, dwarf_r18, LLDB_INVALID_REGNUM,
156               LLDB_INVALID_REGNUM),
157    DEFINE_GPR(r19, nullptr, dwarf_r19, dwarf_r19, LLDB_INVALID_REGNUM,
158               LLDB_INVALID_REGNUM),
159    DEFINE_GPR(r20, nullptr, dwarf_r20, dwarf_r20, LLDB_INVALID_REGNUM,
160               LLDB_INVALID_REGNUM),
161    DEFINE_GPR(r21, nullptr, dwarf_r21, dwarf_r21, LLDB_INVALID_REGNUM,
162               LLDB_INVALID_REGNUM),
163    DEFINE_GPR(r22, nullptr, dwarf_r22, dwarf_r22, LLDB_INVALID_REGNUM,
164               LLDB_INVALID_REGNUM),
165    DEFINE_GPR(r23, nullptr, dwarf_r23, dwarf_r23, LLDB_INVALID_REGNUM,
166               LLDB_INVALID_REGNUM),
167    DEFINE_GPR(r24, nullptr, dwarf_r24, dwarf_r24, LLDB_INVALID_REGNUM,
168               LLDB_INVALID_REGNUM),
169    DEFINE_GPR(r25, nullptr, dwarf_r25, dwarf_r25, LLDB_INVALID_REGNUM,
170               LLDB_INVALID_REGNUM),
171    DEFINE_GPR(r26, nullptr, dwarf_r26, dwarf_r26, LLDB_INVALID_REGNUM,
172               LLDB_INVALID_REGNUM),
173    DEFINE_GPR(r27, nullptr, dwarf_r27, dwarf_r27, LLDB_INVALID_REGNUM,
174               LLDB_INVALID_REGNUM),
175    DEFINE_GPR(r28, nullptr, dwarf_r28, dwarf_r28, LLDB_INVALID_REGNUM,
176               LLDB_INVALID_REGNUM),
177    DEFINE_GPR(r29, nullptr, dwarf_r29, dwarf_r29, LLDB_INVALID_REGNUM,
178               LLDB_INVALID_REGNUM),
179    DEFINE_GPR(r30, nullptr, dwarf_r30, dwarf_r30, LLDB_INVALID_REGNUM,
180               LLDB_INVALID_REGNUM),
181    DEFINE_GPR(r31, nullptr, dwarf_r31, dwarf_r31, LLDB_INVALID_REGNUM,
182               LLDB_INVALID_REGNUM),
183    DEFINE_GPR(lr, "lr", dwarf_lr, dwarf_lr, LLDB_REGNUM_GENERIC_RA,
184               LLDB_INVALID_REGNUM),
185    DEFINE_GPR(cr, "cr", dwarf_cr, dwarf_cr, LLDB_REGNUM_GENERIC_FLAGS,
186               LLDB_INVALID_REGNUM),
187    DEFINE_GPR(xer, "xer", dwarf_xer, dwarf_xer, LLDB_INVALID_REGNUM,
188               LLDB_INVALID_REGNUM),
189    DEFINE_GPR(ctr, "ctr", dwarf_ctr, dwarf_ctr, LLDB_INVALID_REGNUM,
190               LLDB_INVALID_REGNUM),
191    DEFINE_GPR(pc, "pc", dwarf_pc, dwarf_pc, LLDB_REGNUM_GENERIC_PC,
192               LLDB_INVALID_REGNUM),
193    {nullptr,
194     nullptr,
195     8,
196     0,
197     eEncodingUint,
198     eFormatHex,
199     {dwarf_cfa, dwarf_cfa, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM},
200     nullptr,
201     nullptr,
202     nullptr,
203     0}};
204
205static const uint32_t k_num_register_infos =
206    llvm::array_lengthof(g_register_infos);
207
208const lldb_private::RegisterInfo *
209ABISysV_ppc::GetRegisterInfoArray(uint32_t &count) {
210  count = k_num_register_infos;
211  return g_register_infos;
212}
213
214size_t ABISysV_ppc::GetRedZoneSize() const { return 224; }
215
216// Static Functions
217
218ABISP
219ABISysV_ppc::CreateInstance(lldb::ProcessSP process_sp, const ArchSpec &arch) {
220  if (arch.GetTriple().getArch() == llvm::Triple::ppc) {
221    return ABISP(
222        new ABISysV_ppc(std::move(process_sp), MakeMCRegisterInfo(arch)));
223  }
224  return ABISP();
225}
226
227bool ABISysV_ppc::PrepareTrivialCall(Thread &thread, addr_t sp,
228                                     addr_t func_addr, addr_t return_addr,
229                                     llvm::ArrayRef<addr_t> args) const {
230  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
231
232  if (log) {
233    StreamString s;
234    s.Printf("ABISysV_ppc::PrepareTrivialCall (tid = 0x%" PRIx64
235             ", sp = 0x%" PRIx64 ", func_addr = 0x%" PRIx64
236             ", return_addr = 0x%" PRIx64,
237             thread.GetID(), (uint64_t)sp, (uint64_t)func_addr,
238             (uint64_t)return_addr);
239
240    for (size_t i = 0; i < args.size(); ++i)
241      s.Printf(", arg%" PRIu64 " = 0x%" PRIx64, static_cast<uint64_t>(i + 1),
242               args[i]);
243    s.PutCString(")");
244    log->PutString(s.GetString());
245  }
246
247  RegisterContext *reg_ctx = thread.GetRegisterContext().get();
248  if (!reg_ctx)
249    return false;
250
251  const RegisterInfo *reg_info = nullptr;
252
253  if (args.size() > 8) // TODO handle more than 8 arguments
254    return false;
255
256  for (size_t i = 0; i < args.size(); ++i) {
257    reg_info = reg_ctx->GetRegisterInfo(eRegisterKindGeneric,
258                                        LLDB_REGNUM_GENERIC_ARG1 + i);
259    LLDB_LOGF(log, "About to write arg%" PRIu64 " (0x%" PRIx64 ") into %s",
260              static_cast<uint64_t>(i + 1), args[i], reg_info->name);
261    if (!reg_ctx->WriteRegisterFromUnsigned(reg_info, args[i]))
262      return false;
263  }
264
265  // First, align the SP
266
267  LLDB_LOGF(log, "16-byte aligning SP: 0x%" PRIx64 " to 0x%" PRIx64,
268            (uint64_t)sp, (uint64_t)(sp & ~0xfull));
269
270  sp &= ~(0xfull); // 16-byte alignment
271
272  sp -= 8;
273
274  Status error;
275  const RegisterInfo *pc_reg_info =
276      reg_ctx->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
277  const RegisterInfo *sp_reg_info =
278      reg_ctx->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_SP);
279  ProcessSP process_sp(thread.GetProcess());
280
281  RegisterValue reg_value;
282
283  LLDB_LOGF(log,
284            "Pushing the return address onto the stack: 0x%" PRIx64
285            ": 0x%" PRIx64,
286            (uint64_t)sp, (uint64_t)return_addr);
287
288  // Save return address onto the stack
289  if (!process_sp->WritePointerToMemory(sp, return_addr, error))
290    return false;
291
292  // %r1 is set to the actual stack value.
293
294  LLDB_LOGF(log, "Writing SP: 0x%" PRIx64, (uint64_t)sp);
295
296  if (!reg_ctx->WriteRegisterFromUnsigned(sp_reg_info, sp))
297    return false;
298
299  // %pc is set to the address of the called function.
300
301  LLDB_LOGF(log, "Writing IP: 0x%" PRIx64, (uint64_t)func_addr);
302
303  if (!reg_ctx->WriteRegisterFromUnsigned(pc_reg_info, func_addr))
304    return false;
305
306  return true;
307}
308
309static bool ReadIntegerArgument(Scalar &scalar, unsigned int bit_width,
310                                bool is_signed, Thread &thread,
311                                uint32_t *argument_register_ids,
312                                unsigned int &current_argument_register,
313                                addr_t &current_stack_argument) {
314  if (bit_width > 64)
315    return false; // Scalar can't hold large integer arguments
316
317  if (current_argument_register < 6) {
318    scalar = thread.GetRegisterContext()->ReadRegisterAsUnsigned(
319        argument_register_ids[current_argument_register], 0);
320    current_argument_register++;
321    if (is_signed)
322      scalar.SignExtend(bit_width);
323  } else {
324    uint32_t byte_size = (bit_width + (8 - 1)) / 8;
325    Status error;
326    if (thread.GetProcess()->ReadScalarIntegerFromMemory(
327            current_stack_argument, byte_size, is_signed, scalar, error)) {
328      current_stack_argument += byte_size;
329      return true;
330    }
331    return false;
332  }
333  return true;
334}
335
336bool ABISysV_ppc::GetArgumentValues(Thread &thread, ValueList &values) const {
337  unsigned int num_values = values.GetSize();
338  unsigned int value_index;
339
340  // Extract the register context so we can read arguments from registers
341
342  RegisterContext *reg_ctx = thread.GetRegisterContext().get();
343
344  if (!reg_ctx)
345    return false;
346
347  // Get the pointer to the first stack argument so we have a place to start
348  // when reading data
349
350  addr_t sp = reg_ctx->GetSP(0);
351
352  if (!sp)
353    return false;
354
355  addr_t current_stack_argument = sp + 48; // jump over return address
356
357  uint32_t argument_register_ids[8];
358
359  argument_register_ids[0] =
360      reg_ctx->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_ARG1)
361          ->kinds[eRegisterKindLLDB];
362  argument_register_ids[1] =
363      reg_ctx->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_ARG2)
364          ->kinds[eRegisterKindLLDB];
365  argument_register_ids[2] =
366      reg_ctx->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_ARG3)
367          ->kinds[eRegisterKindLLDB];
368  argument_register_ids[3] =
369      reg_ctx->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_ARG4)
370          ->kinds[eRegisterKindLLDB];
371  argument_register_ids[4] =
372      reg_ctx->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_ARG5)
373          ->kinds[eRegisterKindLLDB];
374  argument_register_ids[5] =
375      reg_ctx->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_ARG6)
376          ->kinds[eRegisterKindLLDB];
377  argument_register_ids[6] =
378      reg_ctx->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_ARG7)
379          ->kinds[eRegisterKindLLDB];
380  argument_register_ids[7] =
381      reg_ctx->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_ARG8)
382          ->kinds[eRegisterKindLLDB];
383
384  unsigned int current_argument_register = 0;
385
386  for (value_index = 0; value_index < num_values; ++value_index) {
387    Value *value = values.GetValueAtIndex(value_index);
388
389    if (!value)
390      return false;
391
392    // We currently only support extracting values with Clang QualTypes. Do we
393    // care about others?
394    CompilerType compiler_type = value->GetCompilerType();
395    llvm::Optional<uint64_t> bit_size = compiler_type.GetBitSize(&thread);
396    if (!bit_size)
397      return false;
398    bool is_signed;
399    if (compiler_type.IsIntegerOrEnumerationType(is_signed))
400      ReadIntegerArgument(value->GetScalar(), *bit_size, is_signed, thread,
401                          argument_register_ids, current_argument_register,
402                          current_stack_argument);
403    else if (compiler_type.IsPointerType())
404      ReadIntegerArgument(value->GetScalar(), *bit_size, false, thread,
405                          argument_register_ids, current_argument_register,
406                          current_stack_argument);
407  }
408
409  return true;
410}
411
412Status ABISysV_ppc::SetReturnValueObject(lldb::StackFrameSP &frame_sp,
413                                         lldb::ValueObjectSP &new_value_sp) {
414  Status error;
415  if (!new_value_sp) {
416    error.SetErrorString("Empty value object for return value.");
417    return error;
418  }
419
420  CompilerType compiler_type = new_value_sp->GetCompilerType();
421  if (!compiler_type) {
422    error.SetErrorString("Null clang type for return value.");
423    return error;
424  }
425
426  Thread *thread = frame_sp->GetThread().get();
427
428  bool is_signed;
429  uint32_t count;
430  bool is_complex;
431
432  RegisterContext *reg_ctx = thread->GetRegisterContext().get();
433
434  bool set_it_simple = false;
435  if (compiler_type.IsIntegerOrEnumerationType(is_signed) ||
436      compiler_type.IsPointerType()) {
437    const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoByName("r3", 0);
438
439    DataExtractor data;
440    Status data_error;
441    size_t num_bytes = new_value_sp->GetData(data, data_error);
442    if (data_error.Fail()) {
443      error.SetErrorStringWithFormat(
444          "Couldn't convert return value to raw data: %s",
445          data_error.AsCString());
446      return error;
447    }
448    lldb::offset_t offset = 0;
449    if (num_bytes <= 8) {
450      uint64_t raw_value = data.GetMaxU64(&offset, num_bytes);
451
452      if (reg_ctx->WriteRegisterFromUnsigned(reg_info, raw_value))
453        set_it_simple = true;
454    } else {
455      error.SetErrorString("We don't support returning longer than 64 bit "
456                           "integer values at present.");
457    }
458  } else if (compiler_type.IsFloatingPointType(count, is_complex)) {
459    if (is_complex)
460      error.SetErrorString(
461          "We don't support returning complex values at present");
462    else {
463      llvm::Optional<uint64_t> bit_width =
464          compiler_type.GetBitSize(frame_sp.get());
465      if (!bit_width) {
466        error.SetErrorString("can't get type size");
467        return error;
468      }
469      if (*bit_width <= 64) {
470        DataExtractor data;
471        Status data_error;
472        size_t num_bytes = new_value_sp->GetData(data, data_error);
473        if (data_error.Fail()) {
474          error.SetErrorStringWithFormat(
475              "Couldn't convert return value to raw data: %s",
476              data_error.AsCString());
477          return error;
478        }
479
480        unsigned char buffer[16];
481        ByteOrder byte_order = data.GetByteOrder();
482
483        data.CopyByteOrderedData(0, num_bytes, buffer, 16, byte_order);
484        set_it_simple = true;
485      } else {
486        // FIXME - don't know how to do 80 bit long doubles yet.
487        error.SetErrorString(
488            "We don't support returning float values > 64 bits at present");
489      }
490    }
491  }
492
493  if (!set_it_simple) {
494    // Okay we've got a structure or something that doesn't fit in a simple
495    // register. We should figure out where it really goes, but we don't
496    // support this yet.
497    error.SetErrorString("We only support setting simple integer and float "
498                         "return types at present.");
499  }
500
501  return error;
502}
503
504ValueObjectSP ABISysV_ppc::GetReturnValueObjectSimple(
505    Thread &thread, CompilerType &return_compiler_type) const {
506  ValueObjectSP return_valobj_sp;
507  Value value;
508
509  if (!return_compiler_type)
510    return return_valobj_sp;
511
512  // value.SetContext (Value::eContextTypeClangType, return_value_type);
513  value.SetCompilerType(return_compiler_type);
514
515  RegisterContext *reg_ctx = thread.GetRegisterContext().get();
516  if (!reg_ctx)
517    return return_valobj_sp;
518
519  const uint32_t type_flags = return_compiler_type.GetTypeInfo();
520  if (type_flags & eTypeIsScalar) {
521    value.SetValueType(Value::eValueTypeScalar);
522
523    bool success = false;
524    if (type_flags & eTypeIsInteger) {
525      // Extract the register context so we can read arguments from registers
526
527      llvm::Optional<uint64_t> byte_size =
528          return_compiler_type.GetByteSize(nullptr);
529      if (!byte_size)
530        return return_valobj_sp;
531      uint64_t raw_value = thread.GetRegisterContext()->ReadRegisterAsUnsigned(
532          reg_ctx->GetRegisterInfoByName("r3", 0), 0);
533      const bool is_signed = (type_flags & eTypeIsSigned) != 0;
534      switch (*byte_size) {
535      default:
536        break;
537
538      case sizeof(uint64_t):
539        if (is_signed)
540          value.GetScalar() = (int64_t)(raw_value);
541        else
542          value.GetScalar() = (uint64_t)(raw_value);
543        success = true;
544        break;
545
546      case sizeof(uint32_t):
547        if (is_signed)
548          value.GetScalar() = (int32_t)(raw_value & UINT32_MAX);
549        else
550          value.GetScalar() = (uint32_t)(raw_value & UINT32_MAX);
551        success = true;
552        break;
553
554      case sizeof(uint16_t):
555        if (is_signed)
556          value.GetScalar() = (int16_t)(raw_value & UINT16_MAX);
557        else
558          value.GetScalar() = (uint16_t)(raw_value & UINT16_MAX);
559        success = true;
560        break;
561
562      case sizeof(uint8_t):
563        if (is_signed)
564          value.GetScalar() = (int8_t)(raw_value & UINT8_MAX);
565        else
566          value.GetScalar() = (uint8_t)(raw_value & UINT8_MAX);
567        success = true;
568        break;
569      }
570    } else if (type_flags & eTypeIsFloat) {
571      if (type_flags & eTypeIsComplex) {
572        // Don't handle complex yet.
573      } else {
574        llvm::Optional<uint64_t> byte_size =
575            return_compiler_type.GetByteSize(nullptr);
576        if (byte_size && *byte_size <= sizeof(long double)) {
577          const RegisterInfo *f1_info = reg_ctx->GetRegisterInfoByName("f1", 0);
578          RegisterValue f1_value;
579          if (reg_ctx->ReadRegister(f1_info, f1_value)) {
580            DataExtractor data;
581            if (f1_value.GetData(data)) {
582              lldb::offset_t offset = 0;
583              if (*byte_size == sizeof(float)) {
584                value.GetScalar() = (float)data.GetFloat(&offset);
585                success = true;
586              } else if (*byte_size == sizeof(double)) {
587                value.GetScalar() = (double)data.GetDouble(&offset);
588                success = true;
589              }
590            }
591          }
592        }
593      }
594    }
595
596    if (success)
597      return_valobj_sp = ValueObjectConstResult::Create(
598          thread.GetStackFrameAtIndex(0).get(), value, ConstString(""));
599  } else if (type_flags & eTypeIsPointer) {
600    unsigned r3_id =
601        reg_ctx->GetRegisterInfoByName("r3", 0)->kinds[eRegisterKindLLDB];
602    value.GetScalar() =
603        (uint64_t)thread.GetRegisterContext()->ReadRegisterAsUnsigned(r3_id, 0);
604    value.SetValueType(Value::eValueTypeScalar);
605    return_valobj_sp = ValueObjectConstResult::Create(
606        thread.GetStackFrameAtIndex(0).get(), value, ConstString(""));
607  } else if (type_flags & eTypeIsVector) {
608    llvm::Optional<uint64_t> byte_size =
609        return_compiler_type.GetByteSize(nullptr);
610    if (byte_size && *byte_size > 0) {
611      const RegisterInfo *altivec_reg = reg_ctx->GetRegisterInfoByName("v2", 0);
612      if (altivec_reg) {
613        if (*byte_size <= altivec_reg->byte_size) {
614          ProcessSP process_sp(thread.GetProcess());
615          if (process_sp) {
616            std::unique_ptr<DataBufferHeap> heap_data_up(
617                new DataBufferHeap(*byte_size, 0));
618            const ByteOrder byte_order = process_sp->GetByteOrder();
619            RegisterValue reg_value;
620            if (reg_ctx->ReadRegister(altivec_reg, reg_value)) {
621              Status error;
622              if (reg_value.GetAsMemoryData(
623                      altivec_reg, heap_data_up->GetBytes(),
624                      heap_data_up->GetByteSize(), byte_order, error)) {
625                DataExtractor data(DataBufferSP(heap_data_up.release()),
626                                   byte_order,
627                                   process_sp->GetTarget()
628                                       .GetArchitecture()
629                                       .GetAddressByteSize());
630                return_valobj_sp = ValueObjectConstResult::Create(
631                    &thread, return_compiler_type, ConstString(""), data);
632              }
633            }
634          }
635        }
636      }
637    }
638  }
639
640  return return_valobj_sp;
641}
642
643ValueObjectSP ABISysV_ppc::GetReturnValueObjectImpl(
644    Thread &thread, CompilerType &return_compiler_type) const {
645  ValueObjectSP return_valobj_sp;
646
647  if (!return_compiler_type)
648    return return_valobj_sp;
649
650  ExecutionContext exe_ctx(thread.shared_from_this());
651  return_valobj_sp = GetReturnValueObjectSimple(thread, return_compiler_type);
652  if (return_valobj_sp)
653    return return_valobj_sp;
654
655  RegisterContextSP reg_ctx_sp = thread.GetRegisterContext();
656  if (!reg_ctx_sp)
657    return return_valobj_sp;
658
659  llvm::Optional<uint64_t> bit_width = return_compiler_type.GetBitSize(&thread);
660  if (!bit_width)
661    return return_valobj_sp;
662  if (return_compiler_type.IsAggregateType()) {
663    Target *target = exe_ctx.GetTargetPtr();
664    bool is_memory = true;
665    if (*bit_width <= 128) {
666      ByteOrder target_byte_order = target->GetArchitecture().GetByteOrder();
667      DataBufferSP data_sp(new DataBufferHeap(16, 0));
668      DataExtractor return_ext(data_sp, target_byte_order,
669                               target->GetArchitecture().GetAddressByteSize());
670
671      const RegisterInfo *r3_info = reg_ctx_sp->GetRegisterInfoByName("r3", 0);
672      const RegisterInfo *rdx_info =
673          reg_ctx_sp->GetRegisterInfoByName("rdx", 0);
674
675      RegisterValue r3_value, rdx_value;
676      reg_ctx_sp->ReadRegister(r3_info, r3_value);
677      reg_ctx_sp->ReadRegister(rdx_info, rdx_value);
678
679      DataExtractor r3_data, rdx_data;
680
681      r3_value.GetData(r3_data);
682      rdx_value.GetData(rdx_data);
683
684      uint32_t fp_bytes =
685          0; // Tracks how much of the xmm registers we've consumed so far
686      uint32_t integer_bytes =
687          0; // Tracks how much of the r3/rds registers we've consumed so far
688
689      const uint32_t num_children = return_compiler_type.GetNumFields();
690
691      // Since we are in the small struct regime, assume we are not in memory.
692      is_memory = false;
693
694      for (uint32_t idx = 0; idx < num_children; idx++) {
695        std::string name;
696        uint64_t field_bit_offset = 0;
697        bool is_signed;
698        bool is_complex;
699        uint32_t count;
700
701        CompilerType field_compiler_type = return_compiler_type.GetFieldAtIndex(
702            idx, name, &field_bit_offset, nullptr, nullptr);
703        llvm::Optional<uint64_t> field_bit_width =
704            field_compiler_type.GetBitSize(&thread);
705        if (!field_bit_width)
706          return return_valobj_sp;
707
708        // If there are any unaligned fields, this is stored in memory.
709        if (field_bit_offset % *field_bit_width != 0) {
710          is_memory = true;
711          break;
712        }
713
714        uint32_t field_byte_width = *field_bit_width / 8;
715        uint32_t field_byte_offset = field_bit_offset / 8;
716
717        DataExtractor *copy_from_extractor = nullptr;
718        uint32_t copy_from_offset = 0;
719
720        if (field_compiler_type.IsIntegerOrEnumerationType(is_signed) ||
721            field_compiler_type.IsPointerType()) {
722          if (integer_bytes < 8) {
723            if (integer_bytes + field_byte_width <= 8) {
724              // This is in RAX, copy from register to our result structure:
725              copy_from_extractor = &r3_data;
726              copy_from_offset = integer_bytes;
727              integer_bytes += field_byte_width;
728            } else {
729              // The next field wouldn't fit in the remaining space, so we
730              // pushed it to rdx.
731              copy_from_extractor = &rdx_data;
732              copy_from_offset = 0;
733              integer_bytes = 8 + field_byte_width;
734            }
735          } else if (integer_bytes + field_byte_width <= 16) {
736            copy_from_extractor = &rdx_data;
737            copy_from_offset = integer_bytes - 8;
738            integer_bytes += field_byte_width;
739          } else {
740            // The last field didn't fit.  I can't see how that would happen
741            // w/o the overall size being greater than 16 bytes.  For now,
742            // return a nullptr return value object.
743            return return_valobj_sp;
744          }
745        } else if (field_compiler_type.IsFloatingPointType(count, is_complex)) {
746          // Structs with long doubles are always passed in memory.
747          if (*field_bit_width == 128) {
748            is_memory = true;
749            break;
750          } else if (*field_bit_width == 64) {
751            copy_from_offset = 0;
752            fp_bytes += field_byte_width;
753          } else if (*field_bit_width == 32) {
754            // This one is kind of complicated.  If we are in an "eightbyte"
755            // with another float, we'll be stuffed into an xmm register with
756            // it.  If we are in an "eightbyte" with one or more ints, then we
757            // will be stuffed into the appropriate GPR with them.
758            bool in_gpr;
759            if (field_byte_offset % 8 == 0) {
760              // We are at the beginning of one of the eightbytes, so check the
761              // next element (if any)
762              if (idx == num_children - 1)
763                in_gpr = false;
764              else {
765                uint64_t next_field_bit_offset = 0;
766                CompilerType next_field_compiler_type =
767                    return_compiler_type.GetFieldAtIndex(idx + 1, name,
768                                                         &next_field_bit_offset,
769                                                         nullptr, nullptr);
770                if (next_field_compiler_type.IsIntegerOrEnumerationType(
771                        is_signed))
772                  in_gpr = true;
773                else {
774                  copy_from_offset = 0;
775                  in_gpr = false;
776                }
777              }
778            } else if (field_byte_offset % 4 == 0) {
779              // We are inside of an eightbyte, so see if the field before us
780              // is floating point: This could happen if somebody put padding
781              // in the structure.
782              if (idx == 0)
783                in_gpr = false;
784              else {
785                uint64_t prev_field_bit_offset = 0;
786                CompilerType prev_field_compiler_type =
787                    return_compiler_type.GetFieldAtIndex(idx - 1, name,
788                                                         &prev_field_bit_offset,
789                                                         nullptr, nullptr);
790                if (prev_field_compiler_type.IsIntegerOrEnumerationType(
791                        is_signed))
792                  in_gpr = true;
793                else {
794                  copy_from_offset = 4;
795                  in_gpr = false;
796                }
797              }
798            } else {
799              is_memory = true;
800              continue;
801            }
802
803            // Okay, we've figured out whether we are in GPR or XMM, now figure
804            // out which one.
805            if (in_gpr) {
806              if (integer_bytes < 8) {
807                // This is in RAX, copy from register to our result structure:
808                copy_from_extractor = &r3_data;
809                copy_from_offset = integer_bytes;
810                integer_bytes += field_byte_width;
811              } else {
812                copy_from_extractor = &rdx_data;
813                copy_from_offset = integer_bytes - 8;
814                integer_bytes += field_byte_width;
815              }
816            } else {
817              fp_bytes += field_byte_width;
818            }
819          }
820        }
821
822        // These two tests are just sanity checks.  If I somehow get the type
823        // calculation wrong above it is better to just return nothing than to
824        // assert or crash.
825        if (!copy_from_extractor)
826          return return_valobj_sp;
827        if (copy_from_offset + field_byte_width >
828            copy_from_extractor->GetByteSize())
829          return return_valobj_sp;
830
831        copy_from_extractor->CopyByteOrderedData(
832            copy_from_offset, field_byte_width,
833            data_sp->GetBytes() + field_byte_offset, field_byte_width,
834            target_byte_order);
835      }
836
837      if (!is_memory) {
838        // The result is in our data buffer.  Let's make a variable object out
839        // of it:
840        return_valobj_sp = ValueObjectConstResult::Create(
841            &thread, return_compiler_type, ConstString(""), return_ext);
842      }
843    }
844
845    // FIXME: This is just taking a guess, r3 may very well no longer hold the
846    // return storage location.
847    // If we are going to do this right, when we make a new frame we should
848    // check to see if it uses a memory return, and if we are at the first
849    // instruction and if so stash away the return location.  Then we would
850    // only return the memory return value if we know it is valid.
851
852    if (is_memory) {
853      unsigned r3_id =
854          reg_ctx_sp->GetRegisterInfoByName("r3", 0)->kinds[eRegisterKindLLDB];
855      lldb::addr_t storage_addr =
856          (uint64_t)thread.GetRegisterContext()->ReadRegisterAsUnsigned(r3_id,
857                                                                        0);
858      return_valobj_sp = ValueObjectMemory::Create(
859          &thread, "", Address(storage_addr, nullptr), return_compiler_type);
860    }
861  }
862
863  return return_valobj_sp;
864}
865
866bool ABISysV_ppc::CreateFunctionEntryUnwindPlan(UnwindPlan &unwind_plan) {
867  unwind_plan.Clear();
868  unwind_plan.SetRegisterKind(eRegisterKindDWARF);
869
870  uint32_t lr_reg_num = dwarf_lr;
871  uint32_t sp_reg_num = dwarf_r1;
872  uint32_t pc_reg_num = dwarf_pc;
873
874  UnwindPlan::RowSP row(new UnwindPlan::Row);
875
876  // Our Call Frame Address is the stack pointer value
877  row->GetCFAValue().SetIsRegisterPlusOffset(sp_reg_num, 0);
878
879  // The previous PC is in the LR
880  row->SetRegisterLocationToRegister(pc_reg_num, lr_reg_num, true);
881  unwind_plan.AppendRow(row);
882
883  // All other registers are the same.
884
885  unwind_plan.SetSourceName("ppc at-func-entry default");
886  unwind_plan.SetSourcedFromCompiler(eLazyBoolNo);
887
888  return true;
889}
890
891bool ABISysV_ppc::CreateDefaultUnwindPlan(UnwindPlan &unwind_plan) {
892  unwind_plan.Clear();
893  unwind_plan.SetRegisterKind(eRegisterKindDWARF);
894
895  uint32_t sp_reg_num = dwarf_r1;
896  uint32_t pc_reg_num = dwarf_lr;
897
898  UnwindPlan::RowSP row(new UnwindPlan::Row);
899
900  const int32_t ptr_size = 4;
901  row->GetCFAValue().SetIsRegisterDereferenced(sp_reg_num);
902
903  row->SetRegisterLocationToAtCFAPlusOffset(pc_reg_num, ptr_size * 1, true);
904  row->SetRegisterLocationToIsCFAPlusOffset(sp_reg_num, 0, true);
905
906  unwind_plan.AppendRow(row);
907  unwind_plan.SetSourceName("ppc default unwind plan");
908  unwind_plan.SetSourcedFromCompiler(eLazyBoolNo);
909  unwind_plan.SetUnwindPlanValidAtAllInstructions(eLazyBoolNo);
910  unwind_plan.SetUnwindPlanForSignalTrap(eLazyBoolNo);
911  unwind_plan.SetReturnAddressRegister(dwarf_lr);
912  return true;
913}
914
915bool ABISysV_ppc::RegisterIsVolatile(const RegisterInfo *reg_info) {
916  return !RegisterIsCalleeSaved(reg_info);
917}
918
919// See "Register Usage" in the
920// "System V Application Binary Interface"
921// "64-bit PowerPC ELF Application Binary Interface Supplement" current version
922// is 1.9 released 2004 at http://refspecs.linuxfoundation.org/ELF/ppc/PPC-
923// elf64abi-1.9.pdf
924
925bool ABISysV_ppc::RegisterIsCalleeSaved(const RegisterInfo *reg_info) {
926  if (reg_info) {
927    // Preserved registers are :
928    //    r1,r2,r13-r31
929    //    f14-f31 (not yet)
930    //    v20-v31 (not yet)
931    //    vrsave (not yet)
932
933    const char *name = reg_info->name;
934    if (name[0] == 'r') {
935      if ((name[1] == '1' || name[1] == '2') && name[2] == '\0')
936        return true;
937      if (name[1] == '1' && name[2] > '2')
938        return true;
939      if ((name[1] == '2' || name[1] == '3') && name[2] != '\0')
940        return true;
941    }
942
943    if (name[0] == 'f' && name[1] >= '0' && name[1] <= '9') {
944      if (name[3] == '1' && name[4] >= '4')
945        return true;
946      if ((name[3] == '2' || name[3] == '3') && name[4] != '\0')
947        return true;
948    }
949
950    if (name[0] == 's' && name[1] == 'p' && name[2] == '\0') // sp
951      return true;
952    if (name[0] == 'f' && name[1] == 'p' && name[2] == '\0') // fp
953      return true;
954    if (name[0] == 'p' && name[1] == 'c' && name[2] == '\0') // pc
955      return true;
956  }
957  return false;
958}
959
960void ABISysV_ppc::Initialize() {
961  PluginManager::RegisterPlugin(GetPluginNameStatic(),
962                                "System V ABI for ppc targets", CreateInstance);
963}
964
965void ABISysV_ppc::Terminate() {
966  PluginManager::UnregisterPlugin(CreateInstance);
967}
968
969lldb_private::ConstString ABISysV_ppc::GetPluginNameStatic() {
970  static ConstString g_name("sysv-ppc");
971  return g_name;
972}
973
974// PluginInterface protocol
975
976lldb_private::ConstString ABISysV_ppc::GetPluginName() {
977  return GetPluginNameStatic();
978}
979
980uint32_t ABISysV_ppc::GetPluginVersion() { return 1; }
981