 # fibonacci numbers
 
-TARGET_INDEX = 10
+MAX_FIB = 29
 
 llvm = require '../'
 

# have the blocks aready we have to terminate them.
fib.return one

main.return main.callFunction fib, main.value i32, TARGET_INDEX

mod.writeBitcodeToFile "fib.bc"
mod.dump()

vd = llvm.type.void

mod = llvm.CodeUnit "fib"

putchar = mod.declareFunction "putchar", vd, i32
putOnes = mod.makeFunction "putOnes", vd, i32
putTens = mod.makeFunction "putTens", vd, i32
puti = mod.makeFunction "puti", vd, i32

newline = mod.makeFunction "newline"
newline.callFunction putchar, newline.value(i32, 10)
newline.return()

onesCh = putOnes.add putOnes.value(i32, 48),
  putOnes.urem putOnes.parameter(0), putOnes.value(i32, 10)
putOnes.callFunction putchar, onesCh
putOnes.return()

divTen = putTens.udiv putTens.parameter(0), putTens.value(i32, 10)
hasTens = putTens.if putTens.equal putTens.value(i32, 0), divTen
hasTens.then.callFunction putchar, putTens.value(i32, 32)
hasTens.else.callFunction putOnes, divTen
putTens.return()

puti.callFunction putTens, puti.udiv puti.parameter(0),
  puti.value(i32, 10000)
puti.callFunction putTens, puti.udiv puti.parameter(0),
  puti.value(i32, 1000)
puti.callFunction putTens, puti.udiv puti.parameter(0),
  puti.value(i32, 100)
puti.callFunction putTens, puti.udiv puti.parameter(0),
  puti.value(i32, 10)
puti.callFunction putTens, puti.parameter(0)
puti.callFunction putOnes, puti.parameter(0)
puti.callFunction newline
puti.return()

main = mod.makeFunction "main", i32
fib = mod.makeFunction "fib", i32, i32
