ISA & Assembly
How is a call through a C function pointer, "(*fp)(x)", generally performed in RISC-V?
- AThe function address is placed in a register, and jalr jumps to that register's address
- Bjal jumps with the function address written as an immediate
- Cbeq compares with the function address and jumps if equal
Show answer and explanation
Answer: A. The function address is placed in a register, and jalr jumps to that register's address
The target of a function pointer is not known until run time, so jal, whose target is written in the instruction, cannot be used. Instead the pointer value is loaded into a register and the code jumps to it with, for example, "jalr ra, 0(t0)", leaving the return address in ra. Calls to C++ virtual functions and shared-library functions are similar indirect calls. Because the target can change, CPUs predict it with an indirect branch predictor.
- A. Correct. It is an indirect call whose target is set at run time.
- B. jal's target is fixed in the instruction and cannot change at run time.
- C. beq is a conditional branch, not used for calls.