PowerPC Calling convention
The PowerPC calling convention is a set of rules that dictate how functions receive parameters and return values, how the stack is managed, and how registers are used. This ensures that code generated by different compilers can interoperate.
Key Points of the PowerPC Calling Convention
Registers:
General-purpose registers: R0-R31.
Stack pointer: R1.
Link register: LR.
Condition register: CR.
Parameter Passing:
The first eight integer or pointer arguments are passed in registers R3-R10.
Additional arguments are passed on the stack.
Return Values:
The primary return value is placed in R3.
If a function returns a structure or a union, the address of the return value is passed as a hidden first parameter.
Stack Management:
The stack must be 16-byte aligned at the point of a function call.
The caller is responsible for allocating space for the return address and any arguments that do not fit in registers.
Callee-saved Registers:
Registers R14-R31 must be preserved by the callee.
The callee must save and restore these registers if it uses them.
Example
Here is an example of a simple function in PowerPC assembly that adds two integers:
Explanation (1)
The function
addtakes two integer arguments in registersR3andR4.It adds the values in
R3andR4, storing the result inR3.The
blrinstruction returns to the caller, with the result inR3.
Example with Stack Usage
Here is an example of a function that uses the stack to store local variables:
Explanation (2)
The function
sum_arraytakes two arguments: a pointer to an array inR3and the array length inR4.It saves the link register and sets up the stack frame.
It allocates space for local variables.
It initializes the sum and index to 0.
It enters a loop to iterate over the array, loading each element, adding it to the sum, and incrementing the index.
After the loop, it moves the sum to the return register (
R3), deallocates the local variables, and restores the link register.It returns with the sum in
R3.
These examples illustrate the basic principles of the PowerPC calling convention, including register usage, parameter passing, and stack management.