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 
16 #include <assert.h>
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 
add(int32_t X,int32_t Y)26 int32_t add(int32_t X, int32_t Y) { return X + Y; }
27 
mul(int32_t X,int32_t Y)28 int32_t mul(int32_t X, int32_t Y) { return X * Y; }
29 
allowedSymbols(void * Ctx,LLVMOrcSymbolStringPoolEntryRef Sym)30 int allowedSymbols(void *Ctx, LLVMOrcSymbolStringPoolEntryRef Sym) {
31   assert(Ctx && "Cannot call allowedSymbols with a null context");
32 
33   LLVMOrcSymbolStringPoolEntryRef *AllowList =
34       (LLVMOrcSymbolStringPoolEntryRef *)Ctx;
35 
36   // If Sym appears in the allowed list then return true.
37   LLVMOrcSymbolStringPoolEntryRef *P = AllowList;
38   while (*P) {
39     if (Sym == *P)
40       return 1;
41     ++P;
42   }
43 
44   // otherwise return false.
45   return 0;
46 }
47 
createDemoModule(void)48 LLVMOrcThreadSafeModuleRef createDemoModule(void) {
49   // Create a new ThreadSafeContext and underlying LLVMContext.
50   LLVMOrcThreadSafeContextRef TSCtx = LLVMOrcCreateNewThreadSafeContext();
51 
52   // Get a reference to the underlying LLVMContext.
53   LLVMContextRef Ctx = LLVMOrcThreadSafeContextGetContext(TSCtx);
54 
55   // Create a new LLVM module.
56   LLVMModuleRef M = LLVMModuleCreateWithNameInContext("demo", Ctx);
57 
58   // Add a "sum" function":
59   //  - Create the function type and function instance.
60   LLVMTypeRef I32BinOpParamTypes[] = {LLVMInt32Type(), LLVMInt32Type()};
61   LLVMTypeRef I32BinOpFunctionType =
62       LLVMFunctionType(LLVMInt32Type(), I32BinOpParamTypes, 2, 0);
63   LLVMValueRef AddI32Function = LLVMAddFunction(M, "add", I32BinOpFunctionType);
64   LLVMValueRef MulI32Function = LLVMAddFunction(M, "mul", I32BinOpFunctionType);
65 
66   LLVMTypeRef MulAddParamTypes[] = {LLVMInt32Type(), LLVMInt32Type(),
67                                     LLVMInt32Type()};
68   LLVMTypeRef MulAddFunctionType =
69       LLVMFunctionType(LLVMInt32Type(), MulAddParamTypes, 3, 0);
70   LLVMValueRef MulAddFunction =
71       LLVMAddFunction(M, "mul_add", MulAddFunctionType);
72 
73   //  - Add a basic block to the function.
74   LLVMBasicBlockRef EntryBB = LLVMAppendBasicBlock(MulAddFunction, "entry");
75 
76   //  - Add an IR builder and point it at the end of the basic block.
77   LLVMBuilderRef Builder = LLVMCreateBuilder();
78   LLVMPositionBuilderAtEnd(Builder, EntryBB);
79 
80   //  - Get the three function arguments and use them co construct calls to
81   //    'mul' and 'add':
82   //
83   //    i32 mul_add(i32 %0, i32 %1, i32 %2) {
84   //      %t = call i32 @mul(i32 %0, i32 %1)
85   //      %r = call i32 @add(i32 %t, i32 %2)
86   //      ret i32 %r
87   //    }
88   LLVMValueRef SumArg0 = LLVMGetParam(MulAddFunction, 0);
89   LLVMValueRef SumArg1 = LLVMGetParam(MulAddFunction, 1);
90   LLVMValueRef SumArg2 = LLVMGetParam(MulAddFunction, 2);
91 
92   LLVMValueRef MulArgs[] = {SumArg0, SumArg1};
93   LLVMValueRef MulResult = LLVMBuildCall2(Builder, I32BinOpFunctionType,
94                                           MulI32Function, MulArgs, 2, "t");
95 
96   LLVMValueRef AddArgs[] = {MulResult, SumArg2};
97   LLVMValueRef AddResult = LLVMBuildCall2(Builder, I32BinOpFunctionType,
98                                           AddI32Function, AddArgs, 2, "r");
99 
100   //  - Build the return instruction.
101   LLVMBuildRet(Builder, AddResult);
102 
103   //  - Free the builder.
104   LLVMDisposeBuilder(Builder);
105 
106   // Our demo module is now complete. Wrap it and our ThreadSafeContext in a
107   // ThreadSafeModule.
108   LLVMOrcThreadSafeModuleRef TSM = LLVMOrcCreateNewThreadSafeModule(M, TSCtx);
109 
110   // Dispose of our local ThreadSafeContext value. The underlying LLVMContext
111   // will be kept alive by our ThreadSafeModule, TSM.
112   LLVMOrcDisposeThreadSafeContext(TSCtx);
113 
114   // Return the result.
115   return TSM;
116 }
117 
main(int argc,char * argv[])118 int main(int argc, char *argv[]) {
119 
120   int MainResult = 0;
121 
122   // Parse command line arguments and initialize LLVM Core.
123   LLVMParseCommandLineOptions(argc, (const char **)argv, "");
124   LLVMInitializeCore(LLVMGetGlobalPassRegistry());
125 
126   // Initialize native target codegen and asm printer.
127   LLVMInitializeNativeTarget();
128   LLVMInitializeNativeAsmPrinter();
129 
130   // Create the JIT instance.
131   LLVMOrcLLJITRef J;
132   {
133     LLVMErrorRef Err;
134     if ((Err = LLVMOrcCreateLLJIT(&J, 0))) {
135       MainResult = handleError(Err);
136       goto llvm_shutdown;
137     }
138   }
139 
140   // Build a filter to allow JIT'd code to only access allowed symbols.
141   // This filter is optional: If a null value is suppled for the Filter
142   // argument to LLVMOrcCreateDynamicLibrarySearchGeneratorForProcess then
143   // all process symbols will be reflected.
144   LLVMOrcSymbolStringPoolEntryRef AllowList[] = {
145       LLVMOrcLLJITMangleAndIntern(J, "mul"),
146       LLVMOrcLLJITMangleAndIntern(J, "add"), 0};
147 
148   {
149     LLVMOrcDefinitionGeneratorRef ProcessSymbolsGenerator = 0;
150     LLVMErrorRef Err;
151     if ((Err = LLVMOrcCreateDynamicLibrarySearchGeneratorForProcess(
152              &ProcessSymbolsGenerator, LLVMOrcLLJITGetGlobalPrefix(J),
153              allowedSymbols, AllowList))) {
154       MainResult = handleError(Err);
155       goto jit_cleanup;
156     }
157 
158     LLVMOrcJITDylibAddGenerator(LLVMOrcLLJITGetMainJITDylib(J),
159                                 ProcessSymbolsGenerator);
160   }
161 
162   // Create our demo module.
163   LLVMOrcThreadSafeModuleRef TSM = createDemoModule();
164 
165   // Add our demo module to the JIT.
166   {
167     LLVMOrcJITDylibRef MainJD = LLVMOrcLLJITGetMainJITDylib(J);
168     LLVMErrorRef Err;
169     if ((Err = LLVMOrcLLJITAddLLVMIRModule(J, MainJD, TSM))) {
170       // If adding the ThreadSafeModule fails then we need to clean it up
171       // ourselves. If adding it succeeds the JIT will manage the memory.
172       LLVMOrcDisposeThreadSafeModule(TSM);
173       MainResult = handleError(Err);
174       goto jit_cleanup;
175     }
176   }
177 
178   // Look up the address of our demo entry point.
179   LLVMOrcJITTargetAddress MulAddAddr;
180   {
181     LLVMErrorRef Err;
182     if ((Err = LLVMOrcLLJITLookup(J, &MulAddAddr, "mul_add"))) {
183       MainResult = handleError(Err);
184       goto jit_cleanup;
185     }
186   }
187 
188   // If we made it here then everything succeeded. Execute our JIT'd code.
189   int32_t (*MulAdd)(int32_t, int32_t, int32_t) =
190       (int32_t(*)(int32_t, int32_t, int32_t))MulAddAddr;
191   int32_t Result = MulAdd(3, 4, 5);
192 
193   // Print the result.
194   printf("3 * 4 + 5 = %i\n", Result);
195 
196 jit_cleanup:
197   // Release all symbol string pool entries that we have allocated. In this
198   // example that's just our allowed entries.
199   {
200     LLVMOrcSymbolStringPoolEntryRef *P = AllowList;
201     while (*P)
202       LLVMOrcReleaseSymbolStringPoolEntry(*P++);
203   }
204 
205   // Destroy our JIT instance. This will clean up any memory that the JIT has
206   // taken ownership of. This operation is non-trivial (e.g. it may need to
207   // JIT static destructors) and may also fail. In that case we want to render
208   // the error to stderr, but not overwrite any existing return value.
209   {
210     LLVMErrorRef Err;
211     if ((Err = LLVMOrcDisposeLLJIT(J))) {
212       int NewFailureResult = handleError(Err);
213       if (MainResult == 0)
214         MainResult = NewFailureResult;
215     }
216   }
217 
218 llvm_shutdown:
219   // Shut down LLVM.
220   LLVMShutdown();
221 
222   return MainResult;
223 }
224