Skip to content

Project Demo

Nat edited this page May 15, 2026 · 2 revisions

Two example programs have been provided along with their IR output, assembly output, and execution in the RARS simulator.

Fibonacci Sequence

This example demonstrates function calls and loops.

C code:

int fib(int n);

int main() {
    int fib10 = fib(10);
    return fib10;
}

int fib(int n) {
    int a = 0;
    int b = 1;
    for (int i = 0; i < n; ++i) {
        int c = a + b;
        a = b;
        b = c;
    }

    return a;
}

Intermediate Representation:

fn %main() {
@0: (precedes)
	ptr $fib10 = allocate 32
	i32 $0 = call %fib, i32 10
	store i32 $0 at ptr $fib10
	i32 $1 = load ptr $fib10
	ret i32 $1

}

fn %fib(i32 $n) {
@0: (precedes @1)
	ptr $0 = allocate 32
	store i32 $n at ptr $0
	ptr $a = allocate 32
	store i32 0 at ptr $a
	ptr $b = allocate 32
	store i32 1 at ptr $b
	ptr $i = allocate 32
	store i32 0 at ptr $i

@1: (precedes @3 @2)
	i32 $1 = load ptr $i
	i32 $2 = cmp slt i32 $1, i32 10
	br to @3 if i32 $2 = 0
	ptr $c = allocate 32
	i32 $3 = load ptr $a
	i32 $4 = load ptr $b
	i32 $5 = add i32 $3, i32 $4
	store i32 $5 at ptr $c
	i32 $6 = load ptr $b
	store i32 $6 at ptr $a
	i32 $7 = load ptr $c
	store i32 $7 at ptr $b

@2: (precedes @1)
	i32 $8 = load ptr $i
	i32 $8 = add i32 $8, i32 1
	store i32 $8 at ptr $i
	jmp to @1

@3: (precedes)
	i32 $9 = load ptr $a
	ret i32 $9

}

RISC-V Assembly generation

.text
_start:
	j main
puts:
	li a7, 11
	ecall
	ret
main:
	addi sp, sp, -16
	sw ra, 12(sp)
.L_main_0:
	li a0, 10
	jal fib
	mv t0, a0
	sw t0, 8(sp)
	lw t1, 8(sp)
	mv a0, t1
	lw ra, 12(sp)
	addi sp, sp, 16
	ret
fib:
	addi sp, sp, -32
	sw ra, 28(sp)
.L_fib_0:
	sw a0, 24(sp)
	li t0, 0
	sw t0, 20(sp)
	li t0, 1
	sw t0, 16(sp)
	li t0, 0
	sw t0, 12(sp)
.L_fib_1:
	lw t0, 12(sp)
	slti t1, t0, 10
	beqz t1, .L_fib_3
	lw t2, 20(sp)
	lw s0, 16(sp)
	add s1, t2, s0
	sw s1, 8(sp)
	lw s2, 16(sp)
	sw s2, 20(sp)
	lw s3, 8(sp)
	sw s3, 16(sp)
.L_fib_2:
	lw s4, 12(sp)
	addi s4, s4, 1
	sw s4, 12(sp)
	j .L_fib_1
.L_fib_3:
	lw s5, 20(sp)
	mv a0, s5
	lw ra, 28(sp)
	addi sp, sp, 32
	ret

RARS output for fibonacci program

Factorial

Clone this wiki locally