ParallelJIT.cpp 9.7 KB

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