sdiehl / kaleidoscope

Haskell LLVM JIT Compiler Tutorial
http://www.stephendiehl.com/llvm
Other
1.03k stars 131 forks source link

Only the first top level expression gets evaluated #50

Open ChickenProp opened 5 years ago

ChickenProp commented 5 years ago

For example

$ stack exec chapter4                                                                                                                                  [0 git/remotes/origin/HEAD]
ready> extern sin(x);
; ModuleID = 'my cool jit'
source_filename = "<string>"

declare double @sin(double)

ready> sin(1);
; ModuleID = 'my cool jit'
source_filename = "<string>"

declare double @sin(double)

define double @main() {
entry:
  %0 = call double @sin(double 1.000000e+00)
  ret double %0
}

Evaluated to: 0.8414709848078965
ready> sin(2);
; ModuleID = 'my cool jit'
source_filename = "<string>"

declare double @sin(double)

define double @main() {
entry:
  %0 = call double @sin(double 1.000000e+00)
  ret double %0
}

define double @main.1() {
entry:
  %0 = call double @sin(double 2.000000e+00)
  ret double %0
}

Evaluated to: 0.8414709848078965
ready> 
Goodbye.

sin(2) is 0.91, and if we try that prior to sin(1), that's the answer we get. But here, the result is 0.84 from both.

The problem seems to be that the JIT always executes the function "main" if it exists:

          EE.withModuleInEngine executionEngine m $ \ee -> do
            mainfn <- EE.getFunction ee (AST.Name "main")
            case mainfn of
              Just fn -> do
                res <- run fn
                putStrLn $ "Evaluated to: " ++ show res
              Nothing -> return ()

but in codegenTop we use define double "main", which only generates a function named "main" if it doesn't already exist. If it does exist, we get "main.1", "main.2" and so on.

Solution might be to have a version of define that handles these name conflicts like the current one, and a version that allows overwriting them. (Somehow? We can filter moduleDefinitions, but presumably mkName "main" will still give us "main.1".) I'm not sure if that's the best way to go about it.