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/IR/FunctionImplementation.h" 10 #include "mlir/IR/Builders.h" 11 #include "mlir/IR/FunctionSupport.h" 12 #include "mlir/IR/SymbolTable.h" 13 14 using namespace mlir; 15 16 ParseResult mlir::impl::parseFunctionArgumentList( 17 OpAsmParser &parser, bool allowAttributes, bool allowVariadic, 18 SmallVectorImpl<OpAsmParser::OperandType> &argNames, 19 SmallVectorImpl<Type> &argTypes, SmallVectorImpl<NamedAttrList> &argAttrs, 20 bool &isVariadic) { 21 if (parser.parseLParen()) 22 return failure(); 23 24 // The argument list either has to consistently have ssa-id's followed by 25 // types, or just be a type list. It isn't ok to sometimes have SSA ID's and 26 // sometimes not. 27 auto parseArgument = [&]() -> ParseResult { 28 llvm::SMLoc loc = parser.getCurrentLocation(); 29 30 // Parse argument name if present. 31 OpAsmParser::OperandType argument; 32 Type argumentType; 33 if (succeeded(parser.parseOptionalRegionArgument(argument)) && 34 !argument.name.empty()) { 35 // Reject this if the preceding argument was missing a name. 36 if (argNames.empty() && !argTypes.empty()) 37 return parser.emitError(loc, "expected type instead of SSA identifier"); 38 argNames.push_back(argument); 39 40 if (parser.parseColonType(argumentType)) 41 return failure(); 42 } else if (allowVariadic && succeeded(parser.parseOptionalEllipsis())) { 43 isVariadic = true; 44 return success(); 45 } else if (!argNames.empty()) { 46 // Reject this if the preceding argument had a name. 47 return parser.emitError(loc, "expected SSA identifier"); 48 } else if (parser.parseType(argumentType)) { 49 return failure(); 50 } 51 52 // Add the argument type. 53 argTypes.push_back(argumentType); 54 55 // Parse any argument attributes. 56 NamedAttrList attrs; 57 if (parser.parseOptionalAttrDict(attrs)) 58 return failure(); 59 if (!allowAttributes && !attrs.empty()) 60 return parser.emitError(loc, "expected arguments without attributes"); 61 argAttrs.push_back(attrs); 62 return success(); 63 }; 64 65 // Parse the function arguments. 66 isVariadic = false; 67 if (failed(parser.parseOptionalRParen())) { 68 do { 69 unsigned numTypedArguments = argTypes.size(); 70 if (parseArgument()) 71 return failure(); 72 73 llvm::SMLoc loc = parser.getCurrentLocation(); 74 if (argTypes.size() == numTypedArguments && 75 succeeded(parser.parseOptionalComma())) 76 return parser.emitError( 77 loc, "variadic arguments must be in the end of the argument list"); 78 } while (succeeded(parser.parseOptionalComma())); 79 parser.parseRParen(); 80 } 81 82 return success(); 83 } 84 85 /// Parse a function result list. 86 /// 87 /// function-result-list ::= function-result-list-parens 88 /// | non-function-type 89 /// function-result-list-parens ::= `(` `)` 90 /// | `(` function-result-list-no-parens `)` 91 /// function-result-list-no-parens ::= function-result (`,` function-result)* 92 /// function-result ::= type attribute-dict? 93 /// 94 static ParseResult 95 parseFunctionResultList(OpAsmParser &parser, SmallVectorImpl<Type> &resultTypes, 96 SmallVectorImpl<NamedAttrList> &resultAttrs) { 97 if (failed(parser.parseOptionalLParen())) { 98 // We already know that there is no `(`, so parse a type. 99 // Because there is no `(`, it cannot be a function type. 100 Type ty; 101 if (parser.parseType(ty)) 102 return failure(); 103 resultTypes.push_back(ty); 104 resultAttrs.emplace_back(); 105 return success(); 106 } 107 108 // Special case for an empty set of parens. 109 if (succeeded(parser.parseOptionalRParen())) 110 return success(); 111 112 // Parse individual function results. 113 do { 114 resultTypes.emplace_back(); 115 resultAttrs.emplace_back(); 116 if (parser.parseType(resultTypes.back()) || 117 parser.parseOptionalAttrDict(resultAttrs.back())) { 118 return failure(); 119 } 120 } while (succeeded(parser.parseOptionalComma())); 121 return parser.parseRParen(); 122 } 123 124 /// Parses a function signature using `parser`. The `allowVariadic` argument 125 /// indicates whether functions with variadic arguments are supported. The 126 /// trailing arguments are populated by this function with names, types and 127 /// attributes of the arguments and those of the results. 128 ParseResult mlir::impl::parseFunctionSignature( 129 OpAsmParser &parser, bool allowVariadic, 130 SmallVectorImpl<OpAsmParser::OperandType> &argNames, 131 SmallVectorImpl<Type> &argTypes, SmallVectorImpl<NamedAttrList> &argAttrs, 132 bool &isVariadic, SmallVectorImpl<Type> &resultTypes, 133 SmallVectorImpl<NamedAttrList> &resultAttrs) { 134 bool allowArgAttrs = true; 135 if (parseFunctionArgumentList(parser, allowArgAttrs, allowVariadic, argNames, 136 argTypes, argAttrs, isVariadic)) 137 return failure(); 138 if (succeeded(parser.parseOptionalArrow())) 139 return parseFunctionResultList(parser, resultTypes, resultAttrs); 140 return success(); 141 } 142 143 void mlir::impl::addArgAndResultAttrs(Builder &builder, OperationState &result, 144 ArrayRef<NamedAttrList> argAttrs, 145 ArrayRef<NamedAttrList> resultAttrs) { 146 // Add the attributes to the function arguments. 147 SmallString<8> attrNameBuf; 148 for (unsigned i = 0, e = argAttrs.size(); i != e; ++i) 149 if (!argAttrs[i].empty()) 150 result.addAttribute(getArgAttrName(i, attrNameBuf), 151 builder.getDictionaryAttr(argAttrs[i])); 152 153 // Add the attributes to the function results. 154 for (unsigned i = 0, e = resultAttrs.size(); i != e; ++i) 155 if (!resultAttrs[i].empty()) 156 result.addAttribute(getResultAttrName(i, attrNameBuf), 157 builder.getDictionaryAttr(resultAttrs[i])); 158 } 159 160 /// Parser implementation for function-like operations. Uses `funcTypeBuilder` 161 /// to construct the custom function type given lists of input and output types. 162 ParseResult 163 mlir::impl::parseFunctionLikeOp(OpAsmParser &parser, OperationState &result, 164 bool allowVariadic, 165 mlir::impl::FuncTypeBuilder funcTypeBuilder) { 166 SmallVector<OpAsmParser::OperandType, 4> entryArgs; 167 SmallVector<NamedAttrList, 4> argAttrs; 168 SmallVector<NamedAttrList, 4> resultAttrs; 169 SmallVector<Type, 4> argTypes; 170 SmallVector<Type, 4> resultTypes; 171 auto &builder = parser.getBuilder(); 172 173 // Parse visibility. 174 impl::parseOptionalVisibilityKeyword(parser, result.attributes); 175 176 // Parse the name as a symbol. 177 StringAttr nameAttr; 178 if (parser.parseSymbolName(nameAttr, SymbolTable::getSymbolAttrName(), 179 result.attributes)) 180 return failure(); 181 182 // Parse the function signature. 183 auto signatureLocation = parser.getCurrentLocation(); 184 bool isVariadic = false; 185 if (parseFunctionSignature(parser, allowVariadic, entryArgs, argTypes, 186 argAttrs, isVariadic, resultTypes, resultAttrs)) 187 return failure(); 188 189 std::string errorMessage; 190 if (auto type = funcTypeBuilder(builder, argTypes, resultTypes, 191 impl::VariadicFlag(isVariadic), errorMessage)) 192 result.addAttribute(getTypeAttrName(), TypeAttr::get(type)); 193 else 194 return parser.emitError(signatureLocation) 195 << "failed to construct function type" 196 << (errorMessage.empty() ? "" : ": ") << errorMessage; 197 198 // If function attributes are present, parse them. 199 if (parser.parseOptionalAttrDictWithKeyword(result.attributes)) 200 return failure(); 201 202 // Add the attributes to the function arguments. 203 assert(argAttrs.size() == argTypes.size()); 204 assert(resultAttrs.size() == resultTypes.size()); 205 addArgAndResultAttrs(builder, result, argAttrs, resultAttrs); 206 207 // Parse the optional function body. 208 auto *body = result.addRegion(); 209 return parser.parseOptionalRegion( 210 *body, entryArgs, entryArgs.empty() ? ArrayRef<Type>() : argTypes); 211 } 212 213 // Print a function result list. 214 static void printFunctionResultList(OpAsmPrinter &p, ArrayRef<Type> types, 215 ArrayRef<ArrayRef<NamedAttribute>> attrs) { 216 assert(!types.empty() && "Should not be called for empty result list."); 217 auto &os = p.getStream(); 218 bool needsParens = 219 types.size() > 1 || types[0].isa<FunctionType>() || !attrs[0].empty(); 220 if (needsParens) 221 os << '('; 222 llvm::interleaveComma( 223 llvm::zip(types, attrs), os, 224 [&](const std::tuple<Type, ArrayRef<NamedAttribute>> &t) { 225 p.printType(std::get<0>(t)); 226 p.printOptionalAttrDict(std::get<1>(t)); 227 }); 228 if (needsParens) 229 os << ')'; 230 } 231 232 /// Print the signature of the function-like operation `op`. Assumes `op` has 233 /// the FunctionLike trait and passed the verification. 234 void mlir::impl::printFunctionSignature(OpAsmPrinter &p, Operation *op, 235 ArrayRef<Type> argTypes, 236 bool isVariadic, 237 ArrayRef<Type> resultTypes) { 238 Region &body = op->getRegion(0); 239 bool isExternal = body.empty(); 240 241 p << '('; 242 for (unsigned i = 0, e = argTypes.size(); i < e; ++i) { 243 if (i > 0) 244 p << ", "; 245 246 if (!isExternal) { 247 p.printOperand(body.getArgument(i)); 248 p << ": "; 249 } 250 251 p.printType(argTypes[i]); 252 p.printOptionalAttrDict(::mlir::impl::getArgAttrs(op, i)); 253 } 254 255 if (isVariadic) { 256 if (!argTypes.empty()) 257 p << ", "; 258 p << "..."; 259 } 260 261 p << ')'; 262 263 if (!resultTypes.empty()) { 264 p.getStream() << " -> "; 265 SmallVector<ArrayRef<NamedAttribute>, 4> resultAttrs; 266 for (int i = 0, e = resultTypes.size(); i < e; ++i) 267 resultAttrs.push_back(::mlir::impl::getResultAttrs(op, i)); 268 printFunctionResultList(p, resultTypes, resultAttrs); 269 } 270 } 271 272 /// Prints the list of function prefixed with the "attributes" keyword. The 273 /// attributes with names listed in "elided" as well as those used by the 274 /// function-like operation internally are not printed. Nothing is printed 275 /// if all attributes are elided. Assumes `op` has the `FunctionLike` trait and 276 /// passed the verification. 277 void mlir::impl::printFunctionAttributes(OpAsmPrinter &p, Operation *op, 278 unsigned numInputs, 279 unsigned numResults, 280 ArrayRef<StringRef> elided) { 281 // Print out function attributes, if present. 282 SmallVector<StringRef, 2> ignoredAttrs = { 283 ::mlir::SymbolTable::getSymbolAttrName(), getTypeAttrName()}; 284 ignoredAttrs.append(elided.begin(), elided.end()); 285 286 SmallString<8> attrNameBuf; 287 288 // Ignore any argument attributes. 289 std::vector<SmallString<8>> argAttrStorage; 290 for (unsigned i = 0; i != numInputs; ++i) 291 if (op->getAttr(getArgAttrName(i, attrNameBuf))) 292 argAttrStorage.emplace_back(attrNameBuf); 293 ignoredAttrs.append(argAttrStorage.begin(), argAttrStorage.end()); 294 295 // Ignore any result attributes. 296 std::vector<SmallString<8>> resultAttrStorage; 297 for (unsigned i = 0; i != numResults; ++i) 298 if (op->getAttr(getResultAttrName(i, attrNameBuf))) 299 resultAttrStorage.emplace_back(attrNameBuf); 300 ignoredAttrs.append(resultAttrStorage.begin(), resultAttrStorage.end()); 301 302 p.printOptionalAttrDictWithKeyword(op->getAttrs(), ignoredAttrs); 303 } 304 305 /// Printer implementation for function-like operations. Accepts lists of 306 /// argument and result types to use while printing. 307 void mlir::impl::printFunctionLikeOp(OpAsmPrinter &p, Operation *op, 308 ArrayRef<Type> argTypes, bool isVariadic, 309 ArrayRef<Type> resultTypes) { 310 // Print the operation and the function name. 311 auto funcName = 312 op->getAttrOfType<StringAttr>(SymbolTable::getSymbolAttrName()) 313 .getValue(); 314 p << op->getName() << ' '; 315 316 StringRef visibilityAttrName = SymbolTable::getVisibilityAttrName(); 317 if (auto visibility = op->getAttrOfType<StringAttr>(visibilityAttrName)) 318 p << visibility.getValue() << ' '; 319 p.printSymbolName(funcName); 320 321 printFunctionSignature(p, op, argTypes, isVariadic, resultTypes); 322 printFunctionAttributes(p, op, argTypes.size(), resultTypes.size(), 323 {visibilityAttrName}); 324 // Print the body if this is not an external function. 325 Region &body = op->getRegion(0); 326 if (!body.empty()) 327 p.printRegion(body, /*printEntryBlockArgs=*/false, 328 /*printBlockTerminators=*/true); 329 } 330