1212#include < llvm/Support/TargetSelect.h>
1313#include < llvm/Support/raw_ostream.h>
1414
15+ #include < functional>
1516#include < memory>
1617
1718#include " JitFromScratch.h"
@@ -24,7 +25,7 @@ Expected<std::string> codegenIR(Module &module, unsigned items) {
2425 LLVMContext &ctx = module .getContext ();
2526 IRBuilder<> B (ctx);
2627
27- auto name = " getZero " ;
28+ auto name = " substract " ;
2829 auto returnTy = Type::getInt32Ty (ctx);
2930 auto argTy = Type::getInt32Ty (ctx);
3031 auto signature = FunctionType::get (returnTy, {argTy, argTy}, false );
@@ -33,7 +34,12 @@ Expected<std::string> codegenIR(Module &module, unsigned items) {
3334 auto fn = Function::Create (signature, linkage, name, module );
3435
3536 B.SetInsertPoint (BasicBlock::Create (ctx, " entry" , fn));
36- B.CreateRet (ConstantInt::get (returnTy, 0 ));
37+ {
38+ Argument *argX = fn->arg_begin ();
39+ Argument *argY = fn->arg_begin () + 1 ;
40+ Value *difference = B.CreateSub (argX, argY);
41+ B.CreateRet (difference);
42+ }
3743
3844 std::string buffer;
3945 raw_string_ostream es (buffer);
@@ -71,14 +77,17 @@ int *customIntAllocator(unsigned items) {
7177 return block;
7278}
7379
80+ // Temporary global variable to replace below function step-by-step.
81+ std::function<int (int , int )> substract;
82+
7483// This function will be replaced by a runtime-time compiled version.
7584template <size_t sizeOfArray>
7685int *integerDistances (const int (&x)[sizeOfArray], int *y) {
7786 unsigned items = arrayElements (x);
7887 int *results = customIntAllocator (items);
7988
8089 for (int i = 0 ; i < items; i++) {
81- results[i] = abs (x[i] - y[i]);
90+ results[i] = abs (substract ( x[i], y[i]) );
8291 }
8392
8493 return results;
@@ -113,10 +122,9 @@ int main(int argc, char **argv) {
113122 ExitOnErr (Jit.submitModule (std::move (M), std::move (C)));
114123
115124 // Request function; this compiles to machine code and links.
116- auto getZero = ExitOnErr (Jit.getFunction <int (int , int )>(JitedFnName));
125+ substract = ExitOnErr (Jit.getFunction <int (int , int )>(JitedFnName));
117126
118127 int *z = integerDistances (x, y);
119- z[1 ] = getZero (0 , 0 );
120128
121129 outs () << format (" Integer Distances: %d, %d, %d\n\n " , z[0 ], z[1 ], z[2 ]);
122130 outs ().flush ();
0 commit comments