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   return M;
54 }
55 
main(int argc,char * argv[])56 int main(int argc, char *argv[]) {
57 
58   int MainResult = 0;
59 
60   // Parse command line arguments and initialize LLVM Core.
61   LLVMParseCommandLineOptions(argc, (const char **)argv, "");
62   LLVMInitializeCore(LLVMGetGlobalPassRegistry());
63 
64   // Initialize native target codegen and asm printer.
65   LLVMInitializeNativeTarget();
66   LLVMInitializeNativeAsmPrinter();
67 
68   // Create the JIT instance.
69   LLVMOrcLLJITRef J;
70   {
71     LLVMErrorRef Err;
72     if ((Err = LLVMOrcCreateLLJIT(&J, 0))) {
73       MainResult = handleError(Err);
74       goto llvm_shutdown;
75     }
76   }
77 
78   // Create our demo object file.
79   LLVMMemoryBufferRef ObjectFileBuffer;
80   {
81     // Create a module.
82     LLVMContextRef Ctx = LLVMContextCreate();
83     LLVMModuleRef M = createDemoModule(Ctx);
84 
85     // Get the Target.
86     const char *Triple = LLVMOrcLLJITGetTripleString(J);
87     LLVMTargetRef Target = 0;
88     char *ErrorMsg = 0;
89     if (LLVMGetTargetFromTriple(Triple, &Target, &ErrorMsg)) {
90       fprintf(stderr, "Error getting target for %s: %s\n", Triple, ErrorMsg);
91       LLVMDisposeModule(M);
92       LLVMContextDispose(Ctx);
93       goto jit_cleanup;
94     }
95 
96     // Construct a TargetMachine.
97     LLVMTargetMachineRef TM =
98         LLVMCreateTargetMachine(Target, Triple, "", "", LLVMCodeGenLevelNone,
99                                 LLVMRelocDefault, LLVMCodeModelDefault);
100 
101     // Run CodeGen to produce the buffer.
102     if (LLVMTargetMachineEmitToMemoryBuffer(TM, M, LLVMObjectFile, &ErrorMsg,
103                                             &ObjectFileBuffer)) {
104       fprintf(stderr, "Error emitting object: %s\n", ErrorMsg);
105       LLVMDisposeTargetMachine(TM);
106       LLVMDisposeModule(M);
107       LLVMContextDispose(Ctx);
108       goto jit_cleanup;
109     }
110   }
111 
112   // Add our object file buffer to the JIT.
113   {
114     LLVMOrcJITDylibRef MainJD = LLVMOrcLLJITGetMainJITDylib(J);
115     LLVMErrorRef Err;
116     if ((Err = LLVMOrcLLJITAddObjectFile(J, MainJD, ObjectFileBuffer))) {
117       MainResult = handleError(Err);
118       goto jit_cleanup;
119     }
120   }
121 
122   // Look up the address of our demo entry point.
123   LLVMOrcJITTargetAddress SumAddr;
124   {
125     LLVMErrorRef Err;
126     if ((Err = LLVMOrcLLJITLookup(J, &SumAddr, "sum"))) {
127       MainResult = handleError(Err);
128       goto jit_cleanup;
129     }
130   }
131 
132   // If we made it here then everything succeeded. Execute our JIT'd code.
133   int32_t (*Sum)(int32_t, int32_t) = (int32_t(*)(int32_t, int32_t))SumAddr;
134   int32_t Result = Sum(1, 2);
135 
136   // Print the result.
137   printf("1 + 2 = %i\n", Result);
138 
139 jit_cleanup:
140   // Destroy our JIT instance. This will clean up any memory that the JIT has
141   // taken ownership of. This operation is non-trivial (e.g. it may need to
142   // JIT static destructors) and may also fail. In that case we want to render
143   // the error to stderr, but not overwrite any existing return value.
144   {
145     LLVMErrorRef Err;
146     if ((Err = LLVMOrcDisposeLLJIT(J))) {
147       int NewFailureResult = handleError(Err);
148       if (MainResult == 0)
149         MainResult = NewFailureResult;
150     }
151   }
152 
153 llvm_shutdown:
154   // Shut down LLVM.
155   LLVMShutdown();
156 
157   return MainResult;
158 }
159