1 //===-------- BasicOrcV2CBindings.c - Basic OrcV2 C Bindings Demo ---------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "llvm-c/Core.h"
10 #include "llvm-c/Error.h"
11 #include "llvm-c/Initialization.h"
12 #include "llvm-c/LLJIT.h"
13 #include "llvm-c/Support.h"
14 #include "llvm-c/Target.h"
15 #include "llvm-c/TargetMachine.h"
16 
17 #include <stdio.h>
18 
handleError(LLVMErrorRef Err)19 int handleError(LLVMErrorRef Err) {
20   char *ErrMsg = LLVMGetErrorMessage(Err);
21   fprintf(stderr, "Error: %s\n", ErrMsg);
22   LLVMDisposeErrorMessage(ErrMsg);
23   return 1;
24 }
25 
createDemoModule(LLVMContextRef Ctx)26 LLVMModuleRef createDemoModule(LLVMContextRef Ctx) {
27   // Create a new LLVM module.
28   LLVMModuleRef M = LLVMModuleCreateWithNameInContext("demo", Ctx);
29 
30   // Add a "sum" function":
31   //  - Create the function type and function instance.
32   LLVMTypeRef ParamTypes[] = {LLVMInt32Type(), LLVMInt32Type()};
33   LLVMTypeRef SumFunctionType =
34       LLVMFunctionType(LLVMInt32Type(), ParamTypes, 2, 0);
35   LLVMValueRef SumFunction = LLVMAddFunction(M, "sum", SumFunctionType);
36 
37   //  - Add a basic block to the function.
38   LLVMBasicBlockRef EntryBB = LLVMAppendBasicBlock(SumFunction, "entry");
39 
40   //  - Add an IR builder and point it at the end of the basic block.
41   LLVMBuilderRef Builder = LLVMCreateBuilder();
42   LLVMPositionBuilderAtEnd(Builder, EntryBB);
43 
44   //  - Get the two function arguments and use them co construct an "add"
45   //    instruction.
46   LLVMValueRef SumArg0 = LLVMGetParam(SumFunction, 0);
47   LLVMValueRef SumArg1 = LLVMGetParam(SumFunction, 1);
48   LLVMValueRef Result = LLVMBuildAdd(Builder, SumArg0, SumArg1, "result");
49 
50   //  - Build the return instruction.
51   LLVMBuildRet(Builder, Result);
52 
53   //  - Free the builder.
54   LLVMDisposeBuilder(Builder);
55 
56   return M;
57 }
58 
main(int argc,char * argv[])59 int main(int argc, char *argv[]) {
60 
61   int MainResult = 0;
62 
63   // Parse command line arguments and initialize LLVM Core.
64   LLVMParseCommandLineOptions(argc, (const char **)argv, "");
65   LLVMInitializeCore(LLVMGetGlobalPassRegistry());
66 
67   // Initialize native target codegen and asm printer.
68   LLVMInitializeNativeTarget();
69   LLVMInitializeNativeAsmPrinter();
70 
71   // Create the JIT instance.
72   LLVMOrcLLJITRef J;
73   {
74     LLVMErrorRef Err;
75     if ((Err = LLVMOrcCreateLLJIT(&J, 0))) {
76       MainResult = handleError(Err);
77       goto llvm_shutdown;
78     }
79   }
80 
81   // Create our demo object file.
82   LLVMMemoryBufferRef ObjectFileBuffer;
83   {
84     // Create a module.
85     LLVMContextRef Ctx = LLVMContextCreate();
86     LLVMModuleRef M = createDemoModule(Ctx);
87 
88     // Get the Target.
89     const char *Triple = LLVMOrcLLJITGetTripleString(J);
90     LLVMTargetRef Target = 0;
91     char *ErrorMsg = 0;
92     if (LLVMGetTargetFromTriple(Triple, &Target, &ErrorMsg)) {
93       fprintf(stderr, "Error getting target for %s: %s\n", Triple, ErrorMsg);
94       LLVMDisposeModule(M);
95       LLVMContextDispose(Ctx);
96       goto jit_cleanup;
97     }
98 
99     // Construct a TargetMachine.
100     LLVMTargetMachineRef TM =
101         LLVMCreateTargetMachine(Target, Triple, "", "", LLVMCodeGenLevelNone,
102                                 LLVMRelocDefault, LLVMCodeModelDefault);
103 
104     // Run CodeGen to produce the buffer.
105     if (LLVMTargetMachineEmitToMemoryBuffer(TM, M, LLVMObjectFile, &ErrorMsg,
106                                             &ObjectFileBuffer)) {
107       fprintf(stderr, "Error emitting object: %s\n", ErrorMsg);
108       LLVMDisposeTargetMachine(TM);
109       LLVMDisposeModule(M);
110       LLVMContextDispose(Ctx);
111       goto jit_cleanup;
112     }
113 
114     // CodeGen succeeded -- We have our module, so free the Module, LLVMContext,
115     // and TargetMachine.
116     LLVMDisposeModule(M);
117     LLVMContextDispose(Ctx);
118     LLVMDisposeTargetMachine(TM);
119   }
120 
121   // Add our object file buffer to the JIT.
122   {
123     LLVMOrcJITDylibRef MainJD = LLVMOrcLLJITGetMainJITDylib(J);
124     LLVMErrorRef Err;
125     if ((Err = LLVMOrcLLJITAddObjectFile(J, MainJD, ObjectFileBuffer))) {
126       MainResult = handleError(Err);
127       goto jit_cleanup;
128     }
129   }
130 
131   // Look up the address of our demo entry point.
132   LLVMOrcJITTargetAddress SumAddr;
133   {
134     LLVMErrorRef Err;
135     if ((Err = LLVMOrcLLJITLookup(J, &SumAddr, "sum"))) {
136       MainResult = handleError(Err);
137       goto jit_cleanup;
138     }
139   }
140 
141   // If we made it here then everything succeeded. Execute our JIT'd code.
142   int32_t (*Sum)(int32_t, int32_t) = (int32_t(*)(int32_t, int32_t))SumAddr;
143   int32_t Result = Sum(1, 2);
144 
145   // Print the result.
146   printf("1 + 2 = %i\n", Result);
147 
148 jit_cleanup:
149   // Destroy our JIT instance. This will clean up any memory that the JIT has
150   // taken ownership of. This operation is non-trivial (e.g. it may need to
151   // JIT static destructors) and may also fail. In that case we want to render
152   // the error to stderr, but not overwrite any existing return value.
153   {
154     LLVMErrorRef Err;
155     if ((Err = LLVMOrcDisposeLLJIT(J))) {
156       int NewFailureResult = handleError(Err);
157       if (MainResult == 0)
158         MainResult = NewFailureResult;
159     }
160   }
161 
162 llvm_shutdown:
163   // Shut down LLVM.
164   LLVMShutdown();
165 
166   return MainResult;
167 }
168