github.com/llir/llvm@v0.3.6/ir/main_test.go (about) 1 package ir_test 2 3 import ( 4 "fmt" 5 6 "github.com/llir/llvm/ir" 7 "github.com/llir/llvm/ir/constant" 8 "github.com/llir/llvm/ir/types" 9 ) 10 11 func Example_main() { 12 // This example produces LLVM IR code equivalent to the following C code: 13 // 14 // int main() { 15 // int a = 32; 16 // int b = 16; 17 // return a + b; 18 // } 19 // 20 // Read: https://blog.felixangell.com/an-introduction-to-llvm-in-go for inspiration. 21 22 // Create convenience types. 23 i32 := types.I32 24 25 // Create a new LLVM IR module. 26 m := ir.NewModule() 27 // int main() { ... } 28 main := m.NewFunc("main", i32) 29 30 // Create an unnamed entry basic block and append it to the `main` function. 31 entry := main.NewBlock("") 32 // Create instructions and append them to the entry basic block. 33 34 // %a = alloca i32 35 a := entry.NewAlloca(i32) 36 a.SetName("a") 37 38 // %b = alloca i32 39 b := entry.NewAlloca(i32) 40 b.SetName("b") 41 42 // store i32 32, i32* %a 43 entry.NewStore(constant.NewInt(i32, 32), a) 44 45 // store i32 16, i32* %b 46 entry.NewStore(constant.NewInt(i32, 16), b) 47 48 // %1 = load i32, i32* %a 49 tmpA := entry.NewLoad(types.I32, a) 50 51 // %2 = load i32, i32* %b 52 tmpB := entry.NewLoad(types.I32, b) 53 54 // %3 = add nsw i32 %1, %2 55 tmpC := entry.NewAdd(tmpA, tmpB) 56 57 // ret i32 %3 58 entry.NewRet(tmpC) 59 60 // Print the LLVM IR assembly of the module. 61 fmt.Println(m) 62 63 // Output: 64 // 65 // define i32 @main() { 66 // 0: 67 // %a = alloca i32 68 // %b = alloca i32 69 // store i32 32, i32* %a 70 // store i32 16, i32* %b 71 // %1 = load i32, i32* %a 72 // %2 = load i32, i32* %b 73 // %3 = add i32 %1, %2 74 // ret i32 %3 75 // } 76 }