Last active
November 22, 2018 01:10
-
-
Save CAFxX/9d69bf3fb4bd36f1e8985ef165535c6f to your computer and use it in GitHub Desktop.
Visualize what a Golang JIT would look like
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "go/jit" | |
func main() { | |
// jit.Run is a shorthand for jit.Compile, jit.Link and jit.Load | |
c, err := jit.Run(` | |
// - compiler is the same as the one used to build the executable | |
// the jit is running in | |
// - imports are allowed (but are restricted to the imports of | |
// the executable the jit is running in) | |
// - visibility rules are as usual (first uppercase symbols are | |
// exported from the jitted package, everything else is private) | |
// - init() is allowed (it runs during jit.Load) | |
package example | |
// - if two jitted modules have the same package name linking will | |
// fail | |
// - stacktraces will show go/jit/module/<package>/<symbol> <file>:<line>+<jitline> | |
// for symbols (e.g. for the return line in the jitted B function below | |
// "go/jit/module/example/B gojit.go:7+21") | |
var A int | |
var i int = 5 | |
func B(b int) (r int) { | |
i, r = b, i | |
return | |
} | |
`) | |
// compilation and dynlinking errors | |
if err != nil { | |
panic(err) | |
} | |
// plugin-style lookup (error checking omitted for brevity) | |
A := c.Lookup("A").(*int) | |
B := c.Lookup("B").(func(int)(int)) | |
// indirect call, no reflection | |
*A = B(3) | |
// other goodies | |
c.Loaded() // false if the package was just compiled, true if it was also loaded | |
c.PackageName() // returns the package name | |
c.Source() // returns the source of the jitted package | |
c.Ast() // returns the AST of the jitted package | |
c.Symbols() // returns a list of symbols exported by the package | |
jit.Modules() // returns a list of jitted packages | |
// A, B and c are all dead here, GC will eventually unload/free | |
// the jitted module. To avoid this keep the references alive | |
// (e.g. store in long-lived objects/goroutines or package-level | |
// variables). | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment