1//===- GlobalIdRewriter.cpp - Implementation of GlobalId rewriting -------===//
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 in-dialect rewriting of the global_id op for archs
10// where global_id.x = threadId.x + blockId.x * blockDim.x
11//
12//===----------------------------------------------------------------------===//
13
14#include "mlir/Dialect/GPU/IR/GPUDialect.h"
15#include "mlir/Dialect/GPU/Transforms/Passes.h"
16#include "mlir/Dialect/Index/IR/IndexOps.h"
17#include "mlir/IR/PatternMatch.h"
18
19using namespace mlir;
20
21namespace {
22struct GpuGlobalIdRewriter : public OpRewritePattern<gpu::GlobalIdOp> {
23 using OpRewritePattern<gpu::GlobalIdOp>::OpRewritePattern;
24
25 LogicalResult matchAndRewrite(gpu::GlobalIdOp op,
26 PatternRewriter &rewriter) const override {
27 Location loc = op.getLoc();
28 auto dim = op.getDimension();
29 auto blockId = rewriter.create<gpu::BlockIdOp>(location: loc, args&: dim);
30 auto blockDim = rewriter.create<gpu::BlockDimOp>(location: loc, args&: dim);
31 // Compute blockId.x * blockDim.x
32 auto tmp = rewriter.create<index::MulOp>(location: op.getLoc(), args&: blockId, args&: blockDim);
33 auto threadId = rewriter.create<gpu::ThreadIdOp>(location: loc, args&: dim);
34 // Compute threadId.x + blockId.x * blockDim.x
35 rewriter.replaceOpWithNewOp<index::AddOp>(op, args&: threadId, args&: tmp);
36 return success();
37 }
38};
39} // namespace
40
41void mlir::populateGpuGlobalIdPatterns(RewritePatternSet &patterns) {
42 patterns.add<GpuGlobalIdRewriter>(arg: patterns.getContext());
43}
44

source code of mlir/lib/Dialect/GPU/Transforms/GlobalIdRewriter.cpp