1 //===- AsyncRuntime.cpp - Async runtime reference implementation ----------===// 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 // This file implements basic Async runtime API for supporting Async dialect 10 // to LLVM dialect lowering. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "mlir/ExecutionEngine/AsyncRuntime.h" 15 16 #ifdef MLIR_ASYNCRUNTIME_DEFINE_FUNCTIONS 17 18 #include <atomic> 19 #include <cassert> 20 #include <condition_variable> 21 #include <functional> 22 #include <iostream> 23 #include <mutex> 24 #include <thread> 25 #include <vector> 26 27 using namespace mlir::runtime; 28 29 //===----------------------------------------------------------------------===// 30 // Async runtime API. 31 //===----------------------------------------------------------------------===// 32 33 namespace mlir { 34 namespace runtime { 35 namespace { 36 37 // Forward declare class defined below. 38 class RefCounted; 39 40 // -------------------------------------------------------------------------- // 41 // AsyncRuntime orchestrates all async operations and Async runtime API is built 42 // on top of the default runtime instance. 43 // -------------------------------------------------------------------------- // 44 45 class AsyncRuntime { 46 public: 47 AsyncRuntime() : numRefCountedObjects(0) {} 48 49 ~AsyncRuntime() { 50 assert(getNumRefCountedObjects() == 0 && 51 "all ref counted objects must be destroyed"); 52 } 53 54 int32_t getNumRefCountedObjects() { 55 return numRefCountedObjects.load(std::memory_order_relaxed); 56 } 57 58 private: 59 friend class RefCounted; 60 61 // Count the total number of reference counted objects in this instance 62 // of an AsyncRuntime. For debugging purposes only. 63 void addNumRefCountedObjects() { 64 numRefCountedObjects.fetch_add(1, std::memory_order_relaxed); 65 } 66 void dropNumRefCountedObjects() { 67 numRefCountedObjects.fetch_sub(1, std::memory_order_relaxed); 68 } 69 70 std::atomic<int32_t> numRefCountedObjects; 71 }; 72 73 // -------------------------------------------------------------------------- // 74 // A base class for all reference counted objects created by the async runtime. 75 // -------------------------------------------------------------------------- // 76 77 class RefCounted { 78 public: 79 RefCounted(AsyncRuntime *runtime, int32_t refCount = 1) 80 : runtime(runtime), refCount(refCount) { 81 runtime->addNumRefCountedObjects(); 82 } 83 84 virtual ~RefCounted() { 85 assert(refCount.load() == 0 && "reference count must be zero"); 86 runtime->dropNumRefCountedObjects(); 87 } 88 89 RefCounted(const RefCounted &) = delete; 90 RefCounted &operator=(const RefCounted &) = delete; 91 92 void addRef(int32_t count = 1) { refCount.fetch_add(count); } 93 94 void dropRef(int32_t count = 1) { 95 int32_t previous = refCount.fetch_sub(count); 96 assert(previous >= count && "reference count should not go below zero"); 97 if (previous == count) 98 destroy(); 99 } 100 101 protected: 102 virtual void destroy() { delete this; } 103 104 private: 105 AsyncRuntime *runtime; 106 std::atomic<int32_t> refCount; 107 }; 108 109 } // namespace 110 111 // Returns the default per-process instance of an async runtime. 112 static AsyncRuntime *getDefaultAsyncRuntimeInstance() { 113 static auto runtime = std::make_unique<AsyncRuntime>(); 114 return runtime.get(); 115 } 116 117 struct AsyncToken : public RefCounted { 118 // AsyncToken created with a reference count of 2 because it will be returned 119 // to the `async.execute` caller and also will be later on emplaced by the 120 // asynchronously executed task. If the caller immediately will drop its 121 // reference we must ensure that the token will be alive until the 122 // asynchronous operation is completed. 123 AsyncToken(AsyncRuntime *runtime) : RefCounted(runtime, /*count=*/2) {} 124 125 // Internal state below guarded by a mutex. 126 std::mutex mu; 127 std::condition_variable cv; 128 129 bool ready = false; 130 std::vector<std::function<void()>> awaiters; 131 }; 132 133 struct AsyncGroup : public RefCounted { 134 AsyncGroup(AsyncRuntime *runtime) 135 : RefCounted(runtime), pendingTokens(0), rank(0) {} 136 137 std::atomic<int> pendingTokens; 138 std::atomic<int> rank; 139 140 // Internal state below guarded by a mutex. 141 std::mutex mu; 142 std::condition_variable cv; 143 144 std::vector<std::function<void()>> awaiters; 145 }; 146 147 } // namespace runtime 148 } // namespace mlir 149 150 // Adds references to reference counted runtime object. 151 extern "C" void mlirAsyncRuntimeAddRef(RefCountedObjPtr ptr, int32_t count) { 152 RefCounted *refCounted = static_cast<RefCounted *>(ptr); 153 refCounted->addRef(count); 154 } 155 156 // Drops references from reference counted runtime object. 157 extern "C" void mlirAsyncRuntimeDropRef(RefCountedObjPtr ptr, int32_t count) { 158 RefCounted *refCounted = static_cast<RefCounted *>(ptr); 159 refCounted->dropRef(count); 160 } 161 162 // Create a new `async.token` in not-ready state. 163 extern "C" AsyncToken *mlirAsyncRuntimeCreateToken() { 164 AsyncToken *token = new AsyncToken(getDefaultAsyncRuntimeInstance()); 165 return token; 166 } 167 168 // Create a new `async.group` in empty state. 169 extern "C" AsyncGroup *mlirAsyncRuntimeCreateGroup() { 170 AsyncGroup *group = new AsyncGroup(getDefaultAsyncRuntimeInstance()); 171 return group; 172 } 173 174 extern "C" int64_t mlirAsyncRuntimeAddTokenToGroup(AsyncToken *token, 175 AsyncGroup *group) { 176 std::unique_lock<std::mutex> lockToken(token->mu); 177 std::unique_lock<std::mutex> lockGroup(group->mu); 178 179 // Get the rank of the token inside the group before we drop the reference. 180 int rank = group->rank.fetch_add(1); 181 group->pendingTokens.fetch_add(1); 182 183 auto onTokenReady = [group]() { 184 // Run all group awaiters if it was the last token in the group. 185 if (group->pendingTokens.fetch_sub(1) == 1) { 186 group->cv.notify_all(); 187 for (auto &awaiter : group->awaiters) 188 awaiter(); 189 } 190 }; 191 192 if (token->ready) { 193 // Update group pending tokens immediately and maybe run awaiters. 194 onTokenReady(); 195 196 } else { 197 // Update group pending tokens when token will become ready. Because this 198 // will happen asynchronously we must ensure that `group` is alive until 199 // then, and re-ackquire the lock. 200 group->addRef(); 201 202 token->awaiters.push_back([group, onTokenReady]() { 203 // Make sure that `dropRef` does not destroy the mutex owned by the lock. 204 { 205 std::unique_lock<std::mutex> lockGroup(group->mu); 206 onTokenReady(); 207 } 208 group->dropRef(); 209 }); 210 } 211 212 return rank; 213 } 214 215 // Switches `async.token` to ready state and runs all awaiters. 216 extern "C" void mlirAsyncRuntimeEmplaceToken(AsyncToken *token) { 217 // Make sure that `dropRef` does not destroy the mutex owned by the lock. 218 { 219 std::unique_lock<std::mutex> lock(token->mu); 220 token->ready = true; 221 token->cv.notify_all(); 222 for (auto &awaiter : token->awaiters) 223 awaiter(); 224 } 225 226 // Async tokens created with a ref count `2` to keep token alive until the 227 // async task completes. Drop this reference explicitly when token emplaced. 228 token->dropRef(); 229 } 230 231 extern "C" void mlirAsyncRuntimeAwaitToken(AsyncToken *token) { 232 std::unique_lock<std::mutex> lock(token->mu); 233 if (!token->ready) 234 token->cv.wait(lock, [token] { return token->ready; }); 235 } 236 237 extern "C" void mlirAsyncRuntimeAwaitAllInGroup(AsyncGroup *group) { 238 std::unique_lock<std::mutex> lock(group->mu); 239 if (group->pendingTokens != 0) 240 group->cv.wait(lock, [group] { return group->pendingTokens == 0; }); 241 } 242 243 extern "C" void mlirAsyncRuntimeExecute(CoroHandle handle, CoroResume resume) { 244 (*resume)(handle); 245 } 246 247 extern "C" void mlirAsyncRuntimeAwaitTokenAndExecute(AsyncToken *token, 248 CoroHandle handle, 249 CoroResume resume) { 250 std::unique_lock<std::mutex> lock(token->mu); 251 auto execute = [handle, resume]() { (*resume)(handle); }; 252 if (token->ready) 253 execute(); 254 else 255 token->awaiters.push_back([execute]() { execute(); }); 256 } 257 258 extern "C" void mlirAsyncRuntimeAwaitAllInGroupAndExecute(AsyncGroup *group, 259 CoroHandle handle, 260 CoroResume resume) { 261 std::unique_lock<std::mutex> lock(group->mu); 262 auto execute = [handle, resume]() { (*resume)(handle); }; 263 if (group->pendingTokens == 0) 264 execute(); 265 else 266 group->awaiters.push_back([execute]() { execute(); }); 267 } 268 269 //===----------------------------------------------------------------------===// 270 // Small async runtime support library for testing. 271 //===----------------------------------------------------------------------===// 272 273 extern "C" void mlirAsyncRuntimePrintCurrentThreadId() { 274 static thread_local std::thread::id thisId = std::this_thread::get_id(); 275 std::cout << "Current thread id: " << thisId << std::endl; 276 } 277 278 #endif // MLIR_ASYNCRUNTIME_DEFINE_FUNCTIONS 279