Skip to content

Instantly share code, notes, and snippets.

@kaushikcfd
Last active November 19, 2021 13:46
Show Gist options
  • Save kaushikcfd/17c66e08b9b1ae87a20d9c6969867f30 to your computer and use it in GitHub Desktop.
Save kaushikcfd/17c66e08b9b1ae87a20d9c6969867f30 to your computer and use it in GitHub Desktop.
Calling MLIR kernels from C
func @saxpy(%a : f32, %x : memref<?xf32>, %y : memref<?xf32>) {
%c0 = constant 0: index
%n = dim %x, %c0 : memref<?xf32>
affine.for %i = 0 to %n {
%xi = affine.load %x[%i] : memref<?xf32>
%axi = mulf %a, %xi : f32
%yi = affine.load %y[%i] : memref<?xf32>
%axpyi = addf %yi, %axi : f32
affine.store %axpyi, %y[%i] : memref<?xf32>
}
return
}
#include <stdio.h>
struct OneDMemrefF32 {
float* ptrToData;
float* alignedPtrToData;
float offset;
long shape[1];
long stride[1];
};
#define N 4
#define REAL float
#define AXPY _mlir_ciface_saxpy
#define MEMREF OneDMemrefF32
extern void _mlir_ciface_saxpy(float, struct OneDMemrefF32*, struct OneDMemrefF32*);
int main() {
REAL x[N], y[N], alpha = 2.0;
struct MEMREF xMemref = {x, x, 0, {N}, {1}};
struct MEMREF yMemref = {y, y, 0, {N}, {1}};
for (int i=0; i<N; ++i) {
x[i] = i*i;
y[i] = i;
}
printf("x: {");
for (int i=0; i<N-1; ++i)
printf("%3.1f, ", x[i]);
printf("%3.1f}\n", x[N-1]);
printf("y: {");
for (int i=0; i<N-1; ++i)
printf("%3.1f, ", y[i]);
printf("%3.1f}\n", y[N-1]);
AXPY(alpha, &xMemref, &yMemref);
printf("%3.2fx + y: {", alpha);
for (int i=0; i<N-1; ++i)
printf("%3.1f, ", y[i]);
printf("%3.1f}\n", y[N-1]);
}

Step 1. Lower axpy.mlir to axpy.ll

mlir-opt -lower-affine -convert-loop-to-std -convert-std-to-llvm='emit-c-wrappers=1' axpy.mlir | mlir-translate --mlir-to-llvmir -o axpy.ll

Step 2. Get bitcode for the caller C.

clang -emit-llvm call_axpy.c -S -o call_axpy.bc

Step 3. axpy.ll -> axpy.bc

llvm-as axpy.ll -o axpy.bc

Step 4. Link the bitcodes

llvm-link call_axpy.bc axpy.bc -o result.bc

Step 5. Run the bitcode

$ lli result.bc 
x: {0.0, 1.0, 4.0, 9.0}
y: {0.0, 1.0, 2.0, 3.0}
2.00x + y: {0.0, 3.0, 10.0, 21.0}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment