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 } // end anonymous namespace. 51 52 void BuiltinDialect::initialize() { 53 addTypes<ComplexType, BFloat16Type, Float16Type, Float32Type, Float64Type, 54 Float80Type, Float128Type, FunctionType, IndexType, IntegerType, 55 MemRefType, UnrankedMemRefType, NoneType, OpaqueType, 56 RankedTensorType, TupleType, UnrankedTensorType, VectorType>(); 57 addAttributes<AffineMapAttr, ArrayAttr, DenseIntOrFPElementsAttr, 58 DenseStringElementsAttr, DictionaryAttr, FloatAttr, 59 SymbolRefAttr, IntegerAttr, IntegerSetAttr, OpaqueAttr, 60 OpaqueElementsAttr, SparseElementsAttr, StringAttr, TypeAttr, 61 UnitAttr>(); 62 addAttributes<CallSiteLoc, FileLineColLoc, FusedLoc, NameLoc, OpaqueLoc, 63 UnknownLoc>(); 64 addOperations< 65 #define GET_OP_LIST 66 #include "mlir/IR/BuiltinOps.cpp.inc" 67 >(); 68 addInterfaces<BuiltinOpAsmDialectInterface>(); 69 } 70 71 //===----------------------------------------------------------------------===// 72 // FuncOp 73 //===----------------------------------------------------------------------===// 74 75 FuncOp FuncOp::create(Location location, StringRef name, FunctionType type, 76 ArrayRef<NamedAttribute> attrs) { 77 OperationState state(location, "func"); 78 OpBuilder builder(location->getContext()); 79 FuncOp::build(builder, state, name, type, attrs); 80 return cast<FuncOp>(Operation::create(state)); 81 } 82 FuncOp FuncOp::create(Location location, StringRef name, FunctionType type, 83 iterator_range<dialect_attr_iterator> attrs) { 84 SmallVector<NamedAttribute, 8> attrRef(attrs); 85 return create(location, name, type, llvm::makeArrayRef(attrRef)); 86 } 87 FuncOp FuncOp::create(Location location, StringRef name, FunctionType type, 88 ArrayRef<NamedAttribute> attrs, 89 ArrayRef<DictionaryAttr> argAttrs) { 90 FuncOp func = create(location, name, type, attrs); 91 func.setAllArgAttrs(argAttrs); 92 return func; 93 } 94 95 void FuncOp::build(OpBuilder &builder, OperationState &state, StringRef name, 96 FunctionType type, ArrayRef<NamedAttribute> attrs, 97 ArrayRef<DictionaryAttr> argAttrs) { 98 state.addAttribute(SymbolTable::getSymbolAttrName(), 99 builder.getStringAttr(name)); 100 state.addAttribute(getTypeAttrName(), TypeAttr::get(type)); 101 state.attributes.append(attrs.begin(), attrs.end()); 102 state.addRegion(); 103 104 if (argAttrs.empty()) 105 return; 106 assert(type.getNumInputs() == argAttrs.size()); 107 SmallString<8> argAttrName; 108 for (unsigned i = 0, e = type.getNumInputs(); i != e; ++i) 109 if (DictionaryAttr argDict = argAttrs[i]) 110 state.addAttribute(getArgAttrName(i, argAttrName), argDict); 111 } 112 113 static ParseResult parseFuncOp(OpAsmParser &parser, OperationState &result) { 114 auto buildFuncType = [](Builder &builder, ArrayRef<Type> argTypes, 115 ArrayRef<Type> results, impl::VariadicFlag, 116 std::string &) { 117 return builder.getFunctionType(argTypes, results); 118 }; 119 120 return impl::parseFunctionLikeOp(parser, result, /*allowVariadic=*/false, 121 buildFuncType); 122 } 123 124 static void print(FuncOp op, OpAsmPrinter &p) { 125 FunctionType fnType = op.getType(); 126 impl::printFunctionLikeOp(p, op, fnType.getInputs(), /*isVariadic=*/false, 127 fnType.getResults()); 128 } 129 130 static LogicalResult verify(FuncOp op) { 131 // If this function is external there is nothing to do. 132 if (op.isExternal()) 133 return success(); 134 135 // Verify that the argument list of the function and the arg list of the entry 136 // block line up. The trait already verified that the number of arguments is 137 // the same between the signature and the block. 138 auto fnInputTypes = op.getType().getInputs(); 139 Block &entryBlock = op.front(); 140 for (unsigned i = 0, e = entryBlock.getNumArguments(); i != e; ++i) 141 if (fnInputTypes[i] != entryBlock.getArgument(i).getType()) 142 return op.emitOpError("type of entry block argument #") 143 << i << '(' << entryBlock.getArgument(i).getType() 144 << ") must match the type of the corresponding argument in " 145 << "function signature(" << fnInputTypes[i] << ')'; 146 147 return success(); 148 } 149 150 /// Clone the internal blocks from this function into dest and all attributes 151 /// from this function to dest. 152 void FuncOp::cloneInto(FuncOp dest, BlockAndValueMapping &mapper) { 153 // Add the attributes of this function to dest. 154 llvm::MapVector<Identifier, Attribute> newAttrs; 155 for (auto &attr : dest.getAttrs()) 156 newAttrs.insert(attr); 157 for (auto &attr : getAttrs()) 158 newAttrs.insert(attr); 159 dest->setAttrs(DictionaryAttr::get(newAttrs.takeVector(), getContext())); 160 161 // Clone the body. 162 getBody().cloneInto(&dest.getBody(), mapper); 163 } 164 165 /// Create a deep copy of this function and all of its blocks, remapping 166 /// any operands that use values outside of the function using the map that is 167 /// provided (leaving them alone if no entry is present). Replaces references 168 /// to cloned sub-values with the corresponding value that is copied, and adds 169 /// those mappings to the mapper. 170 FuncOp FuncOp::clone(BlockAndValueMapping &mapper) { 171 FunctionType newType = getType(); 172 173 // If the function has a body, then the user might be deleting arguments to 174 // the function by specifying them in the mapper. If so, we don't add the 175 // argument to the input type vector. 176 bool isExternalFn = isExternal(); 177 if (!isExternalFn) { 178 SmallVector<Type, 4> inputTypes; 179 inputTypes.reserve(newType.getNumInputs()); 180 for (unsigned i = 0, e = getNumArguments(); i != e; ++i) 181 if (!mapper.contains(getArgument(i))) 182 inputTypes.push_back(newType.getInput(i)); 183 newType = FunctionType::get(getContext(), inputTypes, newType.getResults()); 184 } 185 186 // Create the new function. 187 FuncOp newFunc = cast<FuncOp>(getOperation()->cloneWithoutRegions()); 188 newFunc.setType(newType); 189 190 /// Set the argument attributes for arguments that aren't being replaced. 191 for (unsigned i = 0, e = getNumArguments(), destI = 0; i != e; ++i) 192 if (isExternalFn || !mapper.contains(getArgument(i))) 193 newFunc.setArgAttrs(destI++, getArgAttrs(i)); 194 195 /// Clone the current function into the new one and return it. 196 cloneInto(newFunc, mapper); 197 return newFunc; 198 } 199 FuncOp FuncOp::clone() { 200 BlockAndValueMapping mapper; 201 return clone(mapper); 202 } 203 204 //===----------------------------------------------------------------------===// 205 // ModuleOp 206 //===----------------------------------------------------------------------===// 207 208 void ModuleOp::build(OpBuilder &builder, OperationState &state, 209 Optional<StringRef> name) { 210 ensureTerminator(*state.addRegion(), builder, state.location); 211 if (name) { 212 state.attributes.push_back(builder.getNamedAttr( 213 mlir::SymbolTable::getSymbolAttrName(), builder.getStringAttr(*name))); 214 } 215 } 216 217 /// Construct a module from the given context. 218 ModuleOp ModuleOp::create(Location loc, Optional<StringRef> name) { 219 OpBuilder builder(loc->getContext()); 220 return builder.create<ModuleOp>(loc, name); 221 } 222 223 static LogicalResult verify(ModuleOp op) { 224 // Check that none of the attributes are non-dialect attributes, except for 225 // the symbol related attributes. 226 for (auto attr : op.getAttrs()) { 227 if (!attr.first.strref().contains('.') && 228 !llvm::is_contained( 229 ArrayRef<StringRef>{mlir::SymbolTable::getSymbolAttrName(), 230 mlir::SymbolTable::getVisibilityAttrName()}, 231 attr.first.strref())) 232 return op.emitOpError() << "can only contain attributes with " 233 "dialect-prefixed names, found: '" 234 << attr.first << "'"; 235 } 236 237 return success(); 238 } 239 240 //===----------------------------------------------------------------------===// 241 // UnrealizedConversionCastOp 242 //===----------------------------------------------------------------------===// 243 244 LogicalResult 245 UnrealizedConversionCastOp::fold(ArrayRef<Attribute> attrOperands, 246 SmallVectorImpl<OpFoldResult> &foldResults) { 247 OperandRange operands = inputs(); 248 if (operands.empty()) 249 return failure(); 250 251 // Check that the input is a cast with results that all feed into this 252 // operation, and operand types that directly match the result types of this 253 // operation. 254 ResultRange results = outputs(); 255 Value firstInput = operands.front(); 256 auto inputOp = firstInput.getDefiningOp<UnrealizedConversionCastOp>(); 257 if (!inputOp || inputOp.getResults() != operands || 258 inputOp.getOperandTypes() != results.getTypes()) 259 return failure(); 260 261 // If everything matches up, we can fold the passthrough. 262 foldResults.append(inputOp->operand_begin(), inputOp->operand_end()); 263 return success(); 264 } 265 266 bool UnrealizedConversionCastOp::areCastCompatible(TypeRange inputs, 267 TypeRange outputs) { 268 // `UnrealizedConversionCastOp` is agnostic of the input/output types. 269 return true; 270 } 271 272 //===----------------------------------------------------------------------===// 273 // TableGen'd op method definitions 274 //===----------------------------------------------------------------------===// 275 276 #define GET_OP_CLASSES 277 #include "mlir/IR/BuiltinOps.cpp.inc" 278