Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ;; lisp compiler input
- ;; `integer` maps to 64 bit integer / uint64_t / i64
- (compile-function
- 'factorial 'integer '((x . integer))
- '((entry (goto-if (= integer x 0) zero else))
- (zero (return integer 1))
- (else (return integer (* integer x (call integer factorial (integer - integer x 1)))))))
- ;; LLVM output
- define i64 @factorial(i64 %x) {
- ;; if X = 0, factorial(X) = 1
- ;; if X > 0, factorial(X) = x * factorial(X-1)
- ENTRY:
- %ENTRY0_1 = icmp eq i64 %x, 0 ;; compare X to 0
- br i1 %ENTRY0_1, label %ZERO, label %ELSE ;; if X is zero, go to ZERO, else ELSE
- ZERO:
- ret i64 1 ;; return 1
- ELSE:
- %ELSE0_1 = sub i64 %x, 1 ;; take 1 from X
- %ELSE0_2 = call i64 @factorial(i64 %ELSE0_1) ;; call factorial with the decremented X
- %ELSE0_3 = mul i64 %x, %ELSE0_2 ;; multiply it by X
- ret i64 %ELSE0_3 ;; return X * factorial(x-1)
- }
- * ^D
- $ cat testfact.c
- #include <stdint.h>
- #include <stdio.h>
- extern uint64_t factorial(uint64_t x);
- int main() {
- uint64_t x = 10;
- printf("%llu! = %llu", x, factorial(x));
- return (int)x;
- }
- $ clang -c fact.ll -o fact.o
- $ clang fact.o testfact.c -o fact
- $ ./fact
- 10! = 3628800
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement