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