Skip to content

Instantly share code, notes, and snippets.

@ishikawa
Created May 17, 2014 13:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ishikawa/e15079906bef03a891c9 to your computer and use it in GitHub Desktop.
Save ishikawa/e15079906bef03a891c9 to your computer and use it in GitHub Desktop.
Sample POSIX "Hello World" Application (ruby-llvm)
require 'llvm/core'
require 'llvm/analysis'
require 'llvm/execution_engine'
mod = LLVM::Module.new("test")
str = "Hello, World!"
STRING = mod.globals.add(LLVM::Array(LLVM::Int8, str.size + 1), "str") do |value|
value.linkage = :internal
value.unnamed_addr = true
value.global_constant = 1
value.initializer = LLVM::ConstantArray.string(str)
end
fn_puts = mod.functions.add("puts", [LLVM::Pointer(LLVM::Int8)], LLVM::Int) do |fn|
fn.add_attribute(:no_unwind_attribute)
end
mod.functions.add("main", [], LLVM::Int) do |fn|
fn.basic_blocks.append.build do |builder|
ptr = builder.gep(STRING, [LLVM::Int(0), LLVM::Int(0)])
builder.call(fn_puts, ptr)
builder.ret LLVM::Int(0)
end
end
mod.verify!
mod.dump
# ; ModuleID = 'test'
#
# @str = internal unnamed_addr constant [14 x i8] c"Hello, World!\00"
#
# ; Function Attrs: nounwind
# declare i32 @puts(i8*) #0
#
# define i32 @main() {
# %1 = call i32 @puts(i8* getelementptr inbounds ([14 x i8]* @str, i32 0, i32 0))
# ret i32 0
# }
# ---- JIT
LLVM.init_jit
engine = LLVM::JITCompiler.new(mod)
engine.run_function(mod.functions["main"])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment