17330f729Sjoerg //===-- examples/ParallelJIT/ParallelJIT.cpp - Exercise threaded-safe JIT -===//
27330f729Sjoerg //
37330f729Sjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
47330f729Sjoerg // See https://llvm.org/LICENSE.txt for license information.
57330f729Sjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
67330f729Sjoerg //
77330f729Sjoerg //===----------------------------------------------------------------------===//
87330f729Sjoerg //
97330f729Sjoerg // Parallel JIT
107330f729Sjoerg //
117330f729Sjoerg // This test program creates two LLVM functions then calls them from three
127330f729Sjoerg // separate threads. It requires the pthreads library.
137330f729Sjoerg // The three threads are created and then block waiting on a condition variable.
147330f729Sjoerg // Once all threads are blocked on the conditional variable, the main thread
157330f729Sjoerg // wakes them up. This complicated work is performed so that all three threads
167330f729Sjoerg // call into the JIT at the same time (or the best possible approximation of the
177330f729Sjoerg // same time). This test had assertion errors until I got the locking right.
187330f729Sjoerg //
197330f729Sjoerg //===----------------------------------------------------------------------===//
207330f729Sjoerg
217330f729Sjoerg #include "llvm/ADT/APInt.h"
227330f729Sjoerg #include "llvm/ADT/STLExtras.h"
237330f729Sjoerg #include "llvm/ExecutionEngine/ExecutionEngine.h"
247330f729Sjoerg #include "llvm/ExecutionEngine/GenericValue.h"
25*82d56013Sjoerg #include "llvm/ExecutionEngine/MCJIT.h"
267330f729Sjoerg #include "llvm/IR/Argument.h"
277330f729Sjoerg #include "llvm/IR/BasicBlock.h"
287330f729Sjoerg #include "llvm/IR/Constants.h"
297330f729Sjoerg #include "llvm/IR/DerivedTypes.h"
307330f729Sjoerg #include "llvm/IR/Function.h"
317330f729Sjoerg #include "llvm/IR/InstrTypes.h"
327330f729Sjoerg #include "llvm/IR/Instruction.h"
337330f729Sjoerg #include "llvm/IR/Instructions.h"
347330f729Sjoerg #include "llvm/IR/LLVMContext.h"
357330f729Sjoerg #include "llvm/IR/Module.h"
367330f729Sjoerg #include "llvm/IR/Type.h"
377330f729Sjoerg #include "llvm/Support/Casting.h"
387330f729Sjoerg #include "llvm/Support/TargetSelect.h"
397330f729Sjoerg #include <algorithm>
407330f729Sjoerg #include <cassert>
417330f729Sjoerg #include <cstddef>
427330f729Sjoerg #include <cstdint>
437330f729Sjoerg #include <iostream>
447330f729Sjoerg #include <memory>
457330f729Sjoerg #include <vector>
467330f729Sjoerg #include <pthread.h>
477330f729Sjoerg
487330f729Sjoerg using namespace llvm;
497330f729Sjoerg
createAdd1(Module * M)507330f729Sjoerg static Function* createAdd1(Module *M) {
517330f729Sjoerg LLVMContext &Context = M->getContext();
527330f729Sjoerg // Create the add1 function entry and insert this entry into module M. The
537330f729Sjoerg // function will have a return type of "int" and take an argument of "int".
547330f729Sjoerg Function *Add1F =
557330f729Sjoerg Function::Create(FunctionType::get(Type::getInt32Ty(Context),
567330f729Sjoerg {Type::getInt32Ty(Context)}, false),
577330f729Sjoerg Function::ExternalLinkage, "add1", M);
587330f729Sjoerg
597330f729Sjoerg // Add a basic block to the function. As before, it automatically inserts
607330f729Sjoerg // because of the last argument.
617330f729Sjoerg BasicBlock *BB = BasicBlock::Create(Context, "EntryBlock", Add1F);
627330f729Sjoerg
637330f729Sjoerg // Get pointers to the constant `1'.
647330f729Sjoerg Value *One = ConstantInt::get(Type::getInt32Ty(Context), 1);
657330f729Sjoerg
667330f729Sjoerg // Get pointers to the integer argument of the add1 function...
677330f729Sjoerg assert(Add1F->arg_begin() != Add1F->arg_end()); // Make sure there's an arg
687330f729Sjoerg Argument *ArgX = &*Add1F->arg_begin(); // Get the arg
697330f729Sjoerg ArgX->setName("AnArg"); // Give it a nice symbolic name for fun.
707330f729Sjoerg
717330f729Sjoerg // Create the add instruction, inserting it into the end of BB.
727330f729Sjoerg Instruction *Add = BinaryOperator::CreateAdd(One, ArgX, "addresult", BB);
737330f729Sjoerg
747330f729Sjoerg // Create the return instruction and add it to the basic block
757330f729Sjoerg ReturnInst::Create(Context, Add, BB);
767330f729Sjoerg
777330f729Sjoerg // Now, function add1 is ready.
787330f729Sjoerg return Add1F;
797330f729Sjoerg }
807330f729Sjoerg
CreateFibFunction(Module * M)817330f729Sjoerg static Function *CreateFibFunction(Module *M) {
827330f729Sjoerg LLVMContext &Context = M->getContext();
837330f729Sjoerg // Create the fib function and insert it into module M. This function is said
847330f729Sjoerg // to return an int and take an int parameter.
857330f729Sjoerg FunctionType *FibFTy = FunctionType::get(Type::getInt32Ty(Context),
867330f729Sjoerg {Type::getInt32Ty(Context)}, false);
877330f729Sjoerg Function *FibF =
887330f729Sjoerg Function::Create(FibFTy, Function::ExternalLinkage, "fib", M);
897330f729Sjoerg
907330f729Sjoerg // Add a basic block to the function.
917330f729Sjoerg BasicBlock *BB = BasicBlock::Create(Context, "EntryBlock", FibF);
927330f729Sjoerg
937330f729Sjoerg // Get pointers to the constants.
947330f729Sjoerg Value *One = ConstantInt::get(Type::getInt32Ty(Context), 1);
957330f729Sjoerg Value *Two = ConstantInt::get(Type::getInt32Ty(Context), 2);
967330f729Sjoerg
977330f729Sjoerg // Get pointer to the integer argument of the add1 function...
987330f729Sjoerg Argument *ArgX = &*FibF->arg_begin(); // Get the arg.
997330f729Sjoerg ArgX->setName("AnArg"); // Give it a nice symbolic name for fun.
1007330f729Sjoerg
1017330f729Sjoerg // Create the true_block.
1027330f729Sjoerg BasicBlock *RetBB = BasicBlock::Create(Context, "return", FibF);
1037330f729Sjoerg // Create an exit block.
1047330f729Sjoerg BasicBlock *RecurseBB = BasicBlock::Create(Context, "recurse", FibF);
1057330f729Sjoerg
1067330f729Sjoerg // Create the "if (arg < 2) goto exitbb"
1077330f729Sjoerg Value *CondInst = new ICmpInst(*BB, ICmpInst::ICMP_SLE, ArgX, Two, "cond");
1087330f729Sjoerg BranchInst::Create(RetBB, RecurseBB, CondInst, BB);
1097330f729Sjoerg
1107330f729Sjoerg // Create: ret int 1
1117330f729Sjoerg ReturnInst::Create(Context, One, RetBB);
1127330f729Sjoerg
1137330f729Sjoerg // create fib(x-1)
1147330f729Sjoerg Value *Sub = BinaryOperator::CreateSub(ArgX, One, "arg", RecurseBB);
1157330f729Sjoerg Value *CallFibX1 = CallInst::Create(FibF, Sub, "fibx1", RecurseBB);
1167330f729Sjoerg
1177330f729Sjoerg // create fib(x-2)
1187330f729Sjoerg Sub = BinaryOperator::CreateSub(ArgX, Two, "arg", RecurseBB);
1197330f729Sjoerg Value *CallFibX2 = CallInst::Create(FibF, Sub, "fibx2", RecurseBB);
1207330f729Sjoerg
1217330f729Sjoerg // fib(x-1)+fib(x-2)
1227330f729Sjoerg Value *Sum =
1237330f729Sjoerg BinaryOperator::CreateAdd(CallFibX1, CallFibX2, "addresult", RecurseBB);
1247330f729Sjoerg
1257330f729Sjoerg // Create the return instruction and add it to the basic block
1267330f729Sjoerg ReturnInst::Create(Context, Sum, RecurseBB);
1277330f729Sjoerg
1287330f729Sjoerg return FibF;
1297330f729Sjoerg }
1307330f729Sjoerg
1317330f729Sjoerg struct threadParams {
1327330f729Sjoerg ExecutionEngine* EE;
1337330f729Sjoerg Function* F;
1347330f729Sjoerg int value;
1357330f729Sjoerg };
1367330f729Sjoerg
1377330f729Sjoerg // We block the subthreads just before they begin to execute:
1387330f729Sjoerg // we want all of them to call into the JIT at the same time,
1397330f729Sjoerg // to verify that the locking is working correctly.
1407330f729Sjoerg class WaitForThreads
1417330f729Sjoerg {
1427330f729Sjoerg public:
WaitForThreads()1437330f729Sjoerg WaitForThreads()
1447330f729Sjoerg {
1457330f729Sjoerg n = 0;
1467330f729Sjoerg waitFor = 0;
1477330f729Sjoerg
1487330f729Sjoerg int result = pthread_cond_init( &condition, nullptr );
1497330f729Sjoerg (void)result;
1507330f729Sjoerg assert( result == 0 );
1517330f729Sjoerg
1527330f729Sjoerg result = pthread_mutex_init( &mutex, nullptr );
1537330f729Sjoerg assert( result == 0 );
1547330f729Sjoerg }
1557330f729Sjoerg
~WaitForThreads()1567330f729Sjoerg ~WaitForThreads()
1577330f729Sjoerg {
1587330f729Sjoerg int result = pthread_cond_destroy( &condition );
1597330f729Sjoerg (void)result;
1607330f729Sjoerg assert( result == 0 );
1617330f729Sjoerg
1627330f729Sjoerg result = pthread_mutex_destroy( &mutex );
1637330f729Sjoerg assert( result == 0 );
1647330f729Sjoerg }
1657330f729Sjoerg
1667330f729Sjoerg // All threads will stop here until another thread calls releaseThreads
block()1677330f729Sjoerg void block()
1687330f729Sjoerg {
1697330f729Sjoerg int result = pthread_mutex_lock( &mutex );
1707330f729Sjoerg (void)result;
1717330f729Sjoerg assert( result == 0 );
1727330f729Sjoerg n ++;
1737330f729Sjoerg //~ std::cout << "block() n " << n << " waitFor " << waitFor << std::endl;
1747330f729Sjoerg
1757330f729Sjoerg assert( waitFor == 0 || n <= waitFor );
1767330f729Sjoerg if ( waitFor > 0 && n == waitFor )
1777330f729Sjoerg {
1787330f729Sjoerg // There are enough threads blocked that we can release all of them
1797330f729Sjoerg std::cout << "Unblocking threads from block()" << std::endl;
1807330f729Sjoerg unblockThreads();
1817330f729Sjoerg }
1827330f729Sjoerg else
1837330f729Sjoerg {
1847330f729Sjoerg // We just need to wait until someone unblocks us
1857330f729Sjoerg result = pthread_cond_wait( &condition, &mutex );
1867330f729Sjoerg assert( result == 0 );
1877330f729Sjoerg }
1887330f729Sjoerg
1897330f729Sjoerg // unlock the mutex before returning
1907330f729Sjoerg result = pthread_mutex_unlock( &mutex );
1917330f729Sjoerg assert( result == 0 );
1927330f729Sjoerg }
1937330f729Sjoerg
1947330f729Sjoerg // If there are num or more threads blocked, it will signal them all
1957330f729Sjoerg // Otherwise, this thread blocks until there are enough OTHER threads
1967330f729Sjoerg // blocked
releaseThreads(size_t num)1977330f729Sjoerg void releaseThreads( size_t num )
1987330f729Sjoerg {
1997330f729Sjoerg int result = pthread_mutex_lock( &mutex );
2007330f729Sjoerg (void)result;
2017330f729Sjoerg assert( result == 0 );
2027330f729Sjoerg
2037330f729Sjoerg if ( n >= num ) {
2047330f729Sjoerg std::cout << "Unblocking threads from releaseThreads()" << std::endl;
2057330f729Sjoerg unblockThreads();
2067330f729Sjoerg }
2077330f729Sjoerg else
2087330f729Sjoerg {
2097330f729Sjoerg waitFor = num;
2107330f729Sjoerg pthread_cond_wait( &condition, &mutex );
2117330f729Sjoerg }
2127330f729Sjoerg
2137330f729Sjoerg // unlock the mutex before returning
2147330f729Sjoerg result = pthread_mutex_unlock( &mutex );
2157330f729Sjoerg assert( result == 0 );
2167330f729Sjoerg }
2177330f729Sjoerg
2187330f729Sjoerg private:
unblockThreads()2197330f729Sjoerg void unblockThreads()
2207330f729Sjoerg {
2217330f729Sjoerg // Reset the counters to zero: this way, if any new threads
2227330f729Sjoerg // enter while threads are exiting, they will block instead
2237330f729Sjoerg // of triggering a new release of threads
2247330f729Sjoerg n = 0;
2257330f729Sjoerg
2267330f729Sjoerg // Reset waitFor to zero: this way, if waitFor threads enter
2277330f729Sjoerg // while threads are exiting, they will block instead of
2287330f729Sjoerg // triggering a new release of threads
2297330f729Sjoerg waitFor = 0;
2307330f729Sjoerg
2317330f729Sjoerg int result = pthread_cond_broadcast( &condition );
2327330f729Sjoerg (void)result;
2337330f729Sjoerg assert(result == 0);
2347330f729Sjoerg }
2357330f729Sjoerg
2367330f729Sjoerg size_t n;
2377330f729Sjoerg size_t waitFor;
2387330f729Sjoerg pthread_cond_t condition;
2397330f729Sjoerg pthread_mutex_t mutex;
2407330f729Sjoerg };
2417330f729Sjoerg
2427330f729Sjoerg static WaitForThreads synchronize;
2437330f729Sjoerg
callFunc(void * param)2447330f729Sjoerg void* callFunc( void* param )
2457330f729Sjoerg {
2467330f729Sjoerg struct threadParams* p = (struct threadParams*) param;
2477330f729Sjoerg
2487330f729Sjoerg // Call the `foo' function with no arguments:
2497330f729Sjoerg std::vector<GenericValue> Args(1);
2507330f729Sjoerg Args[0].IntVal = APInt(32, p->value);
2517330f729Sjoerg
2527330f729Sjoerg synchronize.block(); // wait until other threads are at this point
2537330f729Sjoerg GenericValue gv = p->EE->runFunction(p->F, Args);
2547330f729Sjoerg
2557330f729Sjoerg return (void*)(intptr_t)gv.IntVal.getZExtValue();
2567330f729Sjoerg }
2577330f729Sjoerg
main()2587330f729Sjoerg int main() {
2597330f729Sjoerg InitializeNativeTarget();
260*82d56013Sjoerg LLVMInitializeNativeAsmPrinter();
2617330f729Sjoerg LLVMContext Context;
2627330f729Sjoerg
2637330f729Sjoerg // Create some module to put our function into it.
2647330f729Sjoerg std::unique_ptr<Module> Owner = std::make_unique<Module>("test", Context);
2657330f729Sjoerg Module *M = Owner.get();
2667330f729Sjoerg
2677330f729Sjoerg Function* add1F = createAdd1( M );
2687330f729Sjoerg Function* fibF = CreateFibFunction( M );
2697330f729Sjoerg
2707330f729Sjoerg // Now we create the JIT.
2717330f729Sjoerg ExecutionEngine* EE = EngineBuilder(std::move(Owner)).create();
2727330f729Sjoerg
2737330f729Sjoerg //~ std::cout << "We just constructed this LLVM module:\n\n" << *M;
2747330f729Sjoerg //~ std::cout << "\n\nRunning foo: " << std::flush;
2757330f729Sjoerg
2767330f729Sjoerg // Create one thread for add1 and two threads for fib
2777330f729Sjoerg struct threadParams add1 = { EE, add1F, 1000 };
2787330f729Sjoerg struct threadParams fib1 = { EE, fibF, 39 };
2797330f729Sjoerg struct threadParams fib2 = { EE, fibF, 42 };
2807330f729Sjoerg
2817330f729Sjoerg pthread_t add1Thread;
2827330f729Sjoerg int result = pthread_create( &add1Thread, nullptr, callFunc, &add1 );
2837330f729Sjoerg if ( result != 0 ) {
2847330f729Sjoerg std::cerr << "Could not create thread" << std::endl;
2857330f729Sjoerg return 1;
2867330f729Sjoerg }
2877330f729Sjoerg
2887330f729Sjoerg pthread_t fibThread1;
2897330f729Sjoerg result = pthread_create( &fibThread1, nullptr, callFunc, &fib1 );
2907330f729Sjoerg if ( result != 0 ) {
2917330f729Sjoerg std::cerr << "Could not create thread" << std::endl;
2927330f729Sjoerg return 1;
2937330f729Sjoerg }
2947330f729Sjoerg
2957330f729Sjoerg pthread_t fibThread2;
2967330f729Sjoerg result = pthread_create( &fibThread2, nullptr, callFunc, &fib2 );
2977330f729Sjoerg if ( result != 0 ) {
2987330f729Sjoerg std::cerr << "Could not create thread" << std::endl;
2997330f729Sjoerg return 1;
3007330f729Sjoerg }
3017330f729Sjoerg
3027330f729Sjoerg synchronize.releaseThreads(3); // wait until other threads are at this point
3037330f729Sjoerg
3047330f729Sjoerg void* returnValue;
3057330f729Sjoerg result = pthread_join( add1Thread, &returnValue );
3067330f729Sjoerg if ( result != 0 ) {
3077330f729Sjoerg std::cerr << "Could not join thread" << std::endl;
3087330f729Sjoerg return 1;
3097330f729Sjoerg }
3107330f729Sjoerg std::cout << "Add1 returned " << intptr_t(returnValue) << std::endl;
3117330f729Sjoerg
3127330f729Sjoerg result = pthread_join( fibThread1, &returnValue );
3137330f729Sjoerg if ( result != 0 ) {
3147330f729Sjoerg std::cerr << "Could not join thread" << std::endl;
3157330f729Sjoerg return 1;
3167330f729Sjoerg }
3177330f729Sjoerg std::cout << "Fib1 returned " << intptr_t(returnValue) << std::endl;
3187330f729Sjoerg
3197330f729Sjoerg result = pthread_join( fibThread2, &returnValue );
3207330f729Sjoerg if ( result != 0 ) {
3217330f729Sjoerg std::cerr << "Could not join thread" << std::endl;
3227330f729Sjoerg return 1;
3237330f729Sjoerg }
3247330f729Sjoerg std::cout << "Fib2 returned " << intptr_t(returnValue) << std::endl;
3257330f729Sjoerg
3267330f729Sjoerg return 0;
3277330f729Sjoerg }
328