ParallelJIT.cpp revision 333c40096561218bc3597cf153c0a3895274414c
1//===-- examples/ParallelJIT/ParallelJIT.cpp - Exercise threaded-safe JIT -===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Parallel JIT
11//
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.
19
20#include <pthread.h>
21#include "llvm/LLVMContext.h"
22#include "llvm/Module.h"
23#include "llvm/Constants.h"
24#include "llvm/DerivedTypes.h"
25#include "llvm/Instructions.h"
26#include "llvm/ModuleProvider.h"
27#include "llvm/ExecutionEngine/JIT.h"
28#include "llvm/ExecutionEngine/Interpreter.h"
29#include "llvm/ExecutionEngine/GenericValue.h"
30#include "llvm/Target/TargetSelect.h"
31#include <iostream>
32using namespace llvm;
33
34static Function* createAdd1(Module *M) {
35  // Create the add1 function entry and insert this entry into module M.  The
36  // function will have a return type of "int" and take an argument of "int".
37  // The '0' terminates the list of argument types.
38  Function *Add1F =
39    cast<Function>(M->getOrInsertFunction("add1", Type::Int32Ty, Type::Int32Ty,
40                                          (Type *)0));
41
42  // Add a basic block to the function. As before, it automatically inserts
43  // because of the last argument.
44  BasicBlock *BB = BasicBlock::Create("EntryBlock", Add1F);
45
46  // Get pointers to the constant `1'.
47  Value *One = ConstantInt::get(Type::Int32Ty, 1);
48
49  // Get pointers to the integer argument of the add1 function...
50  assert(Add1F->arg_begin() != Add1F->arg_end()); // Make sure there's an arg
51  Argument *ArgX = Add1F->arg_begin();  // Get the arg
52  ArgX->setName("AnArg");            // Give it a nice symbolic name for fun.
53
54  // Create the add instruction, inserting it into the end of BB.
55  Instruction *Add = BinaryOperator::CreateAdd(One, ArgX, "addresult", BB);
56
57  // Create the return instruction and add it to the basic block
58  ReturnInst::Create(Add, BB);
59
60  // Now, function add1 is ready.
61  return Add1F;
62}
63
64static Function *CreateFibFunction(Module *M) {
65  // Create the fib function and insert it into module M.  This function is said
66  // to return an int and take an int parameter.
67  Function *FibF =
68    cast<Function>(M->getOrInsertFunction("fib", Type::Int32Ty, Type::Int32Ty,
69                                          (Type *)0));
70
71  // Add a basic block to the function.
72  BasicBlock *BB = BasicBlock::Create("EntryBlock", FibF);
73
74  // Get pointers to the constants.
75  Value *One = ConstantInt::get(Type::Int32Ty, 1);
76  Value *Two = ConstantInt::get(Type::Int32Ty, 2);
77
78  // Get pointer to the integer argument of the add1 function...
79  Argument *ArgX = FibF->arg_begin();   // Get the arg.
80  ArgX->setName("AnArg");            // Give it a nice symbolic name for fun.
81
82  // Create the true_block.
83  BasicBlock *RetBB = BasicBlock::Create("return", FibF);
84  // Create an exit block.
85  BasicBlock* RecurseBB = BasicBlock::Create("recurse", FibF);
86
87  // Create the "if (arg < 2) goto exitbb"
88  Value *CondInst = new ICmpInst(*BB, ICmpInst::ICMP_SLE, ArgX, Two, "cond");
89  BranchInst::Create(RetBB, RecurseBB, CondInst, BB);
90
91  // Create: ret int 1
92  ReturnInst::Create(One, RetBB);
93
94  // create fib(x-1)
95  Value *Sub = BinaryOperator::CreateSub(ArgX, One, "arg", RecurseBB);
96  Value *CallFibX1 = CallInst::Create(FibF, Sub, "fibx1", RecurseBB);
97
98  // create fib(x-2)
99  Sub = BinaryOperator::CreateSub(ArgX, Two, "arg", RecurseBB);
100  Value *CallFibX2 = CallInst::Create(FibF, Sub, "fibx2", RecurseBB);
101
102  // fib(x-1)+fib(x-2)
103  Value *Sum =
104    BinaryOperator::CreateAdd(CallFibX1, CallFibX2, "addresult", RecurseBB);
105
106  // Create the return instruction and add it to the basic block
107  ReturnInst::Create(Sum, RecurseBB);
108
109  return FibF;
110}
111
112struct threadParams {
113  ExecutionEngine* EE;
114  Function* F;
115  int value;
116};
117
118// We block the subthreads just before they begin to execute:
119// we want all of them to call into the JIT at the same time,
120// to verify that the locking is working correctly.
121class WaitForThreads
122{
123public:
124  WaitForThreads()
125  {
126    n = 0;
127    waitFor = 0;
128
129    int result = pthread_cond_init( &condition, NULL );
130    assert( result == 0 );
131
132    result = pthread_mutex_init( &mutex, NULL );
133    assert( result == 0 );
134  }
135
136  ~WaitForThreads()
137  {
138    int result = pthread_cond_destroy( &condition );
139    assert( result == 0 );
140
141    result = pthread_mutex_destroy( &mutex );
142    assert( result == 0 );
143  }
144
145  // All threads will stop here until another thread calls releaseThreads
146  void block()
147  {
148    int result = pthread_mutex_lock( &mutex );
149    assert( result == 0 );
150    n ++;
151    //~ std::cout << "block() n " << n << " waitFor " << waitFor << std::endl;
152
153    assert( waitFor == 0 || n <= waitFor );
154    if ( waitFor > 0 && n == waitFor )
155    {
156      // There are enough threads blocked that we can release all of them
157      std::cout << "Unblocking threads from block()" << std::endl;
158      unblockThreads();
159    }
160    else
161    {
162      // We just need to wait until someone unblocks us
163      result = pthread_cond_wait( &condition, &mutex );
164      assert( result == 0 );
165    }
166
167    // unlock the mutex before returning
168    result = pthread_mutex_unlock( &mutex );
169    assert( result == 0 );
170  }
171
172  // If there are num or more threads blocked, it will signal them all
173  // Otherwise, this thread blocks until there are enough OTHER threads
174  // blocked
175  void releaseThreads( size_t num )
176  {
177    int result = pthread_mutex_lock( &mutex );
178    assert( result == 0 );
179
180    if ( n >= num ) {
181      std::cout << "Unblocking threads from releaseThreads()" << std::endl;
182      unblockThreads();
183    }
184    else
185    {
186      waitFor = num;
187      pthread_cond_wait( &condition, &mutex );
188    }
189
190    // unlock the mutex before returning
191    result = pthread_mutex_unlock( &mutex );
192    assert( result == 0 );
193  }
194
195private:
196  void unblockThreads()
197  {
198    // Reset the counters to zero: this way, if any new threads
199    // enter while threads are exiting, they will block instead
200    // of triggering a new release of threads
201    n = 0;
202
203    // Reset waitFor to zero: this way, if waitFor threads enter
204    // while threads are exiting, they will block instead of
205    // triggering a new release of threads
206    waitFor = 0;
207
208    int result = pthread_cond_broadcast( &condition );
209    assert(result == 0); result=result;
210  }
211
212  size_t n;
213  size_t waitFor;
214  pthread_cond_t condition;
215  pthread_mutex_t mutex;
216};
217
218static WaitForThreads synchronize;
219
220void* callFunc( void* param )
221{
222  struct threadParams* p = (struct threadParams*) param;
223
224  // Call the `foo' function with no arguments:
225  std::vector<GenericValue> Args(1);
226  Args[0].IntVal = APInt(32, p->value);
227
228  synchronize.block(); // wait until other threads are at this point
229  GenericValue gv = p->EE->runFunction(p->F, Args);
230
231  return (void*)(intptr_t)gv.IntVal.getZExtValue();
232}
233
234int main() {
235  InitializeNativeTarget();
236  LLVMContext Context;
237
238  // Create some module to put our function into it.
239  Module *M = new Module("test", Context);
240
241  Function* add1F = createAdd1( M );
242  Function* fibF = CreateFibFunction( M );
243
244  // Now we create the JIT.
245  ExistingModuleProvider* MP = new ExistingModuleProvider(M);
246  ExecutionEngine* EE = ExecutionEngine::create(MP, false);
247
248  //~ std::cout << "We just constructed this LLVM module:\n\n" << *M;
249  //~ std::cout << "\n\nRunning foo: " << std::flush;
250
251  // Create one thread for add1 and two threads for fib
252  struct threadParams add1 = { EE, add1F, 1000 };
253  struct threadParams fib1 = { EE, fibF, 39 };
254  struct threadParams fib2 = { EE, fibF, 42 };
255
256  pthread_t add1Thread;
257  int result = pthread_create( &add1Thread, NULL, callFunc, &add1 );
258  if ( result != 0 ) {
259          std::cerr << "Could not create thread" << std::endl;
260          return 1;
261  }
262
263  pthread_t fibThread1;
264  result = pthread_create( &fibThread1, NULL, callFunc, &fib1 );
265  if ( result != 0 ) {
266          std::cerr << "Could not create thread" << std::endl;
267          return 1;
268  }
269
270  pthread_t fibThread2;
271  result = pthread_create( &fibThread2, NULL, callFunc, &fib2 );
272  if ( result != 0 ) {
273          std::cerr << "Could not create thread" << std::endl;
274          return 1;
275  }
276
277  synchronize.releaseThreads(3); // wait until other threads are at this point
278
279  void* returnValue;
280  result = pthread_join( add1Thread, &returnValue );
281  if ( result != 0 ) {
282          std::cerr << "Could not join thread" << std::endl;
283          return 1;
284  }
285  std::cout << "Add1 returned " << intptr_t(returnValue) << std::endl;
286
287  result = pthread_join( fibThread1, &returnValue );
288  if ( result != 0 ) {
289          std::cerr << "Could not join thread" << std::endl;
290          return 1;
291  }
292  std::cout << "Fib1 returned " << intptr_t(returnValue) << std::endl;
293
294  result = pthread_join( fibThread2, &returnValue );
295  if ( result != 0 ) {
296          std::cerr << "Could not join thread" << std::endl;
297          return 1;
298  }
299  std::cout << "Fib2 returned " << intptr_t(returnValue) << std::endl;
300
301  return 0;
302}
303