3.5. Example

3.5.1. A trivial function

Define a function adding two double-precision floating-point numbers.

This file demonstrates a trivial function "fpadd" returning the sum of
two floating-point numbers.

from llvmlite import ir

# Create some useful types
double = ir.DoubleType()
fnty = ir.FunctionType(double, (double, double))

# Create an empty module...
module = ir.Module(name=__file__)
# and declare a function named "fpadd" inside it
func = ir.Function(module, fnty, name="fpadd")

# Now implement the function
block = func.append_basic_block(name="entry")
builder = ir.IRBuilder(block)
a, b = func.args
result = builder.fadd(a, b, name="res")

# Print the module IR

The generated LLVM IR is printed out at the end, and should look like this:

; ModuleID = "examples/ir_fpadd.py"
target triple = "unknown-unknown-unknown"
target datalayout = ""

define double @"fpadd"(double %".1", double %".2")
  %"res" = fadd double %".1", %".2"
  ret double %"res"

To learn how to compile and execute this function, refer to the binding layer documentation.