Skip to content

Instantly share code, notes, and snippets.

@DocBohn
Created May 5, 2025 16:06
Show Gist options
  • Save DocBohn/8cf317a94afeb9ec7b46672f69010b29 to your computer and use it in GitHub Desktop.
Save DocBohn/8cf317a94afeb9ec7b46672f69010b29 to your computer and use it in GitHub Desktop.
Code demonstrating hand-crafted and compiler-generated function inlining
static int compute_triangle_number(int base) {
int base_incremented = base + 1;
int numerator = base * base_incremented;
return numerator/2;
}
long simple_bonus_threshold(unsigned int number) {
int triangle_number = compute_triangle_number(number);
return 3 * triangle_number;
}
// -finline-functions-called-once
// or
// -finline-small-functions
// or
// -finline-functions
// and/or
// mark compute_triangle_number as `inline`
simple_bonus_threshold:
madd w0, w0, w0, w0
add w0, w0, w0, lsr 31
and w1, w0, -2
add w0, w1, w0, asr 1
sxtw x0, w0
ret
# -finline-functions-called-once
# or
# -finline-small-functions
# or
# -finline-functions
# and/or
# mark compute_triangle_number as `inline`
simple_bonus_threshold:
leal 1(%rdi), %eax
imull %eax, %edi
movl %edi, %eax
shrl $31, %eax
addl %edi, %eax
movl %eax, %edx
sarl %edx
andl $-2, %eax
addl %edx, %eax
cltq
ret
compute_triangle_number:
madd w0, w0, w0, w0
add w0, w0, w0, lsr 31
asr w0, w0, 1
ret
simple_bonus_threshold:
stp x29, x30, [sp, -16]!
mov x29, sp
bl compute_triangle_number
add w0, w0, w0, lsl 1
sxtw x0, w0
ldp x29, x30, [sp], 16
ret
compute_triangle_number:
leal 1(%rdi), %eax
imull %eax, %edi
movl %edi, %eax
shrl $31, %eax
addl %edi, %eax
sarl %eax
ret
simple_bonus_threshold:
call compute_triangle_number
leal (%rax,%rax,2), %eax
cltq
ret
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment