1 //===- FuncToSPIRV.cpp - Func to SPIR-V Patterns ------------------===//
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 patterns to convert Func dialect to SPIR-V dialect.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "mlir/Conversion/FuncToSPIRV/FuncToSPIRV.h"
14 #include "../SPIRVCommon/Pattern.h"
15 #include "mlir/Dialect/Func/IR/FuncOps.h"
16 #include "mlir/Dialect/SPIRV/IR/SPIRVDialect.h"
17 #include "mlir/Dialect/SPIRV/IR/SPIRVOps.h"
18 #include "mlir/Dialect/SPIRV/Transforms/SPIRVConversion.h"
19 #include "mlir/Dialect/SPIRV/Utils/LayoutUtils.h"
20 #include "mlir/IR/AffineMap.h"
21 #include "mlir/Support/LogicalResult.h"
22 #include "llvm/ADT/SetVector.h"
23 #include "llvm/Support/Debug.h"
24 
25 #define DEBUG_TYPE "func-to-spirv-pattern"
26 
27 using namespace mlir;
28 
29 //===----------------------------------------------------------------------===//
30 // Operation conversion
31 //===----------------------------------------------------------------------===//
32 
33 // Note that DRR cannot be used for the patterns in this file: we may need to
34 // convert type along the way, which requires ConversionPattern. DRR generates
35 // normal RewritePattern.
36 
37 namespace {
38 
39 /// Converts func.return to spv.Return.
40 class ReturnOpPattern final : public OpConversionPattern<func::ReturnOp> {
41 public:
42   using OpConversionPattern<func::ReturnOp>::OpConversionPattern;
43 
44   LogicalResult
45   matchAndRewrite(func::ReturnOp returnOp, OpAdaptor adaptor,
46                   ConversionPatternRewriter &rewriter) const override {
47     if (returnOp.getNumOperands() > 1)
48       return failure();
49 
50     if (returnOp.getNumOperands() == 1) {
51       rewriter.replaceOpWithNewOp<spirv::ReturnValueOp>(
52           returnOp, adaptor.getOperands()[0]);
53     } else {
54       rewriter.replaceOpWithNewOp<spirv::ReturnOp>(returnOp);
55     }
56     return success();
57   }
58 };
59 
60 } // namespace
61 
62 //===----------------------------------------------------------------------===//
63 // Pattern population
64 //===----------------------------------------------------------------------===//
65 
66 void mlir::populateFuncToSPIRVPatterns(SPIRVTypeConverter &typeConverter,
67                                        RewritePatternSet &patterns) {
68   MLIRContext *context = patterns.getContext();
69 
70   patterns.add<ReturnOpPattern>(typeConverter, context);
71 }
72