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