From 2294180c3778d0fcfa877818e98c420fcd54bb8a Mon Sep 17 00:00:00 2001 From: johannst Date: Tue, 5 Dec 2023 22:08:06 +0000 Subject: deploy: 7e98f5def5942969f97f5f015e7fb8417793d132 --- src/fib/fib.rs.html | 157 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 157 insertions(+) create mode 100644 src/fib/fib.rs.html (limited to 'src/fib/fib.rs.html') diff --git a/src/fib/fib.rs.html b/src/fib/fib.rs.html new file mode 100644 index 0000000..87a1bbf --- /dev/null +++ b/src/fib/fib.rs.html @@ -0,0 +1,157 @@ +fib.rs - source
1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+
//! Fibonacci example.
+//!
+//! Jit compile a function at runtime (generate native host code) to compute the fibonacci sequence
+//! to demonstrate the [`juicebox_asm`] crate.
+
+use juicebox_asm::prelude::*;
+use juicebox_asm::Runtime;
+
+const fn fib_rs(n: u64) -> u64 {
+    match n {
+        0 => 0,
+        1 => 1,
+        _ => fib_rs(n - 2) + fib_rs(n - 1),
+    }
+}
+
+fn main() {
+    let mut asm = Asm::new();
+
+    let mut lp = Label::new();
+    let mut end = Label::new();
+
+    // Reference implementation:
+    //
+    // int fib(int n) {
+    //   int tmp = 0;
+    //   int prv = 1;
+    //   int sum = 0;
+    // loop:
+    //   if (n == 0) goto end;
+    //   tmp = sum;
+    //   sum += prv;
+    //   prv = tmp;
+    //   --n;
+    //   goto loop;
+    // end:
+    //   return sum;
+    // }
+
+    // SystemV abi:
+    //   rdi -> first argument
+    //   rax -> return value
+    let n = Reg64::rdi;
+    let sum = Reg64::rax;
+
+    let tmp = Reg64::rcx;
+    let prv = Reg64::rbx;
+
+    asm.mov(tmp, Imm64::from(0));
+    asm.mov(prv, Imm64::from(1));
+    asm.mov(sum, Imm64::from(0));
+
+    asm.bind(&mut lp);
+    asm.test(n, n);
+    asm.jz(&mut end);
+    asm.mov(tmp, sum);
+    asm.add(sum, prv);
+    asm.mov(prv, tmp);
+    asm.dec(n);
+    asm.jmp(&mut lp);
+    asm.bind(&mut end);
+    asm.ret();
+
+    // Write out JIT code for visualization.
+    // Disassemble for example with `ndisasm -b 64 jit.asm`.
+    let code = asm.into_code();
+    std::fs::write("jit.asm", &code).unwrap();
+
+    // Move code into executable page and get function pointer to it.
+    let mut rt = Runtime::new();
+    let fib = unsafe { rt.add_code::<extern "C" fn(u64) -> u64>(code) };
+
+    for n in 0..15 {
+        let fib_jit = fib(n);
+        println!("fib({}) = {}", n, fib_jit);
+        assert_eq!(fib_jit, fib_rs(n));
+    }
+}
+
\ No newline at end of file -- cgit v1.2.3