Skip to content

Instantly share code, notes, and snippets.

@niuk
Created January 26, 2012 11:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save niuk/1682420 to your computer and use it in GitHub Desktop.
Save niuk/1682420 to your computer and use it in GitHub Desktop.
This runs just fine.
#include <stdbool.h>
#include <stdio.h>
#include <llvm-c/Core.h>
#include <llvm-c/ExecutionEngine.h>
int main(int argc, char **argv) {
LLVMLinkInJIT();
if (LLVMInitializeNativeTarget()) {
fprintf(stderr, "Failed to initialize native target.\n");
}
// first, create a module
LLVMModuleRef module = LLVMModuleCreateWithName("myModule");
// add a function
LLVMValueRef function = LLVMAddFunction
( module
, "myFunction"
, LLVMFunctionType
( LLVMInt64Type()
, (LLVMTypeRef[2]){LLVMInt64Type(), LLVMInt64Type()}, 2
, false
));
LLVMBasicBlockRef block = LLVMAppendBasicBlock(function, "myBlock");
LLVMBuilderRef builder = LLVMCreateBuilder();
LLVMPositionBuilderAtEnd(builder, block);
LLVMValueRef temp = LLVMBuildAdd
( builder
, LLVMGetParam(function, 0), LLVMGetParam(function, 1)
, "add");
LLVMBuildRet(builder, temp);
// create an execution engine
LLVMExecutionEngineRef engine;
char *error;
if (LLVMCreateJITCompilerForModule(&engine, module, 0, &error)) {
fprintf(stderr, "%s\n", error);
}
unsigned long long result = LLVMGenericValueToInt
( LLVMRunFunction
( engine
, function
, 2, (LLVMGenericValueRef[2])
{ LLVMCreateGenericValueOfInt(LLVMInt64Type(), 42, false)
, LLVMCreateGenericValueOfInt(LLVMInt64Type(), 3, false)
}
)
, 0
);
printf("result = %llu\n", result);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment