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

Add Hello, World example #228

Closed eigenhombre closed 1 year ago

eigenhombre commented 1 year ago

Alternatively, one of the two IR generation examples could be source-only in an examples directory.

For #227.

mewmew commented 1 year ago

Looks good!

I did some minor update/cleanup. Mostly changed a few local variable names, and also inferred the array type from the hello variable instead of using 15 as a magic value.

package main

import (
    "fmt"

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

func main() {
    // Create a new LLVM IR module.
    m := ir.NewModule()
    hello := constant.NewCharArrayFromString("Hello, world!\n\x00")
    str := m.NewGlobalDef("str", hello)
    // Add external function declaration of puts.
    puts := m.NewFunc("puts", types.I32, ir.NewParam("", types.NewPointer(types.I8)))
    main := m.NewFunc("main", types.I32)
    entry := main.NewBlock("")
    // Cast *[15]i8 to *i8.
    zero := constant.NewInt(types.I64, 0)
    gep := constant.NewGetElementPtr(hello.Typ, str, zero, zero)
    entry.NewCall(puts, gep)
    entry.NewRet(constant.NewInt(types.I32, 0))
    fmt.Println(m)
}
mewmew commented 1 year ago

Alternatively, one of the two IR generation examples could be source-only in an examples directory.

A third alternative would be to just add this to the documentation as a run-able example, like this:

https://pkg.go.dev/github.com/llir/llvm/ir#example-package-Main

Something like https://github.com/llir/llvm/blob/master/ir/example_test.go or https://github.com/llir/llvm/blob/master/ir/evaluator_test.go

Consider adding a func Example_hello() example function to e.g. llvm/ir/hello_test.go

Cheers, Robin

eigenhombre commented 1 year ago

Updated PR per suggestions, thanks for the feedback!