1 //===-- examples/ParallelJIT/ParallelJIT.cpp - Exercise threaded-safe JIT -===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
12 // This test program creates two LLVM functions then calls them from three
13 // separate threads. It requires the pthreads library.
14 // The three threads are created and then block waiting on a condition variable.
15 // Once all threads are blocked on the conditional variable, the main thread
16 // wakes them up. This complicated work is performed so that all three threads
17 // call into the JIT at the same time (or the best possible approximation of the
18 // same time). This test had assertion errors until I got the locking right.
21 #include "llvm/Module.h"
22 #include "llvm/Constants.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/ModuleProvider.h"
26 #include "llvm/ExecutionEngine/JIT.h"
27 #include "llvm/ExecutionEngine/Interpreter.h"
28 #include "llvm/ExecutionEngine/GenericValue.h"
29 #include "llvm/Target/TargetSelect.h"
33 static Function* createAdd1(Module *M) {
34 // Create the add1 function entry and insert this entry into module M. The
35 // function will have a return type of "int" and take an argument of "int".
36 // The '0' terminates the list of argument types.
38 cast<Function>(M->getOrInsertFunction("add1", Type::Int32Ty, Type::Int32Ty,
41 // Add a basic block to the function. As before, it automatically inserts
42 // because of the last argument.
43 BasicBlock *BB = BasicBlock::Create("EntryBlock", Add1F);
45 // Get pointers to the constant `1'.
46 Value *One = ConstantInt::get(Type::Int32Ty, 1);
48 // Get pointers to the integer argument of the add1 function...
49 assert(Add1F->arg_begin() != Add1F->arg_end()); // Make sure there's an arg
50 Argument *ArgX = Add1F->arg_begin(); // Get the arg
51 ArgX->setName("AnArg"); // Give it a nice symbolic name for fun.
53 // Create the add instruction, inserting it into the end of BB.
54 Instruction *Add = BinaryOperator::CreateAdd(One, ArgX, "addresult", BB);
56 // Create the return instruction and add it to the basic block
57 ReturnInst::Create(Add, BB);
59 // Now, function add1 is ready.
63 static Function *CreateFibFunction(Module *M) {
64 // Create the fib function and insert it into module M. This function is said
65 // to return an int and take an int parameter.
67 cast<Function>(M->getOrInsertFunction("fib", Type::Int32Ty, Type::Int32Ty,
70 // Add a basic block to the function.
71 BasicBlock *BB = BasicBlock::Create("EntryBlock", FibF);
73 // Get pointers to the constants.
74 Value *One = ConstantInt::get(Type::Int32Ty, 1);
75 Value *Two = ConstantInt::get(Type::Int32Ty, 2);
77 // Get pointer to the integer argument of the add1 function...
78 Argument *ArgX = FibF->arg_begin(); // Get the arg.
79 ArgX->setName("AnArg"); // Give it a nice symbolic name for fun.
81 // Create the true_block.
82 BasicBlock *RetBB = BasicBlock::Create("return", FibF);
83 // Create an exit block.
84 BasicBlock* RecurseBB = BasicBlock::Create("recurse", FibF);
86 // Create the "if (arg < 2) goto exitbb"
87 Value *CondInst = new ICmpInst(ICmpInst::ICMP_SLE, ArgX, Two, "cond", BB);
88 BranchInst::Create(RetBB, RecurseBB, CondInst, BB);
91 ReturnInst::Create(One, RetBB);
94 Value *Sub = BinaryOperator::CreateSub(ArgX, One, "arg", RecurseBB);
95 Value *CallFibX1 = CallInst::Create(FibF, Sub, "fibx1", RecurseBB);
98 Sub = BinaryOperator::CreateSub(ArgX, Two, "arg", RecurseBB);
99 Value *CallFibX2 = CallInst::Create(FibF, Sub, "fibx2", RecurseBB);
103 BinaryOperator::CreateAdd(CallFibX1, CallFibX2, "addresult", RecurseBB);
105 // Create the return instruction and add it to the basic block
106 ReturnInst::Create(Sum, RecurseBB);
111 struct threadParams {
117 // We block the subthreads just before they begin to execute:
118 // we want all of them to call into the JIT at the same time,
119 // to verify that the locking is working correctly.
128 int result = pthread_cond_init( &condition, NULL );
129 assert( result == 0 );
131 result = pthread_mutex_init( &mutex, NULL );
132 assert( result == 0 );
137 int result = pthread_cond_destroy( &condition );
138 assert( result == 0 );
140 result = pthread_mutex_destroy( &mutex );
141 assert( result == 0 );
144 // All threads will stop here until another thread calls releaseThreads
147 int result = pthread_mutex_lock( &mutex );
148 assert( result == 0 );
150 //~ std::cout << "block() n " << n << " waitFor " << waitFor << std::endl;
152 assert( waitFor == 0 || n <= waitFor );
153 if ( waitFor > 0 && n == waitFor )
155 // There are enough threads blocked that we can release all of them
156 std::cout << "Unblocking threads from block()" << std::endl;
161 // We just need to wait until someone unblocks us
162 result = pthread_cond_wait( &condition, &mutex );
163 assert( result == 0 );
166 // unlock the mutex before returning
167 result = pthread_mutex_unlock( &mutex );
168 assert( result == 0 );
171 // If there are num or more threads blocked, it will signal them all
172 // Otherwise, this thread blocks until there are enough OTHER threads
174 void releaseThreads( size_t num )
176 int result = pthread_mutex_lock( &mutex );
177 assert( result == 0 );
180 std::cout << "Unblocking threads from releaseThreads()" << std::endl;
186 pthread_cond_wait( &condition, &mutex );
189 // unlock the mutex before returning
190 result = pthread_mutex_unlock( &mutex );
191 assert( result == 0 );
195 void unblockThreads()
197 // Reset the counters to zero: this way, if any new threads
198 // enter while threads are exiting, they will block instead
199 // of triggering a new release of threads
202 // Reset waitFor to zero: this way, if waitFor threads enter
203 // while threads are exiting, they will block instead of
204 // triggering a new release of threads
207 int result = pthread_cond_broadcast( &condition );
208 assert(result == 0); result=result;
213 pthread_cond_t condition;
214 pthread_mutex_t mutex;
217 static WaitForThreads synchronize;
219 void* callFunc( void* param )
221 struct threadParams* p = (struct threadParams*) param;
223 // Call the `foo' function with no arguments:
224 std::vector<GenericValue> Args(1);
225 Args[0].IntVal = APInt(32, p->value);
227 synchronize.block(); // wait until other threads are at this point
228 GenericValue gv = p->EE->runFunction(p->F, Args);
230 return (void*)(intptr_t)gv.IntVal.getZExtValue();
234 InitializeNativeTarget();
236 // Create some module to put our function into it.
237 Module *M = new Module("test");
239 Function* add1F = createAdd1( M );
240 Function* fibF = CreateFibFunction( M );
242 // Now we create the JIT.
243 ExistingModuleProvider* MP = new ExistingModuleProvider(M);
244 ExecutionEngine* EE = ExecutionEngine::create(MP, false);
246 //~ std::cout << "We just constructed this LLVM module:\n\n" << *M;
247 //~ std::cout << "\n\nRunning foo: " << std::flush;
249 // Create one thread for add1 and two threads for fib
250 struct threadParams add1 = { EE, add1F, 1000 };
251 struct threadParams fib1 = { EE, fibF, 39 };
252 struct threadParams fib2 = { EE, fibF, 42 };
254 pthread_t add1Thread;
255 int result = pthread_create( &add1Thread, NULL, callFunc, &add1 );
257 std::cerr << "Could not create thread" << std::endl;
261 pthread_t fibThread1;
262 result = pthread_create( &fibThread1, NULL, callFunc, &fib1 );
264 std::cerr << "Could not create thread" << std::endl;
268 pthread_t fibThread2;
269 result = pthread_create( &fibThread2, NULL, callFunc, &fib2 );
271 std::cerr << "Could not create thread" << std::endl;
275 synchronize.releaseThreads(3); // wait until other threads are at this point
278 result = pthread_join( add1Thread, &returnValue );
280 std::cerr << "Could not join thread" << std::endl;
283 std::cout << "Add1 returned " << intptr_t(returnValue) << std::endl;
285 result = pthread_join( fibThread1, &returnValue );
287 std::cerr << "Could not join thread" << std::endl;
290 std::cout << "Fib1 returned " << intptr_t(returnValue) << std::endl;
292 result = pthread_join( fibThread2, &returnValue );
294 std::cerr << "Could not join thread" << std::endl;
297 std::cout << "Fib2 returned " << intptr_t(returnValue) << std::endl;