blob: 362f868aed585fefe22839a87f1bef8524da1295 [file] [log] [blame]
Chris Lattnere79379a2018-06-22 10:39:19 -07001//===- Parser.cpp - MLIR Parser Implementation ----------------------------===//
2//
3// Copyright 2019 The MLIR Authors.
4//
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16// =============================================================================
17//
18// This file implements the parser for the MLIR textual form.
19//
20//===----------------------------------------------------------------------===//
21
22#include "mlir/Parser.h"
23#include "Lexer.h"
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -070024#include "mlir/IR/AffineExpr.h"
MLIR Teamf85a6262018-06-27 11:03:08 -070025#include "mlir/IR/AffineMap.h"
Chris Lattner7121b802018-07-04 20:45:39 -070026#include "mlir/IR/Attributes.h"
Chris Lattner158e0a3e2018-07-08 20:51:38 -070027#include "mlir/IR/Builders.h"
Tatiana Shpeismanc96b5872018-06-28 17:02:32 -070028#include "mlir/IR/MLFunction.h"
Chris Lattner21e67f62018-07-06 10:46:19 -070029#include "mlir/IR/Module.h"
Chris Lattner85ee1512018-07-25 11:15:20 -070030#include "mlir/IR/OpImplementation.h"
Chris Lattner21e67f62018-07-06 10:46:19 -070031#include "mlir/IR/OperationSet.h"
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -070032#include "mlir/IR/Statements.h"
Chris Lattnerf7e22732018-06-22 22:03:48 -070033#include "mlir/IR/Types.h"
Chris Lattner6119d382018-07-20 18:41:34 -070034#include "llvm/ADT/DenseMap.h"
Chris Lattnere79379a2018-06-22 10:39:19 -070035#include "llvm/Support/SourceMgr.h"
36using namespace mlir;
Chris Lattner4c95a502018-06-23 16:03:42 -070037using llvm::SMLoc;
James Molloy0ff71542018-07-23 16:56:32 -070038using llvm::SourceMgr;
Chris Lattnere79379a2018-06-22 10:39:19 -070039
Chris Lattnerf7e22732018-06-22 22:03:48 -070040/// Simple enum to make code read better in cases that would otherwise return a
41/// bool value. Failure is "true" in a boolean context.
James Molloy0ff71542018-07-23 16:56:32 -070042enum ParseResult { ParseSuccess, ParseFailure };
Chris Lattnere79379a2018-06-22 10:39:19 -070043
Chris Lattner48af7d12018-07-09 19:05:38 -070044namespace {
45class Parser;
46
47/// This class refers to all of the state maintained globally by the parser,
48/// such as the current lexer position etc. The Parser base class provides
49/// methods to access this.
50class ParserState {
Chris Lattnered65a732018-06-28 20:45:33 -070051public:
Chris Lattner2e595eb2018-07-10 10:08:27 -070052 ParserState(llvm::SourceMgr &sourceMgr, Module *module,
Chris Lattner48af7d12018-07-09 19:05:38 -070053 SMDiagnosticHandlerTy errorReporter)
Chris Lattner2e595eb2018-07-10 10:08:27 -070054 : context(module->getContext()), module(module),
55 lex(sourceMgr, errorReporter), curToken(lex.lexToken()),
Chris Lattner85ee1512018-07-25 11:15:20 -070056 errorReporter(errorReporter), operationSet(OperationSet::get(context)) {
57 }
Chris Lattner2e595eb2018-07-10 10:08:27 -070058
59 // A map from affine map identifier to AffineMap.
60 llvm::StringMap<AffineMap *> affineMapDefinitions;
Chris Lattnere79379a2018-06-22 10:39:19 -070061
Chris Lattnere79379a2018-06-22 10:39:19 -070062private:
Chris Lattner48af7d12018-07-09 19:05:38 -070063 ParserState(const ParserState &) = delete;
64 void operator=(const ParserState &) = delete;
65
66 friend class Parser;
67
68 // The context we're parsing into.
Chris Lattner2e595eb2018-07-10 10:08:27 -070069 MLIRContext *const context;
70
71 // This is the module we are parsing into.
72 Module *const module;
Chris Lattnerf7e22732018-06-22 22:03:48 -070073
74 // The lexer for the source file we're parsing.
Chris Lattnere79379a2018-06-22 10:39:19 -070075 Lexer lex;
76
77 // This is the next token that hasn't been consumed yet.
78 Token curToken;
79
Jacques Pienaar9c411be2018-06-24 19:17:35 -070080 // The diagnostic error reporter.
Chris Lattner2e595eb2018-07-10 10:08:27 -070081 SMDiagnosticHandlerTy const errorReporter;
Chris Lattner85ee1512018-07-25 11:15:20 -070082
83 // The active OperationSet we're parsing with.
84 OperationSet &operationSet;
Chris Lattner48af7d12018-07-09 19:05:38 -070085};
86} // end anonymous namespace
MLIR Teamf85a6262018-06-27 11:03:08 -070087
Chris Lattner48af7d12018-07-09 19:05:38 -070088namespace {
89
Chris Lattner7f9cc272018-07-19 08:35:28 -070090typedef std::function<Operation *(Identifier, ArrayRef<SSAValue *>,
91 ArrayRef<Type *>, ArrayRef<NamedAttribute>)>
Tatiana Shpeisman565b9642018-07-16 11:47:09 -070092 CreateOperationFunction;
93
Chris Lattner48af7d12018-07-09 19:05:38 -070094/// This class implement support for parsing global entities like types and
95/// shared entities like SSA names. It is intended to be subclassed by
96/// specialized subparsers that include state, e.g. when a local symbol table.
97class Parser {
98public:
Chris Lattner2e595eb2018-07-10 10:08:27 -070099 Builder builder;
Chris Lattner48af7d12018-07-09 19:05:38 -0700100
Chris Lattner2e595eb2018-07-10 10:08:27 -0700101 Parser(ParserState &state) : builder(state.context), state(state) {}
102
103 // Helper methods to get stuff from the parser-global state.
104 ParserState &getState() const { return state; }
Chris Lattner48af7d12018-07-09 19:05:38 -0700105 MLIRContext *getContext() const { return state.context; }
Chris Lattner2e595eb2018-07-10 10:08:27 -0700106 Module *getModule() { return state.module; }
Chris Lattner85ee1512018-07-25 11:15:20 -0700107 OperationSet &getOperationSet() const { return state.operationSet; }
Chris Lattner48af7d12018-07-09 19:05:38 -0700108
109 /// Return the current token the parser is inspecting.
110 const Token &getToken() const { return state.curToken; }
111 StringRef getTokenSpelling() const { return state.curToken.getSpelling(); }
Chris Lattnere79379a2018-06-22 10:39:19 -0700112
113 /// Emit an error and return failure.
Chris Lattner4c95a502018-06-23 16:03:42 -0700114 ParseResult emitError(const Twine &message) {
Chris Lattner48af7d12018-07-09 19:05:38 -0700115 return emitError(state.curToken.getLoc(), message);
Chris Lattner4c95a502018-06-23 16:03:42 -0700116 }
117 ParseResult emitError(SMLoc loc, const Twine &message);
Chris Lattnere79379a2018-06-22 10:39:19 -0700118
119 /// Advance the current lexer onto the next token.
120 void consumeToken() {
Chris Lattner48af7d12018-07-09 19:05:38 -0700121 assert(state.curToken.isNot(Token::eof, Token::error) &&
Chris Lattnere79379a2018-06-22 10:39:19 -0700122 "shouldn't advance past EOF or errors");
Chris Lattner48af7d12018-07-09 19:05:38 -0700123 state.curToken = state.lex.lexToken();
Chris Lattnere79379a2018-06-22 10:39:19 -0700124 }
125
126 /// Advance the current lexer onto the next token, asserting what the expected
127 /// current token is. This is preferred to the above method because it leads
128 /// to more self-documenting code with better checking.
Chris Lattner8da0c282018-06-29 11:15:56 -0700129 void consumeToken(Token::Kind kind) {
Chris Lattner48af7d12018-07-09 19:05:38 -0700130 assert(state.curToken.is(kind) && "consumed an unexpected token");
Chris Lattnere79379a2018-06-22 10:39:19 -0700131 consumeToken();
132 }
133
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700134 /// If the current token has the specified kind, consume it and return true.
135 /// If not, return false.
Chris Lattner8da0c282018-06-29 11:15:56 -0700136 bool consumeIf(Token::Kind kind) {
Chris Lattner48af7d12018-07-09 19:05:38 -0700137 if (state.curToken.isNot(kind))
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700138 return false;
139 consumeToken(kind);
140 return true;
141 }
142
Chris Lattnerf7702a62018-07-23 17:30:01 -0700143 /// Consume the specified token if present and return success. On failure,
144 /// output a diagnostic and return failure.
145 ParseResult parseToken(Token::Kind expectedToken, const Twine &message);
146
Chris Lattner40746442018-07-21 14:32:09 -0700147 /// Parse a comma-separated list of elements up until the specified end token.
148 ParseResult
149 parseCommaSeparatedListUntil(Token::Kind rightToken,
150 const std::function<ParseResult()> &parseElement,
151 bool allowEmptyList = true);
152
153 /// Parse a comma separated list of elements that must have at least one entry
154 /// in it.
155 ParseResult
156 parseCommaSeparatedList(const std::function<ParseResult()> &parseElement);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700157
Chris Lattnerf7e22732018-06-22 22:03:48 -0700158 // We have two forms of parsing methods - those that return a non-null
159 // pointer on success, and those that return a ParseResult to indicate whether
160 // they returned a failure. The second class fills in by-reference arguments
161 // as the results of their action.
162
Chris Lattnere79379a2018-06-22 10:39:19 -0700163 // Type parsing.
Chris Lattnerf958bbe2018-06-29 22:08:05 -0700164 Type *parsePrimitiveType();
Chris Lattnerf7e22732018-06-22 22:03:48 -0700165 Type *parseElementType();
166 VectorType *parseVectorType();
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700167 ParseResult parseDimensionListRanked(SmallVectorImpl<int> &dimensions);
Chris Lattnerf7e22732018-06-22 22:03:48 -0700168 Type *parseTensorType();
169 Type *parseMemRefType();
170 Type *parseFunctionType();
171 Type *parseType();
Chris Lattner1604e472018-07-23 08:42:19 -0700172 ParseResult parseTypeListNoParens(SmallVectorImpl<Type *> &elements);
James Molloy0ff71542018-07-23 16:56:32 -0700173 ParseResult parseTypeList(SmallVectorImpl<Type *> &elements);
Chris Lattnere79379a2018-06-22 10:39:19 -0700174
Chris Lattner7121b802018-07-04 20:45:39 -0700175 // Attribute parsing.
176 Attribute *parseAttribute();
177 ParseResult parseAttributeDict(SmallVectorImpl<NamedAttribute> &attributes);
178
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700179 // Polyhedral structures.
Chris Lattner2e595eb2018-07-10 10:08:27 -0700180 AffineMap *parseAffineMapInline();
MLIR Team718c82f2018-07-16 09:45:22 -0700181 AffineMap *parseAffineMapReference();
MLIR Teamf85a6262018-06-27 11:03:08 -0700182
Chris Lattner48af7d12018-07-09 19:05:38 -0700183private:
184 // The Parser is subclassed and reinstantiated. Do not add additional
185 // non-trivial state here, add it to the ParserState class.
186 ParserState &state;
Chris Lattnere79379a2018-06-22 10:39:19 -0700187};
188} // end anonymous namespace
189
190//===----------------------------------------------------------------------===//
191// Helper methods.
192//===----------------------------------------------------------------------===//
193
Chris Lattner4c95a502018-06-23 16:03:42 -0700194ParseResult Parser::emitError(SMLoc loc, const Twine &message) {
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700195 // If we hit a parse error in response to a lexer error, then the lexer
Jacques Pienaar9c411be2018-06-24 19:17:35 -0700196 // already reported the error.
Chris Lattner48af7d12018-07-09 19:05:38 -0700197 if (getToken().is(Token::error))
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700198 return ParseFailure;
199
Chris Lattner48af7d12018-07-09 19:05:38 -0700200 auto &sourceMgr = state.lex.getSourceMgr();
201 state.errorReporter(sourceMgr.GetMessage(loc, SourceMgr::DK_Error, message));
Chris Lattnere79379a2018-06-22 10:39:19 -0700202 return ParseFailure;
203}
204
Chris Lattnerf7702a62018-07-23 17:30:01 -0700205/// Consume the specified token if present and return success. On failure,
206/// output a diagnostic and return failure.
207ParseResult Parser::parseToken(Token::Kind expectedToken,
208 const Twine &message) {
209 if (consumeIf(expectedToken))
210 return ParseSuccess;
211 return emitError(message);
212}
213
Chris Lattner40746442018-07-21 14:32:09 -0700214/// Parse a comma separated list of elements that must have at least one entry
215/// in it.
216ParseResult Parser::parseCommaSeparatedList(
217 const std::function<ParseResult()> &parseElement) {
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700218 // Non-empty case starts with an element.
219 if (parseElement())
220 return ParseFailure;
221
222 // Otherwise we have a list of comma separated elements.
223 while (consumeIf(Token::comma)) {
224 if (parseElement())
225 return ParseFailure;
226 }
Chris Lattner40746442018-07-21 14:32:09 -0700227 return ParseSuccess;
228}
229
230/// Parse a comma-separated list of elements, terminated with an arbitrary
231/// token. This allows empty lists if allowEmptyList is true.
232///
233/// abstract-list ::= rightToken // if allowEmptyList == true
234/// abstract-list ::= element (',' element)* rightToken
235///
236ParseResult Parser::parseCommaSeparatedListUntil(
237 Token::Kind rightToken, const std::function<ParseResult()> &parseElement,
238 bool allowEmptyList) {
239 // Handle the empty case.
240 if (getToken().is(rightToken)) {
241 if (!allowEmptyList)
242 return emitError("expected list element");
243 consumeToken(rightToken);
244 return ParseSuccess;
245 }
246
Chris Lattnerf7702a62018-07-23 17:30:01 -0700247 if (parseCommaSeparatedList(parseElement) ||
248 parseToken(rightToken, "expected ',' or '" +
249 Token::getTokenSpelling(rightToken) + "'"))
Chris Lattner40746442018-07-21 14:32:09 -0700250 return ParseFailure;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700251
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700252 return ParseSuccess;
253}
Chris Lattnere79379a2018-06-22 10:39:19 -0700254
255//===----------------------------------------------------------------------===//
256// Type Parsing
257//===----------------------------------------------------------------------===//
258
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700259/// Parse the low-level fixed dtypes in the system.
260///
Chris Lattnerf958bbe2018-06-29 22:08:05 -0700261/// primitive-type ::= `f16` | `bf16` | `f32` | `f64`
262/// primitive-type ::= integer-type
263/// primitive-type ::= `affineint`
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700264///
Chris Lattnerf958bbe2018-06-29 22:08:05 -0700265Type *Parser::parsePrimitiveType() {
Chris Lattner48af7d12018-07-09 19:05:38 -0700266 switch (getToken().getKind()) {
Chris Lattnerf7e22732018-06-22 22:03:48 -0700267 default:
268 return (emitError("expected type"), nullptr);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700269 case Token::kw_bf16:
270 consumeToken(Token::kw_bf16);
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700271 return builder.getBF16Type();
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700272 case Token::kw_f16:
273 consumeToken(Token::kw_f16);
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700274 return builder.getF16Type();
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700275 case Token::kw_f32:
276 consumeToken(Token::kw_f32);
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700277 return builder.getF32Type();
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700278 case Token::kw_f64:
279 consumeToken(Token::kw_f64);
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700280 return builder.getF64Type();
Chris Lattnerf958bbe2018-06-29 22:08:05 -0700281 case Token::kw_affineint:
282 consumeToken(Token::kw_affineint);
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700283 return builder.getAffineIntType();
Chris Lattnerf958bbe2018-06-29 22:08:05 -0700284 case Token::inttype: {
Chris Lattner48af7d12018-07-09 19:05:38 -0700285 auto width = getToken().getIntTypeBitwidth();
Chris Lattnerf958bbe2018-06-29 22:08:05 -0700286 if (!width.hasValue())
287 return (emitError("invalid integer width"), nullptr);
288 consumeToken(Token::inttype);
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700289 return builder.getIntegerType(width.getValue());
Chris Lattnerf958bbe2018-06-29 22:08:05 -0700290 }
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700291 }
292}
293
294/// Parse the element type of a tensor or memref type.
295///
296/// element-type ::= primitive-type | vector-type
297///
Chris Lattnerf7e22732018-06-22 22:03:48 -0700298Type *Parser::parseElementType() {
Chris Lattner48af7d12018-07-09 19:05:38 -0700299 if (getToken().is(Token::kw_vector))
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700300 return parseVectorType();
301
302 return parsePrimitiveType();
303}
304
305/// Parse a vector type.
306///
307/// vector-type ::= `vector` `<` const-dimension-list primitive-type `>`
308/// const-dimension-list ::= (integer-literal `x`)+
309///
Chris Lattnerf7e22732018-06-22 22:03:48 -0700310VectorType *Parser::parseVectorType() {
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700311 consumeToken(Token::kw_vector);
312
Chris Lattnerf7702a62018-07-23 17:30:01 -0700313 if (parseToken(Token::less, "expected '<' in vector type"))
314 return nullptr;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700315
Chris Lattner48af7d12018-07-09 19:05:38 -0700316 if (getToken().isNot(Token::integer))
Chris Lattnerf7e22732018-06-22 22:03:48 -0700317 return (emitError("expected dimension size in vector type"), nullptr);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700318
319 SmallVector<unsigned, 4> dimensions;
Chris Lattner48af7d12018-07-09 19:05:38 -0700320 while (getToken().is(Token::integer)) {
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700321 // Make sure this integer value is in bound and valid.
Chris Lattner48af7d12018-07-09 19:05:38 -0700322 auto dimension = getToken().getUnsignedIntegerValue();
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700323 if (!dimension.hasValue())
Chris Lattnerf7e22732018-06-22 22:03:48 -0700324 return (emitError("invalid dimension in vector type"), nullptr);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700325 dimensions.push_back(dimension.getValue());
326
327 consumeToken(Token::integer);
328
329 // Make sure we have an 'x' or something like 'xbf32'.
Chris Lattner48af7d12018-07-09 19:05:38 -0700330 if (getToken().isNot(Token::bare_identifier) ||
331 getTokenSpelling()[0] != 'x')
Chris Lattnerf7e22732018-06-22 22:03:48 -0700332 return (emitError("expected 'x' in vector dimension list"), nullptr);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700333
334 // If we had a prefix of 'x', lex the next token immediately after the 'x'.
Chris Lattner48af7d12018-07-09 19:05:38 -0700335 if (getTokenSpelling().size() != 1)
336 state.lex.resetPointer(getTokenSpelling().data() + 1);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700337
338 // Consume the 'x'.
339 consumeToken(Token::bare_identifier);
340 }
341
342 // Parse the element type.
Chris Lattnerf7e22732018-06-22 22:03:48 -0700343 auto *elementType = parsePrimitiveType();
344 if (!elementType)
345 return nullptr;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700346
Chris Lattnerf7702a62018-07-23 17:30:01 -0700347 if (parseToken(Token::greater, "expected '>' in vector type"))
348 return nullptr;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700349
Chris Lattnerf7e22732018-06-22 22:03:48 -0700350 return VectorType::get(dimensions, elementType);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700351}
352
353/// Parse a dimension list of a tensor or memref type. This populates the
354/// dimension list, returning -1 for the '?' dimensions.
355///
356/// dimension-list-ranked ::= (dimension `x`)*
357/// dimension ::= `?` | integer-literal
358///
359ParseResult Parser::parseDimensionListRanked(SmallVectorImpl<int> &dimensions) {
Chris Lattner48af7d12018-07-09 19:05:38 -0700360 while (getToken().isAny(Token::integer, Token::question)) {
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700361 if (consumeIf(Token::question)) {
362 dimensions.push_back(-1);
363 } else {
364 // Make sure this integer value is in bound and valid.
Chris Lattner48af7d12018-07-09 19:05:38 -0700365 auto dimension = getToken().getUnsignedIntegerValue();
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700366 if (!dimension.hasValue() || (int)dimension.getValue() < 0)
367 return emitError("invalid dimension");
368 dimensions.push_back((int)dimension.getValue());
369 consumeToken(Token::integer);
370 }
371
372 // Make sure we have an 'x' or something like 'xbf32'.
Chris Lattner48af7d12018-07-09 19:05:38 -0700373 if (getToken().isNot(Token::bare_identifier) ||
374 getTokenSpelling()[0] != 'x')
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700375 return emitError("expected 'x' in dimension list");
376
377 // If we had a prefix of 'x', lex the next token immediately after the 'x'.
Chris Lattner48af7d12018-07-09 19:05:38 -0700378 if (getTokenSpelling().size() != 1)
379 state.lex.resetPointer(getTokenSpelling().data() + 1);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700380
381 // Consume the 'x'.
382 consumeToken(Token::bare_identifier);
383 }
384
385 return ParseSuccess;
386}
387
388/// Parse a tensor type.
389///
390/// tensor-type ::= `tensor` `<` dimension-list element-type `>`
391/// dimension-list ::= dimension-list-ranked | `??`
392///
Chris Lattnerf7e22732018-06-22 22:03:48 -0700393Type *Parser::parseTensorType() {
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700394 consumeToken(Token::kw_tensor);
395
Chris Lattnerf7702a62018-07-23 17:30:01 -0700396 if (parseToken(Token::less, "expected '<' in tensor type"))
397 return nullptr;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700398
399 bool isUnranked;
400 SmallVector<int, 4> dimensions;
401
402 if (consumeIf(Token::questionquestion)) {
403 isUnranked = true;
404 } else {
405 isUnranked = false;
406 if (parseDimensionListRanked(dimensions))
Chris Lattnerf7e22732018-06-22 22:03:48 -0700407 return nullptr;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700408 }
409
410 // Parse the element type.
Chris Lattnerf7e22732018-06-22 22:03:48 -0700411 auto elementType = parseElementType();
412 if (!elementType)
413 return nullptr;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700414
Chris Lattnerf7702a62018-07-23 17:30:01 -0700415 if (parseToken(Token::greater, "expected '>' in tensor type"))
416 return nullptr;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700417
MLIR Team355ec862018-06-23 18:09:09 -0700418 if (isUnranked)
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700419 return builder.getTensorType(elementType);
420 return builder.getTensorType(dimensions, elementType);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700421}
422
423/// Parse a memref type.
424///
425/// memref-type ::= `memref` `<` dimension-list-ranked element-type
426/// (`,` semi-affine-map-composition)? (`,` memory-space)? `>`
427///
428/// semi-affine-map-composition ::= (semi-affine-map `,` )* semi-affine-map
429/// memory-space ::= integer-literal /* | TODO: address-space-id */
430///
Chris Lattnerf7e22732018-06-22 22:03:48 -0700431Type *Parser::parseMemRefType() {
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700432 consumeToken(Token::kw_memref);
433
Chris Lattnerf7702a62018-07-23 17:30:01 -0700434 if (parseToken(Token::less, "expected '<' in memref type"))
435 return nullptr;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700436
437 SmallVector<int, 4> dimensions;
438 if (parseDimensionListRanked(dimensions))
Chris Lattnerf7e22732018-06-22 22:03:48 -0700439 return nullptr;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700440
441 // Parse the element type.
Chris Lattnerf7e22732018-06-22 22:03:48 -0700442 auto elementType = parseElementType();
443 if (!elementType)
444 return nullptr;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700445
MLIR Team718c82f2018-07-16 09:45:22 -0700446 // Parse semi-affine-map-composition.
James Molloy0ff71542018-07-23 16:56:32 -0700447 SmallVector<AffineMap *, 2> affineMapComposition;
Chris Lattner413db6a2018-07-25 12:55:50 -0700448 unsigned memorySpace = 0;
MLIR Team718c82f2018-07-16 09:45:22 -0700449 bool parsedMemorySpace = false;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700450
MLIR Team718c82f2018-07-16 09:45:22 -0700451 auto parseElt = [&]() -> ParseResult {
452 if (getToken().is(Token::integer)) {
453 // Parse memory space.
454 if (parsedMemorySpace)
455 return emitError("multiple memory spaces specified in memref type");
456 auto v = getToken().getUnsignedIntegerValue();
457 if (!v.hasValue())
458 return emitError("invalid memory space in memref type");
459 memorySpace = v.getValue();
460 consumeToken(Token::integer);
461 parsedMemorySpace = true;
462 } else {
463 // Parse affine map.
464 if (parsedMemorySpace)
465 return emitError("affine map after memory space in memref type");
James Molloy0ff71542018-07-23 16:56:32 -0700466 auto *affineMap = parseAffineMapReference();
MLIR Team718c82f2018-07-16 09:45:22 -0700467 if (affineMap == nullptr)
468 return ParseFailure;
469 affineMapComposition.push_back(affineMap);
470 }
471 return ParseSuccess;
472 };
473
Chris Lattner413db6a2018-07-25 12:55:50 -0700474 // Parse a list of mappings and address space if present.
475 if (consumeIf(Token::comma)) {
476 // Parse comma separated list of affine maps, followed by memory space.
477 if (parseCommaSeparatedListUntil(Token::greater, parseElt,
478 /*allowEmptyList=*/false)) {
479 return nullptr;
480 }
481 } else {
482 if (parseToken(Token::greater, "expected ',' or '>' in memref type"))
483 return nullptr;
MLIR Team718c82f2018-07-16 09:45:22 -0700484 }
MLIR Team718c82f2018-07-16 09:45:22 -0700485
486 return MemRefType::get(dimensions, elementType, affineMapComposition,
487 memorySpace);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700488}
489
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700490/// Parse a function type.
491///
492/// function-type ::= type-list-parens `->` type-list
493///
Chris Lattnerf7e22732018-06-22 22:03:48 -0700494Type *Parser::parseFunctionType() {
Chris Lattner48af7d12018-07-09 19:05:38 -0700495 assert(getToken().is(Token::l_paren));
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700496
Chris Lattnerf7702a62018-07-23 17:30:01 -0700497 SmallVector<Type *, 4> arguments, results;
498 if (parseTypeList(arguments) ||
499 parseToken(Token::arrow, "expected '->' in function type") ||
500 parseTypeList(results))
Chris Lattnerf7e22732018-06-22 22:03:48 -0700501 return nullptr;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700502
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700503 return builder.getFunctionType(arguments, results);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700504}
505
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700506/// Parse an arbitrary type.
507///
508/// type ::= primitive-type
509/// | vector-type
510/// | tensor-type
511/// | memref-type
512/// | function-type
513/// element-type ::= primitive-type | vector-type
514///
Chris Lattnerf7e22732018-06-22 22:03:48 -0700515Type *Parser::parseType() {
Chris Lattner48af7d12018-07-09 19:05:38 -0700516 switch (getToken().getKind()) {
James Molloy0ff71542018-07-23 16:56:32 -0700517 case Token::kw_memref:
518 return parseMemRefType();
519 case Token::kw_tensor:
520 return parseTensorType();
521 case Token::kw_vector:
522 return parseVectorType();
523 case Token::l_paren:
524 return parseFunctionType();
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700525 default:
526 return parsePrimitiveType();
527 }
528}
529
Chris Lattner1604e472018-07-23 08:42:19 -0700530/// Parse a list of types without an enclosing parenthesis. The list must have
531/// at least one member.
532///
533/// type-list-no-parens ::= type (`,` type)*
534///
535ParseResult Parser::parseTypeListNoParens(SmallVectorImpl<Type *> &elements) {
536 auto parseElt = [&]() -> ParseResult {
537 auto elt = parseType();
538 elements.push_back(elt);
539 return elt ? ParseSuccess : ParseFailure;
540 };
541
542 return parseCommaSeparatedList(parseElt);
543}
544
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700545/// Parse a "type list", which is a singular type, or a parenthesized list of
546/// types.
547///
548/// type-list ::= type-list-parens | type
549/// type-list-parens ::= `(` `)`
Chris Lattner1604e472018-07-23 08:42:19 -0700550/// | `(` type-list-no-parens `)`
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700551///
James Molloy0ff71542018-07-23 16:56:32 -0700552ParseResult Parser::parseTypeList(SmallVectorImpl<Type *> &elements) {
Chris Lattnerf7e22732018-06-22 22:03:48 -0700553 auto parseElt = [&]() -> ParseResult {
554 auto elt = parseType();
555 elements.push_back(elt);
556 return elt ? ParseSuccess : ParseFailure;
557 };
558
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700559 // If there is no parens, then it must be a singular type.
560 if (!consumeIf(Token::l_paren))
Chris Lattnerf7e22732018-06-22 22:03:48 -0700561 return parseElt();
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700562
Chris Lattner40746442018-07-21 14:32:09 -0700563 if (parseCommaSeparatedListUntil(Token::r_paren, parseElt))
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700564 return ParseFailure;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700565
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700566 return ParseSuccess;
567}
568
Chris Lattner4c95a502018-06-23 16:03:42 -0700569//===----------------------------------------------------------------------===//
Chris Lattner7121b802018-07-04 20:45:39 -0700570// Attribute parsing.
571//===----------------------------------------------------------------------===//
572
Chris Lattner7121b802018-07-04 20:45:39 -0700573/// Attribute parsing.
574///
575/// attribute-value ::= bool-literal
576/// | integer-literal
577/// | float-literal
578/// | string-literal
579/// | `[` (attribute-value (`,` attribute-value)*)? `]`
580///
581Attribute *Parser::parseAttribute() {
Chris Lattner48af7d12018-07-09 19:05:38 -0700582 switch (getToken().getKind()) {
Chris Lattner7121b802018-07-04 20:45:39 -0700583 case Token::kw_true:
584 consumeToken(Token::kw_true);
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700585 return builder.getBoolAttr(true);
Chris Lattner7121b802018-07-04 20:45:39 -0700586 case Token::kw_false:
587 consumeToken(Token::kw_false);
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700588 return builder.getBoolAttr(false);
Chris Lattner7121b802018-07-04 20:45:39 -0700589
590 case Token::integer: {
Chris Lattner48af7d12018-07-09 19:05:38 -0700591 auto val = getToken().getUInt64IntegerValue();
Chris Lattner7121b802018-07-04 20:45:39 -0700592 if (!val.hasValue() || (int64_t)val.getValue() < 0)
593 return (emitError("integer too large for attribute"), nullptr);
594 consumeToken(Token::integer);
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700595 return builder.getIntegerAttr((int64_t)val.getValue());
Chris Lattner7121b802018-07-04 20:45:39 -0700596 }
597
598 case Token::minus: {
599 consumeToken(Token::minus);
Chris Lattner48af7d12018-07-09 19:05:38 -0700600 if (getToken().is(Token::integer)) {
601 auto val = getToken().getUInt64IntegerValue();
Chris Lattner7121b802018-07-04 20:45:39 -0700602 if (!val.hasValue() || (int64_t)-val.getValue() >= 0)
603 return (emitError("integer too large for attribute"), nullptr);
604 consumeToken(Token::integer);
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700605 return builder.getIntegerAttr((int64_t)-val.getValue());
Chris Lattner7121b802018-07-04 20:45:39 -0700606 }
607
608 return (emitError("expected constant integer or floating point value"),
609 nullptr);
610 }
611
612 case Token::string: {
Chris Lattner48af7d12018-07-09 19:05:38 -0700613 auto val = getToken().getStringValue();
Chris Lattner7121b802018-07-04 20:45:39 -0700614 consumeToken(Token::string);
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700615 return builder.getStringAttr(val);
Chris Lattner7121b802018-07-04 20:45:39 -0700616 }
617
Chris Lattner85ee1512018-07-25 11:15:20 -0700618 case Token::l_square: {
619 consumeToken(Token::l_square);
James Molloy0ff71542018-07-23 16:56:32 -0700620 SmallVector<Attribute *, 4> elements;
Chris Lattner7121b802018-07-04 20:45:39 -0700621
622 auto parseElt = [&]() -> ParseResult {
623 elements.push_back(parseAttribute());
624 return elements.back() ? ParseSuccess : ParseFailure;
625 };
626
Chris Lattner85ee1512018-07-25 11:15:20 -0700627 if (parseCommaSeparatedListUntil(Token::r_square, parseElt))
Chris Lattner7121b802018-07-04 20:45:39 -0700628 return nullptr;
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700629 return builder.getArrayAttr(elements);
Chris Lattner7121b802018-07-04 20:45:39 -0700630 }
631 default:
MLIR Teamb61885d2018-07-18 16:29:21 -0700632 // Try to parse affine map reference.
James Molloy0ff71542018-07-23 16:56:32 -0700633 auto *affineMap = parseAffineMapReference();
MLIR Teamb61885d2018-07-18 16:29:21 -0700634 if (affineMap != nullptr)
635 return builder.getAffineMapAttr(affineMap);
636
Chris Lattner7121b802018-07-04 20:45:39 -0700637 // TODO: Handle floating point.
638 return (emitError("expected constant attribute value"), nullptr);
639 }
640}
641
Chris Lattner7121b802018-07-04 20:45:39 -0700642/// Attribute dictionary.
643///
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700644/// attribute-dict ::= `{` `}`
645/// | `{` attribute-entry (`,` attribute-entry)* `}`
646/// attribute-entry ::= bare-id `:` attribute-value
Chris Lattner7121b802018-07-04 20:45:39 -0700647///
James Molloy0ff71542018-07-23 16:56:32 -0700648ParseResult
649Parser::parseAttributeDict(SmallVectorImpl<NamedAttribute> &attributes) {
Chris Lattner7121b802018-07-04 20:45:39 -0700650 consumeToken(Token::l_brace);
651
652 auto parseElt = [&]() -> ParseResult {
653 // We allow keywords as attribute names.
Chris Lattner48af7d12018-07-09 19:05:38 -0700654 if (getToken().isNot(Token::bare_identifier, Token::inttype) &&
655 !getToken().isKeyword())
Chris Lattner7121b802018-07-04 20:45:39 -0700656 return emitError("expected attribute name");
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700657 auto nameId = builder.getIdentifier(getTokenSpelling());
Chris Lattner7121b802018-07-04 20:45:39 -0700658 consumeToken();
659
Chris Lattnerf7702a62018-07-23 17:30:01 -0700660 if (parseToken(Token::colon, "expected ':' in attribute list"))
661 return ParseFailure;
Chris Lattner7121b802018-07-04 20:45:39 -0700662
663 auto attr = parseAttribute();
James Molloy0ff71542018-07-23 16:56:32 -0700664 if (!attr)
665 return ParseFailure;
Chris Lattner7121b802018-07-04 20:45:39 -0700666
667 attributes.push_back({nameId, attr});
668 return ParseSuccess;
669 };
670
Chris Lattner40746442018-07-21 14:32:09 -0700671 if (parseCommaSeparatedListUntil(Token::r_brace, parseElt))
Chris Lattner7121b802018-07-04 20:45:39 -0700672 return ParseFailure;
673
674 return ParseSuccess;
675}
676
677//===----------------------------------------------------------------------===//
MLIR Teamf85a6262018-06-27 11:03:08 -0700678// Polyhedral structures.
679//===----------------------------------------------------------------------===//
680
Chris Lattner2e595eb2018-07-10 10:08:27 -0700681/// Lower precedence ops (all at the same precedence level). LNoOp is false in
682/// the boolean sense.
683enum AffineLowPrecOp {
684 /// Null value.
685 LNoOp,
686 Add,
687 Sub
688};
MLIR Teamf85a6262018-06-27 11:03:08 -0700689
Chris Lattner2e595eb2018-07-10 10:08:27 -0700690/// Higher precedence ops - all at the same precedence level. HNoOp is false in
691/// the boolean sense.
692enum AffineHighPrecOp {
693 /// Null value.
694 HNoOp,
695 Mul,
696 FloorDiv,
697 CeilDiv,
698 Mod
699};
Chris Lattner7121b802018-07-04 20:45:39 -0700700
Chris Lattner2e595eb2018-07-10 10:08:27 -0700701namespace {
702/// This is a specialized parser for AffineMap's, maintaining the state
703/// transient to their bodies.
704class AffineMapParser : public Parser {
705public:
706 explicit AffineMapParser(ParserState &state) : Parser(state) {}
Chris Lattner7121b802018-07-04 20:45:39 -0700707
Chris Lattner2e595eb2018-07-10 10:08:27 -0700708 AffineMap *parseAffineMapInline();
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -0700709
Chris Lattner2e595eb2018-07-10 10:08:27 -0700710private:
Chris Lattner2e595eb2018-07-10 10:08:27 -0700711 // Binary affine op parsing.
712 AffineLowPrecOp consumeIfLowPrecOp();
713 AffineHighPrecOp consumeIfHighPrecOp();
MLIR Teamf85a6262018-06-27 11:03:08 -0700714
Chris Lattner2e595eb2018-07-10 10:08:27 -0700715 // Identifier lists for polyhedral structures.
Chris Lattner413db6a2018-07-25 12:55:50 -0700716 ParseResult parseDimIdList(unsigned &numDims);
717 ParseResult parseSymbolIdList(unsigned &numSymbols);
718 ParseResult parseIdentifierDefinition(AffineExpr *idExpr);
Chris Lattner2e595eb2018-07-10 10:08:27 -0700719
720 AffineExpr *parseAffineExpr();
721 AffineExpr *parseParentheticalExpr();
722 AffineExpr *parseNegateExpression(AffineExpr *lhs);
723 AffineExpr *parseIntegerExpr();
724 AffineExpr *parseBareIdExpr();
725
726 AffineExpr *getBinaryAffineOpExpr(AffineHighPrecOp op, AffineExpr *lhs,
Uday Bondhugula851b8fd2018-07-20 14:57:21 -0700727 AffineExpr *rhs, SMLoc opLoc);
Chris Lattner2e595eb2018-07-10 10:08:27 -0700728 AffineExpr *getBinaryAffineOpExpr(AffineLowPrecOp op, AffineExpr *lhs,
729 AffineExpr *rhs);
730 AffineExpr *parseAffineOperandExpr(AffineExpr *lhs);
731 AffineExpr *parseAffineLowPrecOpExpr(AffineExpr *llhs,
732 AffineLowPrecOp llhsOp);
733 AffineExpr *parseAffineHighPrecOpExpr(AffineExpr *llhs,
Uday Bondhugula851b8fd2018-07-20 14:57:21 -0700734 AffineHighPrecOp llhsOp,
735 SMLoc llhsOpLoc);
Chris Lattner2e595eb2018-07-10 10:08:27 -0700736
737private:
Chris Lattner413db6a2018-07-25 12:55:50 -0700738 SmallVector<std::pair<StringRef, AffineExpr *>, 4> dimsAndSymbols;
Chris Lattner2e595eb2018-07-10 10:08:27 -0700739};
740} // end anonymous namespace
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -0700741
Uday Bondhugula851b8fd2018-07-20 14:57:21 -0700742/// Create an affine binary high precedence op expression (mul's, div's, mod).
743/// opLoc is the location of the op token to be used to report errors
744/// for non-conforming expressions.
Chris Lattner2e595eb2018-07-10 10:08:27 -0700745AffineExpr *AffineMapParser::getBinaryAffineOpExpr(AffineHighPrecOp op,
746 AffineExpr *lhs,
Chris Lattner40746442018-07-21 14:32:09 -0700747 AffineExpr *rhs,
748 SMLoc opLoc) {
Uday Bondhugula0115dbb2018-07-11 21:31:07 -0700749 // TODO: make the error location info accurate.
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700750 switch (op) {
751 case Mul:
Uday Bondhugulacbe4cca2018-07-19 13:07:16 -0700752 if (!lhs->isSymbolicOrConstant() && !rhs->isSymbolicOrConstant()) {
Uday Bondhugula851b8fd2018-07-20 14:57:21 -0700753 emitError(opLoc, "non-affine expression: at least one of the multiply "
754 "operands has to be either a constant or symbolic");
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700755 return nullptr;
756 }
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700757 return builder.getMulExpr(lhs, rhs);
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700758 case FloorDiv:
Uday Bondhugulacbe4cca2018-07-19 13:07:16 -0700759 if (!rhs->isSymbolicOrConstant()) {
Uday Bondhugula851b8fd2018-07-20 14:57:21 -0700760 emitError(opLoc, "non-affine expression: right operand of floordiv "
761 "has to be either a constant or symbolic");
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700762 return nullptr;
763 }
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700764 return builder.getFloorDivExpr(lhs, rhs);
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700765 case CeilDiv:
Uday Bondhugulacbe4cca2018-07-19 13:07:16 -0700766 if (!rhs->isSymbolicOrConstant()) {
Uday Bondhugula851b8fd2018-07-20 14:57:21 -0700767 emitError(opLoc, "non-affine expression: right operand of ceildiv "
768 "has to be either a constant or symbolic");
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700769 return nullptr;
770 }
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700771 return builder.getCeilDivExpr(lhs, rhs);
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700772 case Mod:
Uday Bondhugulacbe4cca2018-07-19 13:07:16 -0700773 if (!rhs->isSymbolicOrConstant()) {
Uday Bondhugula851b8fd2018-07-20 14:57:21 -0700774 emitError(opLoc, "non-affine expression: right operand of mod "
775 "has to be either a constant or symbolic");
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700776 return nullptr;
777 }
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700778 return builder.getModExpr(lhs, rhs);
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700779 case HNoOp:
780 llvm_unreachable("can't create affine expression for null high prec op");
781 return nullptr;
782 }
783}
784
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700785/// Create an affine binary low precedence op expression (add, sub).
Chris Lattner2e595eb2018-07-10 10:08:27 -0700786AffineExpr *AffineMapParser::getBinaryAffineOpExpr(AffineLowPrecOp op,
787 AffineExpr *lhs,
788 AffineExpr *rhs) {
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700789 switch (op) {
790 case AffineLowPrecOp::Add:
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700791 return builder.getAddExpr(lhs, rhs);
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700792 case AffineLowPrecOp::Sub:
Uday Bondhugulac1faf662018-07-19 14:08:50 -0700793 return builder.getAddExpr(
794 lhs, builder.getMulExpr(rhs, builder.getConstantExpr(-1)));
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700795 case AffineLowPrecOp::LNoOp:
796 llvm_unreachable("can't create affine expression for null low prec op");
797 return nullptr;
798 }
799}
800
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700801/// Consume this token if it is a lower precedence affine op (there are only two
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700802/// precedence levels).
Chris Lattner2e595eb2018-07-10 10:08:27 -0700803AffineLowPrecOp AffineMapParser::consumeIfLowPrecOp() {
Chris Lattner48af7d12018-07-09 19:05:38 -0700804 switch (getToken().getKind()) {
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700805 case Token::plus:
806 consumeToken(Token::plus);
807 return AffineLowPrecOp::Add;
808 case Token::minus:
809 consumeToken(Token::minus);
810 return AffineLowPrecOp::Sub;
811 default:
812 return AffineLowPrecOp::LNoOp;
813 }
814}
815
816/// Consume this token if it is a higher precedence affine op (there are only
817/// two precedence levels)
Chris Lattner2e595eb2018-07-10 10:08:27 -0700818AffineHighPrecOp AffineMapParser::consumeIfHighPrecOp() {
Chris Lattner48af7d12018-07-09 19:05:38 -0700819 switch (getToken().getKind()) {
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700820 case Token::star:
821 consumeToken(Token::star);
822 return Mul;
823 case Token::kw_floordiv:
824 consumeToken(Token::kw_floordiv);
825 return FloorDiv;
826 case Token::kw_ceildiv:
827 consumeToken(Token::kw_ceildiv);
828 return CeilDiv;
829 case Token::kw_mod:
830 consumeToken(Token::kw_mod);
831 return Mod;
832 default:
833 return HNoOp;
834 }
835}
836
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700837/// Parse a high precedence op expression list: mul, div, and mod are high
838/// precedence binary ops, i.e., parse a
839/// expr_1 op_1 expr_2 op_2 ... expr_n
840/// where op_1, op_2 are all a AffineHighPrecOp (mul, div, mod).
841/// All affine binary ops are left associative.
842/// Given llhs, returns (llhs llhsOp lhs) op rhs, or (lhs op rhs) if llhs is
843/// null. If no rhs can be found, returns (llhs llhsOp lhs) or lhs if llhs is
Uday Bondhugula851b8fd2018-07-20 14:57:21 -0700844/// null. llhsOpLoc is the location of the llhsOp token that will be used to
845/// report an error for non-conforming expressions.
846AffineExpr *AffineMapParser::parseAffineHighPrecOpExpr(AffineExpr *llhs,
847 AffineHighPrecOp llhsOp,
848 SMLoc llhsOpLoc) {
Chris Lattner2e595eb2018-07-10 10:08:27 -0700849 AffineExpr *lhs = parseAffineOperandExpr(llhs);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700850 if (!lhs)
851 return nullptr;
852
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700853 // Found an LHS. Parse the remaining expression.
Uday Bondhugula851b8fd2018-07-20 14:57:21 -0700854 auto opLoc = getToken().getLoc();
Chris Lattner2e595eb2018-07-10 10:08:27 -0700855 if (AffineHighPrecOp op = consumeIfHighPrecOp()) {
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700856 if (llhs) {
Uday Bondhugula851b8fd2018-07-20 14:57:21 -0700857 AffineExpr *expr = getBinaryAffineOpExpr(llhsOp, llhs, lhs, opLoc);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700858 if (!expr)
859 return nullptr;
Uday Bondhugula851b8fd2018-07-20 14:57:21 -0700860 return parseAffineHighPrecOpExpr(expr, op, opLoc);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700861 }
862 // No LLHS, get RHS
Uday Bondhugula851b8fd2018-07-20 14:57:21 -0700863 return parseAffineHighPrecOpExpr(lhs, op, opLoc);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700864 }
865
866 // This is the last operand in this expression.
867 if (llhs)
Uday Bondhugula851b8fd2018-07-20 14:57:21 -0700868 return getBinaryAffineOpExpr(llhsOp, llhs, lhs, llhsOpLoc);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700869
870 // No llhs, 'lhs' itself is the expression.
871 return lhs;
872}
873
874/// Parse an affine expression inside parentheses.
875///
876/// affine-expr ::= `(` affine-expr `)`
Chris Lattner2e595eb2018-07-10 10:08:27 -0700877AffineExpr *AffineMapParser::parseParentheticalExpr() {
Chris Lattnerf7702a62018-07-23 17:30:01 -0700878 if (parseToken(Token::l_paren, "expected '('"))
879 return nullptr;
Chris Lattner48af7d12018-07-09 19:05:38 -0700880 if (getToken().is(Token::r_paren))
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700881 return (emitError("no expression inside parentheses"), nullptr);
Chris Lattnerf7702a62018-07-23 17:30:01 -0700882
Chris Lattner2e595eb2018-07-10 10:08:27 -0700883 auto *expr = parseAffineExpr();
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700884 if (!expr)
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700885 return nullptr;
Chris Lattnerf7702a62018-07-23 17:30:01 -0700886 if (parseToken(Token::r_paren, "expected ')'"))
887 return nullptr;
888
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700889 return expr;
890}
891
892/// Parse the negation expression.
893///
894/// affine-expr ::= `-` affine-expr
Chris Lattner2e595eb2018-07-10 10:08:27 -0700895AffineExpr *AffineMapParser::parseNegateExpression(AffineExpr *lhs) {
Chris Lattnerf7702a62018-07-23 17:30:01 -0700896 if (parseToken(Token::minus, "expected '-'"))
897 return nullptr;
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700898
Chris Lattner2e595eb2018-07-10 10:08:27 -0700899 AffineExpr *operand = parseAffineOperandExpr(lhs);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700900 // Since negation has the highest precedence of all ops (including high
901 // precedence ops) but lower than parentheses, we are only going to use
902 // parseAffineOperandExpr instead of parseAffineExpr here.
903 if (!operand)
904 // Extra error message although parseAffineOperandExpr would have
905 // complained. Leads to a better diagnostic.
906 return (emitError("missing operand of negation"), nullptr);
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700907 auto *minusOne = builder.getConstantExpr(-1);
908 return builder.getMulExpr(minusOne, operand);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700909}
910
911/// Parse a bare id that may appear in an affine expression.
912///
913/// affine-expr ::= bare-id
Chris Lattner2e595eb2018-07-10 10:08:27 -0700914AffineExpr *AffineMapParser::parseBareIdExpr() {
Chris Lattner48af7d12018-07-09 19:05:38 -0700915 if (getToken().isNot(Token::bare_identifier))
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700916 return (emitError("expected bare identifier"), nullptr);
917
Chris Lattner48af7d12018-07-09 19:05:38 -0700918 StringRef sRef = getTokenSpelling();
Chris Lattner413db6a2018-07-25 12:55:50 -0700919 for (auto entry : dimsAndSymbols) {
Chris Lattnera8e47672018-07-25 14:08:16 -0700920 if (entry.first == sRef) {
921 consumeToken(Token::bare_identifier);
922 return entry.second;
923 }
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700924 }
Uday Bondhugula0115dbb2018-07-11 21:31:07 -0700925
926 return (emitError("use of undeclared identifier"), nullptr);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700927}
928
929/// Parse a positive integral constant appearing in an affine expression.
930///
931/// affine-expr ::= integer-literal
Chris Lattner2e595eb2018-07-10 10:08:27 -0700932AffineExpr *AffineMapParser::parseIntegerExpr() {
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700933 // No need to handle negative numbers separately here. They are naturally
934 // handled via the unary negation operator, although (FIXME) MININT_64 still
935 // not correctly handled.
Chris Lattner48af7d12018-07-09 19:05:38 -0700936 if (getToken().isNot(Token::integer))
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700937 return (emitError("expected integer"), nullptr);
938
Chris Lattner48af7d12018-07-09 19:05:38 -0700939 auto val = getToken().getUInt64IntegerValue();
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700940 if (!val.hasValue() || (int64_t)val.getValue() < 0) {
941 return (emitError("constant too large for affineint"), nullptr);
942 }
943 consumeToken(Token::integer);
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700944 return builder.getConstantExpr((int64_t)val.getValue());
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700945}
946
947/// Parses an expression that can be a valid operand of an affine expression.
Uday Bondhugula76345202018-07-09 13:47:52 -0700948/// lhs: if non-null, lhs is an affine expression that is the lhs of a binary
949/// operator, the rhs of which is being parsed. This is used to determine
950/// whether an error should be emitted for a missing right operand.
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700951// Eg: for an expression without parentheses (like i + j + k + l), each
952// of the four identifiers is an operand. For i + j*k + l, j*k is not an
953// operand expression, it's an op expression and will be parsed via
954// parseAffineHighPrecOpExpression(). However, for i + (j*k) + -l, (j*k) and -l
955// are valid operands that will be parsed by this function.
Chris Lattner2e595eb2018-07-10 10:08:27 -0700956AffineExpr *AffineMapParser::parseAffineOperandExpr(AffineExpr *lhs) {
Chris Lattner48af7d12018-07-09 19:05:38 -0700957 switch (getToken().getKind()) {
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700958 case Token::bare_identifier:
Chris Lattner2e595eb2018-07-10 10:08:27 -0700959 return parseBareIdExpr();
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700960 case Token::integer:
Chris Lattner2e595eb2018-07-10 10:08:27 -0700961 return parseIntegerExpr();
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700962 case Token::l_paren:
Chris Lattner2e595eb2018-07-10 10:08:27 -0700963 return parseParentheticalExpr();
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700964 case Token::minus:
Chris Lattner2e595eb2018-07-10 10:08:27 -0700965 return parseNegateExpression(lhs);
Uday Bondhugula76345202018-07-09 13:47:52 -0700966 case Token::kw_ceildiv:
967 case Token::kw_floordiv:
968 case Token::kw_mod:
969 case Token::plus:
970 case Token::star:
971 if (lhs)
972 emitError("missing right operand of binary operator");
973 else
974 emitError("missing left operand of binary operator");
975 return nullptr;
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700976 default:
977 if (lhs)
Uday Bondhugula76345202018-07-09 13:47:52 -0700978 emitError("missing right operand of binary operator");
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700979 else
980 emitError("expected affine expression");
981 return nullptr;
982 }
983}
984
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700985/// Parse affine expressions that are bare-id's, integer constants,
986/// parenthetical affine expressions, and affine op expressions that are a
987/// composition of those.
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -0700988///
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700989/// All binary op's associate from left to right.
990///
991/// {add, sub} have lower precedence than {mul, div, and mod}.
992///
Uday Bondhugula76345202018-07-09 13:47:52 -0700993/// Add, sub'are themselves at the same precedence level. Mul, floordiv,
994/// ceildiv, and mod are at the same higher precedence level. Negation has
995/// higher precedence than any binary op.
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700996///
997/// llhs: the affine expression appearing on the left of the one being parsed.
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700998/// This function will return ((llhs llhsOp lhs) op rhs) if llhs is non null,
999/// and lhs op rhs otherwise; if there is no rhs, llhs llhsOp lhs is returned if
1000/// llhs is non-null; otherwise lhs is returned. This is to deal with left
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001001/// associativity.
1002///
1003/// Eg: when the expression is e1 + e2*e3 + e4, with e1 as llhs, this function
Uday Bondhugula3934d4d2018-07-09 09:00:25 -07001004/// will return the affine expr equivalent of (e1 + (e2*e3)) + e4, where (e2*e3)
1005/// will be parsed using parseAffineHighPrecOpExpr().
Chris Lattner2e595eb2018-07-10 10:08:27 -07001006AffineExpr *AffineMapParser::parseAffineLowPrecOpExpr(AffineExpr *llhs,
1007 AffineLowPrecOp llhsOp) {
Uday Bondhugula76345202018-07-09 13:47:52 -07001008 AffineExpr *lhs;
Chris Lattner2e595eb2018-07-10 10:08:27 -07001009 if (!(lhs = parseAffineOperandExpr(llhs)))
Uday Bondhugula3934d4d2018-07-09 09:00:25 -07001010 return nullptr;
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001011
1012 // Found an LHS. Deal with the ops.
Chris Lattner2e595eb2018-07-10 10:08:27 -07001013 if (AffineLowPrecOp lOp = consumeIfLowPrecOp()) {
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001014 if (llhs) {
Chris Lattner158e0a3e2018-07-08 20:51:38 -07001015 AffineExpr *sum = getBinaryAffineOpExpr(llhsOp, llhs, lhs);
Chris Lattner2e595eb2018-07-10 10:08:27 -07001016 return parseAffineLowPrecOpExpr(sum, lOp);
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001017 }
1018 // No LLHS, get RHS and form the expression.
Chris Lattner2e595eb2018-07-10 10:08:27 -07001019 return parseAffineLowPrecOpExpr(lhs, lOp);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -07001020 }
Uday Bondhugula851b8fd2018-07-20 14:57:21 -07001021 auto opLoc = getToken().getLoc();
Chris Lattner2e595eb2018-07-10 10:08:27 -07001022 if (AffineHighPrecOp hOp = consumeIfHighPrecOp()) {
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001023 // We have a higher precedence op here. Get the rhs operand for the llhs
1024 // through parseAffineHighPrecOpExpr.
Uday Bondhugula851b8fd2018-07-20 14:57:21 -07001025 AffineExpr *highRes = parseAffineHighPrecOpExpr(lhs, hOp, opLoc);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -07001026 if (!highRes)
1027 return nullptr;
Chris Lattner2e595eb2018-07-10 10:08:27 -07001028
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001029 // If llhs is null, the product forms the first operand of the yet to be
Uday Bondhugula3934d4d2018-07-09 09:00:25 -07001030 // found expression. If non-null, the op to associate with llhs is llhsOp.
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001031 AffineExpr *expr =
Chris Lattner158e0a3e2018-07-08 20:51:38 -07001032 llhs ? getBinaryAffineOpExpr(llhsOp, llhs, highRes) : highRes;
Chris Lattner2e595eb2018-07-10 10:08:27 -07001033
Uday Bondhugula3934d4d2018-07-09 09:00:25 -07001034 // Recurse for subsequent low prec op's after the affine high prec op
1035 // expression.
Chris Lattner2e595eb2018-07-10 10:08:27 -07001036 if (AffineLowPrecOp nextOp = consumeIfLowPrecOp())
1037 return parseAffineLowPrecOpExpr(expr, nextOp);
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001038 return expr;
1039 }
Uday Bondhugula3934d4d2018-07-09 09:00:25 -07001040 // Last operand in the expression list.
1041 if (llhs)
1042 return getBinaryAffineOpExpr(llhsOp, llhs, lhs);
1043 // No llhs, 'lhs' itself is the expression.
1044 return lhs;
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001045}
1046
1047/// Parse an affine expression.
Uday Bondhugula3934d4d2018-07-09 09:00:25 -07001048/// affine-expr ::= `(` affine-expr `)`
1049/// | `-` affine-expr
1050/// | affine-expr `+` affine-expr
1051/// | affine-expr `-` affine-expr
1052/// | affine-expr `*` affine-expr
1053/// | affine-expr `floordiv` affine-expr
1054/// | affine-expr `ceildiv` affine-expr
1055/// | affine-expr `mod` affine-expr
1056/// | bare-id
1057/// | integer-literal
1058///
1059/// Additional conditions are checked depending on the production. For eg., one
1060/// of the operands for `*` has to be either constant/symbolic; the second
1061/// operand for floordiv, ceildiv, and mod has to be a positive integer.
Chris Lattner2e595eb2018-07-10 10:08:27 -07001062AffineExpr *AffineMapParser::parseAffineExpr() {
1063 return parseAffineLowPrecOpExpr(nullptr, AffineLowPrecOp::LNoOp);
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001064}
1065
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001066/// Parse a dim or symbol from the lists appearing before the actual expressions
Chris Lattner2e595eb2018-07-10 10:08:27 -07001067/// of the affine map. Update our state to store the dimensional/symbolic
Chris Lattner413db6a2018-07-25 12:55:50 -07001068/// identifier.
1069ParseResult AffineMapParser::parseIdentifierDefinition(AffineExpr *idExpr) {
Chris Lattner48af7d12018-07-09 19:05:38 -07001070 if (getToken().isNot(Token::bare_identifier))
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001071 return emitError("expected bare identifier");
Chris Lattner413db6a2018-07-25 12:55:50 -07001072
1073 auto name = getTokenSpelling();
1074 for (auto entry : dimsAndSymbols) {
1075 if (entry.first == name)
1076 return emitError("redefinition of identifier '" + Twine(name) + "'");
1077 }
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001078 consumeToken(Token::bare_identifier);
Chris Lattner413db6a2018-07-25 12:55:50 -07001079
1080 dimsAndSymbols.push_back({name, idExpr});
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001081 return ParseSuccess;
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001082}
1083
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001084/// Parse the list of symbolic identifiers to an affine map.
Chris Lattner413db6a2018-07-25 12:55:50 -07001085ParseResult AffineMapParser::parseSymbolIdList(unsigned &numSymbols) {
1086 consumeToken(Token::l_square);
1087 auto parseElt = [&]() -> ParseResult {
1088 auto *symbol = AffineSymbolExpr::get(numSymbols++, getContext());
1089 return parseIdentifierDefinition(symbol);
1090 };
Chris Lattner85ee1512018-07-25 11:15:20 -07001091 return parseCommaSeparatedListUntil(Token::r_square, parseElt);
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001092}
1093
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001094/// Parse the list of dimensional identifiers to an affine map.
Chris Lattner413db6a2018-07-25 12:55:50 -07001095ParseResult AffineMapParser::parseDimIdList(unsigned &numDims) {
Chris Lattnerf7702a62018-07-23 17:30:01 -07001096 if (parseToken(Token::l_paren,
1097 "expected '(' at start of dimensional identifiers list"))
1098 return ParseFailure;
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001099
Chris Lattner413db6a2018-07-25 12:55:50 -07001100 auto parseElt = [&]() -> ParseResult {
1101 auto *dimension = AffineDimExpr::get(numDims++, getContext());
1102 return parseIdentifierDefinition(dimension);
1103 };
Chris Lattner40746442018-07-21 14:32:09 -07001104 return parseCommaSeparatedListUntil(Token::r_paren, parseElt);
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001105}
1106
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001107/// Parse an affine map definition.
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001108///
Uday Bondhugula3934d4d2018-07-09 09:00:25 -07001109/// affine-map-inline ::= dim-and-symbol-id-lists `->` multi-dim-affine-expr
1110/// (`size` `(` dim-size (`,` dim-size)* `)`)?
1111/// dim-size ::= affine-expr | `min` `(` affine-expr ( `,` affine-expr)+ `)`
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001112///
Uday Bondhugula3934d4d2018-07-09 09:00:25 -07001113/// multi-dim-affine-expr ::= `(` affine-expr (`,` affine-expr)* `)
Chris Lattner2e595eb2018-07-10 10:08:27 -07001114AffineMap *AffineMapParser::parseAffineMapInline() {
Chris Lattner413db6a2018-07-25 12:55:50 -07001115 unsigned numDims = 0, numSymbols = 0;
1116
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001117 // List of dimensional identifiers.
Chris Lattner413db6a2018-07-25 12:55:50 -07001118 if (parseDimIdList(numDims))
Chris Lattner7121b802018-07-04 20:45:39 -07001119 return nullptr;
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001120
1121 // Symbols are optional.
Chris Lattner85ee1512018-07-25 11:15:20 -07001122 if (getToken().is(Token::l_square)) {
Chris Lattner413db6a2018-07-25 12:55:50 -07001123 if (parseSymbolIdList(numSymbols))
Chris Lattner7121b802018-07-04 20:45:39 -07001124 return nullptr;
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001125 }
Chris Lattnerf7702a62018-07-23 17:30:01 -07001126
1127 if (parseToken(Token::arrow, "expected '->' or '['") ||
1128 parseToken(Token::l_paren, "expected '(' at start of affine map range"))
Chris Lattner7121b802018-07-04 20:45:39 -07001129 return nullptr;
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001130
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001131 SmallVector<AffineExpr *, 4> exprs;
1132 auto parseElt = [&]() -> ParseResult {
Chris Lattner2e595eb2018-07-10 10:08:27 -07001133 auto *elt = parseAffineExpr();
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001134 ParseResult res = elt ? ParseSuccess : ParseFailure;
1135 exprs.push_back(elt);
1136 return res;
1137 };
1138
1139 // Parse a multi-dimensional affine expression (a comma-separated list of 1-d
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001140 // affine expressions); the list cannot be empty.
1141 // Grammar: multi-dim-affine-expr ::= `(` affine-expr (`,` affine-expr)* `)
Chris Lattner40746442018-07-21 14:32:09 -07001142 if (parseCommaSeparatedListUntil(Token::r_paren, parseElt, false))
Chris Lattner7121b802018-07-04 20:45:39 -07001143 return nullptr;
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001144
Uday Bondhugula0115dbb2018-07-11 21:31:07 -07001145 // Parse optional range sizes.
Uday Bondhugula1e500b42018-07-12 18:04:04 -07001146 // range-sizes ::= (`size` `(` dim-size (`,` dim-size)* `)`)?
1147 // dim-size ::= affine-expr | `min` `(` affine-expr (`,` affine-expr)+ `)`
1148 // TODO(bondhugula): support for min of several affine expressions.
Uday Bondhugula0115dbb2018-07-11 21:31:07 -07001149 // TODO: check if sizes are non-negative whenever they are constant.
1150 SmallVector<AffineExpr *, 4> rangeSizes;
1151 if (consumeIf(Token::kw_size)) {
1152 // Location of the l_paren token (if it exists) for error reporting later.
1153 auto loc = getToken().getLoc();
Chris Lattnerf7702a62018-07-23 17:30:01 -07001154 if (parseToken(Token::l_paren, "expected '(' at start of affine map range"))
1155 return nullptr;
Uday Bondhugula0115dbb2018-07-11 21:31:07 -07001156
1157 auto parseRangeSize = [&]() -> ParseResult {
Chris Lattner413db6a2018-07-25 12:55:50 -07001158 auto loc = getToken().getLoc();
Uday Bondhugula0115dbb2018-07-11 21:31:07 -07001159 auto *elt = parseAffineExpr();
Chris Lattner413db6a2018-07-25 12:55:50 -07001160 if (!elt)
1161 return ParseFailure;
1162
1163 if (!elt->isSymbolicOrConstant())
1164 return emitError(loc,
1165 "size expressions cannot refer to dimension values");
1166
Uday Bondhugula0115dbb2018-07-11 21:31:07 -07001167 rangeSizes.push_back(elt);
Chris Lattner413db6a2018-07-25 12:55:50 -07001168 return ParseSuccess;
Uday Bondhugula0115dbb2018-07-11 21:31:07 -07001169 };
1170
Chris Lattner40746442018-07-21 14:32:09 -07001171 if (parseCommaSeparatedListUntil(Token::r_paren, parseRangeSize, false))
Uday Bondhugula0115dbb2018-07-11 21:31:07 -07001172 return nullptr;
1173 if (exprs.size() > rangeSizes.size())
1174 return (emitError(loc, "fewer range sizes than range expressions"),
1175 nullptr);
1176 if (exprs.size() < rangeSizes.size())
1177 return (emitError(loc, "more range sizes than range expressions"),
1178 nullptr);
1179 }
1180
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001181 // Parsed a valid affine map.
Chris Lattner413db6a2018-07-25 12:55:50 -07001182 return builder.getAffineMap(numDims, numSymbols, exprs, rangeSizes);
MLIR Teamf85a6262018-06-27 11:03:08 -07001183}
1184
Chris Lattner2e595eb2018-07-10 10:08:27 -07001185AffineMap *Parser::parseAffineMapInline() {
1186 return AffineMapParser(state).parseAffineMapInline();
1187}
1188
MLIR Team718c82f2018-07-16 09:45:22 -07001189AffineMap *Parser::parseAffineMapReference() {
1190 if (getToken().is(Token::hash_identifier)) {
1191 // Parse affine map identifier and verify that it exists.
1192 StringRef affineMapId = getTokenSpelling().drop_front();
1193 if (getState().affineMapDefinitions.count(affineMapId) == 0)
1194 return (emitError("undefined affine map id '" + affineMapId + "'"),
1195 nullptr);
1196 consumeToken(Token::hash_identifier);
1197 return getState().affineMapDefinitions[affineMapId];
1198 }
1199 // Try to parse inline affine map.
1200 return parseAffineMapInline();
1201}
1202
MLIR Teamf85a6262018-06-27 11:03:08 -07001203//===----------------------------------------------------------------------===//
Chris Lattner7f9cc272018-07-19 08:35:28 -07001204// FunctionParser
Chris Lattner4c95a502018-06-23 16:03:42 -07001205//===----------------------------------------------------------------------===//
Chris Lattnere79379a2018-06-22 10:39:19 -07001206
Chris Lattner7f9cc272018-07-19 08:35:28 -07001207namespace {
1208/// This class contains parser state that is common across CFG and ML functions,
1209/// notably for dealing with operations and SSA values.
1210class FunctionParser : public Parser {
1211public:
1212 FunctionParser(ParserState &state) : Parser(state) {}
1213
Chris Lattner6119d382018-07-20 18:41:34 -07001214 /// After the function is finished parsing, this function checks to see if
1215 /// there are any remaining issues.
Chris Lattner40746442018-07-21 14:32:09 -07001216 ParseResult finalizeFunction(Function *func, SMLoc loc);
Chris Lattner6119d382018-07-20 18:41:34 -07001217
1218 /// This represents a use of an SSA value in the program. The first two
1219 /// entries in the tuple are the name and result number of a reference. The
1220 /// third is the location of the reference, which is used in case this ends up
1221 /// being a use of an undefined value.
1222 struct SSAUseInfo {
1223 StringRef name; // Value name, e.g. %42 or %abc
1224 unsigned number; // Number, specified with #12
1225 SMLoc loc; // Location of first definition or use.
1226 };
Chris Lattner7f9cc272018-07-19 08:35:28 -07001227
1228 /// Given a reference to an SSA value and its type, return a reference. This
1229 /// returns null on failure.
1230 SSAValue *resolveSSAUse(SSAUseInfo useInfo, Type *type);
1231
1232 /// Register a definition of a value with the symbol table.
1233 ParseResult addDefinition(SSAUseInfo useInfo, SSAValue *value);
1234
1235 // SSA parsing productions.
1236 ParseResult parseSSAUse(SSAUseInfo &result);
Chris Lattner40746442018-07-21 14:32:09 -07001237 ParseResult parseOptionalSSAUseList(SmallVectorImpl<SSAUseInfo> &results);
James Molloy61a656c2018-07-22 15:45:24 -07001238
1239 template <typename ResultType>
1240 ResultType parseSSADefOrUseAndType(
1241 const std::function<ResultType(SSAUseInfo, Type *)> &action);
1242
1243 SSAValue *parseSSAUseAndType() {
1244 return parseSSADefOrUseAndType<SSAValue *>(
1245 [&](SSAUseInfo useInfo, Type *type) -> SSAValue * {
1246 return resolveSSAUse(useInfo, type);
1247 });
1248 }
Chris Lattner40746442018-07-21 14:32:09 -07001249
1250 template <typename ValueTy>
Chris Lattner7f9cc272018-07-19 08:35:28 -07001251 ParseResult
Chris Lattner2c402672018-07-23 11:56:17 -07001252 parseOptionalSSAUseAndTypeList(SmallVectorImpl<ValueTy *> &results,
1253 bool isParenthesized);
Chris Lattner7f9cc272018-07-19 08:35:28 -07001254
1255 // Operations
1256 ParseResult parseOperation(const CreateOperationFunction &createOpFunc);
Chris Lattner85ee1512018-07-25 11:15:20 -07001257 Operation *parseVerboseOperation(const CreateOperationFunction &createOpFunc);
1258 Operation *parseCustomOperation(const CreateOperationFunction &createOpFunc);
Chris Lattner7f9cc272018-07-19 08:35:28 -07001259
1260private:
1261 /// This keeps track of all of the SSA values we are tracking, indexed by
Chris Lattner6119d382018-07-20 18:41:34 -07001262 /// their name. This has one entry per result number.
1263 llvm::StringMap<SmallVector<std::pair<SSAValue *, SMLoc>, 1>> values;
1264
1265 /// These are all of the placeholders we've made along with the location of
1266 /// their first reference, to allow checking for use of undefined values.
1267 DenseMap<SSAValue *, SMLoc> forwardReferencePlaceholders;
1268
1269 SSAValue *createForwardReferencePlaceholder(SMLoc loc, Type *type);
1270
1271 /// Return true if this is a forward reference.
1272 bool isForwardReferencePlaceholder(SSAValue *value) {
1273 return forwardReferencePlaceholders.count(value);
1274 }
Chris Lattner7f9cc272018-07-19 08:35:28 -07001275};
1276} // end anonymous namespace
1277
Chris Lattner6119d382018-07-20 18:41:34 -07001278/// Create and remember a new placeholder for a forward reference.
1279SSAValue *FunctionParser::createForwardReferencePlaceholder(SMLoc loc,
1280 Type *type) {
1281 // Forward references are always created as instructions, even in ML
1282 // functions, because we just need something with a def/use chain.
1283 //
1284 // We create these placeholders as having an empty name, which we know cannot
1285 // be created through normal user input, allowing us to distinguish them.
1286 auto name = Identifier::get("placeholder", getContext());
1287 auto *inst = OperationInst::create(name, /*operands*/ {}, type, /*attrs*/ {},
1288 getContext());
1289 forwardReferencePlaceholders[inst->getResult(0)] = loc;
1290 return inst->getResult(0);
1291}
1292
Chris Lattner7f9cc272018-07-19 08:35:28 -07001293/// Given an unbound reference to an SSA value and its type, return a the value
1294/// it specifies. This returns null on failure.
1295SSAValue *FunctionParser::resolveSSAUse(SSAUseInfo useInfo, Type *type) {
Chris Lattner6119d382018-07-20 18:41:34 -07001296 auto &entries = values[useInfo.name];
1297
Chris Lattner7f9cc272018-07-19 08:35:28 -07001298 // If we have already seen a value of this name, return it.
Chris Lattner6119d382018-07-20 18:41:34 -07001299 if (useInfo.number < entries.size() && entries[useInfo.number].first) {
1300 auto *result = entries[useInfo.number].first;
Chris Lattner7f9cc272018-07-19 08:35:28 -07001301 // Check that the type matches the other uses.
Chris Lattner7f9cc272018-07-19 08:35:28 -07001302 if (result->getType() == type)
1303 return result;
1304
Chris Lattner6119d382018-07-20 18:41:34 -07001305 emitError(useInfo.loc, "use of value '" + useInfo.name.str() +
1306 "' expects different type than prior uses");
1307 emitError(entries[useInfo.number].second, "prior use here");
Chris Lattner7f9cc272018-07-19 08:35:28 -07001308 return nullptr;
1309 }
1310
Chris Lattner6119d382018-07-20 18:41:34 -07001311 // Make sure we have enough slots for this.
1312 if (entries.size() <= useInfo.number)
1313 entries.resize(useInfo.number + 1);
1314
1315 // If the value has already been defined and this is an overly large result
1316 // number, diagnose that.
1317 if (entries[0].first && !isForwardReferencePlaceholder(entries[0].first))
1318 return (emitError(useInfo.loc, "reference to invalid result number"),
1319 nullptr);
1320
1321 // Otherwise, this is a forward reference. Create a placeholder and remember
1322 // that we did so.
1323 auto *result = createForwardReferencePlaceholder(useInfo.loc, type);
1324 entries[useInfo.number].first = result;
1325 entries[useInfo.number].second = useInfo.loc;
1326 return result;
Chris Lattner7f9cc272018-07-19 08:35:28 -07001327}
1328
1329/// Register a definition of a value with the symbol table.
1330ParseResult FunctionParser::addDefinition(SSAUseInfo useInfo, SSAValue *value) {
Chris Lattner6119d382018-07-20 18:41:34 -07001331 auto &entries = values[useInfo.name];
Chris Lattner7f9cc272018-07-19 08:35:28 -07001332
Chris Lattner6119d382018-07-20 18:41:34 -07001333 // Make sure there is a slot for this value.
1334 if (entries.size() <= useInfo.number)
1335 entries.resize(useInfo.number + 1);
Chris Lattner7f9cc272018-07-19 08:35:28 -07001336
Chris Lattner6119d382018-07-20 18:41:34 -07001337 // If we already have an entry for this, check to see if it was a definition
1338 // or a forward reference.
1339 if (auto *existing = entries[useInfo.number].first) {
1340 if (!isForwardReferencePlaceholder(existing)) {
1341 emitError(useInfo.loc,
1342 "redefinition of SSA value '" + useInfo.name + "'");
1343 return emitError(entries[useInfo.number].second,
1344 "previously defined here");
1345 }
1346
1347 // If it was a forward reference, update everything that used it to use the
1348 // actual definition instead, delete the forward ref, and remove it from our
1349 // set of forward references we track.
1350 existing->replaceAllUsesWith(value);
1351 existing->getDefiningInst()->destroy();
1352 forwardReferencePlaceholders.erase(existing);
1353 }
1354
1355 entries[useInfo.number].first = value;
1356 entries[useInfo.number].second = useInfo.loc;
1357 return ParseSuccess;
1358}
1359
1360/// After the function is finished parsing, this function checks to see if
1361/// there are any remaining issues.
Chris Lattner40746442018-07-21 14:32:09 -07001362ParseResult FunctionParser::finalizeFunction(Function *func, SMLoc loc) {
Chris Lattner6119d382018-07-20 18:41:34 -07001363 // Check for any forward references that are left. If we find any, error out.
1364 if (!forwardReferencePlaceholders.empty()) {
1365 SmallVector<std::pair<const char *, SSAValue *>, 4> errors;
1366 // Iteration over the map isn't determinstic, so sort by source location.
1367 for (auto entry : forwardReferencePlaceholders)
1368 errors.push_back({entry.second.getPointer(), entry.first});
1369 llvm::array_pod_sort(errors.begin(), errors.end());
1370
1371 for (auto entry : errors)
1372 emitError(SMLoc::getFromPointer(entry.first),
1373 "use of undeclared SSA value name");
1374 return ParseFailure;
1375 }
1376
Chris Lattner40746442018-07-21 14:32:09 -07001377 // Run the verifier on this function. If an error is detected, report it.
1378 std::string errorString;
1379 if (func->verify(&errorString))
1380 return emitError(loc, errorString);
1381
Chris Lattner6119d382018-07-20 18:41:34 -07001382 return ParseSuccess;
Chris Lattner7f9cc272018-07-19 08:35:28 -07001383}
1384
Chris Lattner78276e32018-07-07 15:48:26 -07001385/// Parse a SSA operand for an instruction or statement.
1386///
James Molloy61a656c2018-07-22 15:45:24 -07001387/// ssa-use ::= ssa-id
Chris Lattner78276e32018-07-07 15:48:26 -07001388///
Chris Lattner7f9cc272018-07-19 08:35:28 -07001389ParseResult FunctionParser::parseSSAUse(SSAUseInfo &result) {
Chris Lattner6119d382018-07-20 18:41:34 -07001390 result.name = getTokenSpelling();
1391 result.number = 0;
1392 result.loc = getToken().getLoc();
Chris Lattnerf7702a62018-07-23 17:30:01 -07001393 if (parseToken(Token::percent_identifier, "expected SSA operand"))
1394 return ParseFailure;
Chris Lattner6119d382018-07-20 18:41:34 -07001395
1396 // If we have an affine map ID, it is a result number.
1397 if (getToken().is(Token::hash_identifier)) {
1398 if (auto value = getToken().getHashIdentifierNumber())
1399 result.number = value.getValue();
1400 else
1401 return emitError("invalid SSA value result number");
1402 consumeToken(Token::hash_identifier);
1403 }
1404
Chris Lattner7f9cc272018-07-19 08:35:28 -07001405 return ParseSuccess;
Chris Lattner78276e32018-07-07 15:48:26 -07001406}
1407
1408/// Parse a (possibly empty) list of SSA operands.
1409///
1410/// ssa-use-list ::= ssa-use (`,` ssa-use)*
1411/// ssa-use-list-opt ::= ssa-use-list?
1412///
Chris Lattner7f9cc272018-07-19 08:35:28 -07001413ParseResult
Chris Lattner40746442018-07-21 14:32:09 -07001414FunctionParser::parseOptionalSSAUseList(SmallVectorImpl<SSAUseInfo> &results) {
Chris Lattner85ee1512018-07-25 11:15:20 -07001415 if (getToken().isNot(Token::percent_identifier))
Chris Lattner40746442018-07-21 14:32:09 -07001416 return ParseSuccess;
1417 return parseCommaSeparatedList([&]() -> ParseResult {
Chris Lattner7f9cc272018-07-19 08:35:28 -07001418 SSAUseInfo result;
1419 if (parseSSAUse(result))
1420 return ParseFailure;
1421 results.push_back(result);
1422 return ParseSuccess;
1423 });
Chris Lattner78276e32018-07-07 15:48:26 -07001424}
1425
1426/// Parse an SSA use with an associated type.
1427///
1428/// ssa-use-and-type ::= ssa-use `:` type
James Molloy61a656c2018-07-22 15:45:24 -07001429template <typename ResultType>
1430ResultType FunctionParser::parseSSADefOrUseAndType(
1431 const std::function<ResultType(SSAUseInfo, Type *)> &action) {
Chris Lattner78276e32018-07-07 15:48:26 -07001432
Chris Lattnerf7702a62018-07-23 17:30:01 -07001433 SSAUseInfo useInfo;
1434 if (parseSSAUse(useInfo) ||
1435 parseToken(Token::colon, "expected ':' and type for SSA operand"))
1436 return nullptr;
Chris Lattner78276e32018-07-07 15:48:26 -07001437
Chris Lattner7f9cc272018-07-19 08:35:28 -07001438 auto *type = parseType();
1439 if (!type)
1440 return nullptr;
Chris Lattner78276e32018-07-07 15:48:26 -07001441
James Molloy61a656c2018-07-22 15:45:24 -07001442 return action(useInfo, type);
Chris Lattner78276e32018-07-07 15:48:26 -07001443}
1444
Chris Lattner2c402672018-07-23 11:56:17 -07001445/// Parse a (possibly empty) list of SSA operands, followed by a colon, then
1446/// followed by a type list. If hasParens is true, then the operands are
1447/// surrounded by parens.
Chris Lattner78276e32018-07-07 15:48:26 -07001448///
Chris Lattner2c402672018-07-23 11:56:17 -07001449/// ssa-use-and-type-list[parens]
1450/// ::= `(` ssa-use-list `)` ':' type-list-no-parens
1451///
1452/// ssa-use-and-type-list[!parens]
1453/// ::= ssa-use-list ':' type-list-no-parens
Chris Lattner78276e32018-07-07 15:48:26 -07001454///
Chris Lattner40746442018-07-21 14:32:09 -07001455template <typename ValueTy>
Chris Lattner7f9cc272018-07-19 08:35:28 -07001456ParseResult FunctionParser::parseOptionalSSAUseAndTypeList(
Chris Lattner2c402672018-07-23 11:56:17 -07001457 SmallVectorImpl<ValueTy *> &results, bool isParenthesized) {
1458
1459 // If we are in the parenthesized form and no paren exists, then we succeed
1460 // with an empty list.
1461 if (isParenthesized && !consumeIf(Token::l_paren))
Chris Lattner40746442018-07-21 14:32:09 -07001462 return ParseSuccess;
1463
Chris Lattner2c402672018-07-23 11:56:17 -07001464 SmallVector<SSAUseInfo, 4> valueIDs;
1465 if (parseOptionalSSAUseList(valueIDs))
Chris Lattner7f9cc272018-07-19 08:35:28 -07001466 return ParseFailure;
Chris Lattner2c402672018-07-23 11:56:17 -07001467
1468 if (isParenthesized && !consumeIf(Token::r_paren))
1469 return emitError("expected ')' in operand list");
1470
1471 // If there were no operands, then there is no colon or type lists.
1472 if (valueIDs.empty())
1473 return ParseSuccess;
1474
Chris Lattner2c402672018-07-23 11:56:17 -07001475 SmallVector<Type *, 4> types;
Chris Lattnerf7702a62018-07-23 17:30:01 -07001476 if (parseToken(Token::colon, "expected ':' in operand list") ||
1477 parseTypeListNoParens(types))
Chris Lattner2c402672018-07-23 11:56:17 -07001478 return ParseFailure;
1479
1480 if (valueIDs.size() != types.size())
1481 return emitError("expected " + Twine(valueIDs.size()) +
1482 " types to match operand list");
1483
1484 results.reserve(valueIDs.size());
1485 for (unsigned i = 0, e = valueIDs.size(); i != e; ++i) {
1486 if (auto *value = resolveSSAUse(valueIDs[i], types[i]))
1487 results.push_back(cast<ValueTy>(value));
1488 else
1489 return ParseFailure;
1490 }
1491
1492 return ParseSuccess;
Chris Lattner78276e32018-07-07 15:48:26 -07001493}
1494
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001495/// Parse the CFG or MLFunc operation.
1496///
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001497/// operation ::=
1498/// (ssa-id `=`)? string '(' ssa-use-list? ')' attribute-dict?
1499/// `:` function-type
1500///
1501ParseResult
Chris Lattner7f9cc272018-07-19 08:35:28 -07001502FunctionParser::parseOperation(const CreateOperationFunction &createOpFunc) {
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001503 auto loc = getToken().getLoc();
1504
1505 StringRef resultID;
1506 if (getToken().is(Token::percent_identifier)) {
Chris Lattner7f9cc272018-07-19 08:35:28 -07001507 resultID = getTokenSpelling();
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001508 consumeToken(Token::percent_identifier);
Chris Lattnerf7702a62018-07-23 17:30:01 -07001509 if (parseToken(Token::equal, "expected '=' after SSA name"))
1510 return ParseFailure;
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001511 }
1512
Chris Lattner85ee1512018-07-25 11:15:20 -07001513 Operation *op;
1514 if (getToken().is(Token::bare_identifier) || getToken().isKeyword())
1515 op = parseCustomOperation(createOpFunc);
1516 else if (getToken().is(Token::string))
1517 op = parseVerboseOperation(createOpFunc);
1518 else
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001519 return emitError("expected operation name in quotes");
1520
Chris Lattner85ee1512018-07-25 11:15:20 -07001521 // If parsing of the basic operation failed, then this whole thing fails.
Chris Lattner7f9cc272018-07-19 08:35:28 -07001522 if (!op)
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001523 return ParseFailure;
1524
1525 // We just parsed an operation. If it is a recognized one, verify that it
1526 // is structurally as we expect. If not, produce an error with a reasonable
1527 // source location.
Chris Lattner7f9cc272018-07-19 08:35:28 -07001528 if (auto *opInfo = op->getAbstractOperation(builder.getContext())) {
1529 if (auto error = opInfo->verifyInvariants(op))
Chris Lattner9361fb32018-07-24 08:34:58 -07001530 return emitError(loc, Twine("'") + op->getName().str() + "' op " + error);
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001531 }
1532
Chris Lattner7f9cc272018-07-19 08:35:28 -07001533 // If the instruction had a name, register it.
1534 if (!resultID.empty()) {
1535 // FIXME: Add result infra to handle Stmt results as well to make this
1536 // generic.
1537 if (auto *inst = dyn_cast<OperationInst>(op)) {
Chris Lattnerf8cce872018-07-20 09:28:54 -07001538 if (inst->getNumResults() == 0)
Chris Lattner7f9cc272018-07-19 08:35:28 -07001539 return emitError(loc, "cannot name an operation with no results");
1540
Chris Lattner6119d382018-07-20 18:41:34 -07001541 for (unsigned i = 0, e = inst->getNumResults(); i != e; ++i)
1542 addDefinition({resultID, i, loc}, inst->getResult(i));
Chris Lattner7f9cc272018-07-19 08:35:28 -07001543 }
1544 }
1545
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001546 return ParseSuccess;
1547}
Chris Lattnere79379a2018-06-22 10:39:19 -07001548
Chris Lattner85ee1512018-07-25 11:15:20 -07001549Operation *FunctionParser::parseVerboseOperation(
1550 const CreateOperationFunction &createOpFunc) {
1551 auto name = getToken().getStringValue();
1552 if (name.empty())
1553 return (emitError("empty operation name is invalid"), nullptr);
1554
1555 consumeToken(Token::string);
1556
1557 // Parse the operand list.
1558 SmallVector<SSAUseInfo, 8> operandInfos;
1559
1560 if (parseToken(Token::l_paren, "expected '(' to start operand list") ||
1561 parseOptionalSSAUseList(operandInfos) ||
1562 parseToken(Token::r_paren, "expected ')' to end operand list")) {
1563 return nullptr;
1564 }
1565
1566 SmallVector<NamedAttribute, 4> attributes;
1567 if (getToken().is(Token::l_brace)) {
1568 if (parseAttributeDict(attributes))
1569 return nullptr;
1570 }
1571
1572 if (parseToken(Token::colon, "expected ':' followed by instruction type"))
1573 return nullptr;
1574
1575 auto typeLoc = getToken().getLoc();
1576 auto type = parseType();
1577 if (!type)
1578 return nullptr;
1579 auto fnType = dyn_cast<FunctionType>(type);
1580 if (!fnType)
1581 return (emitError(typeLoc, "expected function type"), nullptr);
1582
1583 // Check that we have the right number of types for the operands.
1584 auto operandTypes = fnType->getInputs();
1585 if (operandTypes.size() != operandInfos.size()) {
1586 auto plural = "s"[operandInfos.size() == 1];
1587 return (emitError(typeLoc, "expected " + llvm::utostr(operandInfos.size()) +
1588 " operand type" + plural + " but had " +
1589 llvm::utostr(operandTypes.size())),
1590 nullptr);
1591 }
1592
1593 // Resolve all of the operands.
1594 SmallVector<SSAValue *, 8> operands;
1595 for (unsigned i = 0, e = operandInfos.size(); i != e; ++i) {
1596 operands.push_back(resolveSSAUse(operandInfos[i], operandTypes[i]));
1597 if (!operands.back())
1598 return nullptr;
1599 }
1600
1601 auto nameId = builder.getIdentifier(name);
1602 return createOpFunc(nameId, operands, fnType->getResults(), attributes);
1603}
1604
1605namespace {
1606class CustomOpAsmParser : public OpAsmParser {
1607public:
1608 CustomOpAsmParser(SMLoc nameLoc, StringRef opName, FunctionParser &parser)
1609 : nameLoc(nameLoc), opName(opName), parser(parser) {}
1610
1611 /// This is an internal helper to parser a colon, we don't want to expose
1612 /// this to clients.
1613 bool internalParseColon(llvm::SMLoc *loc) {
1614 if (loc)
1615 *loc = parser.getToken().getLoc();
1616 return parser.parseToken(Token::colon, "expected ':'");
1617 }
1618
1619 //===--------------------------------------------------------------------===//
1620 // High level parsing methods.
1621 //===--------------------------------------------------------------------===//
1622
1623 bool parseComma(llvm::SMLoc *loc = nullptr) override {
1624 if (loc)
1625 *loc = parser.getToken().getLoc();
1626 return parser.parseToken(Token::comma, "expected ','");
1627 }
1628
1629 bool parseColonType(Type *&result, llvm::SMLoc *loc = nullptr) override {
1630 return internalParseColon(loc) || !(result = parser.parseType());
1631 }
1632
1633 bool parseColonTypeList(SmallVectorImpl<Type *> &result,
1634 llvm::SMLoc *loc = nullptr) override {
1635 if (internalParseColon(loc))
1636 return true;
1637
1638 do {
1639 if (auto *type = parser.parseType())
1640 result.push_back(type);
1641 else
1642 return true;
1643
1644 } while (parser.consumeIf(Token::comma));
1645 return false;
1646 }
1647
1648 bool parseAttribute(Attribute *&result, llvm::SMLoc *loc = nullptr) override {
1649 if (loc)
1650 *loc = parser.getToken().getLoc();
1651 result = parser.parseAttribute();
1652 return result == nullptr;
1653 }
1654
1655 bool parseOperand(OperandType &result) override {
1656 FunctionParser::SSAUseInfo useInfo;
1657 if (parser.parseSSAUse(useInfo))
1658 return true;
1659
1660 result = {useInfo.loc, useInfo.name, useInfo.number};
1661 return false;
1662 }
1663
1664 bool parseOperandList(SmallVectorImpl<OperandType> &result,
1665 int requiredOperandCount = -1,
1666 Delimeter delimeter = Delimeter::NoDelimeter) override {
1667 auto startLoc = parser.getToken().getLoc();
1668
1669 // Handle delimeters.
1670 switch (delimeter) {
1671 case Delimeter::NoDelimeter:
1672 break;
1673 case Delimeter::ParenDelimeter:
1674 if (parser.parseToken(Token::l_paren, "expected '(' in operand list"))
1675 return true;
1676 break;
1677 case Delimeter::SquareDelimeter:
1678 if (parser.parseToken(Token::l_square, "expected '[' in operand list"))
1679 return true;
1680 break;
1681 }
1682
1683 // Check for zero operands.
1684 if (parser.getToken().is(Token::percent_identifier)) {
1685 do {
1686 OperandType operand;
1687 if (parseOperand(operand))
1688 return true;
1689 result.push_back(operand);
1690 } while (parser.consumeIf(Token::comma));
1691 }
1692
1693 // Handle delimeters.
1694 switch (delimeter) {
1695 case Delimeter::NoDelimeter:
1696 break;
1697 case Delimeter::ParenDelimeter:
1698 if (parser.parseToken(Token::r_paren, "expected ')' in operand list"))
1699 return true;
1700 break;
1701 case Delimeter::SquareDelimeter:
1702 if (parser.parseToken(Token::r_square, "expected ']' in operand list"))
1703 return true;
1704 break;
1705 }
1706
1707 if (requiredOperandCount != -1 && result.size() != requiredOperandCount)
1708 emitError(startLoc,
1709 "expected " + Twine(requiredOperandCount) + " operands");
1710 return false;
1711 }
1712
1713 //===--------------------------------------------------------------------===//
1714 // Methods for interacting with the parser
1715 //===--------------------------------------------------------------------===//
1716
1717 Builder &getBuilder() const override { return parser.builder; }
1718
1719 llvm::SMLoc getNameLoc() const override { return nameLoc; }
1720
1721 bool resolveOperand(OperandType operand, Type *type,
1722 SSAValue *&result) override {
1723 FunctionParser::SSAUseInfo operandInfo = {operand.name, operand.number,
1724 operand.location};
1725 result = parser.resolveSSAUse(operandInfo, type);
1726 return result == nullptr;
1727 }
1728
1729 /// Emit a diagnostic at the specified location.
1730 void emitError(llvm::SMLoc loc, const Twine &message) override {
1731 parser.emitError(loc, "custom op '" + Twine(opName) + "' " + message);
1732 emittedError = true;
1733 }
1734
1735 bool didEmitError() const { return emittedError; }
1736
1737private:
1738 SMLoc nameLoc;
1739 StringRef opName;
1740 FunctionParser &parser;
1741 bool emittedError = false;
1742};
1743} // end anonymous namespace.
1744
1745Operation *FunctionParser::parseCustomOperation(
1746 const CreateOperationFunction &createOpFunc) {
1747 auto opLoc = getToken().getLoc();
1748 auto opName = getTokenSpelling();
1749 CustomOpAsmParser opAsmParser(opLoc, opName, *this);
1750
1751 auto *opDefinition = getOperationSet().lookup(opName);
1752 if (!opDefinition) {
1753 opAsmParser.emitError(opLoc, "is unknown");
1754 return nullptr;
1755 }
1756
1757 consumeToken();
1758
1759 // Have the op implementation take a crack and parsing this.
1760 auto result = opDefinition->parseAssembly(&opAsmParser);
1761
1762 // If it emitted an error, we failed.
1763 if (opAsmParser.didEmitError())
1764 return nullptr;
1765
1766 // Otherwise, we succeeded. Use the state it parsed as our op information.
1767 auto nameId = builder.getIdentifier(opName);
1768 return createOpFunc(nameId, result.operands, result.types, result.attributes);
1769}
1770
Chris Lattner48af7d12018-07-09 19:05:38 -07001771//===----------------------------------------------------------------------===//
1772// CFG Functions
1773//===----------------------------------------------------------------------===//
Chris Lattnere79379a2018-06-22 10:39:19 -07001774
Chris Lattner4c95a502018-06-23 16:03:42 -07001775namespace {
Chris Lattner48af7d12018-07-09 19:05:38 -07001776/// This is a specialized parser for CFGFunction's, maintaining the state
1777/// transient to their bodies.
Chris Lattner7f9cc272018-07-19 08:35:28 -07001778class CFGFunctionParser : public FunctionParser {
Chris Lattner158e0a3e2018-07-08 20:51:38 -07001779public:
Chris Lattner2e595eb2018-07-10 10:08:27 -07001780 CFGFunctionParser(ParserState &state, CFGFunction *function)
Chris Lattner7f9cc272018-07-19 08:35:28 -07001781 : FunctionParser(state), function(function), builder(function) {}
Chris Lattner2e595eb2018-07-10 10:08:27 -07001782
1783 ParseResult parseFunctionBody();
1784
1785private:
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001786 CFGFunction *function;
James Molloy0ff71542018-07-23 16:56:32 -07001787 llvm::StringMap<std::pair<BasicBlock *, SMLoc>> blocksByName;
Chris Lattner48af7d12018-07-09 19:05:38 -07001788
1789 /// This builder intentionally shadows the builder in the base class, with a
1790 /// more specific builder type.
Chris Lattner158e0a3e2018-07-08 20:51:38 -07001791 CFGFuncBuilder builder;
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001792
Chris Lattner4c95a502018-06-23 16:03:42 -07001793 /// Get the basic block with the specified name, creating it if it doesn't
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001794 /// already exist. The location specified is the point of use, which allows
1795 /// us to diagnose references to blocks that are not defined precisely.
1796 BasicBlock *getBlockNamed(StringRef name, SMLoc loc) {
1797 auto &blockAndLoc = blocksByName[name];
1798 if (!blockAndLoc.first) {
Chris Lattner3a467cc2018-07-01 20:28:00 -07001799 blockAndLoc.first = new BasicBlock();
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001800 blockAndLoc.second = loc;
Chris Lattner4c95a502018-06-23 16:03:42 -07001801 }
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001802 return blockAndLoc.first;
Chris Lattner4c95a502018-06-23 16:03:42 -07001803 }
Chris Lattner48af7d12018-07-09 19:05:38 -07001804
James Molloy61a656c2018-07-22 15:45:24 -07001805 ParseResult
1806 parseOptionalBasicBlockArgList(SmallVectorImpl<BBArgument *> &results,
1807 BasicBlock *owner);
James Molloy4f788372018-07-24 15:01:27 -07001808 ParseResult parseBranchBlockAndUseList(BasicBlock *&block,
1809 SmallVectorImpl<CFGValue *> &values);
James Molloy61a656c2018-07-22 15:45:24 -07001810
Chris Lattner48af7d12018-07-09 19:05:38 -07001811 ParseResult parseBasicBlock();
1812 OperationInst *parseCFGOperation();
1813 TerminatorInst *parseTerminator();
Chris Lattner4c95a502018-06-23 16:03:42 -07001814};
1815} // end anonymous namespace
1816
James Molloy61a656c2018-07-22 15:45:24 -07001817/// Parse a (possibly empty) list of SSA operands with types as basic block
Chris Lattner2c402672018-07-23 11:56:17 -07001818/// arguments.
James Molloy61a656c2018-07-22 15:45:24 -07001819///
1820/// ssa-id-and-type-list ::= ssa-id-and-type (`,` ssa-id-and-type)*
1821///
1822ParseResult CFGFunctionParser::parseOptionalBasicBlockArgList(
1823 SmallVectorImpl<BBArgument *> &results, BasicBlock *owner) {
1824 if (getToken().is(Token::r_brace))
1825 return ParseSuccess;
1826
1827 return parseCommaSeparatedList([&]() -> ParseResult {
1828 auto type = parseSSADefOrUseAndType<Type *>(
1829 [&](SSAUseInfo useInfo, Type *type) -> Type * {
1830 BBArgument *arg = owner->addArgument(type);
1831 if (addDefinition(useInfo, arg) == ParseFailure)
1832 return nullptr;
1833 return type;
1834 });
1835 return type ? ParseSuccess : ParseFailure;
1836 });
1837}
1838
Chris Lattner48af7d12018-07-09 19:05:38 -07001839ParseResult CFGFunctionParser::parseFunctionBody() {
Chris Lattner40746442018-07-21 14:32:09 -07001840 auto braceLoc = getToken().getLoc();
Chris Lattnerf7702a62018-07-23 17:30:01 -07001841 if (parseToken(Token::l_brace, "expected '{' in CFG function"))
1842 return ParseFailure;
Chris Lattner48af7d12018-07-09 19:05:38 -07001843
1844 // Make sure we have at least one block.
1845 if (getToken().is(Token::r_brace))
1846 return emitError("CFG functions must have at least one basic block");
Chris Lattner4c95a502018-06-23 16:03:42 -07001847
1848 // Parse the list of blocks.
1849 while (!consumeIf(Token::r_brace))
Chris Lattner48af7d12018-07-09 19:05:38 -07001850 if (parseBasicBlock())
Chris Lattner4c95a502018-06-23 16:03:42 -07001851 return ParseFailure;
1852
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001853 // Verify that all referenced blocks were defined. Iteration over a
1854 // StringMap isn't determinstic, but this is good enough for our purposes.
Chris Lattner48af7d12018-07-09 19:05:38 -07001855 for (auto &elt : blocksByName) {
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001856 auto *bb = elt.second.first;
Chris Lattner3a467cc2018-07-01 20:28:00 -07001857 if (!bb->getFunction())
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001858 return emitError(elt.second.second,
James Molloy0ff71542018-07-23 16:56:32 -07001859 "reference to an undefined basic block '" + elt.first() +
1860 "'");
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001861 }
1862
Chris Lattnera8e47672018-07-25 14:08:16 -07001863 getModule()->getFunctions().push_back(function);
Chris Lattner6119d382018-07-20 18:41:34 -07001864
Chris Lattner40746442018-07-21 14:32:09 -07001865 return finalizeFunction(function, braceLoc);
Chris Lattner4c95a502018-06-23 16:03:42 -07001866}
1867
1868/// Basic block declaration.
1869///
1870/// basic-block ::= bb-label instruction* terminator-stmt
1871/// bb-label ::= bb-id bb-arg-list? `:`
1872/// bb-id ::= bare-id
1873/// bb-arg-list ::= `(` ssa-id-and-type-list? `)`
1874///
Chris Lattner48af7d12018-07-09 19:05:38 -07001875ParseResult CFGFunctionParser::parseBasicBlock() {
1876 SMLoc nameLoc = getToken().getLoc();
1877 auto name = getTokenSpelling();
Chris Lattnerf7702a62018-07-23 17:30:01 -07001878 if (parseToken(Token::bare_identifier, "expected basic block name"))
1879 return ParseFailure;
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001880
Chris Lattner48af7d12018-07-09 19:05:38 -07001881 auto *block = getBlockNamed(name, nameLoc);
Chris Lattner4c95a502018-06-23 16:03:42 -07001882
1883 // If this block has already been parsed, then this is a redefinition with the
1884 // same block name.
Chris Lattner3a467cc2018-07-01 20:28:00 -07001885 if (block->getFunction())
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001886 return emitError(nameLoc, "redefinition of block '" + name.str() + "'");
1887
Chris Lattner78276e32018-07-07 15:48:26 -07001888 // If an argument list is present, parse it.
1889 if (consumeIf(Token::l_paren)) {
James Molloy61a656c2018-07-22 15:45:24 -07001890 SmallVector<BBArgument *, 8> bbArgs;
Chris Lattnerf7702a62018-07-23 17:30:01 -07001891 if (parseOptionalBasicBlockArgList(bbArgs, block) ||
1892 parseToken(Token::r_paren, "expected ')' to end argument list"))
Chris Lattner78276e32018-07-07 15:48:26 -07001893 return ParseFailure;
Chris Lattner78276e32018-07-07 15:48:26 -07001894 }
Chris Lattner4c95a502018-06-23 16:03:42 -07001895
James Molloy61a656c2018-07-22 15:45:24 -07001896 // Add the block to the function.
1897 function->push_back(block);
1898
Chris Lattnerf7702a62018-07-23 17:30:01 -07001899 if (parseToken(Token::colon, "expected ':' after basic block name"))
1900 return ParseFailure;
Chris Lattner4c95a502018-06-23 16:03:42 -07001901
Chris Lattner158e0a3e2018-07-08 20:51:38 -07001902 // Set the insertion point to the block we want to insert new operations into.
Chris Lattner48af7d12018-07-09 19:05:38 -07001903 builder.setInsertionPoint(block);
Chris Lattner158e0a3e2018-07-08 20:51:38 -07001904
Chris Lattner7f9cc272018-07-19 08:35:28 -07001905 auto createOpFunc = [&](Identifier name, ArrayRef<SSAValue *> operands,
1906 ArrayRef<Type *> resultTypes,
1907 ArrayRef<NamedAttribute> attrs) -> Operation * {
1908 SmallVector<CFGValue *, 8> cfgOperands;
1909 cfgOperands.reserve(operands.size());
1910 for (auto *op : operands)
1911 cfgOperands.push_back(cast<CFGValue>(op));
1912 return builder.createOperation(name, cfgOperands, resultTypes, attrs);
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001913 };
1914
Chris Lattnered65a732018-06-28 20:45:33 -07001915 // Parse the list of operations that make up the body of the block.
James Molloy4f788372018-07-24 15:01:27 -07001916 while (getToken().isNot(Token::kw_return, Token::kw_br, Token::kw_cond_br)) {
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001917 if (parseOperation(createOpFunc))
Chris Lattnered65a732018-06-28 20:45:33 -07001918 return ParseFailure;
1919 }
Chris Lattner4c95a502018-06-23 16:03:42 -07001920
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001921 if (!parseTerminator())
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001922 return ParseFailure;
Chris Lattner4c95a502018-06-23 16:03:42 -07001923
1924 return ParseSuccess;
1925}
1926
James Molloy4f788372018-07-24 15:01:27 -07001927ParseResult CFGFunctionParser::parseBranchBlockAndUseList(
1928 BasicBlock *&block, SmallVectorImpl<CFGValue *> &values) {
1929 block = getBlockNamed(getTokenSpelling(), getToken().getLoc());
1930 if (parseToken(Token::bare_identifier, "expected basic block name"))
1931 return ParseFailure;
1932
1933 if (!consumeIf(Token::l_paren))
1934 return ParseSuccess;
1935 if (parseOptionalSSAUseAndTypeList(values, /*isParenthesized*/ false) ||
1936 parseToken(Token::r_paren, "expected ')' to close argument list"))
1937 return ParseFailure;
1938 return ParseSuccess;
1939}
1940
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001941/// Parse the terminator instruction for a basic block.
1942///
1943/// terminator-stmt ::= `br` bb-id branch-use-list?
Chris Lattner1604e472018-07-23 08:42:19 -07001944/// branch-use-list ::= `(` ssa-use-list `)` ':' type-list-no-parens
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001945/// terminator-stmt ::=
1946/// `cond_br` ssa-use `,` bb-id branch-use-list? `,` bb-id branch-use-list?
1947/// terminator-stmt ::= `return` ssa-use-and-type-list?
1948///
Chris Lattner48af7d12018-07-09 19:05:38 -07001949TerminatorInst *CFGFunctionParser::parseTerminator() {
1950 switch (getToken().getKind()) {
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001951 default:
Chris Lattner3a467cc2018-07-01 20:28:00 -07001952 return (emitError("expected terminator at end of basic block"), nullptr);
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001953
Chris Lattner40746442018-07-21 14:32:09 -07001954 case Token::kw_return: {
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001955 consumeToken(Token::kw_return);
Chris Lattner40746442018-07-21 14:32:09 -07001956
Chris Lattner2c402672018-07-23 11:56:17 -07001957 // Parse any operands.
1958 SmallVector<CFGValue *, 8> operands;
1959 if (parseOptionalSSAUseAndTypeList(operands, /*isParenthesized*/ false))
1960 return nullptr;
1961 return builder.createReturnInst(operands);
Chris Lattner40746442018-07-21 14:32:09 -07001962 }
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001963
1964 case Token::kw_br: {
1965 consumeToken(Token::kw_br);
James Molloy4f788372018-07-24 15:01:27 -07001966 BasicBlock *destBB;
1967 SmallVector<CFGValue *, 4> values;
1968 if (parseBranchBlockAndUseList(destBB, values))
Chris Lattnerf7702a62018-07-23 17:30:01 -07001969 return nullptr;
Chris Lattner1604e472018-07-23 08:42:19 -07001970 auto branch = builder.createBranchInst(destBB);
James Molloy4f788372018-07-24 15:01:27 -07001971 branch->addOperands(values);
Chris Lattner1604e472018-07-23 08:42:19 -07001972 return branch;
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001973 }
James Molloy4f788372018-07-24 15:01:27 -07001974
1975 case Token::kw_cond_br: {
1976 consumeToken(Token::kw_cond_br);
1977 SSAUseInfo ssaUse;
1978 if (parseSSAUse(ssaUse))
1979 return nullptr;
1980 auto *cond = resolveSSAUse(ssaUse, builder.getIntegerType(1));
1981 if (!cond)
1982 return (emitError("expected type was boolean (i1)"), nullptr);
1983 if (parseToken(Token::comma, "expected ',' in conditional branch"))
1984 return nullptr;
1985
1986 BasicBlock *trueBlock;
1987 SmallVector<CFGValue *, 4> trueOperands;
1988 if (parseBranchBlockAndUseList(trueBlock, trueOperands))
1989 return nullptr;
1990
1991 if (parseToken(Token::comma, "expected ',' in conditional branch"))
1992 return nullptr;
1993
1994 BasicBlock *falseBlock;
1995 SmallVector<CFGValue *, 4> falseOperands;
1996 if (parseBranchBlockAndUseList(falseBlock, falseOperands))
1997 return nullptr;
1998
1999 auto branch = builder.createCondBranchInst(cast<CFGValue>(cond), trueBlock,
2000 falseBlock);
2001 branch->addTrueOperands(trueOperands);
2002 branch->addFalseOperands(falseOperands);
2003 return branch;
2004 }
Chris Lattnerf6d80a02018-06-24 11:18:29 -07002005 }
2006}
2007
Chris Lattner48af7d12018-07-09 19:05:38 -07002008//===----------------------------------------------------------------------===//
2009// ML Functions
2010//===----------------------------------------------------------------------===//
2011
2012namespace {
2013/// Refined parser for MLFunction bodies.
Chris Lattner7f9cc272018-07-19 08:35:28 -07002014class MLFunctionParser : public FunctionParser {
Chris Lattner48af7d12018-07-09 19:05:38 -07002015public:
Chris Lattner48af7d12018-07-09 19:05:38 -07002016 MLFunctionParser(ParserState &state, MLFunction *function)
Chris Lattner7f9cc272018-07-19 08:35:28 -07002017 : FunctionParser(state), function(function), builder(function) {}
Chris Lattner48af7d12018-07-09 19:05:38 -07002018
2019 ParseResult parseFunctionBody();
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07002020
2021private:
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07002022 MLFunction *function;
2023
2024 /// This builder intentionally shadows the builder in the base class, with a
2025 /// more specific builder type.
2026 MLFuncBuilder builder;
2027
2028 ParseResult parseForStmt();
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002029 AffineConstantExpr *parseIntConstant();
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07002030 ParseResult parseIfStmt();
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07002031 ParseResult parseElseClause(IfClause *elseClause);
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07002032 ParseResult parseStatements(StmtBlock *block);
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07002033 ParseResult parseStmtBlock(StmtBlock *block);
Chris Lattner48af7d12018-07-09 19:05:38 -07002034};
2035} // end anonymous namespace
2036
Chris Lattner48af7d12018-07-09 19:05:38 -07002037ParseResult MLFunctionParser::parseFunctionBody() {
Chris Lattner40746442018-07-21 14:32:09 -07002038 auto braceLoc = getToken().getLoc();
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07002039 // Parse statements in this function
Tatiana Shpeismanc96b5872018-06-28 17:02:32 -07002040
Chris Lattnerf7702a62018-07-23 17:30:01 -07002041 if (parseToken(Token::l_brace, "expected '{' in ML function") ||
2042 parseStatements(function)) {
2043 return ParseFailure;
2044 }
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07002045
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002046 // TODO: store return operands in the IR.
2047 SmallVector<SSAUseInfo, 4> dummyUseInfo;
Tatiana Shpeismanc96b5872018-06-28 17:02:32 -07002048
Chris Lattnerf7702a62018-07-23 17:30:01 -07002049 if (parseToken(Token::kw_return,
2050 "ML function must end with return statement") ||
2051 parseOptionalSSAUseList(dummyUseInfo) ||
2052 parseToken(Token::r_brace, "expected '}' to end mlfunc"))
2053 return ParseFailure;
Chris Lattner40746442018-07-21 14:32:09 -07002054
Chris Lattnera8e47672018-07-25 14:08:16 -07002055 getModule()->getFunctions().push_back(function);
Tatiana Shpeismanc96b5872018-06-28 17:02:32 -07002056
Chris Lattner40746442018-07-21 14:32:09 -07002057 return finalizeFunction(function, braceLoc);
Tatiana Shpeismanc96b5872018-06-28 17:02:32 -07002058}
2059
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07002060/// For statement.
2061///
Chris Lattner48af7d12018-07-09 19:05:38 -07002062/// ml-for-stmt ::= `for` ssa-id `=` lower-bound `to` upper-bound
2063/// (`step` integer-literal)? `{` ml-stmt* `}`
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07002064///
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07002065ParseResult MLFunctionParser::parseForStmt() {
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07002066 consumeToken(Token::kw_for);
2067
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002068 // Parse induction variable
2069 if (getToken().isNot(Token::percent_identifier))
2070 return emitError("expected SSA identifier for the loop variable");
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07002071
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002072 // TODO: create SSA value definition from name
2073 StringRef name = getTokenSpelling().drop_front();
2074 (void)name;
2075
2076 consumeToken(Token::percent_identifier);
2077
Chris Lattnerf7702a62018-07-23 17:30:01 -07002078 if (parseToken(Token::equal, "expected ="))
2079 return ParseFailure;
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002080
2081 // Parse loop bounds
2082 AffineConstantExpr *lowerBound = parseIntConstant();
2083 if (!lowerBound)
2084 return ParseFailure;
2085
Chris Lattnerf7702a62018-07-23 17:30:01 -07002086 if (parseToken(Token::kw_to, "expected 'to' between bounds"))
2087 return ParseFailure;
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002088
2089 AffineConstantExpr *upperBound = parseIntConstant();
2090 if (!upperBound)
2091 return ParseFailure;
2092
2093 // Parse step
2094 AffineConstantExpr *step = nullptr;
2095 if (consumeIf(Token::kw_step)) {
2096 step = parseIntConstant();
2097 if (!step)
2098 return ParseFailure;
2099 }
2100
2101 // Create for statement.
2102 ForStmt *stmt = builder.createFor(lowerBound, upperBound, step);
2103
2104 // If parsing of the for statement body fails,
2105 // MLIR contains for statement with those nested statements that have been
2106 // successfully parsed.
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07002107 if (parseStmtBlock(static_cast<StmtBlock *>(stmt)))
2108 return ParseFailure;
2109
2110 return ParseSuccess;
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07002111}
2112
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002113// This method is temporary workaround to parse simple loop bounds and
2114// step.
2115// TODO: remove this method once it's no longer used.
2116AffineConstantExpr *MLFunctionParser::parseIntConstant() {
2117 if (getToken().isNot(Token::integer))
2118 return (emitError("expected non-negative integer for now"), nullptr);
2119
2120 auto val = getToken().getUInt64IntegerValue();
2121 if (!val.hasValue() || (int64_t)val.getValue() < 0) {
2122 return (emitError("constant too large for affineint"), nullptr);
2123 }
2124 consumeToken(Token::integer);
2125 return builder.getConstantExpr((int64_t)val.getValue());
2126}
2127
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07002128/// If statement.
2129///
Chris Lattner48af7d12018-07-09 19:05:38 -07002130/// ml-if-head ::= `if` ml-if-cond `{` ml-stmt* `}`
2131/// | ml-if-head `else` `if` ml-if-cond `{` ml-stmt* `}`
2132/// ml-if-stmt ::= ml-if-head
2133/// | ml-if-head `else` `{` ml-stmt* `}`
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07002134///
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07002135ParseResult MLFunctionParser::parseIfStmt() {
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07002136 consumeToken(Token::kw_if);
Chris Lattnerf7702a62018-07-23 17:30:01 -07002137 if (parseToken(Token::l_paren, "expected ("))
2138 return ParseFailure;
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07002139
James Molloy0ff71542018-07-23 16:56:32 -07002140 // TODO: parse condition
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07002141
Chris Lattnerf7702a62018-07-23 17:30:01 -07002142 if (parseToken(Token::r_paren, "expected )"))
2143 return ParseFailure;
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07002144
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07002145 IfStmt *ifStmt = builder.createIf();
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07002146 IfClause *thenClause = ifStmt->getThenClause();
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07002147
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002148 // When parsing of an if statement body fails, the IR contains
2149 // the if statement with the portion of the body that has been
2150 // successfully parsed.
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07002151 if (parseStmtBlock(thenClause))
2152 return ParseFailure;
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07002153
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07002154 if (consumeIf(Token::kw_else)) {
Chris Lattnerf7702a62018-07-23 17:30:01 -07002155 auto *elseClause = ifStmt->createElseClause();
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07002156 if (parseElseClause(elseClause))
2157 return ParseFailure;
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07002158 }
2159
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07002160 return ParseSuccess;
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07002161}
2162
2163ParseResult MLFunctionParser::parseElseClause(IfClause *elseClause) {
2164 if (getToken().is(Token::kw_if)) {
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07002165 builder.setInsertionPoint(elseClause);
2166 return parseIfStmt();
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07002167 }
2168
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07002169 return parseStmtBlock(elseClause);
2170}
2171
2172///
2173/// Parse a list of statements ending with `return` or `}`
2174///
2175ParseResult MLFunctionParser::parseStatements(StmtBlock *block) {
Chris Lattner7f9cc272018-07-19 08:35:28 -07002176 auto createOpFunc = [&](Identifier name, ArrayRef<SSAValue *> operands,
2177 ArrayRef<Type *> resultTypes,
2178 ArrayRef<NamedAttribute> attrs) -> Operation * {
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07002179 return builder.createOperation(name, attrs);
2180 };
2181
2182 builder.setInsertionPoint(block);
2183
2184 while (getToken().isNot(Token::kw_return, Token::r_brace)) {
2185 switch (getToken().getKind()) {
2186 default:
2187 if (parseOperation(createOpFunc))
2188 return ParseFailure;
2189 break;
2190 case Token::kw_for:
2191 if (parseForStmt())
2192 return ParseFailure;
2193 break;
2194 case Token::kw_if:
2195 if (parseIfStmt())
2196 return ParseFailure;
2197 break;
2198 } // end switch
2199 }
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07002200
2201 return ParseSuccess;
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07002202}
2203
2204///
2205/// Parse `{` ml-stmt* `}`
2206///
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07002207ParseResult MLFunctionParser::parseStmtBlock(StmtBlock *block) {
Chris Lattnerf7702a62018-07-23 17:30:01 -07002208 if (parseToken(Token::l_brace, "expected '{' before statement list") ||
2209 parseStatements(block) ||
2210 parseToken(Token::r_brace,
2211 "expected '}' at the end of the statement block"))
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07002212 return ParseFailure;
2213
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07002214 return ParseSuccess;
2215}
2216
Chris Lattner4c95a502018-06-23 16:03:42 -07002217//===----------------------------------------------------------------------===//
2218// Top-level entity parsing.
2219//===----------------------------------------------------------------------===//
2220
Chris Lattner2e595eb2018-07-10 10:08:27 -07002221namespace {
2222/// This parser handles entities that are only valid at the top level of the
2223/// file.
2224class ModuleParser : public Parser {
2225public:
2226 explicit ModuleParser(ParserState &state) : Parser(state) {}
2227
2228 ParseResult parseModule();
2229
2230private:
2231 ParseResult parseAffineMapDef();
2232
2233 // Functions.
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002234 ParseResult parseMLArgumentList(SmallVectorImpl<Type *> &argTypes,
2235 SmallVectorImpl<StringRef> &argNames);
2236 ParseResult parseFunctionSignature(StringRef &name, FunctionType *&type,
2237 SmallVectorImpl<StringRef> *argNames);
Chris Lattner2e595eb2018-07-10 10:08:27 -07002238 ParseResult parseExtFunc();
2239 ParseResult parseCFGFunc();
2240 ParseResult parseMLFunc();
2241};
2242} // end anonymous namespace
2243
2244/// Affine map declaration.
2245///
2246/// affine-map-def ::= affine-map-id `=` affine-map-inline
2247///
2248ParseResult ModuleParser::parseAffineMapDef() {
2249 assert(getToken().is(Token::hash_identifier));
2250
2251 StringRef affineMapId = getTokenSpelling().drop_front();
2252
2253 // Check for redefinitions.
2254 auto *&entry = getState().affineMapDefinitions[affineMapId];
2255 if (entry)
2256 return emitError("redefinition of affine map id '" + affineMapId + "'");
2257
2258 consumeToken(Token::hash_identifier);
2259
2260 // Parse the '='
Chris Lattnerf7702a62018-07-23 17:30:01 -07002261 if (parseToken(Token::equal,
2262 "expected '=' in affine map outlined definition"))
2263 return ParseFailure;
Chris Lattner2e595eb2018-07-10 10:08:27 -07002264
2265 entry = parseAffineMapInline();
2266 if (!entry)
2267 return ParseFailure;
2268
Chris Lattner2e595eb2018-07-10 10:08:27 -07002269 return ParseSuccess;
2270}
2271
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002272/// Parse a (possibly empty) list of MLFunction arguments with types.
2273///
2274/// ml-argument ::= ssa-id `:` type
2275/// ml-argument-list ::= ml-argument (`,` ml-argument)* | /*empty*/
2276///
2277ParseResult
2278ModuleParser::parseMLArgumentList(SmallVectorImpl<Type *> &argTypes,
2279 SmallVectorImpl<StringRef> &argNames) {
Chris Lattnerf7702a62018-07-23 17:30:01 -07002280 consumeToken(Token::l_paren);
2281
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002282 auto parseElt = [&]() -> ParseResult {
2283 // Parse argument name
2284 if (getToken().isNot(Token::percent_identifier))
2285 return emitError("expected SSA identifier");
2286
2287 StringRef name = getTokenSpelling().drop_front();
2288 consumeToken(Token::percent_identifier);
2289 argNames.push_back(name);
2290
Chris Lattnerf7702a62018-07-23 17:30:01 -07002291 if (parseToken(Token::colon, "expected ':'"))
2292 return ParseFailure;
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002293
2294 // Parse argument type
2295 auto elt = parseType();
2296 if (!elt)
2297 return ParseFailure;
2298 argTypes.push_back(elt);
2299
2300 return ParseSuccess;
2301 };
2302
Chris Lattner40746442018-07-21 14:32:09 -07002303 return parseCommaSeparatedListUntil(Token::r_paren, parseElt);
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002304}
2305
Chris Lattner2e595eb2018-07-10 10:08:27 -07002306/// Parse a function signature, starting with a name and including the parameter
2307/// list.
2308///
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002309/// argument-list ::= type (`,` type)* | /*empty*/ | ml-argument-list
Chris Lattner2e595eb2018-07-10 10:08:27 -07002310/// function-signature ::= function-id `(` argument-list `)` (`->` type-list)?
2311///
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002312ParseResult
2313ModuleParser::parseFunctionSignature(StringRef &name, FunctionType *&type,
2314 SmallVectorImpl<StringRef> *argNames) {
Chris Lattner2e595eb2018-07-10 10:08:27 -07002315 if (getToken().isNot(Token::at_identifier))
2316 return emitError("expected a function identifier like '@foo'");
2317
2318 name = getTokenSpelling().drop_front();
2319 consumeToken(Token::at_identifier);
2320
2321 if (getToken().isNot(Token::l_paren))
2322 return emitError("expected '(' in function signature");
2323
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002324 SmallVector<Type *, 4> argTypes;
2325 ParseResult parseResult;
2326
2327 if (argNames)
2328 parseResult = parseMLArgumentList(argTypes, *argNames);
2329 else
2330 parseResult = parseTypeList(argTypes);
2331
2332 if (parseResult)
Chris Lattner2e595eb2018-07-10 10:08:27 -07002333 return ParseFailure;
2334
2335 // Parse the return type if present.
2336 SmallVector<Type *, 4> results;
2337 if (consumeIf(Token::arrow)) {
2338 if (parseTypeList(results))
2339 return ParseFailure;
2340 }
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002341 type = builder.getFunctionType(argTypes, results);
Chris Lattner2e595eb2018-07-10 10:08:27 -07002342 return ParseSuccess;
2343}
2344
2345/// External function declarations.
2346///
2347/// ext-func ::= `extfunc` function-signature
2348///
2349ParseResult ModuleParser::parseExtFunc() {
2350 consumeToken(Token::kw_extfunc);
2351
2352 StringRef name;
2353 FunctionType *type = nullptr;
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002354 if (parseFunctionSignature(name, type, /*arguments*/ nullptr))
Chris Lattner2e595eb2018-07-10 10:08:27 -07002355 return ParseFailure;
2356
2357 // Okay, the external function definition was parsed correctly.
Chris Lattnera8e47672018-07-25 14:08:16 -07002358 getModule()->getFunctions().push_back(new ExtFunction(name, type));
Chris Lattner2e595eb2018-07-10 10:08:27 -07002359 return ParseSuccess;
2360}
2361
2362/// CFG function declarations.
2363///
2364/// cfg-func ::= `cfgfunc` function-signature `{` basic-block+ `}`
2365///
2366ParseResult ModuleParser::parseCFGFunc() {
2367 consumeToken(Token::kw_cfgfunc);
2368
2369 StringRef name;
2370 FunctionType *type = nullptr;
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002371 if (parseFunctionSignature(name, type, /*arguments*/ nullptr))
Chris Lattner2e595eb2018-07-10 10:08:27 -07002372 return ParseFailure;
2373
2374 // Okay, the CFG function signature was parsed correctly, create the function.
2375 auto function = new CFGFunction(name, type);
2376
2377 return CFGFunctionParser(getState(), function).parseFunctionBody();
2378}
2379
2380/// ML function declarations.
2381///
2382/// ml-func ::= `mlfunc` ml-func-signature `{` ml-stmt* ml-return-stmt `}`
2383///
2384ParseResult ModuleParser::parseMLFunc() {
2385 consumeToken(Token::kw_mlfunc);
2386
2387 StringRef name;
2388 FunctionType *type = nullptr;
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002389 SmallVector<StringRef, 4> argNames;
Chris Lattner2e595eb2018-07-10 10:08:27 -07002390 // FIXME: Parse ML function signature (args + types)
2391 // by passing pointer to SmallVector<identifier> into parseFunctionSignature
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002392
2393 if (parseFunctionSignature(name, type, &argNames))
Chris Lattner2e595eb2018-07-10 10:08:27 -07002394 return ParseFailure;
2395
2396 // Okay, the ML function signature was parsed correctly, create the function.
2397 auto function = new MLFunction(name, type);
2398
2399 return MLFunctionParser(getState(), function).parseFunctionBody();
2400}
2401
Chris Lattnere79379a2018-06-22 10:39:19 -07002402/// This is the top-level module parser.
Chris Lattner2e595eb2018-07-10 10:08:27 -07002403ParseResult ModuleParser::parseModule() {
Chris Lattnere79379a2018-06-22 10:39:19 -07002404 while (1) {
Chris Lattner48af7d12018-07-09 19:05:38 -07002405 switch (getToken().getKind()) {
Chris Lattnere79379a2018-06-22 10:39:19 -07002406 default:
2407 emitError("expected a top level entity");
Chris Lattner2e595eb2018-07-10 10:08:27 -07002408 return ParseFailure;
Chris Lattnere79379a2018-06-22 10:39:19 -07002409
Uday Bondhugula015cbb12018-07-03 20:16:08 -07002410 // If we got to the end of the file, then we're done.
Chris Lattnere79379a2018-06-22 10:39:19 -07002411 case Token::eof:
Chris Lattner2e595eb2018-07-10 10:08:27 -07002412 return ParseSuccess;
Chris Lattnere79379a2018-06-22 10:39:19 -07002413
2414 // If we got an error token, then the lexer already emitted an error, just
2415 // stop. Someday we could introduce error recovery if there was demand for
2416 // it.
2417 case Token::error:
Chris Lattner2e595eb2018-07-10 10:08:27 -07002418 return ParseFailure;
2419
2420 case Token::hash_identifier:
2421 if (parseAffineMapDef())
2422 return ParseFailure;
2423 break;
Chris Lattnere79379a2018-06-22 10:39:19 -07002424
2425 case Token::kw_extfunc:
Chris Lattner2e595eb2018-07-10 10:08:27 -07002426 if (parseExtFunc())
2427 return ParseFailure;
Chris Lattnere79379a2018-06-22 10:39:19 -07002428 break;
2429
Chris Lattner4c95a502018-06-23 16:03:42 -07002430 case Token::kw_cfgfunc:
Chris Lattner2e595eb2018-07-10 10:08:27 -07002431 if (parseCFGFunc())
2432 return ParseFailure;
MLIR Teamf85a6262018-06-27 11:03:08 -07002433 break;
Chris Lattner4c95a502018-06-23 16:03:42 -07002434
Tatiana Shpeismanc96b5872018-06-28 17:02:32 -07002435 case Token::kw_mlfunc:
Chris Lattner2e595eb2018-07-10 10:08:27 -07002436 if (parseMLFunc())
2437 return ParseFailure;
Tatiana Shpeismanc96b5872018-06-28 17:02:32 -07002438 break;
Chris Lattnere79379a2018-06-22 10:39:19 -07002439 }
2440 }
2441}
2442
2443//===----------------------------------------------------------------------===//
2444
Jacques Pienaar7b829702018-07-03 13:24:09 -07002445void mlir::defaultErrorReporter(const llvm::SMDiagnostic &error) {
2446 const auto &sourceMgr = *error.getSourceMgr();
2447 sourceMgr.PrintMessage(error.getLoc(), error.getKind(), error.getMessage());
2448}
2449
Chris Lattnere79379a2018-06-22 10:39:19 -07002450/// This parses the file specified by the indicated SourceMgr and returns an
2451/// MLIR module if it was valid. If not, it emits diagnostics and returns null.
Jacques Pienaar9c411be2018-06-24 19:17:35 -07002452Module *mlir::parseSourceFile(llvm::SourceMgr &sourceMgr, MLIRContext *context,
Jacques Pienaar7b829702018-07-03 13:24:09 -07002453 SMDiagnosticHandlerTy errorReporter) {
Chris Lattner2e595eb2018-07-10 10:08:27 -07002454 // This is the result module we are parsing into.
2455 std::unique_ptr<Module> module(new Module(context));
2456
2457 ParserState state(sourceMgr, module.get(),
Jacques Pienaar0bffd862018-07-11 13:26:23 -07002458 errorReporter ? errorReporter : defaultErrorReporter);
Chris Lattner2e595eb2018-07-10 10:08:27 -07002459 if (ModuleParser(state).parseModule())
2460 return nullptr;
Chris Lattner21e67f62018-07-06 10:46:19 -07002461
2462 // Make sure the parse module has no other structural problems detected by the
2463 // verifier.
Chris Lattner2e595eb2018-07-10 10:08:27 -07002464 module->verify();
2465 return module.release();
Chris Lattnere79379a2018-06-22 10:39:19 -07002466}