Having successfully built LLVM using MinGW I am now trying to use the C API to implement the program.
As just a starter application to see if the build has been successful I have converted the llvmpy example found here http://www.llvmpy.org/llvmpy-doc/0.9/doc/firstexample.html into (what I think is the) C equivalent however I'm not getting the output I expect from the print function.
My C program is:
#include "llvm-c/Core.h"
#include "stdio.h"
int main(int argc, char* argv[])
{
LLVMInitializeCore(LLVMGetGlobalPassRegistry());
LLVMModuleRef my_module = LLVMModuleCreateWithName("my_module");
LLVMTypeRef ty_int = LLVMInt32Type();
LLVMTypeRef* ParamTypes = new LLVMTypeRef[2];
ParamTypes[0] = ty_int;
ParamTypes[1] = ty_int;
LLVMTypeRef ty_func = LLVMFunctionType(ty_int, ParamTypes, 2, false);
delete[] ParamTypes;
LLVMValueRef f_sum = LLVMAddFunction(my_module, "sum", ty_func);
LLVMValueRef* Params = new LLVMValueRef[2];
LLVMGetParams(f_sum, Params);
LLVMSetValueName(Params[0], "a");
LLVMSetValueName(Params[1], "b");
LLVMBasicBlockRef bb = LLVMAppendBasicBlock(f_sum, "entry");
LLVMBuilderRef builder = LLVMCreateBuilder();
LLVMPositionBuilderAtEnd(builder, bb);
LLVMValueRef tmp = LLVMBuildAdd(builder, Params[0], Params[1], "tmp");
delete[] Params;
LLVMBuildRet(builder, tmp);
printf(LLVMPrintModuleToString(my_module));
//do shutdown
LLVMDisposeBuilder(builder);
LLVMDisposeModule(my_module);
LLVMShutdown();
return 0;
}
The output I get is:
; ModuleID = 'my_module'
define i32 @sum(i32 0x1.74bb00p-1012, i32 b) {
entry:
tmp = add i32 0x1.95bc40p+876, b
ret i32 tmp
}
Note that 0x1.74bb00p-1012 and 0x1.95bc40p+876 should read "%a"
I can only think that is some kind of memory corruption however I don't know the likely cause. How could I change the code so this works?
As it turns out this is a problem with LLVMPrintModuleToStringNw, it uses the C printf function to print to the string and so the percentages are either removed or spew false values out of whatever is on the stack.
See for why %a came out as "0x1.74bb00p-1012" -Aka hexadecimal floating point format. http://www.cplusplus.com/reference/cstdio/printf/
In the end LLVMPrintModuleToString should be replaced with a function that doesn't use the C print family of functions.