MLIR 24.0.0git
FuncOps.cpp
Go to the documentation of this file.
1//===- FuncOps.cpp - Func Dialect 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
10
16#include "mlir/IR/IRMapping.h"
17#include "mlir/IR/Matchers.h"
21#include "mlir/IR/Value.h"
24#include "llvm/ADT/APFloat.h"
25#include "llvm/ADT/MapVector.h"
26#include "llvm/ADT/STLExtras.h"
27#include "llvm/ADT/SmallVectorExtras.h"
28
29#include "mlir/Dialect/Func/IR/FuncOpsDialect.cpp.inc"
30
31using namespace mlir;
32using namespace mlir::func;
33
34namespace {
35struct FuncDialectBytecodeInterface : BytecodeDialectInterface {
36 using BytecodeDialectInterface::BytecodeDialectInterface;
37
38 void writeVersion(DialectBytecodeWriter &writer) const override {
39 writer.writeVarInt(1);
40 }
41
42 std::unique_ptr<DialectVersion>
43 readVersion(DialectBytecodeReader &reader) const override {
44 uint64_t version;
45 if (failed(reader.readVarInt(version)))
46 return nullptr;
47 if (version != 1) {
48 reader.emitError("unsupported func dialect bytecode version");
49 return nullptr;
50 }
51 return std::make_unique<DialectVersion>();
52 }
53};
54} // namespace
55
56//===----------------------------------------------------------------------===//
57// FuncDialect
58//===----------------------------------------------------------------------===//
59
60void FuncDialect::initialize() {
61 addInterfaces<FuncDialectBytecodeInterface>();
62 declarePromisedInterface<ConvertToEmitCPatternInterface, FuncDialect>();
63 declarePromisedInterface<DialectInlinerInterface, FuncDialect>();
64 declarePromisedInterface<ConvertToLLVMPatternInterface, FuncDialect>();
65 declarePromisedInterfaces<bufferization::BufferizableOpInterface, CallOp,
66 FuncOp, ReturnOp>();
67}
68
69/// Materialize a single constant operation from a given attribute value with
70/// the desired resultant type.
71Operation *FuncDialect::materializeConstant(OpBuilder &builder, Attribute value,
72 Type type, Location loc) {
73 if (ConstantOp::isBuildableWith(value, type))
74 return ConstantOp::create(builder, loc, type,
75 llvm::cast<FlatSymbolRefAttr>(value));
76 return nullptr;
77}
78
79//===----------------------------------------------------------------------===//
80// CallOp
81//===----------------------------------------------------------------------===//
82
83LogicalResult CallOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
84 // Check that the callee attribute was specified.
85 auto fnAttr = getCalleeAttr();
86 if (!fnAttr)
87 return emitOpError("requires a 'callee' symbol reference attribute");
88 FuncOp fn = symbolTable.lookupNearestSymbolFrom<FuncOp>(*this, fnAttr);
89 if (!fn)
90 return emitOpError() << "'" << fnAttr.getValue()
91 << "' does not reference a valid function";
92
93 // Verify that the operand and result types match the callee.
95}
96
97FunctionType CallOp::getCalleeType() {
98 return FunctionType::get(getContext(), getOperandTypes(), getResultTypes());
99}
100
101//===----------------------------------------------------------------------===//
102// CallIndirectOp
103//===----------------------------------------------------------------------===//
104
105/// Fold indirect calls that have a constant function as the callee operand.
106LogicalResult CallIndirectOp::canonicalize(CallIndirectOp indirectCall,
107 PatternRewriter &rewriter) {
108 // Check that the callee is a constant callee.
109 FlatSymbolRefAttr calledFn;
110 if (!matchPattern(indirectCall.getCallee(), m_Constant(&calledFn)))
111 return failure();
112
113 // Replace with a direct call, preserving the call-site attributes.
114 auto directCall = CallOp::create(
115 rewriter, indirectCall.getLoc(), indirectCall.getResultTypes(), calledFn,
116 indirectCall.getArgOperands(), indirectCall.getArgAttrsAttr(),
117 indirectCall.getResAttrsAttr());
118 directCall->setDiscardableAttrs(indirectCall->getDiscardableAttrDictionary());
119 rewriter.replaceOp(indirectCall, directCall.getResults());
120 return success();
121}
122
123//===----------------------------------------------------------------------===//
124// ConstantOp
125//===----------------------------------------------------------------------===//
126
127LogicalResult ConstantOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
128 StringRef fnName = getValue();
129 Type type = getType();
130
131 // Try to find the referenced function.
132 auto fn = symbolTable.lookupNearestSymbolFrom<FuncOp>(
133 this->getOperation(), StringAttr::get(getContext(), fnName));
134 if (!fn)
135 return emitOpError() << "reference to undefined function '" << fnName
136 << "'";
137
138 // Check that the referenced function has the correct type.
139 if (fn.getFunctionType() != type)
140 return emitOpError("reference to function with mismatched type");
141
142 return success();
143}
144
145OpFoldResult ConstantOp::fold(FoldAdaptor adaptor) {
146 return getValueAttr();
147}
148
149void ConstantOp::getAsmResultNames(
150 function_ref<void(Value, StringRef)> setNameFn) {
151 setNameFn(getResult(), "f");
152}
153
154bool ConstantOp::isBuildableWith(Attribute value, Type type) {
155 return llvm::isa<FlatSymbolRefAttr>(value) && llvm::isa<FunctionType>(type);
156}
157
158//===----------------------------------------------------------------------===//
159// FuncOp
160//===----------------------------------------------------------------------===//
161
162LogicalResult FuncOp::readProperties(DialectBytecodeReader &reader,
163 OperationState &state) {
164 auto &properties = state.getOrAddProperties<Properties>();
165 // Preserve the pre-DLTI field order for unversioned bytecode.
166 if (failed(reader.readOptionalAttribute(properties.arg_attrs)) ||
167 failed(reader.readAttribute(properties.function_type)) ||
168 failed(reader.readOptionalAttribute(properties.no_inline)) ||
169 failed(reader.readOptionalAttribute(properties.res_attrs)) ||
170 failed(reader.readAttribute(properties.sym_name)) ||
171 failed(reader.readOptionalAttribute(properties.sym_visibility)))
172 return failure();
173
174 if (failed(reader.getDialectVersion<FuncDialect>()))
175 return success();
176 return reader.readOptionalAttribute(properties.dlti);
177}
178
179void FuncOp::writeProperties(DialectBytecodeWriter &writer) {
180 Properties &properties = getProperties();
181 writer.writeOptionalAttribute(properties.arg_attrs);
182 writer.writeAttribute(properties.function_type);
183 writer.writeOptionalAttribute(properties.no_inline);
184 writer.writeOptionalAttribute(properties.res_attrs);
185 writer.writeAttribute(properties.sym_name);
186 writer.writeOptionalAttribute(properties.sym_visibility);
188 writer.writeOptionalAttribute(properties.dlti);
189}
190
191FuncOp FuncOp::create(Location location, StringRef name, FunctionType type,
193 OpBuilder builder(location->getContext());
194 OperationState state(location, getOperationName());
195 FuncOp::build(builder, state, name, type, attrs);
196 return cast<FuncOp>(Operation::create(state));
197}
198FuncOp FuncOp::create(Location location, StringRef name, FunctionType type,
200 SmallVector<NamedAttribute, 8> attrRef(attrs);
201 return create(location, name, type, llvm::ArrayRef(attrRef));
202}
203FuncOp FuncOp::create(Location location, StringRef name, FunctionType type,
205 ArrayRef<DictionaryAttr> argAttrs) {
206 FuncOp func = create(location, name, type, attrs);
207 func.setAllArgAttrs(argAttrs);
208 return func;
209}
210
211void FuncOp::build(OpBuilder &builder, OperationState &state, StringRef name,
212 FunctionType type, ArrayRef<NamedAttribute> attrs,
213 ArrayRef<DictionaryAttr> argAttrs) {
214 state.getOrAddProperties<Properties>().sym_name = builder.getStringAttr(name);
215 state.addAttribute(getFunctionTypeAttrName(state.name), TypeAttr::get(type));
216 state.attributes.append(attrs.begin(), attrs.end());
217 state.addRegion();
218
219 if (argAttrs.empty())
220 return;
221 assert(type.getNumInputs() == argAttrs.size());
223 builder, state, argAttrs, /*resultAttrs=*/{},
224 getArgAttrsAttrName(state.name), getResAttrsAttrName(state.name));
225}
226
227ParseResult FuncOp::parse(OpAsmParser &parser, OperationState &result) {
228 auto buildFuncType =
229 [](Builder &builder, ArrayRef<Type> argTypes, ArrayRef<Type> results,
231 std::string &) { return builder.getFunctionType(argTypes, results); };
232
234 parser, result, /*allowVariadic=*/false,
235 getFunctionTypeAttrName(result.name), buildFuncType,
236 getArgAttrsAttrName(result.name), getResAttrsAttrName(result.name));
237}
238
239void FuncOp::print(OpAsmPrinter &p) {
241 p, *this, /*isVariadic=*/false, getFunctionTypeAttrName(),
242 getArgAttrsAttrName(), getResAttrsAttrName());
243}
244
245/// Clone the internal blocks from this function into dest and all attributes
246/// from this function to dest.
247void FuncOp::cloneInto(FuncOp dest, IRMapping &mapper) {
248 // Add the attributes of this function to dest.
250 for (const auto &attr : dest->getDiscardableAttrDictionary().getValue())
251 newAttrMap.insert({attr.getName(), attr.getValue()});
252 for (const auto &attr : (*this)->getDiscardableAttrDictionary().getValue())
253 newAttrMap.insert({attr.getName(), attr.getValue()});
254
255 auto newAttrs = llvm::map_to_vector(
256 newAttrMap, [](std::pair<StringAttr, Attribute> attrPair) {
257 return NamedAttribute(attrPair.first, attrPair.second);
258 });
259 dest->setDiscardableAttrs(DictionaryAttr::get(getContext(), newAttrs));
260
261 // Clone the body.
262 getBody().cloneInto(&dest.getBody(), mapper);
263}
264
265/// Create a deep copy of this function and all of its blocks, remapping
266/// any operands that use values outside of the function using the map that is
267/// provided (leaving them alone if no entry is present). Replaces references
268/// to cloned sub-values with the corresponding value that is copied, and adds
269/// those mappings to the mapper.
270FuncOp FuncOp::clone(IRMapping &mapper) {
271 // Create the new function.
272 FuncOp newFunc = cast<FuncOp>(getOperation()->cloneWithoutRegions());
273
274 // If the function has a body, then the user might be deleting arguments to
275 // the function by specifying them in the mapper. If so, we don't add the
276 // argument to the input type vector.
277 if (!isExternal()) {
278 FunctionType oldType = getFunctionType();
279
280 unsigned oldNumArgs = oldType.getNumInputs();
281 SmallVector<Type, 4> newInputs;
282 newInputs.reserve(oldNumArgs);
283 for (unsigned i = 0; i != oldNumArgs; ++i)
284 if (!mapper.contains(getArgument(i)))
285 newInputs.push_back(oldType.getInput(i));
286
287 /// If any of the arguments were dropped, update the type and drop any
288 /// necessary argument attributes.
289 if (newInputs.size() != oldNumArgs) {
290 newFunc.setType(FunctionType::get(oldType.getContext(), newInputs,
291 oldType.getResults()));
292
293 if (ArrayAttr argAttrs = getAllArgAttrs()) {
294 SmallVector<Attribute> newArgAttrs;
295 newArgAttrs.reserve(newInputs.size());
296 for (unsigned i = 0; i != oldNumArgs; ++i)
297 if (!mapper.contains(getArgument(i)))
298 newArgAttrs.push_back(argAttrs[i]);
299 newFunc.setAllArgAttrs(newArgAttrs);
300 }
301 }
302 }
303
304 /// Clone the current function into the new one and return it.
305 cloneInto(newFunc, mapper);
306 return newFunc;
307}
308FuncOp FuncOp::clone() {
309 IRMapping mapper;
310 return clone(mapper);
311}
312
313//===----------------------------------------------------------------------===//
314// ReturnOp
315//===----------------------------------------------------------------------===//
316
317LogicalResult FuncOp::verifyRegions() {
318 // External declarations have no body to check.
319 if (isDeclaration())
320 return success();
321 // Hoist the result types once; they are the same for every return site.
322 auto resultTypes = getFunctionType().getResults();
323 for (Block &block : getBody()) {
324 if (block.empty())
325 continue;
326 // Check func.return or other return-like terminators ops (e.g.
327 // llvm.return, test.return).
328 auto returnOp = dyn_cast<RegionBranchTerminatorOpInterface>(&block.back());
329 if (!returnOp)
330 continue;
331 auto operands =
332 returnOp.getMutableSuccessorOperands(RegionSuccessor(getOperation()));
333 if (operands.size() != resultTypes.size())
334 return returnOp->emitOpError("has ")
335 << operands.size() << " operands, but enclosing function (@"
336 << getName() << ") returns " << resultTypes.size();
337
338 for (auto [i, opType] : llvm::enumerate(llvm::zip(operands, resultTypes))) {
339 auto [operand, resTy] = opType;
340 if (operand.get().getType() != resTy)
341 return returnOp->emitError() << "type of return operand " << i << " ("
342 << operand.get().getType()
343 << ") doesn't match function result type ("
344 << resTy << ") in function @" << getName();
345 }
346 }
347
348 return success();
349}
350
351//===----------------------------------------------------------------------===//
352// TableGen'd op method definitions
353//===----------------------------------------------------------------------===//
354
355#define GET_OP_CLASSES
356#include "mlir/Dialect/Func/IR/FuncOps.cpp.inc"
return success()
ArrayAttr()
b getContext())
Attributes are known-constant values of operations.
Definition Attributes.h:25
MLIRContext * getContext() const
Return the context this attribute belongs to.
Block represents an ordered list of Operations.
Definition Block.h:34
This class is a general helper class for creating context-global objects like types,...
Definition Builders.h:51
FunctionType getFunctionType(TypeRange inputs, TypeRange results)
Definition Builders.cpp:84
StringAttr getStringAttr(const Twine &bytes)
Definition Builders.cpp:271
This class defines a virtual interface for reading a bytecode stream, providing hooks into the byteco...
virtual LogicalResult readVarInt(uint64_t &result)=0
Read a variable width integer.
virtual FailureOr< const DialectVersion * > getDialectVersion(StringRef dialectName) const =0
Retrieve the dialect version by name if available.
virtual LogicalResult readOptionalAttribute(Attribute &attr)=0
Read an optional reference to the given attribute.
virtual InFlightDiagnostic emitError(const Twine &msg={}) const =0
Emit an error to the reader.
virtual LogicalResult readAttribute(Attribute &result)=0
Read a reference to the given attribute.
This class defines a virtual interface for writing to a bytecode stream, providing hooks into the byt...
virtual void writeOptionalAttribute(Attribute attr)=0
virtual void writeVarInt(uint64_t value)=0
Write a variable width integer to the output stream.
virtual void writeAttribute(Attribute attr)=0
Write a reference to the given attribute.
virtual int64_t getBytecodeVersion() const =0
Return the bytecode version being emitted for.
A symbol reference with a reference path containing a single element.
This is a utility class for mapping one set of IR entities to another.
Definition IRMapping.h:26
bool contains(T from) const
Checks to see if a mapping for 'from' exists.
Definition IRMapping.h:51
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition Location.h:76
void append(StringRef name, Attribute attr)
Add an attribute with the specified name.
NamedAttribute represents a combination of a name and an Attribute value.
Definition Attributes.h:166
The OpAsmParser has methods for interacting with the asm parser: parsing things from it,...
This is a pure-virtual base class that exposes the asmprinter hooks necessary to implement a custom p...
This class helps build Operations.
Definition Builders.h:210
This class represents a single result from folding an operation.
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
iterator_range< dialect_attr_iterator > dialect_attr_range
Definition Operation.h:688
static Operation * create(Location location, OperationName name, TypeRange resultTypes, ValueRange operands, NamedAttrList &&attributes, PropertyRef properties, BlockRange successors, unsigned numRegions)
Create a new Operation with the specific fields.
Definition Operation.cpp:65
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
This class represents a successor of a region.
virtual void replaceOp(Operation *op, ValueRange newValues)
Replace the results of the given (original) operation with the specified list of values (replacements...
This class represents a collection of SymbolTables.
virtual Operation * lookupNearestSymbolFrom(Operation *from, StringAttr symbol)
Returns the operation registered with the given symbol name within the closest parent operation of,...
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
A named class for passing around the variadic flag.
@ kDialectVersioning
Dialects versioning was added in version 1.
Definition Encoding.h:32
LogicalResult verifyCallOpInterface(CallOpInterface call, TypeRange argumentTypes, TypeRange resultTypes)
Verify that the forwarded operands and results of call are in a 1:1 relationship with the given argum...
void addArgAndResultAttrs(Builder &builder, OperationState &result, ArrayRef< DictionaryAttr > argAttrs, ArrayRef< DictionaryAttr > resultAttrs, StringAttr argAttrsName, StringAttr resAttrsName)
Adds argument and result attributes, provided as argAttrs and resultAttrs arguments,...
void printFunctionOp(OpAsmPrinter &p, FunctionOpInterface op, bool isVariadic, StringRef typeAttrName, StringAttr argAttrsName, StringAttr resAttrsName)
Printer implementation for function-like operations.
ParseResult parseFunctionOp(OpAsmParser &parser, OperationState &result, bool allowVariadic, StringAttr typeAttrName, FuncTypeBuilder funcTypeBuilder, StringAttr argAttrsName, StringAttr resAttrsName)
Parser implementation for function-like operations.
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
Include the generated interface declarations.
bool matchPattern(Value value, const Pattern &pattern)
Entry point for matching a pattern over a Value.
Definition Matchers.h:490
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
Definition Utils.cpp:311
Operation * cloneWithoutRegions(OpBuilder &b, Operation *op, TypeRange newResultTypes, ValueRange newOperands)
Operation * clone(OpBuilder &b, Operation *op, TypeRange newResultTypes, ValueRange newOperands)
detail::constant_op_matcher m_Constant()
Matches a constant foldable operation.
Definition Matchers.h:369
llvm::function_ref< Fn > function_ref
Definition LLVM.h:155
This represents an operation in an abstracted form, suitable for use with the builder APIs.
T & getOrAddProperties()
Get (or create) the properties of the provided type to be set on the operation on creation.
void addAttribute(StringRef name, Attribute attr)
Add an attribute with the specified name.
Region * addRegion()
Create a region that should be attached to the operation.