[LLVMdev] How to declare and use sprintf

Gordon Henriksen gordonhenriksen at mac.com
Sun Nov 25 16:59:59 PST 2007


On Nov 25, 2007, at 19:37, Jon Harrop wrote:

> Awesome stuff. Here is my most elegant Fibonacci example in OCaml so  
> far:
>
> open Llvm
>
> let ( |> ) x f = f x
>
> let int n = const_int i32_type n
>
> let return b x = build_ret x b |> ignore
>
> let build_fib m =
>  let ty =  function_type i32_type [| i32_type |] in
>  let fibf = define_function "fib" ty m in
>  let bb = builder_at_end (entry_block fibf) in
>  let n = param fibf 0 in
>
>  let retbb = append_block "return" fibf in
>  let retb = builder_at_end retbb in
>  let recursebb = append_block "recurse" fibf in
>  let recurseb = builder_at_end recursebb in
>
>  let ( <= ) f g = build_icmp Icmp_sle f g "cond" bb in
>
>  build_cond_br (n <= int 2) retbb recursebb bb |> ignore;
>  return retb (int 1);
>
>  let apply f xs = build_call f xs "apply" recurseb in
>  let ( +: ) f g = build_add f g "add" recurseb in
>  let ( -: ) f g = build_sub f g "sub" recurseb in
>
>  return recurseb
>    (apply fibf [| n -: int 1 |] +: apply fibf [| n -: int 2 |]);
>
>  fibf

Wow, it's “Lambda Calculus Gone Wild!”

> as you can see it already uses some functional features. Next, I'll  
> move the hard-coded program into data and write a more generic  
> compiler in it.

That'll be fun. Code generation in Ocaml is really elegant thanks to  
the matching and variant types. It would be nice to have that  
representation for the LLVM IR as well, but alas, it is not to be—no  
deconstruction for abstract types.

> Looks really good though... :-)

Very cool.

— Gordon





More information about the llvm-dev mailing list