1//===- FunctionImplementation.cpp - Utilities for function-like ops -------===//
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#include "mlir/Interfaces/FunctionImplementation.h"
10#include "mlir/IR/Builders.h"
11#include "mlir/IR/SymbolTable.h"
12#include "mlir/Interfaces/FunctionInterfaces.h"
13
14using namespace mlir;
15
16static ParseResult
17parseFunctionArgumentList(OpAsmParser &parser, bool allowVariadic,
18 SmallVectorImpl<OpAsmParser::Argument> &arguments,
19 bool &isVariadic) {
20
21 // Parse the function arguments. The argument list either has to consistently
22 // have ssa-id's followed by types, or just be a type list. It isn't ok to
23 // sometimes have SSA ID's and sometimes not.
24 isVariadic = false;
25
26 return parser.parseCommaSeparatedList(
27 delimiter: OpAsmParser::Delimiter::Paren, parseElementFn: [&]() -> ParseResult {
28 // Ellipsis must be at end of the list.
29 if (isVariadic)
30 return parser.emitError(
31 loc: parser.getCurrentLocation(),
32 message: "variadic arguments must be in the end of the argument list");
33
34 // Handle ellipsis as a special case.
35 if (allowVariadic && succeeded(Result: parser.parseOptionalEllipsis())) {
36 // This is a variadic designator.
37 isVariadic = true;
38 return success(); // Stop parsing arguments.
39 }
40 // Parse argument name if present.
41 OpAsmParser::Argument argument;
42 auto argPresent = parser.parseOptionalArgument(
43 result&: argument, /*allowType=*/true, /*allowAttrs=*/true);
44 if (argPresent.has_value()) {
45 if (failed(Result: argPresent.value()))
46 return failure(); // Present but malformed.
47
48 // Reject this if the preceding argument was missing a name.
49 if (!arguments.empty() && arguments.back().ssaName.name.empty())
50 return parser.emitError(loc: argument.ssaName.location,
51 message: "expected type instead of SSA identifier");
52
53 } else {
54 argument.ssaName.location = parser.getCurrentLocation();
55 // Otherwise we just have a type list without SSA names. Reject
56 // this if the preceding argument had a name.
57 if (!arguments.empty() && !arguments.back().ssaName.name.empty())
58 return parser.emitError(loc: argument.ssaName.location,
59 message: "expected SSA identifier");
60
61 NamedAttrList attrs;
62 if (parser.parseType(result&: argument.type) ||
63 parser.parseOptionalAttrDict(result&: attrs) ||
64 parser.parseOptionalLocationSpecifier(result&: argument.sourceLoc))
65 return failure();
66 argument.attrs = attrs.getDictionary(context: parser.getContext());
67 }
68 arguments.push_back(Elt: argument);
69 return success();
70 });
71}
72
73ParseResult function_interface_impl::parseFunctionSignatureWithArguments(
74 OpAsmParser &parser, bool allowVariadic,
75 SmallVectorImpl<OpAsmParser::Argument> &arguments, bool &isVariadic,
76 SmallVectorImpl<Type> &resultTypes,
77 SmallVectorImpl<DictionaryAttr> &resultAttrs) {
78 if (parseFunctionArgumentList(parser, allowVariadic, arguments, isVariadic))
79 return failure();
80 if (succeeded(Result: parser.parseOptionalArrow()))
81 return call_interface_impl::parseFunctionResultList(parser, resultTypes,
82 resultAttrs);
83 return success();
84}
85
86ParseResult function_interface_impl::parseFunctionOp(
87 OpAsmParser &parser, OperationState &result, bool allowVariadic,
88 StringAttr typeAttrName, FuncTypeBuilder funcTypeBuilder,
89 StringAttr argAttrsName, StringAttr resAttrsName) {
90 SmallVector<OpAsmParser::Argument> entryArgs;
91 SmallVector<DictionaryAttr> resultAttrs;
92 SmallVector<Type> resultTypes;
93 auto &builder = parser.getBuilder();
94
95 // Parse visibility.
96 (void)impl::parseOptionalVisibilityKeyword(parser, attrs&: result.attributes);
97
98 // Parse the name as a symbol.
99 StringAttr nameAttr;
100 if (parser.parseSymbolName(result&: nameAttr, attrName: "sym_name", attrs&: result.attributes))
101 return failure();
102
103 // Parse the function signature.
104 SMLoc signatureLocation = parser.getCurrentLocation();
105 bool isVariadic = false;
106 if (parseFunctionSignatureWithArguments(parser, allowVariadic, arguments&: entryArgs,
107 isVariadic, resultTypes, resultAttrs))
108 return failure();
109
110 std::string errorMessage;
111 SmallVector<Type> argTypes;
112 argTypes.reserve(N: entryArgs.size());
113 for (auto &arg : entryArgs)
114 argTypes.push_back(Elt: arg.type);
115 Type type = funcTypeBuilder(builder, argTypes, resultTypes,
116 VariadicFlag(isVariadic), errorMessage);
117 if (!type) {
118 return parser.emitError(loc: signatureLocation)
119 << "failed to construct function type"
120 << (errorMessage.empty() ? "" : ": ") << errorMessage;
121 }
122 result.addAttribute(name: typeAttrName, attr: TypeAttr::get(type));
123
124 // If function attributes are present, parse them.
125 NamedAttrList parsedAttributes;
126 SMLoc attributeDictLocation = parser.getCurrentLocation();
127 if (parser.parseOptionalAttrDictWithKeyword(result&: parsedAttributes))
128 return failure();
129
130 // Disallow attributes that are inferred from elsewhere in the attribute
131 // dictionary.
132 for (StringRef disallowed :
133 {SymbolOpInterface::getDefaultVisibilityAttrName(),
134 StringRef("sym_name"), typeAttrName.getValue()}) {
135 if (parsedAttributes.get(name: disallowed))
136 return parser.emitError(loc: attributeDictLocation, message: "'")
137 << disallowed
138 << "' is an inferred attribute and should not be specified in the "
139 "explicit attribute dictionary";
140 }
141 result.attributes.append(newAttributes&: parsedAttributes);
142
143 // Add the attributes to the function arguments.
144 assert(resultAttrs.size() == resultTypes.size());
145 call_interface_impl::addArgAndResultAttrs(
146 builder, result, args: entryArgs, resultAttrs, argAttrsName, resAttrsName);
147
148 // Parse the optional function body. The printer will not print the body if
149 // its empty, so disallow parsing of empty body in the parser.
150 auto *body = result.addRegion();
151 SMLoc loc = parser.getCurrentLocation();
152 OptionalParseResult parseResult =
153 parser.parseOptionalRegion(region&: *body, arguments: entryArgs,
154 /*enableNameShadowing=*/false);
155 if (parseResult.has_value()) {
156 if (failed(Result: *parseResult))
157 return failure();
158 // Function body was parsed, make sure its not empty.
159 if (body->empty())
160 return parser.emitError(loc, message: "expected non-empty function body");
161 }
162 return success();
163}
164
165void function_interface_impl::printFunctionAttributes(
166 OpAsmPrinter &p, Operation *op, ArrayRef<StringRef> elided) {
167 // Print out function attributes, if present.
168 SmallVector<StringRef, 8> ignoredAttrs = {"sym_name"};
169 ignoredAttrs.append(in_start: elided.begin(), in_end: elided.end());
170
171 NamedAttrList attrs(op->getDiscardableAttrDictionary().getValue());
172 op->getName().walkInherentAttrs(
173 op, visitor: [&](StringRef name, Attribute &attr) { attrs.append(name, attr); });
174 p.printOptionalAttrDictWithKeyword(attrs, elidedAttrs: ignoredAttrs);
175}
176
177void function_interface_impl::printFunctionOp(
178 OpAsmPrinter &p, FunctionOpInterface op, bool isVariadic,
179 StringRef typeAttrName, StringAttr argAttrsName, StringAttr resAttrsName) {
180 // Print the operation and the function name.
181 auto symbol = cast<SymbolOpInterface>(Val: op.getOperation());
182 StringRef funcName = symbol.getName();
183 p << ' ';
184
185 StringRef visibilityAttrName =
186 SymbolOpInterface::getDefaultVisibilityAttrName();
187 Attribute visibility =
188 op->getInherentAttr(name: visibilityAttrName).value_or(u: Attribute{});
189 if (auto value = dyn_cast_or_null<StringAttr>(Val&: visibility))
190 p << value.getValue() << ' ';
191 p.printSymbolName(symbolRef: funcName);
192
193 ArrayRef<Type> argTypes = op.getArgumentTypes();
194 ArrayRef<Type> resultTypes = op.getResultTypes();
195 printFunctionSignature(p, op, argTypes, isVariadic, resultTypes);
196 printFunctionAttributes(
197 p, op, elided: {visibilityAttrName, typeAttrName, argAttrsName, resAttrsName});
198 // Print the body if this is not an external function.
199 Region &body = op->getRegion(index: 0);
200 if (!body.empty()) {
201 p << ' ';
202 p.printRegion(blocks&: body, /*printEntryBlockArgs=*/false,
203 /*printBlockTerminators=*/true);
204 }
205}
206