1 //===- BuiltinDialect.cpp - MLIR Builtin Dialect --------------------------===//
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 contains the Builtin dialect that contains all of the attributes,
10 // operations, and types that are necessary for the validity of the IR.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "mlir/IR/BuiltinDialect.h"
15 #include "mlir/IR/BlockAndValueMapping.h"
16 #include "mlir/IR/Builders.h"
17 #include "mlir/IR/BuiltinOps.h"
18 #include "mlir/IR/BuiltinTypes.h"
19 #include "mlir/IR/FunctionImplementation.h"
20 #include "mlir/IR/OpImplementation.h"
21 #include "mlir/IR/PatternMatch.h"
22 #include "llvm/ADT/MapVector.h"
23 
24 using namespace mlir;
25 
26 //===----------------------------------------------------------------------===//
27 // Builtin Dialect
28 //===----------------------------------------------------------------------===//
29 
30 namespace {
31 struct BuiltinOpAsmDialectInterface : public OpAsmDialectInterface {
32   using OpAsmDialectInterface::OpAsmDialectInterface;
33 
34   LogicalResult getAlias(Attribute attr, raw_ostream &os) const override {
35     if (attr.isa<AffineMapAttr>()) {
36       os << "map";
37       return success();
38     }
39     if (attr.isa<IntegerSetAttr>()) {
40       os << "set";
41       return success();
42     }
43     if (attr.isa<LocationAttr>()) {
44       os << "loc";
45       return success();
46     }
47     return failure();
48   }
49 
50   LogicalResult getAlias(Type type, raw_ostream &os) const final {
51     if (auto tupleType = type.dyn_cast<TupleType>()) {
52       if (tupleType.size() > 16) {
53         os << "tuple";
54         return success();
55       }
56     }
57     return failure();
58   }
59 };
60 } // end anonymous namespace.
61 
62 void BuiltinDialect::initialize() {
63   registerTypes();
64   registerAttributes();
65   registerLocationAttributes();
66   addOperations<
67 #define GET_OP_LIST
68 #include "mlir/IR/BuiltinOps.cpp.inc"
69       >();
70   addInterfaces<BuiltinOpAsmDialectInterface>();
71 }
72 
73 //===----------------------------------------------------------------------===//
74 // FuncOp
75 //===----------------------------------------------------------------------===//
76 
77 FuncOp FuncOp::create(Location location, StringRef name, FunctionType type,
78                       ArrayRef<NamedAttribute> attrs) {
79   OperationState state(location, "func");
80   OpBuilder builder(location->getContext());
81   FuncOp::build(builder, state, name, type, attrs);
82   return cast<FuncOp>(Operation::create(state));
83 }
84 FuncOp FuncOp::create(Location location, StringRef name, FunctionType type,
85                       Operation::dialect_attr_range attrs) {
86   SmallVector<NamedAttribute, 8> attrRef(attrs);
87   return create(location, name, type, llvm::makeArrayRef(attrRef));
88 }
89 FuncOp FuncOp::create(Location location, StringRef name, FunctionType type,
90                       ArrayRef<NamedAttribute> attrs,
91                       ArrayRef<DictionaryAttr> argAttrs) {
92   FuncOp func = create(location, name, type, attrs);
93   func.setAllArgAttrs(argAttrs);
94   return func;
95 }
96 
97 void FuncOp::build(OpBuilder &builder, OperationState &state, StringRef name,
98                    FunctionType type, ArrayRef<NamedAttribute> attrs,
99                    ArrayRef<DictionaryAttr> argAttrs) {
100   state.addAttribute(SymbolTable::getSymbolAttrName(),
101                      builder.getStringAttr(name));
102   state.addAttribute(getTypeAttrName(), TypeAttr::get(type));
103   state.attributes.append(attrs.begin(), attrs.end());
104   state.addRegion();
105 
106   if (argAttrs.empty())
107     return;
108   assert(type.getNumInputs() == argAttrs.size());
109   SmallString<8> argAttrName;
110   for (unsigned i = 0, e = type.getNumInputs(); i != e; ++i)
111     if (DictionaryAttr argDict = argAttrs[i])
112       state.addAttribute(getArgAttrName(i, argAttrName), argDict);
113 }
114 
115 static ParseResult parseFuncOp(OpAsmParser &parser, OperationState &result) {
116   auto buildFuncType = [](Builder &builder, ArrayRef<Type> argTypes,
117                           ArrayRef<Type> results, impl::VariadicFlag,
118                           std::string &) {
119     return builder.getFunctionType(argTypes, results);
120   };
121 
122   return impl::parseFunctionLikeOp(parser, result, /*allowVariadic=*/false,
123                                    buildFuncType);
124 }
125 
126 static void print(FuncOp op, OpAsmPrinter &p) {
127   FunctionType fnType = op.getType();
128   impl::printFunctionLikeOp(p, op, fnType.getInputs(), /*isVariadic=*/false,
129                             fnType.getResults());
130 }
131 
132 static LogicalResult verify(FuncOp op) {
133   // If this function is external there is nothing to do.
134   if (op.isExternal())
135     return success();
136 
137   // Verify that the argument list of the function and the arg list of the entry
138   // block line up.  The trait already verified that the number of arguments is
139   // the same between the signature and the block.
140   auto fnInputTypes = op.getType().getInputs();
141   Block &entryBlock = op.front();
142   for (unsigned i = 0, e = entryBlock.getNumArguments(); i != e; ++i)
143     if (fnInputTypes[i] != entryBlock.getArgument(i).getType())
144       return op.emitOpError("type of entry block argument #")
145              << i << '(' << entryBlock.getArgument(i).getType()
146              << ") must match the type of the corresponding argument in "
147              << "function signature(" << fnInputTypes[i] << ')';
148 
149   return success();
150 }
151 
152 /// Clone the internal blocks from this function into dest and all attributes
153 /// from this function to dest.
154 void FuncOp::cloneInto(FuncOp dest, BlockAndValueMapping &mapper) {
155   // Add the attributes of this function to dest.
156   llvm::MapVector<Identifier, Attribute> newAttrs;
157   for (const auto &attr : dest->getAttrs())
158     newAttrs.insert(attr);
159   for (const auto &attr : (*this)->getAttrs())
160     newAttrs.insert(attr);
161   dest->setAttrs(DictionaryAttr::get(getContext(), newAttrs.takeVector()));
162 
163   // Clone the body.
164   getBody().cloneInto(&dest.getBody(), mapper);
165 }
166 
167 /// Create a deep copy of this function and all of its blocks, remapping
168 /// any operands that use values outside of the function using the map that is
169 /// provided (leaving them alone if no entry is present). Replaces references
170 /// to cloned sub-values with the corresponding value that is copied, and adds
171 /// those mappings to the mapper.
172 FuncOp FuncOp::clone(BlockAndValueMapping &mapper) {
173   FunctionType newType = getType();
174 
175   // If the function has a body, then the user might be deleting arguments to
176   // the function by specifying them in the mapper. If so, we don't add the
177   // argument to the input type vector.
178   bool isExternalFn = isExternal();
179   if (!isExternalFn) {
180     SmallVector<Type, 4> inputTypes;
181     inputTypes.reserve(newType.getNumInputs());
182     for (unsigned i = 0, e = getNumArguments(); i != e; ++i)
183       if (!mapper.contains(getArgument(i)))
184         inputTypes.push_back(newType.getInput(i));
185     newType = FunctionType::get(getContext(), inputTypes, newType.getResults());
186   }
187 
188   // Create the new function.
189   FuncOp newFunc = cast<FuncOp>(getOperation()->cloneWithoutRegions());
190   newFunc.setType(newType);
191 
192   /// Set the argument attributes for arguments that aren't being replaced.
193   for (unsigned i = 0, e = getNumArguments(), destI = 0; i != e; ++i)
194     if (isExternalFn || !mapper.contains(getArgument(i)))
195       newFunc.setArgAttrs(destI++, getArgAttrs(i));
196 
197   /// Clone the current function into the new one and return it.
198   cloneInto(newFunc, mapper);
199   return newFunc;
200 }
201 FuncOp FuncOp::clone() {
202   BlockAndValueMapping mapper;
203   return clone(mapper);
204 }
205 
206 //===----------------------------------------------------------------------===//
207 // ModuleOp
208 //===----------------------------------------------------------------------===//
209 
210 void ModuleOp::build(OpBuilder &builder, OperationState &state,
211                      Optional<StringRef> name) {
212   state.addRegion()->emplaceBlock();
213   if (name) {
214     state.attributes.push_back(builder.getNamedAttr(
215         mlir::SymbolTable::getSymbolAttrName(), builder.getStringAttr(*name)));
216   }
217 }
218 
219 /// Construct a module from the given context.
220 ModuleOp ModuleOp::create(Location loc, Optional<StringRef> name) {
221   OpBuilder builder(loc->getContext());
222   return builder.create<ModuleOp>(loc, name);
223 }
224 
225 DataLayoutSpecInterface ModuleOp::getDataLayoutSpec() {
226   // Take the first and only (if present) attribute that implements the
227   // interface. This needs a linear search, but is called only once per data
228   // layout object construction that is used for repeated queries.
229   for (Attribute attr : llvm::make_second_range(getOperation()->getAttrs())) {
230     if (auto spec = attr.dyn_cast<DataLayoutSpecInterface>())
231       return spec;
232   }
233   return {};
234 }
235 
236 static LogicalResult verify(ModuleOp op) {
237   // Check that none of the attributes are non-dialect attributes, except for
238   // the symbol related attributes.
239   for (auto attr : op->getAttrs()) {
240     if (!attr.first.strref().contains('.') &&
241         !llvm::is_contained(
242             ArrayRef<StringRef>{mlir::SymbolTable::getSymbolAttrName(),
243                                 mlir::SymbolTable::getVisibilityAttrName()},
244             attr.first.strref()))
245       return op.emitOpError() << "can only contain attributes with "
246                                  "dialect-prefixed names, found: '"
247                               << attr.first << "'";
248   }
249 
250   // Check that there is at most one data layout spec attribute.
251   StringRef layoutSpecAttrName;
252   DataLayoutSpecInterface layoutSpec;
253   for (const NamedAttribute &na : op->getAttrs()) {
254     if (auto spec = na.second.dyn_cast<DataLayoutSpecInterface>()) {
255       if (layoutSpec) {
256         InFlightDiagnostic diag =
257             op.emitOpError() << "expects at most one data layout attribute";
258         diag.attachNote() << "'" << layoutSpecAttrName
259                           << "' is a data layout attribute";
260         diag.attachNote() << "'" << na.first << "' is a data layout attribute";
261       }
262       layoutSpecAttrName = na.first.strref();
263       layoutSpec = spec;
264     }
265   }
266 
267   return success();
268 }
269 
270 //===----------------------------------------------------------------------===//
271 // UnrealizedConversionCastOp
272 //===----------------------------------------------------------------------===//
273 
274 LogicalResult
275 UnrealizedConversionCastOp::fold(ArrayRef<Attribute> attrOperands,
276                                  SmallVectorImpl<OpFoldResult> &foldResults) {
277   OperandRange operands = inputs();
278   if (operands.empty())
279     return failure();
280 
281   // Check that the input is a cast with results that all feed into this
282   // operation, and operand types that directly match the result types of this
283   // operation.
284   ResultRange results = outputs();
285   Value firstInput = operands.front();
286   auto inputOp = firstInput.getDefiningOp<UnrealizedConversionCastOp>();
287   if (!inputOp || inputOp.getResults() != operands ||
288       inputOp.getOperandTypes() != results.getTypes())
289     return failure();
290 
291   // If everything matches up, we can fold the passthrough.
292   foldResults.append(inputOp->operand_begin(), inputOp->operand_end());
293   return success();
294 }
295 
296 bool UnrealizedConversionCastOp::areCastCompatible(TypeRange inputs,
297                                                    TypeRange outputs) {
298   // `UnrealizedConversionCastOp` is agnostic of the input/output types.
299   return true;
300 }
301 
302 //===----------------------------------------------------------------------===//
303 // TableGen'd op method definitions
304 //===----------------------------------------------------------------------===//
305 
306 #define GET_OP_CLASSES
307 #include "mlir/IR/BuiltinOps.cpp.inc"
308