Skip to content
This repository has been archived by the owner on Jul 3, 2021. It is now read-only.

Commit

Permalink
Emit call to stdlib function abs in JITed code
Browse files Browse the repository at this point in the history
  • Loading branch information
weliveindetail committed Dec 8, 2019
1 parent 03b8701 commit a0cdaad
Showing 1 changed file with 14 additions and 8 deletions.
22 changes: 14 additions & 8 deletions main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,9 @@ Expected<std::string> codegenIR(Module &module, unsigned items) {
LLVMContext &ctx = module.getContext();
IRBuilder<> B(ctx);

auto name = "substract";
auto returnTy = Type::getInt32Ty(ctx);
auto argTy = Type::getInt32Ty(ctx);
auto signature = FunctionType::get(returnTy, {argTy, argTy}, false);
auto name = "abssub";
auto intTy = Type::getInt32Ty(ctx);
auto signature = FunctionType::get(intTy, {intTy, intTy}, false);
auto linkage = Function::ExternalLinkage;

auto fn = Function::Create(signature, linkage, name, module);
Expand All @@ -41,7 +40,11 @@ Expected<std::string> codegenIR(Module &module, unsigned items) {
argY->setName("y");
Value *difference = B.CreateSub(argX, argY, "dist");

B.CreateRet(difference);
auto absSig = FunctionType::get(intTy, {intTy}, false);
FunctionCallee absFunction = module.getOrInsertFunction("abs", absSig);
Value *absDifference = B.CreateCall(absFunction, {difference});

B.CreateRet(absDifference);
}

std::string buffer;
Expand Down Expand Up @@ -80,8 +83,11 @@ int *customIntAllocator(unsigned items) {
return block;
}

// Also called from JITed code; make sure it's available.
extern "C" int abs(int);

// Temporary global variable to replace below function step-by-step.
std::function<int(int, int)> substract;
std::function<int(int, int)> abssub;

// This function will be replaced by a runtime-time compiled version.
template <size_t sizeOfArray>
Expand All @@ -90,7 +96,7 @@ int *integerDistances(const int (&x)[sizeOfArray], int *y) {
int *results = customIntAllocator(items);

for (int i = 0; i < items; i++) {
results[i] = abs(substract(x[i], y[i]));
results[i] = abssub(x[i], y[i]);
}

return results;
Expand Down Expand Up @@ -125,7 +131,7 @@ int main(int argc, char **argv) {
ExitOnErr(Jit.submitModule(std::move(M), std::move(C)));

// Request function; this compiles to machine code and links.
substract = ExitOnErr(Jit.getFunction<int(int, int)>(JitedFnName));
abssub = ExitOnErr(Jit.getFunction<int(int, int)>(JitedFnName));

int *z = integerDistances(x, y);

Expand Down

0 comments on commit a0cdaad

Please sign in to comment.