Skip to content

Instantly share code, notes, and snippets.

@ishikawa
Last active June 1, 2018 16:34
Show Gist options
  • Save ishikawa/4442395 to your computer and use it in GitHub Desktop.
Save ishikawa/4442395 to your computer and use it in GitHub Desktop.
LLVM 'Hello, World!' example from http://llvm.org/docs/LangRef.html#module-structure
; ModuleID = 'hello'
@.str = private constant [14 x i8] c"Hello, World!\00"
declare i32 @puts(i8* nocapture) nounwind
define i32 @main() {
%1 = call i32 @puts(i8* getelementptr inbounds ([14 x i8]* @.str, i32 0, i32 0))
ret i32 0
}
# LLVM 'Hello, World!' example from
# http://llvm.org/docs/LangRef.html#module-structure
require 'llvm/core'
require 'llvm/execution_engine'
HELLO_STRING = "Hello, World!"
mod = LLVM::Module.new('hello')
# Declare the string constant as a global constant.
hello = mod.globals.add(LLVM.Array(LLVM::Int8, HELLO_STRING.size + 1), '.str').tap do |var|
var.linkage = :private
var.global_constant = 1
var.initializer = LLVM::ConstantArray.string(HELLO_STRING)
# TODO LLVM C bindings doesn't support GlobalVariable::setUnnamedAddr(bool)
end
# External declaration of the `puts` function
cputs = mod.functions.add('puts', [LLVM.Pointer(LLVM::Int8)], LLVM::Int32) do |function, string|
function.add_attribute :no_unwind_attribute
string.add_attribute :no_capture_attribute
end
# Definition of main function
main = mod.functions.add('main', [], LLVM::Int32) do |function|
entry = function.basic_blocks.append
entry.build do |b|
zero = LLVM.Int(0)
# Convert [13 x i8]* to i8 *...
cast210 = b.gep hello, [zero, zero], 'cast210'
# Call puts function to write out the string to stdout.
b.call cputs, cast210
b.ret zero
end
end
mod.dump
#mod.dispose
LLVM.init_x86
engine = LLVM::JITCompiler.new(mod)
engine.run_function(main)
engine.dispose
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment