sum.c 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /** This code is public domain, and taken from
  2. * https://github.com/paulsmith/getting-started-llvm-c-api/blob/master/sum.c
  3. */
  4. /**
  5. * LLVM equivalent of:
  6. *
  7. * int sum(int a, int b) {
  8. * return a + b;
  9. * }
  10. */
  11. #include <llvm-c/Core.h>
  12. #include <llvm-c/ExecutionEngine.h>
  13. #include <llvm-c/Target.h>
  14. #include <llvm-c/Analysis.h>
  15. #include <llvm-c/BitWriter.h>
  16. #include <inttypes.h>
  17. #include <stdio.h>
  18. #include <stdlib.h>
  19. int main(int argc, char const *argv[]) {
  20. LLVMModuleRef mod = LLVMModuleCreateWithName("my_module");
  21. LLVMTypeRef param_types[] = { LLVMInt32Type(), LLVMInt32Type() };
  22. LLVMTypeRef ret_type = LLVMFunctionType(LLVMInt32Type(), param_types, 2, 0);
  23. LLVMValueRef sum = LLVMAddFunction(mod, "sum", ret_type);
  24. LLVMBasicBlockRef entry = LLVMAppendBasicBlock(sum, "entry");
  25. LLVMBuilderRef builder = LLVMCreateBuilder();
  26. LLVMPositionBuilderAtEnd(builder, entry);
  27. LLVMValueRef tmp = LLVMBuildAdd(builder, LLVMGetParam(sum, 0), LLVMGetParam(sum, 1), "tmp");
  28. LLVMBuildRet(builder, tmp);
  29. char *error = NULL;
  30. LLVMVerifyModule(mod, LLVMAbortProcessAction, &error);
  31. LLVMDisposeMessage(error);
  32. LLVMExecutionEngineRef engine;
  33. error = NULL;
  34. LLVMLinkInMCJIT();
  35. LLVMInitializeNativeAsmPrinter();
  36. LLVMInitializeNativeTarget();
  37. if (LLVMCreateExecutionEngineForModule(&engine, mod, &error) != 0) {
  38. fprintf(stderr, "failed to create execution engine\n");
  39. abort();
  40. }
  41. if (error) {
  42. fprintf(stderr, "error: %s\n", error);
  43. LLVMDisposeMessage(error);
  44. exit(EXIT_FAILURE);
  45. }
  46. if (argc < 3) {
  47. fprintf(stderr, "usage: %s x y\n", argv[0]);
  48. exit(EXIT_FAILURE);
  49. }
  50. long long x = strtoll(argv[1], NULL, 10);
  51. long long y = strtoll(argv[2], NULL, 10);
  52. LLVMGenericValueRef args[] = {
  53. LLVMCreateGenericValueOfInt(LLVMInt32Type(), x, 0),
  54. LLVMCreateGenericValueOfInt(LLVMInt32Type(), y, 0)
  55. };
  56. LLVMGenericValueRef res = LLVMRunFunction(engine, sum, 2, args);
  57. printf("%d\n", (int)LLVMGenericValueToInt(res, 0));
  58. // Write out bitcode to file
  59. if (LLVMWriteBitcodeToFile(mod, "sum.bc") != 0) {
  60. fprintf(stderr, "error writing bitcode to file, skipping\n");
  61. }
  62. LLVMDisposeBuilder(builder);
  63. LLVMDisposeExecutionEngine(engine);
  64. }