ParallelJIT.cpp 10 KB

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