ParallelJIT.cpp 9.7 KB

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