From C to Machine Code: Calls, Stack and the ABI

A C program is made of functions that call each other. The processor has no idea what a function is. A call is two jumps and an agreement about registers, and this page follows one.

You Will Be Able To

  • Follow a call and a return through jal, jalr and the register ra.
  • Say where the arguments and the result of a function travel.
  • Decide which registers may hold a value across a call, and which may not.
Lesson
S2.3
Time
28 min
Runs on
Your browser
Check
6 questions

Two engineers write two halves of one program. One writes main, the other writes add3, and they never meet. The halves are joined, and the program must still work. For that, main must know where add3 reads its numbers, and add3 must know how to get back.

Before You Start

You need the instruction groups of S2.1. You need jal from S2.18: a jump that also writes a register.

You need to read a few lines of C: a function with arguments, and a return value.

Five questions this page answers
Question
1Which two instructions make a call and a return?
2What does the register ra hold during a call?
3Where do the arguments go, and where does the result come back?
4Which registers may a callee change freely?
5Where must a caller keep a value that it needs after a call?

The Idea: Two Jumps and an Agreement

A function is called from many places, and must return to the right one each time. A plain jump cannot do that. A jump goes somewhere and forgets where it came from.

So a function call is a jump that remembers. The instruction jal writes the address of the instruction after itself into a register, and then jumps. That saved address is the return address. The function ends with a second jump, to whatever address that register holds.

The function that makes the call is the caller. The function that is called is the callee. The same function can be both: it is called by one function and calls another.

Two jumps are not enough. The caller and the callee must also agree where the arguments are, and which registers the callee may overwrite. That agreement is the calling convention. Every compiler for RISC-V follows the same one.

The convention gives each register a job and a second name. Register x1 gets a name of two letters for its job, the return address: it is called ra. Registers x10 to x17 hold arguments, and are called a0 to a7. From here on, this module uses those names.

New Words

New words on this page
WordMeaning
Function callA jump to a function that also keeps the address to come back to.
CallerThe function that makes a call.
CalleeThe function that is called.
Return addressThe address of the instruction after the call. The callee jumps to it when it is done.
Calling conventionThe agreement on where arguments, results and return addresses are, and who may change which register.
ABIApplication binary interface. The full set of such agreements for one ISA. The calling convention is its main part.
raRegister x1 under its second name. It holds the return address.
jalrJump and link register. A jump to the address in a register plus an immediate. It can write a return address too.
Argument registerOne of a0 to a7. Arguments go in, in order. The result comes back in a0.
Temporary registerOne of t0 to t6. A callee may change it without asking.
Saved registerOne of s0 to s11. A callee must hand it back with the value it had.
StackA region of memory where functions keep values while they run. The next lesson covers it.
Hand-compiledTurned from C into assembly by a person, not by a compiler. All assembly on this page is hand-compiled.

One Picture: A Call and a Return

One Call and One ReturnStep through the picture. The caller is on the left and the callee on the right. Three kinds of register connect them.
  • Processor
  • Bus
  • Control / FSM
One Call and One ReturnStep through the picture. The caller is on the left and the callee on the right. Three kinds of register connect them. component The caller: main the function thatmakes the call component a0, a1, a2 the arguments go out;a0 brings the resultback component The callee: add3 the function that iscalled component ra holds the address tocome back to component PC the address of thenext instruction writes the argumentsreads themjal: PC + 4jal: the address ofadd3writes the result intoa0jalr: the PC takes ra
  1. component The caller: mainthe function that makes the call
    • writes the arguments → a0, a1, a2
    • jal: the address of add3 → PC
  2. component a0, a1, a2the arguments go out; a0 brings the result back
    • reads them → The callee: add3
  3. component PCthe address of the next instruction
    • jal: PC + 4 → ra
  4. component raholds the address to come back to
    • jalr: the PC takes ra → PC
  5. component The callee: add3the function that is called
    • writes the result into a0 → a0, a1, a2
  1. The arguments

    The caller puts 1, 2 and 3 into a0, a1 and a2. The callee knows to look there, because both obey one convention.

  2. The call

    One instruction does two things. It writes the address of the instruction after itself into ra. And it writes the address of add3 into the PC.

  3. The work

    The callee reads its arguments and puts the sum into a0. It does not know who called it.

  4. The return

    The callee ends with one instruction that copies ra into the PC. The caller goes on where it left off.

  5. The result

    Back in the caller, a0 holds the result. The caller may use it at once.

Read the diagram as text
  • The caller: main: the function that makes the call
  • a0, a1, a2: the arguments go out; a0 brings the result back
  • The callee: add3: the function that is called
  • ra: holds the address to come back to
  • PC: the address of the next instruction
  • The caller: main → a0, a1, a2: writes the arguments
  • a0, a1, a2 → The callee: add3: reads them
  • PC → ra: jal: PC + 4
  • The caller: main → PC: jal: the address of add3
  • The callee: add3 → a0, a1, a2: writes the result into a0
  • ra → PC: jalr: the PC takes ra

The callee never names its caller. The return address in ra is the only link back.

The 32 registers under their second names
NameRegisterJobAfter a call, the caller finds it
zerox0always 0unchanged: it cannot change
rax1the return addresschanged by its own call
spx2a pointer into the stack: the next lessonunchanged
gp, tpx3, x4two pointers set once at start-upunchanged
t0 to t2x5 to x7temporary valuesperhaps changed
s0, s1x8, x9saved valuesunchanged
a0 to a7x10 to x17arguments; a0 also carries the resultperhaps changed
s2 to s11x18 to x27saved valuesunchanged
t3 to t6x28 to x31temporary valuesperhaps changed

Count the rows: 1 + 1 + 1 + 2 + 3 + 2 + 8 + 10 + 4 is 32. The hardware treats x1 to x31 alike. Only the convention tells them apart.

The Smallest Example, Worked by Hand

Here is a program of two functions in C. The function main calls add3 with 1, 2 and 3, and adds 10 to what comes back.

The C program. No C compiler is used on this page.
int add3(int a, int b, int c) {
  return a + b + c;
}

int main(void) {
  return add3(1, 2, 3) + 10;
}

Below is the same program in assembly, compiled by hand. The function main starts at address 0, and add3 at address 18 in hex.

The program, line by line
AddressAssemblyFrom the C
00addi a0, zero, 1the first argument
04addi a1, zero, 2the second argument
08addi a2, zero, 3the third argument
0cjal ra, 0x18the call of add3
10addi a0, a0, 10+ 10, into the place of the return value of main
14ebreakthe end of main: the lab stops here
18add a0, a0, a1add3: a + b
1cadd a0, a0, a2+ c, into the place of the return value
20jalr zero, 0(ra)return

Addresses are in hex. A real main returns to its own caller. Here it stops at an ebreak.

Follow the call. The jal is at address c. The instruction after it is at 10. So the jal writes 10 into ra, and the PC goes to 18.

Follow the return. The instruction jalr zero, 0(ra) adds 0 to ra and puts the sum into the PC. So the PC goes to 10. Its destination register is zero, which means: keep no return address this time.

The Rules

  1. Rule 1: A call is jal ra, with the address of the function.

    It writes the address of the next instruction into ra, and jumps.

  2. Rule 2: A return is jalr zero, 0(ra).

    The PC takes the value of ra. Assemblers accept the short form ret.

  3. Rule 3: Arguments travel in a0 to a7, in order.

    The result comes back in a0.

  4. Rule 4: A callee may change every temporary and every argument register.

    That is t0 to t6 and a0 to a7. A call also changes ra.

  5. Rule 5: A callee must hand back s0 to s11 and sp as it got them.

    If it uses one, it must save the old value first and restore it at the end.

  6. Rule 6: A value that the caller needs after a call belongs in a saved register.

    Or in memory. Never in a temporary or an argument register.

Sources for These Rules

Every fact about the calling convention on this page is stated as commonly described. That covers the names and jobs of the registers, and which of them a callee may change. It also covers the use of jal and jalr for a call and a return. The document that defines the convention is not in the reference library. So none of these facts is checked against it. The register names were compared with the tables of the assembler of this track.

The plan of this track points to two textbooks for this material. They are Patterson and Hennessy, section 2.8, and Harris and Harris, section 6.3. Those places are not checked either.

Now Run It

The lab at the end of this page runs the hand-compiled program on the small model. The rows now show the registers under their second names.

Printed by the lab on Icarus. The instruction-level model of this track printed the same rows.
00000000 | addi a0, zero, 1 | a0 = 00000001
00000004 | addi a1, zero, 2 | a1 = 00000002
00000008 | addi a2, zero, 3 | a2 = 00000003
0000000c | jal ra, 0x18 | ra = 00000010, next is 00000018
00000018 | add a0, a0, a1 | a0 = 00000003
0000001c | add a0, a0, a2 | a0 = 00000006
00000020 | jalr zero, 0(ra) | next is 00000010
00000010 | addi a0, a0, 10 | a0 = 00000010
00000014 | ebreak | stop
a0=16 ra=00000010

Rule 3 at work: rows 1 to 3 load the arguments. Rows 5 and 6 are the callee, and they read a0, a1 and a2.

Rule 1 at work: row 4. The jal at c writes 10 into ra, and the next instruction is at 18.

Rule 2 at work: row 7. The jalr sends the PC to 10, the value of ra. Row 8 is main again.

Rule 3 again: row 8 reads a0, which holds the 6 from add3, and adds 10. The last row shows 16.

Why It Is Built This Way

Design choiceThe alternativeWhat the choice buys, and costs
The return address in a registerThe call writes it to memoryA function that calls nothing touches no memory at all. A function that does call must save ra itself.
Arguments in registersArguments in memoryNo loads and stores for most calls. Only 8 registers: more arguments go to memory after all.
Two kinds of register: temporary and savedThe caller saves everything, or the callee doesEach side saves only what it uses. Every programmer and compiler must know the two lists.
One convention for everybodyEach compiler choosesCode from any compiler, and hand-written assembly, can be joined. The convention can never change.
The convention outside the hardwareA call instruction that saves registers itselfThe hardware stays simple: jal and jalr are ordinary jumps. Nothing checks that the convention is obeyed.

The Trap: The Temporary That Was Lost in a Call

A programmer writes main by hand. It keeps a number k, which is 5, and calls a function named twice with 3. Then it adds k to the result. The answer should be 6 plus 5, which is 11.

A value needs a register, and t0 is free, so k goes into t0. The function twice was written by someone else. It uses t0 as scratch space, which the convention allows.

The same model. The function twice starts at address 14 in hex.
00000000 | addi t0, zero, 5 | t0 = 00000005
00000004 | addi a0, zero, 3 | a0 = 00000003
00000008 | jal ra, 0x14 | ra = 0000000c, next is 00000014
00000014 | add t0, a0, a0 | t0 = 00000006
00000018 | addi a0, t0, 0 | a0 = 00000006
0000001c | jalr zero, 0(ra) | next is 0000000c
0000000c | add a0, a0, t0 | a0 = 0000000c
00000010 | ebreak | stop
a0=12

Read row 4. The callee writes 6 into t0. The 5 of main is gone, and nothing reported it.

Read the last two rows. Back in main, the add reads t0 and gets 6. The result is 12, not 11.

Both functions are correct by themselves. The bug is in main: it broke rule 6. With k in the saved register s0, the same program gives the right answer:

The last three rows of the same program with s0 in place of t0.
0000000c | add a0, a0, s0 | a0 = 0000000b
00000010 | ebreak | stop
a0=11

This main may use s0 freely, because nothing called it. A function with a caller must save s0 first. The next lesson shows how.

At Scale

This page2 functions, 1 call
A real programthousands of functions, calls many levels deep

This section looks ahead. The convention is what lets millions of functions from different authors run as one program.

  1. Calls inside calls

    A callee that calls another function overwrites ra. It must keep the old value somewhere: the next lesson.

  2. Calls that are far away

    A jal reaches about 1 MiB. A call beyond that is an auipc and a jalr: this is why jalr adds an immediate to a register.

  3. Calls through a pointer

    When the address of a function is known only while the program runs, the call is a jalr through a register.

  4. Interrupts

    An interrupt arrives between any two instructions and obeys no convention. Its handler must save every register it touches. Module S6 covers that.

Try It

Run the lab. Find the row that writes ra, and the row that reads it.

Change the program so that main computes add3(1, 2, 3) + add3(4, 5, 6). Where must the first result wait?

Replace the return of add3 with a jump to address 10 in hex. It works. Why is that still wrong for a function?

RUNIcarus Verilog · in your browser
Edit the code, then run it
Expected: 00000000 | addi a0, zero, 1 | a0 = 00000001 00000004 | addi a1, zero, 2 | a1 = 00000002 00000008 | addi a2, zero, 3 | a2 = 00000003 0000000c | jal ra, 0x18 | ra = 00000010, next is 00000018 00000018 | add a0, a0, a1 | a0 = 00000003 0000001c | add a0, a0, a2 | a0 = 00000006 00000020 | jalr zero, 0(ra) | next is 00000010 00000010 | addi a0, a0, 10 | a0 = 00000010 00000014 | ebreak | stop a0=16 ra=00000010

Check Yourself

Predict the outputThis program puts 7 into a0 and calls a function at address 10 in hex. The function doubles a0. Back in the caller, 1 is added. What does the last row say?
// What do a0 and ra hold at the end?
// The program is the task at the top. Each row is one instruction: i(kind, a, b, c).
// The comment beside a row is the same instruction in assembly.
module tb;
  task automatic the_program();
    i(ADDI,   a0,   zero, 7);      // 00: addi a0, zero, 7
    i(JAL,    ra,   zero, 'h10);   // 04: jal ra, 0x10
    i(ADDI,   a0,   a0,   1);      // 08: addi a0, a0, 1
    i(EBREAK, zero, zero, 0);      // 0c: ebreak
    i(ADD,    a0,   a0,   a0);     // 10: add a0, a0, a0      the function starts here
    i(JALR,   zero, ra,   0);      // 14: jalr zero, 0(ra)
  endtask

  // ---- From here down: a small model of an RV32I processor, as test code. You need not change it. ----
  localparam int LUI = 0, AUIPC = 1, JAL = 2, JALR = 3, BEQ = 4, BNE = 5, BLT = 6, BGE = 7, BLTU = 8, BGEU = 9, LW = 10, SW = 11,
                 ADDI = 12, SLTI = 13, SLTIU = 14, XORI = 15, ORI = 16, ANDI = 17, SLLI = 18, SRLI = 19, SRAI = 20,
                 ADD = 21, SUB = 22, SLL = 23, SLT = 24, SLTU = 25, XOR = 26, SRL = 27, SRA = 28, OR = 29, AND = 30, EBREAK = 31;
  localparam int zero = 0, ra = 1, sp = 2, gp = 3, tp = 4, t0 = 5, t1 = 6, t2 = 7, s0 = 8, s1 = 9, a0 = 10, a1 = 11, a2 = 12, a3 = 13, a4 = 14, a5 = 15,
                 a6 = 16, a7 = 17, s2 = 18, s3 = 19, s4 = 20, s5 = 21, s6 = 22, s7 = 23, s8 = 24, s9 = 25, s10 = 26, s11 = 27, t3 = 28, t4 = 29, t5 = 30, t6 = 31;
  int kind [0:63], fa [0:63], fb [0:63], fc [0:63];   // the program: one row for each instruction
  int rows = 0;
  task automatic i(input int k, input int a, input int b, input int c);   // add one row to the program
    if (rows < 64) begin kind[rows] = k; fa[rows] = a; fb[rows] = b; fc[rows] = c; rows++; end
  endtask
  logic [31:0] x [0:31];             // the 32 registers
  logic [31:0] pc;                   // the address of the next instruction
  logic [31:0] mem [0:16383];        // 64 KiB of data memory, from address 8000_0000 up
  int   steps;
  bit   stopped, faulted;
  function automatic string rn(input int n);                // the name of a register in the calling convention
    case (n)
      0: return "zero"; 1: return "ra"; 2: return "sp"; 3: return "gp"; 4: return "tp"; 5: return "t0"; 6: return "t1"; 7: return "t2"; 
      8: return "s0"; 9: return "s1"; 10: return "a0"; 11: return "a1"; 12: return "a2"; 13: return "a3"; 14: return "a4"; 15: return "a5"; 
      16: return "a6"; 17: return "a7"; 18: return "s2"; 19: return "s3"; 20: return "s4"; 21: return "s5"; 22: return "s6"; 23: return "s7"; 
      24: return "s8"; 25: return "s9"; 26: return "s10"; 27: return "s11"; 28: return "t3"; 29: return "t4"; 30: return "t5"; 31: return "t6"; 
      default: return "?";
    endcase
  endfunction
  function automatic string nm(input int k);                // the name of a kind of instruction
    case (k)
      0: return "lui"; 1: return "auipc"; 2: return "jal"; 3: return "jalr"; 4: return "beq"; 5: return "bne"; 
      6: return "blt"; 7: return "bge"; 8: return "bltu"; 9: return "bgeu"; 10: return "lw"; 11: return "sw"; 
      12: return "addi"; 13: return "slti"; 14: return "sltiu"; 15: return "xori"; 16: return "ori"; 17: return "andi"; 
      18: return "slli"; 19: return "srli"; 20: return "srai"; 21: return "add"; 22: return "sub"; 23: return "sll"; 
      24: return "slt"; 25: return "sltu"; 26: return "xor"; 27: return "srl"; 28: return "sra"; 29: return "or"; 
      30: return "and"; 31: return "ebreak"; 
      default: return "?";
    endcase
  endfunction
  // One instruction: read the row at the PC, do what it says, and print one line.
  task automatic step();
    int k, a, b;
    logic [31:0] c, r1, r2, res, next, ad;
    string text, effect;
    bit writes, go, take;
    go = 1;  k = EBREAK;  a = 0;  b = 0;  c = 0;
    if (pc[1:0] != 0 || pc >= 256) begin
      $display("%08h | no instruction at this address", pc);  faulted = 1;  stopped = 1;  go = 0;
    end
    else begin k = kind[pc >> 2];  a = fa[pc >> 2];  b = fb[pc >> 2];  c = fc[pc >> 2]; end
    r1 = x[b[4:0]];  r2 = x[c[4:0]];
    next = pc + 4;  writes = 1;  res = 0;  effect = "";
    if (go) case (k)
      LUI:   begin res = c << 12;       text = $sformatf("lui %s, 0x%0h", rn(a), c); end
      AUIPC: begin res = pc + (c << 12); text = $sformatf("auipc %s, 0x%0h", rn(a), c); end
      JAL:   begin res = pc + 4;  next = c;  text = $sformatf("jal %s, 0x%0h", rn(a), c); end
      JALR:  begin res = pc + 4;  next = (r1 + c) & ~32'd1;  text = $sformatf("jalr %s, %0d(%s)", rn(a), $signed(c), rn(b)); end
      BEQ, BNE, BLT, BGE, BLTU, BGEU: begin
        r1 = x[a[4:0]];  r2 = x[b[4:0]];  writes = 0;
        case (k)
          BEQ:  take = (r1 == r2);
          BNE:  take = (r1 != r2);
          BLT:  take = ($signed(r1) < $signed(r2));
          BGE:  take = ($signed(r1) >= $signed(r2));
          BLTU: take = (r1 < r2);
          default: take = (r1 >= r2);
        endcase
        if (take) next = c;
        text = $sformatf("%s %s, %s, 0x%0h", nm(k), rn(a), rn(b), c);
        if (take) effect = $sformatf("taken: next is %08h", next);
        else effect = "not taken";
      end
      LW, SW: begin
        ad = r1 + c;
        text = $sformatf("%s %s, %0d(%s)", nm(k), rn(a), $signed(c), rn(b));
        if (ad[1:0] != 0 || ad < 32'h8000_0000 || ad > 32'h8000_fffc) begin
          $display("%08h | %s | no data memory at %08h", pc, text, ad);  faulted = 1;  stopped = 1;  go = 0;
        end
        else if (k == LW) begin res = mem[ad[15:2]];  effect = $sformatf(" from mem[%08h]", ad); end
        else begin mem[ad[15:2]] = x[a[4:0]];  writes = 0;  effect = $sformatf("mem[%08h] = %08h", ad, x[a[4:0]]); end
      end
      ADDI:  res = r1 + c;
      SLTI:  res = ($signed(r1) < $signed(c)) ? 1 : 0;
      SLTIU: res = (r1 < c) ? 1 : 0;
      XORI:  res = r1 ^ c;
      ORI:   res = r1 | c;
      ANDI:  res = r1 & c;
      SLLI:  res = r1 << c[4:0];
      SRLI:  res = r1 >> c[4:0];
      SRAI:  res = $signed(r1) >>> c[4:0];
      ADD:   res = r1 + r2;
      SUB:   res = r1 - r2;
      SLL:   res = r1 << r2[4:0];
      SLT:   res = ($signed(r1) < $signed(r2)) ? 1 : 0;
      SLTU:  res = (r1 < r2) ? 1 : 0;
      XOR:   res = r1 ^ r2;
      SRL:   res = r1 >> r2[4:0];
      SRA:   res = $signed(r1) >>> r2[4:0];
      OR:    res = r1 | r2;
      AND:   res = r1 & r2;
      default: begin
        $display("%08h | ebreak | stop", pc);  stopped = 1;  go = 0;
      end
    endcase
    if (k >= ADDI && k <= SRAI) text = $sformatf("%s %s, %s, %0d", nm(k), rn(a), rn(b), $signed(c));
    if (k >= ADD && k <= AND)   text = $sformatf("%s %s, %s, %s", nm(k), rn(a), rn(b), rn(c[4:0]));
    if (go && writes) begin
      if (a[4:0] != 0) x[a[4:0]] = res;                      // register 0 is never written
      effect = {$sformatf("%s = %08h", rn(a), x[a[4:0]]), effect};
      if (k == JAL || k == JALR) begin                       // a jump with x0 as its destination keeps no return address
        if (a[4:0] == 0) effect = $sformatf("next is %08h", next);
        else effect = {effect, $sformatf(", next is %08h", next)};
      end
    end
    if (go) begin
      $display("%08h | %s | %s", pc, text, effect);
      pc = next;  steps++;
    end
  endtask
  task automatic run(input logic [31:0] start);
    pc = start;  steps = 0;  stopped = 0;  faulted = 0;
    while (!stopped && steps < 2000) step();
  endtask
  initial begin
    for (int n = 0; n < 32; n++) x[n] = 0;
    for (int n = 0; n < 16384; n++) mem[n] = 0;
    the_program();
    run(0);
    if (!stopped) $display("still running after %0d instructions", steps);
    $display("a0=%0d ra=%08h", x[10], x[1]);
  end
endmodule
ConceptWhich two instructions make a call and a return?
ConceptWhat does ra hold while a callee runs?
ConceptA function takes two arguments and gives one result. Which registers carry them?
ConceptWhich of these may a callee change without restoring it?
ConceptA caller needs a value after a call. Where should it keep the value?

Common Mistakes

Wrong Keep a value in t0 or a1 across a call.

A callee may change every temporary and argument register.

Fix Keep it in a saved register, s0 to s11, or in memory.

Wrong Return with a jump to a fixed address.

The function then works for one caller only.

Fix Return with jalr zero, 0(ra), which goes back to whoever called.

Wrong Use a saved register in a callee without saving it.

The caller expects its value back. The caller then computes with a wrong number.

Fix Save the old value first, and restore it before the return.

Remember

  • A call is jal ra: it keeps the address of the next instruction in ra. A return is jalr zero, 0(ra).
  • Arguments travel in a0 to a7. The result comes back in a0.
  • A callee may change t0 to t6, a0 to a7 and ra. It must hand back s0 to s11 and sp.
  • A value that must survive a call lives in a saved register or in memory.

Practice

Report a problem with this page