Giter VIP home page Giter VIP logo

tinyjit's Introduction

Haskell JIT Example

Build Status MIT 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.

.global main

main:
        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.

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.

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, Stephen Diehl

tinyjit's People

Contributors

sdiehl avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.