https://github.com/sdiehl/tinyjit
Haskell JIT
https://github.com/sdiehl/tinyjit
Last synced: 3 months ago
JSON representation
Haskell JIT
- Host: GitHub
- URL: https://github.com/sdiehl/tinyjit
- Owner: sdiehl
- License: mit
- Created: 2016-01-02T00:59:31.000Z (almost 10 years ago)
- Default Branch: master
- Last Pushed: 2020-01-19T12:06:10.000Z (over 5 years ago)
- Last Synced: 2025-04-05T19:41:31.663Z (6 months ago)
- Language: Haskell
- Homepage: http://www.stephendiehl.com/posts/monads_machine_code.html
- Size: 16.6 KB
- Stars: 184
- Watchers: 9
- Forks: 9
- Open Issues: 2
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
Haskell JIT Example
-------------------[](https://travis-ci.org/sdiehl/tinyjit)
[](https://github.com/sdiehl/tinyjit/blob/master/LICENSE)Tiny example of building a intermediate language that JIT compiles Haskell DSL
into x86-64 machine code.Usage
-----The factorial function can be written in assembly, taking the input value in
``%rcx`` and computing the resulting value in ``%rax``.```perl
.global mainmain:
mov rcx, 5
mov rax, 1
.factor:
mul rcx
loop .factor
ret
```In our Haskell logic we compose these operations inside of the ``X86`` monad.
```haskell
factorial :: Int64 -> X86 ()
factorial n = do
mov rcx (I n)
mov rax (I 1)
l1 <- label
mul rcx
loop l1
ret
```The resulting logic can be JIT compiled inside of Haskell and invoked from
inside the Haskell runtime by calling out to the JIT'd memory.```haskell
main :: IO ()
main = do
let jitsize = 256*1024
mem <- allocateMemory jitsize
let jitm = assemble mem (factorial 5)case jitm of
Left err -> putStrLn err
Right jitst -> do
let machCode = _mach jitst
fn <- jit mem machCode
res <- fn
putStrLn $ "Result: " <> show res
```The machine code is generated.
```
48 c7 c1 05 00 00 00 48 c7 c0 01 00 00 00 48 f7 e1 e2 fc c3
```And executed to yield the result:
```
Result: 120
```License
-------Released under the MIT License.
Copyright (c) 2016-2020, Stephen Diehl