ParallelJIT.cpp 10 KB

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