llir / llvm

Library for interacting with LLVM IR in pure Go.
https://llir.github.io/document/
BSD Zero Clause License
1.18k stars 78 forks source link

Provide working Hello, World example #227

Closed eigenhombre closed 1 year ago

eigenhombre commented 1 year ago

I'd like to maybe use this for a language implementation, but am inexperienced with LLVM. It took me some time to come up with a snippet equivalent to this example (Also found here).

I think the README would benefit from a Hello, World example, something along the lines of:

package main

import (
    "fmt"

    "github.com/llir/llvm/ir"
    "github.com/llir/llvm/ir/constant"
    "github.com/llir/llvm/ir/types"
)

// Hello, World in LLVM IR.
func main() {
    // Create a new LLVM IR module.
    m := ir.NewModule()
    arr := constant.NewCharArrayFromString("Hello, world!\n\x00")
    gd := m.NewGlobalDef("str", arr)
    // link to external function puts
    puts := m.NewFunc("puts", types.I32, ir.NewParam("", types.NewPointer(types.I8)))
    main := m.NewFunc("main", types.I32)
    entry := main.NewBlock("")

    // Perform cast per [1]:
    gep := constant.NewGetElementPtr(types.NewArray(15, types.I8),
        gd,
        constant.NewInt(types.I8, 0),
        constant.NewInt(types.I8, 0))
    entry.NewCall(puts, gep)
    entry.NewRet(constant.NewInt(types.I32, 0))
    fmt.Println(m)
}

// See also:
// https://github.com/anoopsarkar/compilers-class-hw/blob/master/llvm-practice/helloworld.ll
mewmew commented 1 year ago

Resolved by #228. Thanks @eigenhombre for adding the most canonical example in all of programming to llir/llvm :D