%rsp
register contains the lowest stack address (“top” of stack)Syntax: pushq
Src
%rsp
by 8%rsp
Syntax: popq
Dest
%rsp
%rsp
by 8%rsp
C code
void multstore (long x, long y, long *dest) {
long t = mult2(x, y);
*dest = t;
}
Assembly
multstore:
push %rbx # save %rbx
mov %rdx, %rbx # save dest
callq mult2 # mult2(x, y)
mov %rax, (%rbx) # save at dest
pop %rbx # restore %rbx
retq # return
C code
long mult2 (long a, long b) {
long s = a * b;
return s;
}
Assembly
mult2:
mov %rdi, %rax # a
imul %rsi, %rax # a * b
retq # return
call
label
ret
%rdi
%rsi
%rdx
%rcx
%r8
%r9
Subsequent parameters (or parameters larger than 64 bits) should be pushed onto the stack, with the first argument topmost.
Return value in %rax
f
: calls g
g
: calls h
twice
h
: recursivecall
instructionret
instructioncall
instruction)incr
C code
long incr(long *p, long val) {
long x = *p;
long y = x + val;
*p = y;
return x;
}
Assembly code
incr:
movq (%rdi), %rax
addq %rax, %rsi
movq %rsi, (%rdi)
ret
foo
calls bar
:
foo
is the callerbar
is the callee%rax
%rdi
, \(\ldots\), %r9
%r10
, %r11
%rbx
, %r12
, %r13
, %r14
%rbp
%rsp
C code
long pcount_r(unsigned long x) {
if (x == 0) {
return 0;
}
else {
return (x & 1) + pcount_r(x >> 1);
}
}
Assembly
pcount_r
movl $0, %eax # base case
testq %rdi, %rdi # |
je .L6 # |
pushq %rbx # caller save
movq %rdi, %rbx # set up call
andl $1, %ebx # | x & 1
shrq %rdi # | x >> 1
call pcount_r # recursive call
addq %rbx, %rax # result
popq %rbx # function completion
.L6:
rep; ret # base case
%rax