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 ensureTerminator(*state.addRegion(), builder, state.location); 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 static LogicalResult verify(ModuleOp op) { 226 // Check that none of the attributes are non-dialect attributes, except for 227 // the symbol related attributes. 228 for (auto attr : op->getAttrs()) { 229 if (!attr.first.strref().contains('.') && 230 !llvm::is_contained( 231 ArrayRef<StringRef>{mlir::SymbolTable::getSymbolAttrName(), 232 mlir::SymbolTable::getVisibilityAttrName()}, 233 attr.first.strref())) 234 return op.emitOpError() << "can only contain attributes with " 235 "dialect-prefixed names, found: '" 236 << attr.first << "'"; 237 } 238 239 return success(); 240 } 241 242 //===----------------------------------------------------------------------===// 243 // UnrealizedConversionCastOp 244 //===----------------------------------------------------------------------===// 245 246 LogicalResult 247 UnrealizedConversionCastOp::fold(ArrayRef<Attribute> attrOperands, 248 SmallVectorImpl<OpFoldResult> &foldResults) { 249 OperandRange operands = inputs(); 250 if (operands.empty()) 251 return failure(); 252 253 // Check that the input is a cast with results that all feed into this 254 // operation, and operand types that directly match the result types of this 255 // operation. 256 ResultRange results = outputs(); 257 Value firstInput = operands.front(); 258 auto inputOp = firstInput.getDefiningOp<UnrealizedConversionCastOp>(); 259 if (!inputOp || inputOp.getResults() != operands || 260 inputOp.getOperandTypes() != results.getTypes()) 261 return failure(); 262 263 // If everything matches up, we can fold the passthrough. 264 foldResults.append(inputOp->operand_begin(), inputOp->operand_end()); 265 return success(); 266 } 267 268 bool UnrealizedConversionCastOp::areCastCompatible(TypeRange inputs, 269 TypeRange outputs) { 270 // `UnrealizedConversionCastOp` is agnostic of the input/output types. 271 return true; 272 } 273 274 //===----------------------------------------------------------------------===// 275 // TableGen'd op method definitions 276 //===----------------------------------------------------------------------===// 277 278 #define GET_OP_CLASSES 279 #include "mlir/IR/BuiltinOps.cpp.inc" 280