1 //===- AsyncRegionRewriter.cpp - Implementation of GPU async rewriters ----===// 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 the GPU dialect pattern rewriters that make GPU op 10 // within a region execute asynchronously. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "PassDetail.h" 15 #include "mlir/Dialect/Async/IR/Async.h" 16 #include "mlir/Dialect/GPU/GPUDialect.h" 17 #include "mlir/Dialect/GPU/Passes.h" 18 #include "mlir/Dialect/GPU/Utils.h" 19 #include "mlir/IR/BlockAndValueMapping.h" 20 #include "mlir/IR/Builders.h" 21 #include "mlir/IR/PatternMatch.h" 22 #include "mlir/IR/SymbolTable.h" 23 #include "mlir/Support/LLVM.h" 24 #include "mlir/Transforms/RegionUtils.h" 25 #include "llvm/ADT/TypeSwitch.h" 26 27 using namespace mlir; 28 namespace { 29 class GpuAsyncRegionPass : public GpuAsyncRegionPassBase<GpuAsyncRegionPass> { 30 struct ThreadTokenCallback; 31 struct DeferWaitCallback; 32 struct SingleTokenUseCallback; 33 void runOnOperation() override; 34 }; 35 } // namespace 36 37 static bool isTerminator(Operation *op) { 38 return op->mightHaveTrait<OpTrait::IsTerminator>(); 39 } 40 static bool hasSideEffects(Operation *op) { 41 return !MemoryEffectOpInterface::hasNoEffect(op); 42 } 43 44 // Region walk callback which makes GPU ops implementing the AsyncOpInterface 45 // execute asynchronously. 46 struct GpuAsyncRegionPass::ThreadTokenCallback { 47 ThreadTokenCallback(MLIRContext &context) : builder(&context) {} 48 49 WalkResult operator()(Block *block) { 50 for (Operation &op : make_early_inc_range(*block)) { 51 if (failed(visit(&op))) 52 return WalkResult::interrupt(); 53 } 54 return WalkResult::advance(); 55 } 56 57 private: 58 // If `op` implements the AsyncOpInterface, insert a `gpu.wait async` to 59 // create a current token (unless it already exists), and 'thread' that token 60 // through the `op` so that it executes asynchronously. 61 // 62 // If `op` is a terminator or an op with side-effects, insert a `gpu.wait` to 63 // host-synchronize execution. A `!gpu.async.token` will therefore only be 64 // used inside of its block and GPU execution will always synchronize with 65 // the host at block boundaries. 66 LogicalResult visit(Operation *op) { 67 if (isa<gpu::LaunchOp>(op)) 68 return op->emitOpError("replace with gpu.launch_func first"); 69 if (auto waitOp = llvm::dyn_cast<gpu::WaitOp>(op)) { 70 if (currentToken) 71 waitOp.addAsyncDependency(currentToken); 72 currentToken = waitOp.asyncToken(); 73 return success(); 74 } 75 builder.setInsertionPoint(op); 76 if (auto asyncOp = dyn_cast<gpu::AsyncOpInterface>(op)) 77 return rewriteAsyncOp(asyncOp); // Replace GPU op with async version. 78 if (!currentToken) 79 return success(); 80 // Insert host synchronization before terminator or op with side effects. 81 if (isTerminator(op) || hasSideEffects(op)) 82 currentToken = createWaitOp(op->getLoc(), Type(), {currentToken}); 83 return success(); 84 } 85 86 // Replaces asyncOp with a clone that returns a token. 87 LogicalResult rewriteAsyncOp(gpu::AsyncOpInterface asyncOp) { 88 auto *op = asyncOp.getOperation(); 89 auto tokenType = builder.getType<gpu::AsyncTokenType>(); 90 91 // If there is no current token, insert a `gpu.wait async` without 92 // dependencies to create one. 93 if (!currentToken) 94 currentToken = createWaitOp(op->getLoc(), tokenType, {}); 95 asyncOp.addAsyncDependency(currentToken); 96 97 // Return early if op returns a token already. 98 currentToken = asyncOp.getAsyncToken(); 99 if (currentToken) 100 return success(); 101 102 // Clone the op to return a token in addition to the other results. 103 SmallVector<Type, 1> resultTypes; 104 resultTypes.reserve(1 + op->getNumResults()); 105 copy(op->getResultTypes(), std::back_inserter(resultTypes)); 106 resultTypes.push_back(tokenType); 107 auto *newOp = Operation::create(op->getLoc(), op->getName(), resultTypes, 108 op->getOperands(), op->getAttrDictionary(), 109 op->getSuccessors(), op->getNumRegions()); 110 111 // Clone regions into new op. 112 BlockAndValueMapping mapping; 113 for (auto pair : llvm::zip_first(op->getRegions(), newOp->getRegions())) 114 std::get<0>(pair).cloneInto(&std::get<1>(pair), mapping); 115 116 // Replace the op with the async clone. 117 auto results = newOp->getResults(); 118 currentToken = results.back(); 119 builder.insert(newOp); 120 op->replaceAllUsesWith(results.drop_back()); 121 op->erase(); 122 123 return success(); 124 } 125 126 Value createWaitOp(Location loc, Type resultType, ValueRange operands) { 127 return builder.create<gpu::WaitOp>(loc, resultType, operands).asyncToken(); 128 } 129 130 OpBuilder builder; 131 132 // The token that represents the current asynchronous dependency. It's valid 133 // range starts with a `gpu.wait async` op, and ends with a `gpu.wait` op. 134 // In between, each gpu::AsyncOpInterface depends on the current token and 135 // produces the new one. 136 Value currentToken = {}; 137 }; 138 139 /// Erases `executeOp` and returns a clone with additional `results`. 140 async::ExecuteOp addExecuteResults(async::ExecuteOp executeOp, 141 ValueRange results) { 142 // Add values to async.yield op. 143 Operation *yieldOp = executeOp.getBody()->getTerminator(); 144 yieldOp->insertOperands(yieldOp->getNumOperands(), results); 145 146 // Construct new result type list with additional types. 147 SmallVector<Type, 2> resultTypes; 148 resultTypes.reserve(executeOp.getNumResults() + results.size()); 149 transform(executeOp.getResultTypes(), std::back_inserter(resultTypes), 150 [](Type type) { 151 // Extract value type from !async.value. 152 if (auto valueType = type.dyn_cast<async::ValueType>()) 153 return valueType.getValueType(); 154 assert(type.isa<async::TokenType>() && "expected token type"); 155 return type; 156 }); 157 transform(results, std::back_inserter(resultTypes), 158 [](Value value) { return value.getType(); }); 159 160 // Clone executeOp with the extra results. 161 OpBuilder builder(executeOp); 162 auto newOp = builder.create<async::ExecuteOp>( 163 executeOp.getLoc(), TypeRange{resultTypes}.drop_front() /*drop token*/, 164 executeOp.dependencies(), executeOp.operands()); 165 BlockAndValueMapping mapper; 166 newOp.getRegion().getBlocks().clear(); 167 executeOp.getRegion().cloneInto(&newOp.getRegion(), mapper); 168 169 // Replace executeOp with cloned one. 170 executeOp.getOperation()->replaceAllUsesWith( 171 newOp.getResults().drop_back(results.size())); 172 executeOp.erase(); 173 174 return newOp; 175 } 176 177 // Callback for `async.execute` ops which tries to push the contained 178 // synchronous `gpu.wait` op to the dependencies of the `async.execute`. 179 struct GpuAsyncRegionPass::DeferWaitCallback { 180 // If the `executeOp`s token is used only in `async.execute` or `async.await` 181 // ops, add the region's last `gpu.wait` op to the worklist if it is 182 // synchronous and is the last op with side effects. 183 void operator()(async::ExecuteOp executeOp) { 184 if (!areAllUsersExecuteOrAwait(executeOp.token())) 185 return; 186 // async.execute's region is currently restricted to one block. 187 for (auto &op : llvm::reverse(executeOp.getBody()->without_terminator())) { 188 if (auto waitOp = dyn_cast<gpu::WaitOp>(op)) { 189 if (!waitOp.asyncToken()) 190 worklist.push_back(waitOp); 191 return; 192 } 193 if (hasSideEffects(&op)) 194 return; 195 } 196 } 197 198 // The destructor performs the actual rewrite work. 199 ~DeferWaitCallback() { 200 for (size_t i = 0; i < worklist.size(); ++i) { 201 auto waitOp = worklist[i]; 202 auto executeOp = waitOp->getParentOfType<async::ExecuteOp>(); 203 204 // Erase `gpu.wait` and return async dependencies from execute op instead. 205 SmallVector<Value, 4> dependencies = waitOp.asyncDependencies(); 206 waitOp.erase(); 207 executeOp = addExecuteResults(executeOp, dependencies); 208 209 // Add the async dependency to each user of the `async.execute` token. 210 auto asyncTokens = executeOp.getResults().take_back(dependencies.size()); 211 for (Operation *user : executeOp.token().getUsers()) 212 addAsyncDependencyAfter(asyncTokens, user); 213 } 214 } 215 216 private: 217 // Returns whether all token users are either 'async.execute' or 'async.await' 218 // ops. This is used as a requirement for pushing 'gpu.wait' ops from a 219 // 'async.execute' body to it's users. Specifically, we do not allow 220 // terminator users, because it could mean that the `async.execute` is inside 221 // control flow code. 222 static bool areAllUsersExecuteOrAwait(Value token) { 223 return !token.use_empty() && 224 llvm::all_of(token.getUsers(), [](Operation *user) { 225 return isa<async::ExecuteOp, async::AwaitOp>(user); 226 }); 227 } 228 229 // Add the `asyncToken` as dependency as needed after `op`. 230 void addAsyncDependencyAfter(ValueRange asyncTokens, Operation *op) { 231 OpBuilder builder(op->getContext()); 232 auto loc = op->getLoc(); 233 234 Block::iterator it; 235 SmallVector<Value, 1> tokens; 236 tokens.reserve(asyncTokens.size()); 237 TypeSwitch<Operation *>(op) 238 .Case<async::AwaitOp>([&](auto awaitOp) { 239 // Add async.await ops to wait for the !gpu.async.tokens. 240 builder.setInsertionPointAfter(op); 241 for (auto asyncToken : asyncTokens) 242 tokens.push_back( 243 builder.create<async::AwaitOp>(loc, asyncToken).result()); 244 // Set `it` after the inserted async.await ops. 245 it = builder.getInsertionPoint(); 246 }) 247 .Case<async::ExecuteOp>([&](auto executeOp) { 248 // Set `it` to the beginning of the region and add asyncTokens to the 249 // async.execute operands. 250 it = executeOp.getBody()->begin(); 251 executeOp.operandsMutable().append(asyncTokens); 252 SmallVector<Type, 1> tokenTypes( 253 asyncTokens.size(), builder.getType<gpu::AsyncTokenType>()); 254 SmallVector<Location, 1> tokenLocs(asyncTokens.size(), 255 executeOp.getLoc()); 256 copy(executeOp.getBody()->addArguments(tokenTypes, tokenLocs), 257 std::back_inserter(tokens)); 258 }); 259 260 // Advance `it` to terminator or op with side-effects. 261 it = std::find_if(it, Block::iterator(), [](Operation &op) { 262 return isTerminator(&op) || hasSideEffects(&op); 263 }); 264 265 // If `op` implements the AsyncOpInterface, add `token` to the list of async 266 // dependencies. 267 if (auto asyncOp = dyn_cast<gpu::AsyncOpInterface>(*it)) { 268 for (auto token : tokens) 269 asyncOp.addAsyncDependency(token); 270 return; 271 } 272 273 // Otherwise, insert a gpu.wait before 'it'. 274 builder.setInsertionPoint(it->getBlock(), it); 275 auto waitOp = builder.create<gpu::WaitOp>(loc, Type{}, tokens); 276 277 // If the new waitOp is at the end of an async.execute region, add it to the 278 // worklist. 'operator()(executeOp)' would do the same, but this is faster. 279 auto executeOp = dyn_cast<async::ExecuteOp>(it->getParentOp()); 280 if (executeOp && areAllUsersExecuteOrAwait(executeOp.token()) && 281 !it->getNextNode()) 282 worklist.push_back(waitOp); 283 } 284 285 SmallVector<gpu::WaitOp, 8> worklist; 286 }; 287 288 // Callback for `async.execute` ops which repeats !gpu.async.token results 289 // so that each of them is only used once. 290 struct GpuAsyncRegionPass::SingleTokenUseCallback { 291 void operator()(async::ExecuteOp executeOp) { 292 // Extract !gpu.async.token results which have multiple uses. 293 auto multiUseResults = 294 llvm::make_filter_range(executeOp.results(), [](OpResult result) { 295 if (result.use_empty() || result.hasOneUse()) 296 return false; 297 auto valueType = result.getType().dyn_cast<async::ValueType>(); 298 return valueType && 299 valueType.getValueType().isa<gpu::AsyncTokenType>(); 300 }); 301 if (multiUseResults.empty()) 302 return; 303 304 // Indices within !async.execute results (i.e. without the async.token). 305 SmallVector<int, 4> indices; 306 transform(multiUseResults, std::back_inserter(indices), 307 [](OpResult result) { 308 return result.getResultNumber() - 1; // Index without token. 309 }); 310 311 for (auto index : indices) { 312 assert(!executeOp.results()[index].getUses().empty()); 313 // Repeat async.yield token result, one for each use after the first one. 314 auto uses = llvm::drop_begin(executeOp.results()[index].getUses()); 315 auto count = std::distance(uses.begin(), uses.end()); 316 auto yieldOp = cast<async::YieldOp>(executeOp.getBody()->getTerminator()); 317 SmallVector<Value, 4> operands(count, yieldOp.getOperand(index)); 318 executeOp = addExecuteResults(executeOp, operands); 319 // Update 'uses' to refer to the new executeOp. 320 uses = llvm::drop_begin(executeOp.results()[index].getUses()); 321 auto results = executeOp.results().take_back(count); 322 for (auto pair : llvm::zip(uses, results)) 323 std::get<0>(pair).set(std::get<1>(pair)); 324 } 325 } 326 }; 327 328 // Replaces synchronous GPU ops in the op's region with asynchronous ones and 329 // inserts the necessary synchronization (as gpu.wait ops). Assumes sequential 330 // execution semantics and that no GPU ops are asynchronous yet. 331 void GpuAsyncRegionPass::runOnOperation() { 332 if (getOperation()->walk(ThreadTokenCallback(getContext())).wasInterrupted()) 333 return signalPassFailure(); 334 335 // Collect gpu.wait ops that we can move out of async.execute regions. 336 getOperation().getRegion().walk(DeferWaitCallback()); 337 // Makes each !gpu.async.token returned from async.execute op have single use. 338 getOperation().getRegion().walk(SingleTokenUseCallback()); 339 } 340 341 std::unique_ptr<OperationPass<FuncOp>> mlir::createGpuAsyncRegionPass() { 342 return std::make_unique<GpuAsyncRegionPass>(); 343 } 344