MLIR  20.0.0git
TensorToSPIRV.cpp
Go to the documentation of this file.
1 //===- TensorToSPIRV.cpp - Tensor 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 Tensor dialect to SPIR-V dialect.
10 //
11 //===----------------------------------------------------------------------===//
12 
14 #include "../SPIRVCommon/Pattern.h"
20 #include "mlir/IR/AffineMap.h"
21 #include "llvm/Support/Debug.h"
22 
23 #define DEBUG_TYPE "tensor-to-spirv-pattern"
24 
25 using namespace mlir;
26 
27 //===----------------------------------------------------------------------===//
28 // Operation conversion
29 //===----------------------------------------------------------------------===//
30 
31 namespace {
32 
33 /// Converts tensor.extract into loading using access chains from SPIR-V local
34 /// variables.
35 class TensorExtractPattern final
36  : public OpConversionPattern<tensor::ExtractOp> {
37 public:
38  TensorExtractPattern(TypeConverter &typeConverter, MLIRContext *context,
39  int64_t threshold, PatternBenefit benefit = 1)
40  : OpConversionPattern(typeConverter, context, benefit),
41  byteCountThreshold(threshold) {}
42 
43  LogicalResult
44  matchAndRewrite(tensor::ExtractOp extractOp, OpAdaptor adaptor,
45  ConversionPatternRewriter &rewriter) const override {
46  auto tensorType = cast<RankedTensorType>(extractOp.getTensor().getType());
47 
48  if (!tensorType.hasStaticShape())
49  return rewriter.notifyMatchFailure(extractOp, "non-static tensor");
50 
51  if (tensorType.getNumElements() * tensorType.getElementTypeBitWidth() >
52  byteCountThreshold * 8)
53  return rewriter.notifyMatchFailure(extractOp,
54  "exceeding byte count threshold");
55 
56  Location loc = extractOp.getLoc();
57 
58  int64_t rank = tensorType.getRank();
59  SmallVector<int64_t, 4> strides(rank, 1);
60  for (int i = rank - 2; i >= 0; --i) {
61  strides[i] = strides[i + 1] * tensorType.getDimSize(i + 1);
62  }
63 
64  Type varType = spirv::PointerType::get(adaptor.getTensor().getType(),
65  spirv::StorageClass::Function);
66 
67  spirv::VariableOp varOp;
68  if (adaptor.getTensor().getDefiningOp<spirv::ConstantOp>()) {
69  // We could use the initializer directly; but certain driver compilers
70  // have bugs dealing with that. So for now, use spirv.Store for
71  // initialization.
72  varOp = rewriter.create<spirv::VariableOp>(loc, varType,
73  spirv::StorageClass::Function,
74  /*initializer=*/nullptr);
75  rewriter.create<spirv::StoreOp>(loc, varOp, adaptor.getTensor());
76  } else {
77  // Need to store the value to the local variable. It's questionable
78  // whether we want to support such case though.
79  return failure();
80  }
81 
82  auto &typeConverter = *getTypeConverter<SPIRVTypeConverter>();
83  auto indexType = typeConverter.getIndexType();
84 
85  Value index = spirv::linearizeIndex(adaptor.getIndices(), strides,
86  /*offset=*/0, indexType, loc, rewriter);
87  auto acOp = rewriter.create<spirv::AccessChainOp>(loc, varOp, index);
88 
89  rewriter.replaceOpWithNewOp<spirv::LoadOp>(extractOp, acOp);
90 
91  return success();
92  }
93 
94 private:
95  int64_t byteCountThreshold;
96 };
97 
98 } // namespace
99 
100 //===----------------------------------------------------------------------===//
101 // Pattern population
102 //===----------------------------------------------------------------------===//
103 
105  int64_t byteCountThreshold,
106  RewritePatternSet &patterns) {
107  patterns.add<TensorExtractPattern>(typeConverter, patterns.getContext(),
108  byteCountThreshold);
109 }
This class implements a pattern rewriter for use with ConversionPatterns.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition: Location.h:63
MLIRContext is the top-level object for a collection of MLIR operations.
Definition: MLIRContext.h:60
Operation * create(const OperationState &state)
Creates an operation given the fields represented as an OperationState.
Definition: Builders.cpp:468
OpConversionPattern is a wrapper around ConversionPattern that allows for matching and rewriting agai...
This class represents the benefit of a pattern match in a unitless scheme that ranges from 0 (very li...
Definition: PatternMatch.h:34
MLIRContext * getContext() const
Definition: PatternMatch.h:823
RewritePatternSet & add(ConstructorArg &&arg, ConstructorArgs &&...args)
Add an instance of each of the pattern types 'Ts' to the pattern list with the given arguments.
Definition: PatternMatch.h:847
std::enable_if_t<!std::is_convertible< CallbackT, Twine >::value, LogicalResult > notifyMatchFailure(Location loc, CallbackT &&reasonCallback)
Used to notify the listener that the IR failed to be rewritten because of a match failure,...
Definition: PatternMatch.h:718
OpTy replaceOpWithNewOp(Operation *op, Args &&...args)
Replace the results of the given (original) op with a new op that is created without verification (re...
Definition: PatternMatch.h:536
Type conversion from builtin types to SPIR-V types for shader interface.
Type conversion class.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition: Types.h:74
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition: Value.h:96
static PointerType get(Type pointeeType, StorageClass storageClass)
Definition: SPIRVTypes.cpp:481
Value linearizeIndex(ValueRange indices, ArrayRef< int64_t > strides, int64_t offset, Type integerType, Location loc, OpBuilder &builder)
Generates IR to perform index linearization with the given indices and their corresponding strides,...
Include the generated interface declarations.
void populateTensorToSPIRVPatterns(SPIRVTypeConverter &typeConverter, int64_t byteCountThreshold, RewritePatternSet &patterns)
Appends to a pattern list additional patterns for translating tensor ops to SPIR-V ops.