1//===- ArmGraphOps.cpp - MLIR SPIR-V SPV_ARM_graph operations -------------===//
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 defines the SPV_ARM_graph operations in the SPIR-V dialect.
10//
11//===----------------------------------------------------------------------===//
12
13#include "mlir/Dialect/SPIRV/IR/SPIRVOps.h"
14
15#include "SPIRVParsingUtils.h"
16
17#include "mlir/Dialect/SPIRV/IR/SPIRVDialect.h"
18#include "mlir/Dialect/SPIRV/IR/SPIRVEnums.h"
19#include "mlir/Dialect/SPIRV/IR/SPIRVTypes.h"
20#include "mlir/IR/Builders.h"
21#include "mlir/IR/BuiltinTypes.h"
22#include "mlir/IR/Operation.h"
23#include "mlir/Interfaces/FunctionImplementation.h"
24#include "llvm/Support/InterleavedRange.h"
25
26using namespace mlir;
27using namespace mlir::spirv::AttrNames;
28
29//===----------------------------------------------------------------------===//
30// spirv.GraphARM
31//===----------------------------------------------------------------------===//
32
33ParseResult spirv::GraphARMOp::parse(OpAsmParser &parser,
34 OperationState &result) {
35 Builder &builder = parser.getBuilder();
36
37 (void)impl::parseOptionalVisibilityKeyword(parser, attrs&: result.attributes);
38
39 // Parse the name as a symbol.
40 StringAttr nameAttr;
41 if (parser.parseSymbolName(result&: nameAttr, attrName: getSymNameAttrName(name: result.name),
42 attrs&: result.attributes))
43 return failure();
44
45 // Parse the function signature.
46 bool isVariadic = false;
47 SmallVector<OpAsmParser::Argument> entryArgs;
48 SmallVector<Type> resultTypes;
49 SmallVector<DictionaryAttr> resultAttrs;
50 if (function_interface_impl::parseFunctionSignatureWithArguments(
51 parser, /*allowVariadic=*/false, arguments&: entryArgs, isVariadic, resultTypes,
52 resultAttrs))
53 return failure();
54
55 SmallVector<Type> argTypes = llvm::map_to_vector(
56 C&: entryArgs, F: [](const OpAsmParser::Argument &arg) { return arg.type; });
57 GraphType grType = builder.getGraphType(inputs: argTypes, results: resultTypes);
58 result.addAttribute(name: getFunctionTypeAttrName(name: result.name),
59 attr: TypeAttr::get(type: grType));
60
61 // If additional attributes are present, parse them.
62 if (parser.parseOptionalAttrDictWithKeyword(result&: result.attributes))
63 return failure();
64
65 // Add the attributes to the function arguments.
66 assert(resultAttrs.size() == resultTypes.size());
67 call_interface_impl::addArgAndResultAttrs(
68 builder, result, args: entryArgs, resultAttrs, argAttrsName: getArgAttrsAttrName(name: result.name),
69 resAttrsName: getResAttrsAttrName(name: result.name));
70
71 // Parse the optional function body.
72 Region *body = result.addRegion();
73 OptionalParseResult parseResult =
74 parser.parseOptionalRegion(region&: *body, arguments: entryArgs);
75 return failure(IsFailure: parseResult.has_value() && failed(Result: *parseResult));
76}
77
78void spirv::GraphARMOp::print(OpAsmPrinter &printer) {
79 // Print graph name, signature, and control.
80 printer << ' ';
81 if (StringAttr visibility = getSymVisibilityAttr())
82 printer << visibility.getValue() << ' ';
83 printer.printSymbolName(symbolRef: getSymName());
84 GraphType grType = getFunctionType();
85 function_interface_impl::printFunctionSignature(
86 p&: printer, op: *this, argTypes: grType.getInputs(),
87 /*isVariadic=*/false, resultTypes: grType.getResults());
88 function_interface_impl::printFunctionAttributes(
89 p&: printer, op: *this,
90 elided: {getFunctionTypeAttrName(), getArgAttrsAttrName(), getResAttrsAttrName(),
91 getSymVisibilityAttrName()});
92
93 // Print the body.
94 Region &body = this->getBody();
95 if (!body.empty()) {
96 printer << ' ';
97 printer.printRegion(blocks&: body, /*printEntryBlockArgs=*/false,
98 /*printBlockTerminators=*/true);
99 }
100}
101
102LogicalResult spirv::GraphARMOp::verifyType() {
103 if (getFunctionType().getNumResults() < 1)
104 return emitOpError(message: "there should be at least one result");
105 return success();
106}
107
108LogicalResult spirv::GraphARMOp::verifyBody() {
109 for (auto [index, graphArgType] : llvm::enumerate(First: getArgumentTypes())) {
110 if (!isa<spirv::TensorArmType>(Val: graphArgType)) {
111 return emitOpError(message: "type of argument #")
112 << index << " must be a TensorArmType, but got " << graphArgType;
113 }
114 }
115 for (auto [index, graphResType] : llvm::enumerate(First: getResultTypes())) {
116 if (!isa<spirv::TensorArmType>(Val: graphResType)) {
117 return emitOpError(message: "type of result #")
118 << index << " must be a TensorArmType, but got " << graphResType;
119 }
120 }
121
122 if (!isExternal()) {
123 Block &entryBlock = front();
124
125 unsigned numArguments = this->getNumArguments();
126 if (entryBlock.getNumArguments() != numArguments)
127 return emitOpError(message: "entry block must have ")
128 << numArguments << " arguments to match graph signature";
129
130 for (auto [index, grArgType, blockArgType] :
131 llvm::enumerate(First: getArgumentTypes(), Rest: entryBlock.getArgumentTypes())) {
132 if (blockArgType != grArgType) {
133 return emitOpError(message: "type of entry block argument #")
134 << index << '(' << blockArgType
135 << ") must match the type of the corresponding argument in "
136 << "graph signature(" << grArgType << ')';
137 }
138 }
139 }
140
141 GraphType grType = getFunctionType();
142 auto walkResult = walk(callback: [grType](spirv::GraphOutputsARMOp op) -> WalkResult {
143 if (grType.getNumResults() != op.getNumOperands())
144 return op.emitOpError(message: "is returning ")
145 << op.getNumOperands()
146 << " value(s) but enclosing spirv.ARM.Graph requires "
147 << grType.getNumResults() << " result(s)";
148
149 ValueTypeRange<OperandRange> graphOutputOperandTypes =
150 op.getValue().getType();
151 for (auto [index, type] : llvm::enumerate(First&: graphOutputOperandTypes)) {
152 if (type != grType.getResult(i: index))
153 return op.emitError(message: "type of return operand ")
154 << index << " (" << type << ") doesn't match graph result type ("
155 << grType.getResult(i: index) << ")";
156 }
157 return WalkResult::advance();
158 });
159
160 return failure(IsFailure: walkResult.wasInterrupted());
161}
162
163void spirv::GraphARMOp::build(OpBuilder &builder, OperationState &state,
164 StringRef name, GraphType type,
165 ArrayRef<NamedAttribute> attrs, bool entryPoint) {
166 state.addAttribute(name: getSymNameAttrName(name: state.name),
167 attr: builder.getStringAttr(bytes: name));
168 state.addAttribute(name: getFunctionTypeAttrName(name: state.name), attr: TypeAttr::get(type));
169 state.attributes.append(newAttributes&: attrs);
170 state.addAttribute(name: getEntryPointAttrName(name: state.name),
171 attr: builder.getBoolAttr(value: entryPoint));
172 state.addRegion();
173}
174
175ArrayRef<Type> spirv::GraphARMOp::getArgumentTypes() {
176 return getFunctionType().getInputs();
177}
178
179ArrayRef<Type> spirv::GraphARMOp::getResultTypes() {
180 return getFunctionType().getResults();
181}
182
183Region *spirv::GraphARMOp::getCallableRegion() {
184 return isExternal() ? nullptr : &getBody();
185}
186
187//===----------------------------------------------------------------------===//
188// spirv.GraphOutputsARM
189//===----------------------------------------------------------------------===//
190
191LogicalResult spirv::GraphOutputsARMOp::verify() {
192 auto graph = cast<GraphARMOp>(Val: (*this)->getParentOp());
193
194 // The operand number and types must match the graph signature.
195 const ArrayRef<Type> &results = graph.getFunctionType().getResults();
196 if (getNumOperands() != results.size())
197 return emitOpError(message: "has ")
198 << getNumOperands() << " operands, but enclosing spirv.ARM.Graph (@"
199 << graph.getName() << ") returns " << results.size();
200
201 for (auto [index, result] : llvm::enumerate(First: results))
202 if (getOperand(i: index).getType() != result)
203 return emitError() << "type of return operand " << index << " ("
204 << getOperand(i: index).getType()
205 << ") doesn't match spirv.ARM.Graph result type ("
206 << result << ")"
207 << " in graph @" << graph.getName();
208 return success();
209}
210
211//===----------------------------------------------------------------------===//
212// spirv.GraphEntryPointARM
213//===----------------------------------------------------------------------===//
214
215void spirv::GraphEntryPointARMOp::build(OpBuilder &builder,
216 OperationState &state,
217 spirv::GraphARMOp graph,
218 ArrayRef<Attribute> interfaceVars) {
219 build(odsBuilder&: builder, odsState&: state, fn: SymbolRefAttr::get(symbol: graph),
220 interface: builder.getArrayAttr(value: interfaceVars));
221}
222
223ParseResult spirv::GraphEntryPointARMOp::parse(OpAsmParser &parser,
224 OperationState &result) {
225 FlatSymbolRefAttr fn;
226 if (parser.parseAttribute(result&: fn, type: Type(), attrName: kFnNameAttrName, attrs&: result.attributes))
227 return failure();
228
229 SmallVector<Attribute, 4> interfaceVars;
230 if (!parser.parseOptionalComma()) {
231 // Parse the interface variables.
232 if (parser.parseCommaSeparatedList(parseElementFn: [&]() -> ParseResult {
233 // The name of the interface variable attribute is not important.
234 FlatSymbolRefAttr var;
235 NamedAttrList attrs;
236 if (parser.parseAttribute(result&: var, type: Type(), attrName: "var_symbol", attrs))
237 return failure();
238 interfaceVars.push_back(Elt: var);
239 return success();
240 }))
241 return failure();
242 }
243 result.addAttribute(name: "interface",
244 attr: parser.getBuilder().getArrayAttr(value: interfaceVars));
245 return success();
246}
247
248void spirv::GraphEntryPointARMOp::print(OpAsmPrinter &printer) {
249 printer << " ";
250 printer.printSymbolName(symbolRef: getFn());
251 ArrayRef<Attribute> interfaceVars = getInterface().getValue();
252 if (!interfaceVars.empty()) {
253 printer << ", " << llvm::interleaved(R: interfaceVars);
254 }
255}
256