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

Commit a0cdaad

Browse files
Emit call to stdlib function abs in JITed code
1 parent 03b8701 commit a0cdaad

File tree

1 file changed

+14
-8
lines changed

1 file changed

+14
-8
lines changed

main.cpp

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,9 @@ Expected<std::string> codegenIR(Module &module, unsigned items) {
2525
LLVMContext &ctx = module.getContext();
2626
IRBuilder<> B(ctx);
2727

28-
auto name = "substract";
29-
auto returnTy = Type::getInt32Ty(ctx);
30-
auto argTy = Type::getInt32Ty(ctx);
31-
auto signature = FunctionType::get(returnTy, {argTy, argTy}, false);
28+
auto name = "abssub";
29+
auto intTy = Type::getInt32Ty(ctx);
30+
auto signature = FunctionType::get(intTy, {intTy, intTy}, false);
3231
auto linkage = Function::ExternalLinkage;
3332

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

44-
B.CreateRet(difference);
43+
auto absSig = FunctionType::get(intTy, {intTy}, false);
44+
FunctionCallee absFunction = module.getOrInsertFunction("abs", absSig);
45+
Value *absDifference = B.CreateCall(absFunction, {difference});
46+
47+
B.CreateRet(absDifference);
4548
}
4649

4750
std::string buffer;
@@ -80,8 +83,11 @@ int *customIntAllocator(unsigned items) {
8083
return block;
8184
}
8285

86+
// Also called from JITed code; make sure it's available.
87+
extern "C" int abs(int);
88+
8389
// Temporary global variable to replace below function step-by-step.
84-
std::function<int(int, int)> substract;
90+
std::function<int(int, int)> abssub;
8591

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

9298
for (int i = 0; i < items; i++) {
93-
results[i] = abs(substract(x[i], y[i]));
99+
results[i] = abssub(x[i], y[i]);
94100
}
95101

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

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

130136
int *z = integerDistances(x, y);
131137

0 commit comments

Comments
 (0)