blob: 3d5c9088a403e42f9250c5a358b727fd99ade818 [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"
30#include "mlir/IR/OperationSet.h"
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -070031#include "mlir/IR/Statements.h"
Chris Lattnerf7e22732018-06-22 22:03:48 -070032#include "mlir/IR/Types.h"
Chris Lattnere79379a2018-06-22 10:39:19 -070033#include "llvm/Support/SourceMgr.h"
34using namespace mlir;
35using llvm::SourceMgr;
Chris Lattner4c95a502018-06-23 16:03:42 -070036using llvm::SMLoc;
Chris Lattnere79379a2018-06-22 10:39:19 -070037
Chris Lattnerf7e22732018-06-22 22:03:48 -070038/// Simple enum to make code read better in cases that would otherwise return a
39/// bool value. Failure is "true" in a boolean context.
Chris Lattnere79379a2018-06-22 10:39:19 -070040enum ParseResult {
41 ParseSuccess,
42 ParseFailure
43};
44
Chris Lattner48af7d12018-07-09 19:05:38 -070045namespace {
46class Parser;
47
48/// This class refers to all of the state maintained globally by the parser,
49/// such as the current lexer position etc. The Parser base class provides
50/// methods to access this.
51class ParserState {
Chris Lattnered65a732018-06-28 20:45:33 -070052public:
Chris Lattner2e595eb2018-07-10 10:08:27 -070053 ParserState(llvm::SourceMgr &sourceMgr, Module *module,
Chris Lattner48af7d12018-07-09 19:05:38 -070054 SMDiagnosticHandlerTy errorReporter)
Chris Lattner2e595eb2018-07-10 10:08:27 -070055 : context(module->getContext()), module(module),
56 lex(sourceMgr, errorReporter), curToken(lex.lexToken()),
Jacques Pienaard4c784e2018-07-11 00:07:36 -070057 errorReporter(errorReporter) {}
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 Lattner48af7d12018-07-09 19:05:38 -070082};
83} // end anonymous namespace
MLIR Teamf85a6262018-06-27 11:03:08 -070084
Chris Lattner48af7d12018-07-09 19:05:38 -070085namespace {
86
Chris Lattner3b2ef762018-07-18 15:31:25 -070087typedef std::function<Operation *(Identifier, ArrayRef<Type *>,
88 ArrayRef<NamedAttribute>)>
Tatiana Shpeisman565b9642018-07-16 11:47:09 -070089 CreateOperationFunction;
90
Chris Lattner48af7d12018-07-09 19:05:38 -070091/// This class implement support for parsing global entities like types and
92/// shared entities like SSA names. It is intended to be subclassed by
93/// specialized subparsers that include state, e.g. when a local symbol table.
94class Parser {
95public:
Chris Lattner2e595eb2018-07-10 10:08:27 -070096 Builder builder;
Chris Lattner48af7d12018-07-09 19:05:38 -070097
Chris Lattner2e595eb2018-07-10 10:08:27 -070098 Parser(ParserState &state) : builder(state.context), state(state) {}
99
100 // Helper methods to get stuff from the parser-global state.
101 ParserState &getState() const { return state; }
Chris Lattner48af7d12018-07-09 19:05:38 -0700102 MLIRContext *getContext() const { return state.context; }
Chris Lattner2e595eb2018-07-10 10:08:27 -0700103 Module *getModule() { return state.module; }
Chris Lattner48af7d12018-07-09 19:05:38 -0700104
105 /// Return the current token the parser is inspecting.
106 const Token &getToken() const { return state.curToken; }
107 StringRef getTokenSpelling() const { return state.curToken.getSpelling(); }
Chris Lattnere79379a2018-06-22 10:39:19 -0700108
109 /// Emit an error and return failure.
Chris Lattner4c95a502018-06-23 16:03:42 -0700110 ParseResult emitError(const Twine &message) {
Chris Lattner48af7d12018-07-09 19:05:38 -0700111 return emitError(state.curToken.getLoc(), message);
Chris Lattner4c95a502018-06-23 16:03:42 -0700112 }
113 ParseResult emitError(SMLoc loc, const Twine &message);
Chris Lattnere79379a2018-06-22 10:39:19 -0700114
115 /// Advance the current lexer onto the next token.
116 void consumeToken() {
Chris Lattner48af7d12018-07-09 19:05:38 -0700117 assert(state.curToken.isNot(Token::eof, Token::error) &&
Chris Lattnere79379a2018-06-22 10:39:19 -0700118 "shouldn't advance past EOF or errors");
Chris Lattner48af7d12018-07-09 19:05:38 -0700119 state.curToken = state.lex.lexToken();
Chris Lattnere79379a2018-06-22 10:39:19 -0700120 }
121
122 /// Advance the current lexer onto the next token, asserting what the expected
123 /// current token is. This is preferred to the above method because it leads
124 /// to more self-documenting code with better checking.
Chris Lattner8da0c282018-06-29 11:15:56 -0700125 void consumeToken(Token::Kind kind) {
Chris Lattner48af7d12018-07-09 19:05:38 -0700126 assert(state.curToken.is(kind) && "consumed an unexpected token");
Chris Lattnere79379a2018-06-22 10:39:19 -0700127 consumeToken();
128 }
129
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700130 /// If the current token has the specified kind, consume it and return true.
131 /// If not, return false.
Chris Lattner8da0c282018-06-29 11:15:56 -0700132 bool consumeIf(Token::Kind kind) {
Chris Lattner48af7d12018-07-09 19:05:38 -0700133 if (state.curToken.isNot(kind))
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700134 return false;
135 consumeToken(kind);
136 return true;
137 }
138
MLIR Team718c82f2018-07-16 09:45:22 -0700139 ParseResult parseCommaSeparatedList(
140 Token::Kind rightToken,
141 const std::function<ParseResult()> &parseElement,
142 bool allowEmptyList = true);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700143
Chris Lattnerf7e22732018-06-22 22:03:48 -0700144 // We have two forms of parsing methods - those that return a non-null
145 // pointer on success, and those that return a ParseResult to indicate whether
146 // they returned a failure. The second class fills in by-reference arguments
147 // as the results of their action.
148
Chris Lattnere79379a2018-06-22 10:39:19 -0700149 // Type parsing.
Chris Lattnerf958bbe2018-06-29 22:08:05 -0700150 Type *parsePrimitiveType();
Chris Lattnerf7e22732018-06-22 22:03:48 -0700151 Type *parseElementType();
152 VectorType *parseVectorType();
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700153 ParseResult parseDimensionListRanked(SmallVectorImpl<int> &dimensions);
Chris Lattnerf7e22732018-06-22 22:03:48 -0700154 Type *parseTensorType();
155 Type *parseMemRefType();
156 Type *parseFunctionType();
157 Type *parseType();
158 ParseResult parseTypeList(SmallVectorImpl<Type*> &elements);
Chris Lattnere79379a2018-06-22 10:39:19 -0700159
Chris Lattner7121b802018-07-04 20:45:39 -0700160 // Attribute parsing.
161 Attribute *parseAttribute();
162 ParseResult parseAttributeDict(SmallVectorImpl<NamedAttribute> &attributes);
163
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700164 // Polyhedral structures.
Chris Lattner2e595eb2018-07-10 10:08:27 -0700165 AffineMap *parseAffineMapInline();
MLIR Team718c82f2018-07-16 09:45:22 -0700166 AffineMap *parseAffineMapReference();
MLIR Teamf85a6262018-06-27 11:03:08 -0700167
Chris Lattner78276e32018-07-07 15:48:26 -0700168 // SSA
169 ParseResult parseSSAUse();
170 ParseResult parseOptionalSSAUseList(Token::Kind endToken);
171 ParseResult parseSSAUseAndType();
172 ParseResult parseOptionalSSAUseAndTypeList(Token::Kind endToken);
173
Tatiana Shpeisman565b9642018-07-16 11:47:09 -0700174 // Operations
175 ParseResult parseOperation(const CreateOperationFunction &createOpFunc);
176
Chris Lattner48af7d12018-07-09 19:05:38 -0700177private:
178 // The Parser is subclassed and reinstantiated. Do not add additional
179 // non-trivial state here, add it to the ParserState class.
180 ParserState &state;
Chris Lattnere79379a2018-06-22 10:39:19 -0700181};
182} // end anonymous namespace
183
184//===----------------------------------------------------------------------===//
185// Helper methods.
186//===----------------------------------------------------------------------===//
187
Chris Lattner4c95a502018-06-23 16:03:42 -0700188ParseResult Parser::emitError(SMLoc loc, const Twine &message) {
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700189 // If we hit a parse error in response to a lexer error, then the lexer
Jacques Pienaar9c411be2018-06-24 19:17:35 -0700190 // already reported the error.
Chris Lattner48af7d12018-07-09 19:05:38 -0700191 if (getToken().is(Token::error))
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700192 return ParseFailure;
193
Chris Lattner48af7d12018-07-09 19:05:38 -0700194 auto &sourceMgr = state.lex.getSourceMgr();
195 state.errorReporter(sourceMgr.GetMessage(loc, SourceMgr::DK_Error, message));
Chris Lattnere79379a2018-06-22 10:39:19 -0700196 return ParseFailure;
197}
198
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700199/// Parse a comma-separated list of elements, terminated with an arbitrary
200/// token. This allows empty lists if allowEmptyList is true.
201///
202/// abstract-list ::= rightToken // if allowEmptyList == true
203/// abstract-list ::= element (',' element)* rightToken
204///
205ParseResult Parser::
Chris Lattner8da0c282018-06-29 11:15:56 -0700206parseCommaSeparatedList(Token::Kind rightToken,
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700207 const std::function<ParseResult()> &parseElement,
208 bool allowEmptyList) {
209 // Handle the empty case.
Chris Lattner48af7d12018-07-09 19:05:38 -0700210 if (getToken().is(rightToken)) {
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700211 if (!allowEmptyList)
212 return emitError("expected list element");
213 consumeToken(rightToken);
214 return ParseSuccess;
215 }
216
217 // Non-empty case starts with an element.
218 if (parseElement())
219 return ParseFailure;
220
221 // Otherwise we have a list of comma separated elements.
222 while (consumeIf(Token::comma)) {
223 if (parseElement())
224 return ParseFailure;
225 }
226
227 // Consume the end character.
228 if (!consumeIf(rightToken))
Chris Lattner8da0c282018-06-29 11:15:56 -0700229 return emitError("expected ',' or '" + Token::getTokenSpelling(rightToken) +
230 "'");
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700231
232 return ParseSuccess;
233}
Chris Lattnere79379a2018-06-22 10:39:19 -0700234
235//===----------------------------------------------------------------------===//
236// Type Parsing
237//===----------------------------------------------------------------------===//
238
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700239/// Parse the low-level fixed dtypes in the system.
240///
Chris Lattnerf958bbe2018-06-29 22:08:05 -0700241/// primitive-type ::= `f16` | `bf16` | `f32` | `f64`
242/// primitive-type ::= integer-type
243/// primitive-type ::= `affineint`
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700244///
Chris Lattnerf958bbe2018-06-29 22:08:05 -0700245Type *Parser::parsePrimitiveType() {
Chris Lattner48af7d12018-07-09 19:05:38 -0700246 switch (getToken().getKind()) {
Chris Lattnerf7e22732018-06-22 22:03:48 -0700247 default:
248 return (emitError("expected type"), nullptr);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700249 case Token::kw_bf16:
250 consumeToken(Token::kw_bf16);
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700251 return builder.getBF16Type();
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700252 case Token::kw_f16:
253 consumeToken(Token::kw_f16);
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700254 return builder.getF16Type();
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700255 case Token::kw_f32:
256 consumeToken(Token::kw_f32);
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700257 return builder.getF32Type();
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700258 case Token::kw_f64:
259 consumeToken(Token::kw_f64);
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700260 return builder.getF64Type();
Chris Lattnerf958bbe2018-06-29 22:08:05 -0700261 case Token::kw_affineint:
262 consumeToken(Token::kw_affineint);
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700263 return builder.getAffineIntType();
Chris Lattnerf958bbe2018-06-29 22:08:05 -0700264 case Token::inttype: {
Chris Lattner48af7d12018-07-09 19:05:38 -0700265 auto width = getToken().getIntTypeBitwidth();
Chris Lattnerf958bbe2018-06-29 22:08:05 -0700266 if (!width.hasValue())
267 return (emitError("invalid integer width"), nullptr);
268 consumeToken(Token::inttype);
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700269 return builder.getIntegerType(width.getValue());
Chris Lattnerf958bbe2018-06-29 22:08:05 -0700270 }
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700271 }
272}
273
274/// Parse the element type of a tensor or memref type.
275///
276/// element-type ::= primitive-type | vector-type
277///
Chris Lattnerf7e22732018-06-22 22:03:48 -0700278Type *Parser::parseElementType() {
Chris Lattner48af7d12018-07-09 19:05:38 -0700279 if (getToken().is(Token::kw_vector))
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700280 return parseVectorType();
281
282 return parsePrimitiveType();
283}
284
285/// Parse a vector type.
286///
287/// vector-type ::= `vector` `<` const-dimension-list primitive-type `>`
288/// const-dimension-list ::= (integer-literal `x`)+
289///
Chris Lattnerf7e22732018-06-22 22:03:48 -0700290VectorType *Parser::parseVectorType() {
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700291 consumeToken(Token::kw_vector);
292
293 if (!consumeIf(Token::less))
Chris Lattnerf7e22732018-06-22 22:03:48 -0700294 return (emitError("expected '<' in vector type"), nullptr);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700295
Chris Lattner48af7d12018-07-09 19:05:38 -0700296 if (getToken().isNot(Token::integer))
Chris Lattnerf7e22732018-06-22 22:03:48 -0700297 return (emitError("expected dimension size in vector type"), nullptr);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700298
299 SmallVector<unsigned, 4> dimensions;
Chris Lattner48af7d12018-07-09 19:05:38 -0700300 while (getToken().is(Token::integer)) {
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700301 // Make sure this integer value is in bound and valid.
Chris Lattner48af7d12018-07-09 19:05:38 -0700302 auto dimension = getToken().getUnsignedIntegerValue();
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700303 if (!dimension.hasValue())
Chris Lattnerf7e22732018-06-22 22:03:48 -0700304 return (emitError("invalid dimension in vector type"), nullptr);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700305 dimensions.push_back(dimension.getValue());
306
307 consumeToken(Token::integer);
308
309 // Make sure we have an 'x' or something like 'xbf32'.
Chris Lattner48af7d12018-07-09 19:05:38 -0700310 if (getToken().isNot(Token::bare_identifier) ||
311 getTokenSpelling()[0] != 'x')
Chris Lattnerf7e22732018-06-22 22:03:48 -0700312 return (emitError("expected 'x' in vector dimension list"), nullptr);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700313
314 // If we had a prefix of 'x', lex the next token immediately after the 'x'.
Chris Lattner48af7d12018-07-09 19:05:38 -0700315 if (getTokenSpelling().size() != 1)
316 state.lex.resetPointer(getTokenSpelling().data() + 1);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700317
318 // Consume the 'x'.
319 consumeToken(Token::bare_identifier);
320 }
321
322 // Parse the element type.
Chris Lattnerf7e22732018-06-22 22:03:48 -0700323 auto *elementType = parsePrimitiveType();
324 if (!elementType)
325 return nullptr;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700326
327 if (!consumeIf(Token::greater))
Chris Lattnerf7e22732018-06-22 22:03:48 -0700328 return (emitError("expected '>' in vector type"), nullptr);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700329
Chris Lattnerf7e22732018-06-22 22:03:48 -0700330 return VectorType::get(dimensions, elementType);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700331}
332
333/// Parse a dimension list of a tensor or memref type. This populates the
334/// dimension list, returning -1 for the '?' dimensions.
335///
336/// dimension-list-ranked ::= (dimension `x`)*
337/// dimension ::= `?` | integer-literal
338///
339ParseResult Parser::parseDimensionListRanked(SmallVectorImpl<int> &dimensions) {
Chris Lattner48af7d12018-07-09 19:05:38 -0700340 while (getToken().isAny(Token::integer, Token::question)) {
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700341 if (consumeIf(Token::question)) {
342 dimensions.push_back(-1);
343 } else {
344 // Make sure this integer value is in bound and valid.
Chris Lattner48af7d12018-07-09 19:05:38 -0700345 auto dimension = getToken().getUnsignedIntegerValue();
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700346 if (!dimension.hasValue() || (int)dimension.getValue() < 0)
347 return emitError("invalid dimension");
348 dimensions.push_back((int)dimension.getValue());
349 consumeToken(Token::integer);
350 }
351
352 // Make sure we have an 'x' or something like 'xbf32'.
Chris Lattner48af7d12018-07-09 19:05:38 -0700353 if (getToken().isNot(Token::bare_identifier) ||
354 getTokenSpelling()[0] != 'x')
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700355 return emitError("expected 'x' in dimension list");
356
357 // If we had a prefix of 'x', lex the next token immediately after the 'x'.
Chris Lattner48af7d12018-07-09 19:05:38 -0700358 if (getTokenSpelling().size() != 1)
359 state.lex.resetPointer(getTokenSpelling().data() + 1);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700360
361 // Consume the 'x'.
362 consumeToken(Token::bare_identifier);
363 }
364
365 return ParseSuccess;
366}
367
368/// Parse a tensor type.
369///
370/// tensor-type ::= `tensor` `<` dimension-list element-type `>`
371/// dimension-list ::= dimension-list-ranked | `??`
372///
Chris Lattnerf7e22732018-06-22 22:03:48 -0700373Type *Parser::parseTensorType() {
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700374 consumeToken(Token::kw_tensor);
375
376 if (!consumeIf(Token::less))
Chris Lattnerf7e22732018-06-22 22:03:48 -0700377 return (emitError("expected '<' in tensor type"), nullptr);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700378
379 bool isUnranked;
380 SmallVector<int, 4> dimensions;
381
382 if (consumeIf(Token::questionquestion)) {
383 isUnranked = true;
384 } else {
385 isUnranked = false;
386 if (parseDimensionListRanked(dimensions))
Chris Lattnerf7e22732018-06-22 22:03:48 -0700387 return nullptr;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700388 }
389
390 // Parse the element type.
Chris Lattnerf7e22732018-06-22 22:03:48 -0700391 auto elementType = parseElementType();
392 if (!elementType)
393 return nullptr;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700394
395 if (!consumeIf(Token::greater))
Chris Lattnerf7e22732018-06-22 22:03:48 -0700396 return (emitError("expected '>' in tensor type"), nullptr);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700397
MLIR Team355ec862018-06-23 18:09:09 -0700398 if (isUnranked)
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700399 return builder.getTensorType(elementType);
400 return builder.getTensorType(dimensions, elementType);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700401}
402
403/// Parse a memref type.
404///
405/// memref-type ::= `memref` `<` dimension-list-ranked element-type
406/// (`,` semi-affine-map-composition)? (`,` memory-space)? `>`
407///
408/// semi-affine-map-composition ::= (semi-affine-map `,` )* semi-affine-map
409/// memory-space ::= integer-literal /* | TODO: address-space-id */
410///
Chris Lattnerf7e22732018-06-22 22:03:48 -0700411Type *Parser::parseMemRefType() {
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700412 consumeToken(Token::kw_memref);
413
414 if (!consumeIf(Token::less))
Chris Lattnerf7e22732018-06-22 22:03:48 -0700415 return (emitError("expected '<' in memref type"), nullptr);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700416
417 SmallVector<int, 4> dimensions;
418 if (parseDimensionListRanked(dimensions))
Chris Lattnerf7e22732018-06-22 22:03:48 -0700419 return nullptr;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700420
421 // Parse the element type.
Chris Lattnerf7e22732018-06-22 22:03:48 -0700422 auto elementType = parseElementType();
423 if (!elementType)
424 return nullptr;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700425
MLIR Team718c82f2018-07-16 09:45:22 -0700426 if (!consumeIf(Token::comma))
427 return (emitError("expected ',' in memref type"), nullptr);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700428
MLIR Team718c82f2018-07-16 09:45:22 -0700429 // Parse semi-affine-map-composition.
430 SmallVector<AffineMap*, 2> affineMapComposition;
431 unsigned memorySpace;
432 bool parsedMemorySpace = false;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700433
MLIR Team718c82f2018-07-16 09:45:22 -0700434 auto parseElt = [&]() -> ParseResult {
435 if (getToken().is(Token::integer)) {
436 // Parse memory space.
437 if (parsedMemorySpace)
438 return emitError("multiple memory spaces specified in memref type");
439 auto v = getToken().getUnsignedIntegerValue();
440 if (!v.hasValue())
441 return emitError("invalid memory space in memref type");
442 memorySpace = v.getValue();
443 consumeToken(Token::integer);
444 parsedMemorySpace = true;
445 } else {
446 // Parse affine map.
447 if (parsedMemorySpace)
448 return emitError("affine map after memory space in memref type");
449 auto* affineMap = parseAffineMapReference();
450 if (affineMap == nullptr)
451 return ParseFailure;
452 affineMapComposition.push_back(affineMap);
453 }
454 return ParseSuccess;
455 };
456
457 // Parse comma separated list of affine maps, followed by memory space.
458 if (parseCommaSeparatedList(Token::greater, parseElt,
459 /*allowEmptyList=*/false)) {
460 return nullptr;
461 }
462 // Check that MemRef type specifies at least one affine map in composition.
463 if (affineMapComposition.empty())
464 return (emitError("expected semi-affine-map in memref type"), nullptr);
465 if (!parsedMemorySpace)
466 return (emitError("expected memory space in memref type"), nullptr);
467
468 return MemRefType::get(dimensions, elementType, affineMapComposition,
469 memorySpace);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700470}
471
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700472/// Parse a function type.
473///
474/// function-type ::= type-list-parens `->` type-list
475///
Chris Lattnerf7e22732018-06-22 22:03:48 -0700476Type *Parser::parseFunctionType() {
Chris Lattner48af7d12018-07-09 19:05:38 -0700477 assert(getToken().is(Token::l_paren));
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700478
Chris Lattnerf7e22732018-06-22 22:03:48 -0700479 SmallVector<Type*, 4> arguments;
480 if (parseTypeList(arguments))
481 return nullptr;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700482
483 if (!consumeIf(Token::arrow))
Chris Lattnerf7e22732018-06-22 22:03:48 -0700484 return (emitError("expected '->' in function type"), nullptr);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700485
Chris Lattnerf7e22732018-06-22 22:03:48 -0700486 SmallVector<Type*, 4> results;
487 if (parseTypeList(results))
488 return nullptr;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700489
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700490 return builder.getFunctionType(arguments, results);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700491}
492
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700493/// Parse an arbitrary type.
494///
495/// type ::= primitive-type
496/// | vector-type
497/// | tensor-type
498/// | memref-type
499/// | function-type
500/// element-type ::= primitive-type | vector-type
501///
Chris Lattnerf7e22732018-06-22 22:03:48 -0700502Type *Parser::parseType() {
Chris Lattner48af7d12018-07-09 19:05:38 -0700503 switch (getToken().getKind()) {
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700504 case Token::kw_memref: return parseMemRefType();
505 case Token::kw_tensor: return parseTensorType();
506 case Token::kw_vector: return parseVectorType();
507 case Token::l_paren: return parseFunctionType();
508 default:
509 return parsePrimitiveType();
510 }
511}
512
513/// Parse a "type list", which is a singular type, or a parenthesized list of
514/// types.
515///
516/// type-list ::= type-list-parens | type
517/// type-list-parens ::= `(` `)`
518/// | `(` type (`,` type)* `)`
519///
Chris Lattnerf7e22732018-06-22 22:03:48 -0700520ParseResult Parser::parseTypeList(SmallVectorImpl<Type*> &elements) {
521 auto parseElt = [&]() -> ParseResult {
522 auto elt = parseType();
523 elements.push_back(elt);
524 return elt ? ParseSuccess : ParseFailure;
525 };
526
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700527 // If there is no parens, then it must be a singular type.
528 if (!consumeIf(Token::l_paren))
Chris Lattnerf7e22732018-06-22 22:03:48 -0700529 return parseElt();
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700530
Chris Lattnerf7e22732018-06-22 22:03:48 -0700531 if (parseCommaSeparatedList(Token::r_paren, parseElt))
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700532 return ParseFailure;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700533
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700534 return ParseSuccess;
535}
536
Chris Lattner4c95a502018-06-23 16:03:42 -0700537//===----------------------------------------------------------------------===//
Chris Lattner7121b802018-07-04 20:45:39 -0700538// Attribute parsing.
539//===----------------------------------------------------------------------===//
540
541
542/// Attribute parsing.
543///
544/// attribute-value ::= bool-literal
545/// | integer-literal
546/// | float-literal
547/// | string-literal
548/// | `[` (attribute-value (`,` attribute-value)*)? `]`
549///
550Attribute *Parser::parseAttribute() {
Chris Lattner48af7d12018-07-09 19:05:38 -0700551 switch (getToken().getKind()) {
Chris Lattner7121b802018-07-04 20:45:39 -0700552 case Token::kw_true:
553 consumeToken(Token::kw_true);
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700554 return builder.getBoolAttr(true);
Chris Lattner7121b802018-07-04 20:45:39 -0700555 case Token::kw_false:
556 consumeToken(Token::kw_false);
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700557 return builder.getBoolAttr(false);
Chris Lattner7121b802018-07-04 20:45:39 -0700558
559 case Token::integer: {
Chris Lattner48af7d12018-07-09 19:05:38 -0700560 auto val = getToken().getUInt64IntegerValue();
Chris Lattner7121b802018-07-04 20:45:39 -0700561 if (!val.hasValue() || (int64_t)val.getValue() < 0)
562 return (emitError("integer too large for attribute"), nullptr);
563 consumeToken(Token::integer);
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700564 return builder.getIntegerAttr((int64_t)val.getValue());
Chris Lattner7121b802018-07-04 20:45:39 -0700565 }
566
567 case Token::minus: {
568 consumeToken(Token::minus);
Chris Lattner48af7d12018-07-09 19:05:38 -0700569 if (getToken().is(Token::integer)) {
570 auto val = getToken().getUInt64IntegerValue();
Chris Lattner7121b802018-07-04 20:45:39 -0700571 if (!val.hasValue() || (int64_t)-val.getValue() >= 0)
572 return (emitError("integer too large for attribute"), nullptr);
573 consumeToken(Token::integer);
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700574 return builder.getIntegerAttr((int64_t)-val.getValue());
Chris Lattner7121b802018-07-04 20:45:39 -0700575 }
576
577 return (emitError("expected constant integer or floating point value"),
578 nullptr);
579 }
580
581 case Token::string: {
Chris Lattner48af7d12018-07-09 19:05:38 -0700582 auto val = getToken().getStringValue();
Chris Lattner7121b802018-07-04 20:45:39 -0700583 consumeToken(Token::string);
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700584 return builder.getStringAttr(val);
Chris Lattner7121b802018-07-04 20:45:39 -0700585 }
586
587 case Token::l_bracket: {
588 consumeToken(Token::l_bracket);
589 SmallVector<Attribute*, 4> elements;
590
591 auto parseElt = [&]() -> ParseResult {
592 elements.push_back(parseAttribute());
593 return elements.back() ? ParseSuccess : ParseFailure;
594 };
595
596 if (parseCommaSeparatedList(Token::r_bracket, parseElt))
597 return nullptr;
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700598 return builder.getArrayAttr(elements);
Chris Lattner7121b802018-07-04 20:45:39 -0700599 }
600 default:
601 // TODO: Handle floating point.
602 return (emitError("expected constant attribute value"), nullptr);
603 }
604}
605
Chris Lattner7121b802018-07-04 20:45:39 -0700606/// Attribute dictionary.
607///
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700608/// attribute-dict ::= `{` `}`
609/// | `{` attribute-entry (`,` attribute-entry)* `}`
610/// attribute-entry ::= bare-id `:` attribute-value
Chris Lattner7121b802018-07-04 20:45:39 -0700611///
612ParseResult Parser::parseAttributeDict(
613 SmallVectorImpl<NamedAttribute> &attributes) {
614 consumeToken(Token::l_brace);
615
616 auto parseElt = [&]() -> ParseResult {
617 // We allow keywords as attribute names.
Chris Lattner48af7d12018-07-09 19:05:38 -0700618 if (getToken().isNot(Token::bare_identifier, Token::inttype) &&
619 !getToken().isKeyword())
Chris Lattner7121b802018-07-04 20:45:39 -0700620 return emitError("expected attribute name");
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700621 auto nameId = builder.getIdentifier(getTokenSpelling());
Chris Lattner7121b802018-07-04 20:45:39 -0700622 consumeToken();
623
624 if (!consumeIf(Token::colon))
625 return emitError("expected ':' in attribute list");
626
627 auto attr = parseAttribute();
628 if (!attr) return ParseFailure;
629
630 attributes.push_back({nameId, attr});
631 return ParseSuccess;
632 };
633
634 if (parseCommaSeparatedList(Token::r_brace, parseElt))
635 return ParseFailure;
636
637 return ParseSuccess;
638}
639
640//===----------------------------------------------------------------------===//
MLIR Teamf85a6262018-06-27 11:03:08 -0700641// Polyhedral structures.
642//===----------------------------------------------------------------------===//
643
Chris Lattner2e595eb2018-07-10 10:08:27 -0700644/// Lower precedence ops (all at the same precedence level). LNoOp is false in
645/// the boolean sense.
646enum AffineLowPrecOp {
647 /// Null value.
648 LNoOp,
649 Add,
650 Sub
651};
MLIR Teamf85a6262018-06-27 11:03:08 -0700652
Chris Lattner2e595eb2018-07-10 10:08:27 -0700653/// Higher precedence ops - all at the same precedence level. HNoOp is false in
654/// the boolean sense.
655enum AffineHighPrecOp {
656 /// Null value.
657 HNoOp,
658 Mul,
659 FloorDiv,
660 CeilDiv,
661 Mod
662};
Chris Lattner7121b802018-07-04 20:45:39 -0700663
Chris Lattner2e595eb2018-07-10 10:08:27 -0700664namespace {
665/// This is a specialized parser for AffineMap's, maintaining the state
666/// transient to their bodies.
667class AffineMapParser : public Parser {
668public:
669 explicit AffineMapParser(ParserState &state) : Parser(state) {}
Chris Lattner7121b802018-07-04 20:45:39 -0700670
Chris Lattner2e595eb2018-07-10 10:08:27 -0700671 AffineMap *parseAffineMapInline();
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -0700672
Chris Lattner2e595eb2018-07-10 10:08:27 -0700673private:
674 unsigned getNumDims() const { return dims.size(); }
675 unsigned getNumSymbols() const { return symbols.size(); }
MLIR Teamf85a6262018-06-27 11:03:08 -0700676
Uday Bondhugula0115dbb2018-07-11 21:31:07 -0700677 /// Returns true if the only identifiers the parser accepts in affine
678 /// expressions are symbolic identifiers.
679 bool isPureSymbolic() const { return pureSymbolic; }
680 void setSymbolicParsing(bool val) { pureSymbolic = val; }
681
Chris Lattner2e595eb2018-07-10 10:08:27 -0700682 // Binary affine op parsing.
683 AffineLowPrecOp consumeIfLowPrecOp();
684 AffineHighPrecOp consumeIfHighPrecOp();
MLIR Teamf85a6262018-06-27 11:03:08 -0700685
Chris Lattner2e595eb2018-07-10 10:08:27 -0700686 // Identifier lists for polyhedral structures.
687 ParseResult parseDimIdList();
688 ParseResult parseSymbolIdList();
689 ParseResult parseDimOrSymbolId(bool isDim);
690
691 AffineExpr *parseAffineExpr();
692 AffineExpr *parseParentheticalExpr();
693 AffineExpr *parseNegateExpression(AffineExpr *lhs);
694 AffineExpr *parseIntegerExpr();
695 AffineExpr *parseBareIdExpr();
696
697 AffineExpr *getBinaryAffineOpExpr(AffineHighPrecOp op, AffineExpr *lhs,
698 AffineExpr *rhs);
699 AffineExpr *getBinaryAffineOpExpr(AffineLowPrecOp op, AffineExpr *lhs,
700 AffineExpr *rhs);
701 AffineExpr *parseAffineOperandExpr(AffineExpr *lhs);
702 AffineExpr *parseAffineLowPrecOpExpr(AffineExpr *llhs,
703 AffineLowPrecOp llhsOp);
704 AffineExpr *parseAffineHighPrecOpExpr(AffineExpr *llhs,
705 AffineHighPrecOp llhsOp);
706
707private:
708 // TODO(bondhugula): could just use an vector/ArrayRef and scan the numbers.
709 llvm::StringMap<unsigned> dims;
710 llvm::StringMap<unsigned> symbols;
Uday Bondhugula0115dbb2018-07-11 21:31:07 -0700711 /// True if the parser should allow only symbolic identifiers in affine
712 /// expressions.
713 bool pureSymbolic = false;
Chris Lattner2e595eb2018-07-10 10:08:27 -0700714};
715} // end anonymous namespace
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -0700716
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700717/// Create an affine binary high precedence op expression (mul's, div's, mod)
Chris Lattner2e595eb2018-07-10 10:08:27 -0700718AffineExpr *AffineMapParser::getBinaryAffineOpExpr(AffineHighPrecOp op,
719 AffineExpr *lhs,
720 AffineExpr *rhs) {
Uday Bondhugula0115dbb2018-07-11 21:31:07 -0700721 // TODO: make the error location info accurate.
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700722 switch (op) {
723 case Mul:
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700724 if (!lhs->isSymbolic() && !rhs->isSymbolic()) {
725 emitError("non-affine expression: at least one of the multiply "
726 "operands has to be either a constant or symbolic");
727 return nullptr;
728 }
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700729 return builder.getMulExpr(lhs, rhs);
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700730 case FloorDiv:
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700731 if (!rhs->isSymbolic()) {
732 emitError("non-affine expression: right operand of floordiv "
733 "has to be either a constant or symbolic");
734 return nullptr;
735 }
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700736 return builder.getFloorDivExpr(lhs, rhs);
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700737 case CeilDiv:
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700738 if (!rhs->isSymbolic()) {
739 emitError("non-affine expression: right operand of ceildiv "
740 "has to be either a constant or symbolic");
741 return nullptr;
742 }
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700743 return builder.getCeilDivExpr(lhs, rhs);
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700744 case Mod:
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700745 if (!rhs->isSymbolic()) {
746 emitError("non-affine expression: right operand of mod "
747 "has to be either a constant or symbolic");
748 return nullptr;
749 }
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700750 return builder.getModExpr(lhs, rhs);
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700751 case HNoOp:
752 llvm_unreachable("can't create affine expression for null high prec op");
753 return nullptr;
754 }
755}
756
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700757/// Create an affine binary low precedence op expression (add, sub).
Chris Lattner2e595eb2018-07-10 10:08:27 -0700758AffineExpr *AffineMapParser::getBinaryAffineOpExpr(AffineLowPrecOp op,
759 AffineExpr *lhs,
760 AffineExpr *rhs) {
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700761 switch (op) {
762 case AffineLowPrecOp::Add:
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700763 return builder.getAddExpr(lhs, rhs);
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700764 case AffineLowPrecOp::Sub:
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700765 return builder.getSubExpr(lhs, rhs);
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700766 case AffineLowPrecOp::LNoOp:
767 llvm_unreachable("can't create affine expression for null low prec op");
768 return nullptr;
769 }
770}
771
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700772/// Consume this token if it is a lower precedence affine op (there are only two
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700773/// precedence levels).
Chris Lattner2e595eb2018-07-10 10:08:27 -0700774AffineLowPrecOp AffineMapParser::consumeIfLowPrecOp() {
Chris Lattner48af7d12018-07-09 19:05:38 -0700775 switch (getToken().getKind()) {
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700776 case Token::plus:
777 consumeToken(Token::plus);
778 return AffineLowPrecOp::Add;
779 case Token::minus:
780 consumeToken(Token::minus);
781 return AffineLowPrecOp::Sub;
782 default:
783 return AffineLowPrecOp::LNoOp;
784 }
785}
786
787/// Consume this token if it is a higher precedence affine op (there are only
788/// two precedence levels)
Chris Lattner2e595eb2018-07-10 10:08:27 -0700789AffineHighPrecOp AffineMapParser::consumeIfHighPrecOp() {
Chris Lattner48af7d12018-07-09 19:05:38 -0700790 switch (getToken().getKind()) {
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700791 case Token::star:
792 consumeToken(Token::star);
793 return Mul;
794 case Token::kw_floordiv:
795 consumeToken(Token::kw_floordiv);
796 return FloorDiv;
797 case Token::kw_ceildiv:
798 consumeToken(Token::kw_ceildiv);
799 return CeilDiv;
800 case Token::kw_mod:
801 consumeToken(Token::kw_mod);
802 return Mod;
803 default:
804 return HNoOp;
805 }
806}
807
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700808/// Parse a high precedence op expression list: mul, div, and mod are high
809/// precedence binary ops, i.e., parse a
810/// expr_1 op_1 expr_2 op_2 ... expr_n
811/// where op_1, op_2 are all a AffineHighPrecOp (mul, div, mod).
812/// All affine binary ops are left associative.
813/// Given llhs, returns (llhs llhsOp lhs) op rhs, or (lhs op rhs) if llhs is
814/// null. If no rhs can be found, returns (llhs llhsOp lhs) or lhs if llhs is
815/// null.
816AffineExpr *
Chris Lattner2e595eb2018-07-10 10:08:27 -0700817AffineMapParser::parseAffineHighPrecOpExpr(AffineExpr *llhs,
818 AffineHighPrecOp llhsOp) {
819 AffineExpr *lhs = parseAffineOperandExpr(llhs);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700820 if (!lhs)
821 return nullptr;
822
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700823 // Found an LHS. Parse the remaining expression.
Chris Lattner2e595eb2018-07-10 10:08:27 -0700824 if (AffineHighPrecOp op = consumeIfHighPrecOp()) {
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700825 if (llhs) {
826 AffineExpr *expr = getBinaryAffineOpExpr(llhsOp, llhs, lhs);
827 if (!expr)
828 return nullptr;
Chris Lattner2e595eb2018-07-10 10:08:27 -0700829 return parseAffineHighPrecOpExpr(expr, op);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700830 }
831 // No LLHS, get RHS
Chris Lattner2e595eb2018-07-10 10:08:27 -0700832 return parseAffineHighPrecOpExpr(lhs, op);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700833 }
834
835 // This is the last operand in this expression.
836 if (llhs)
837 return getBinaryAffineOpExpr(llhsOp, llhs, lhs);
838
839 // No llhs, 'lhs' itself is the expression.
840 return lhs;
841}
842
843/// Parse an affine expression inside parentheses.
844///
845/// affine-expr ::= `(` affine-expr `)`
Chris Lattner2e595eb2018-07-10 10:08:27 -0700846AffineExpr *AffineMapParser::parseParentheticalExpr() {
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700847 if (!consumeIf(Token::l_paren))
848 return (emitError("expected '('"), nullptr);
Chris Lattner48af7d12018-07-09 19:05:38 -0700849 if (getToken().is(Token::r_paren))
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700850 return (emitError("no expression inside parentheses"), nullptr);
Chris Lattner2e595eb2018-07-10 10:08:27 -0700851 auto *expr = parseAffineExpr();
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700852 if (!expr)
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700853 return nullptr;
854 if (!consumeIf(Token::r_paren))
855 return (emitError("expected ')'"), nullptr);
856 return expr;
857}
858
859/// Parse the negation expression.
860///
861/// affine-expr ::= `-` affine-expr
Chris Lattner2e595eb2018-07-10 10:08:27 -0700862AffineExpr *AffineMapParser::parseNegateExpression(AffineExpr *lhs) {
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700863 if (!consumeIf(Token::minus))
864 return (emitError("expected '-'"), nullptr);
865
Chris Lattner2e595eb2018-07-10 10:08:27 -0700866 AffineExpr *operand = parseAffineOperandExpr(lhs);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700867 // Since negation has the highest precedence of all ops (including high
868 // precedence ops) but lower than parentheses, we are only going to use
869 // parseAffineOperandExpr instead of parseAffineExpr here.
870 if (!operand)
871 // Extra error message although parseAffineOperandExpr would have
872 // complained. Leads to a better diagnostic.
873 return (emitError("missing operand of negation"), nullptr);
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700874 auto *minusOne = builder.getConstantExpr(-1);
875 return builder.getMulExpr(minusOne, operand);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700876}
877
878/// Parse a bare id that may appear in an affine expression.
879///
880/// affine-expr ::= bare-id
Chris Lattner2e595eb2018-07-10 10:08:27 -0700881AffineExpr *AffineMapParser::parseBareIdExpr() {
Chris Lattner48af7d12018-07-09 19:05:38 -0700882 if (getToken().isNot(Token::bare_identifier))
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700883 return (emitError("expected bare identifier"), nullptr);
884
Chris Lattner48af7d12018-07-09 19:05:38 -0700885 StringRef sRef = getTokenSpelling();
Uday Bondhugula0115dbb2018-07-11 21:31:07 -0700886 // dims, symbols are all pairwise distinct.
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700887 if (dims.count(sRef)) {
Uday Bondhugula0115dbb2018-07-11 21:31:07 -0700888 if (isPureSymbolic())
889 return (emitError("identifier used is not a symbolic identifier"),
890 nullptr);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700891 consumeToken(Token::bare_identifier);
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700892 return builder.getDimExpr(dims.lookup(sRef));
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700893 }
Uday Bondhugula0115dbb2018-07-11 21:31:07 -0700894
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700895 if (symbols.count(sRef)) {
896 consumeToken(Token::bare_identifier);
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700897 return builder.getSymbolExpr(symbols.lookup(sRef));
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700898 }
Uday Bondhugula0115dbb2018-07-11 21:31:07 -0700899
900 return (emitError("use of undeclared identifier"), nullptr);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700901}
902
903/// Parse a positive integral constant appearing in an affine expression.
904///
905/// affine-expr ::= integer-literal
Chris Lattner2e595eb2018-07-10 10:08:27 -0700906AffineExpr *AffineMapParser::parseIntegerExpr() {
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700907 // No need to handle negative numbers separately here. They are naturally
908 // handled via the unary negation operator, although (FIXME) MININT_64 still
909 // not correctly handled.
Chris Lattner48af7d12018-07-09 19:05:38 -0700910 if (getToken().isNot(Token::integer))
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700911 return (emitError("expected integer"), nullptr);
912
Chris Lattner48af7d12018-07-09 19:05:38 -0700913 auto val = getToken().getUInt64IntegerValue();
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700914 if (!val.hasValue() || (int64_t)val.getValue() < 0) {
915 return (emitError("constant too large for affineint"), nullptr);
916 }
917 consumeToken(Token::integer);
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700918 return builder.getConstantExpr((int64_t)val.getValue());
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700919}
920
921/// Parses an expression that can be a valid operand of an affine expression.
Uday Bondhugula76345202018-07-09 13:47:52 -0700922/// lhs: if non-null, lhs is an affine expression that is the lhs of a binary
923/// operator, the rhs of which is being parsed. This is used to determine
924/// whether an error should be emitted for a missing right operand.
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700925// Eg: for an expression without parentheses (like i + j + k + l), each
926// of the four identifiers is an operand. For i + j*k + l, j*k is not an
927// operand expression, it's an op expression and will be parsed via
928// parseAffineHighPrecOpExpression(). However, for i + (j*k) + -l, (j*k) and -l
929// are valid operands that will be parsed by this function.
Chris Lattner2e595eb2018-07-10 10:08:27 -0700930AffineExpr *AffineMapParser::parseAffineOperandExpr(AffineExpr *lhs) {
Chris Lattner48af7d12018-07-09 19:05:38 -0700931 switch (getToken().getKind()) {
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700932 case Token::bare_identifier:
Chris Lattner2e595eb2018-07-10 10:08:27 -0700933 return parseBareIdExpr();
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700934 case Token::integer:
Chris Lattner2e595eb2018-07-10 10:08:27 -0700935 return parseIntegerExpr();
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700936 case Token::l_paren:
Chris Lattner2e595eb2018-07-10 10:08:27 -0700937 return parseParentheticalExpr();
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700938 case Token::minus:
Chris Lattner2e595eb2018-07-10 10:08:27 -0700939 return parseNegateExpression(lhs);
Uday Bondhugula76345202018-07-09 13:47:52 -0700940 case Token::kw_ceildiv:
941 case Token::kw_floordiv:
942 case Token::kw_mod:
943 case Token::plus:
944 case Token::star:
945 if (lhs)
946 emitError("missing right operand of binary operator");
947 else
948 emitError("missing left operand of binary operator");
949 return nullptr;
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700950 default:
951 if (lhs)
Uday Bondhugula76345202018-07-09 13:47:52 -0700952 emitError("missing right operand of binary operator");
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700953 else
954 emitError("expected affine expression");
955 return nullptr;
956 }
957}
958
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700959/// Parse affine expressions that are bare-id's, integer constants,
960/// parenthetical affine expressions, and affine op expressions that are a
961/// composition of those.
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -0700962///
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700963/// All binary op's associate from left to right.
964///
965/// {add, sub} have lower precedence than {mul, div, and mod}.
966///
Uday Bondhugula76345202018-07-09 13:47:52 -0700967/// Add, sub'are themselves at the same precedence level. Mul, floordiv,
968/// ceildiv, and mod are at the same higher precedence level. Negation has
969/// higher precedence than any binary op.
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700970///
971/// llhs: the affine expression appearing on the left of the one being parsed.
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700972/// This function will return ((llhs llhsOp lhs) op rhs) if llhs is non null,
973/// and lhs op rhs otherwise; if there is no rhs, llhs llhsOp lhs is returned if
974/// llhs is non-null; otherwise lhs is returned. This is to deal with left
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700975/// associativity.
976///
977/// Eg: when the expression is e1 + e2*e3 + e4, with e1 as llhs, this function
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700978/// will return the affine expr equivalent of (e1 + (e2*e3)) + e4, where (e2*e3)
979/// will be parsed using parseAffineHighPrecOpExpr().
Chris Lattner2e595eb2018-07-10 10:08:27 -0700980AffineExpr *AffineMapParser::parseAffineLowPrecOpExpr(AffineExpr *llhs,
981 AffineLowPrecOp llhsOp) {
Uday Bondhugula76345202018-07-09 13:47:52 -0700982 AffineExpr *lhs;
Chris Lattner2e595eb2018-07-10 10:08:27 -0700983 if (!(lhs = parseAffineOperandExpr(llhs)))
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700984 return nullptr;
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700985
986 // Found an LHS. Deal with the ops.
Chris Lattner2e595eb2018-07-10 10:08:27 -0700987 if (AffineLowPrecOp lOp = consumeIfLowPrecOp()) {
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700988 if (llhs) {
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700989 AffineExpr *sum = getBinaryAffineOpExpr(llhsOp, llhs, lhs);
Chris Lattner2e595eb2018-07-10 10:08:27 -0700990 return parseAffineLowPrecOpExpr(sum, lOp);
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700991 }
992 // No LLHS, get RHS and form the expression.
Chris Lattner2e595eb2018-07-10 10:08:27 -0700993 return parseAffineLowPrecOpExpr(lhs, lOp);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700994 }
Chris Lattner2e595eb2018-07-10 10:08:27 -0700995 if (AffineHighPrecOp hOp = consumeIfHighPrecOp()) {
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700996 // We have a higher precedence op here. Get the rhs operand for the llhs
997 // through parseAffineHighPrecOpExpr.
Chris Lattner2e595eb2018-07-10 10:08:27 -0700998 AffineExpr *highRes = parseAffineHighPrecOpExpr(lhs, hOp);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700999 if (!highRes)
1000 return nullptr;
Chris Lattner2e595eb2018-07-10 10:08:27 -07001001
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001002 // If llhs is null, the product forms the first operand of the yet to be
Uday Bondhugula3934d4d2018-07-09 09:00:25 -07001003 // found expression. If non-null, the op to associate with llhs is llhsOp.
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001004 AffineExpr *expr =
Chris Lattner158e0a3e2018-07-08 20:51:38 -07001005 llhs ? getBinaryAffineOpExpr(llhsOp, llhs, highRes) : highRes;
Chris Lattner2e595eb2018-07-10 10:08:27 -07001006
Uday Bondhugula3934d4d2018-07-09 09:00:25 -07001007 // Recurse for subsequent low prec op's after the affine high prec op
1008 // expression.
Chris Lattner2e595eb2018-07-10 10:08:27 -07001009 if (AffineLowPrecOp nextOp = consumeIfLowPrecOp())
1010 return parseAffineLowPrecOpExpr(expr, nextOp);
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001011 return expr;
1012 }
Uday Bondhugula3934d4d2018-07-09 09:00:25 -07001013 // Last operand in the expression list.
1014 if (llhs)
1015 return getBinaryAffineOpExpr(llhsOp, llhs, lhs);
1016 // No llhs, 'lhs' itself is the expression.
1017 return lhs;
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001018}
1019
1020/// Parse an affine expression.
Uday Bondhugula3934d4d2018-07-09 09:00:25 -07001021/// affine-expr ::= `(` affine-expr `)`
1022/// | `-` affine-expr
1023/// | affine-expr `+` affine-expr
1024/// | affine-expr `-` affine-expr
1025/// | affine-expr `*` affine-expr
1026/// | affine-expr `floordiv` affine-expr
1027/// | affine-expr `ceildiv` affine-expr
1028/// | affine-expr `mod` affine-expr
1029/// | bare-id
1030/// | integer-literal
1031///
1032/// Additional conditions are checked depending on the production. For eg., one
1033/// of the operands for `*` has to be either constant/symbolic; the second
1034/// operand for floordiv, ceildiv, and mod has to be a positive integer.
Chris Lattner2e595eb2018-07-10 10:08:27 -07001035AffineExpr *AffineMapParser::parseAffineExpr() {
1036 return parseAffineLowPrecOpExpr(nullptr, AffineLowPrecOp::LNoOp);
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001037}
1038
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001039/// Parse a dim or symbol from the lists appearing before the actual expressions
Chris Lattner2e595eb2018-07-10 10:08:27 -07001040/// of the affine map. Update our state to store the dimensional/symbolic
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001041/// identifier. 'dim': whether it's the dim list or symbol list that is being
1042/// parsed.
Chris Lattner2e595eb2018-07-10 10:08:27 -07001043ParseResult AffineMapParser::parseDimOrSymbolId(bool isDim) {
Chris Lattner48af7d12018-07-09 19:05:38 -07001044 if (getToken().isNot(Token::bare_identifier))
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001045 return emitError("expected bare identifier");
Chris Lattner48af7d12018-07-09 19:05:38 -07001046 auto sRef = getTokenSpelling();
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001047 consumeToken(Token::bare_identifier);
Chris Lattner2e595eb2018-07-10 10:08:27 -07001048 if (dims.count(sRef))
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001049 return emitError("dimensional identifier name reused");
Chris Lattner2e595eb2018-07-10 10:08:27 -07001050 if (symbols.count(sRef))
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001051 return emitError("symbolic identifier name reused");
Chris Lattner2e595eb2018-07-10 10:08:27 -07001052 if (isDim)
1053 dims.insert({sRef, dims.size()});
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001054 else
Chris Lattner2e595eb2018-07-10 10:08:27 -07001055 symbols.insert({sRef, symbols.size()});
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001056 return ParseSuccess;
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001057}
1058
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001059/// Parse the list of symbolic identifiers to an affine map.
Chris Lattner2e595eb2018-07-10 10:08:27 -07001060ParseResult AffineMapParser::parseSymbolIdList() {
1061 if (!consumeIf(Token::l_bracket))
1062 return emitError("expected '['");
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001063
Chris Lattner2e595eb2018-07-10 10:08:27 -07001064 auto parseElt = [&]() -> ParseResult { return parseDimOrSymbolId(false); };
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001065 return parseCommaSeparatedList(Token::r_bracket, parseElt);
1066}
1067
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001068/// Parse the list of dimensional identifiers to an affine map.
Chris Lattner2e595eb2018-07-10 10:08:27 -07001069ParseResult AffineMapParser::parseDimIdList() {
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001070 if (!consumeIf(Token::l_paren))
1071 return emitError("expected '(' at start of dimensional identifiers list");
1072
Chris Lattner2e595eb2018-07-10 10:08:27 -07001073 auto parseElt = [&]() -> ParseResult { return parseDimOrSymbolId(true); };
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001074 return parseCommaSeparatedList(Token::r_paren, parseElt);
1075}
1076
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001077/// Parse an affine map definition.
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001078///
Uday Bondhugula3934d4d2018-07-09 09:00:25 -07001079/// affine-map-inline ::= dim-and-symbol-id-lists `->` multi-dim-affine-expr
1080/// (`size` `(` dim-size (`,` dim-size)* `)`)?
1081/// dim-size ::= affine-expr | `min` `(` affine-expr ( `,` affine-expr)+ `)`
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001082///
Uday Bondhugula3934d4d2018-07-09 09:00:25 -07001083/// multi-dim-affine-expr ::= `(` affine-expr (`,` affine-expr)* `)
Chris Lattner2e595eb2018-07-10 10:08:27 -07001084AffineMap *AffineMapParser::parseAffineMapInline() {
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001085 // List of dimensional identifiers.
Chris Lattner2e595eb2018-07-10 10:08:27 -07001086 if (parseDimIdList())
Chris Lattner7121b802018-07-04 20:45:39 -07001087 return nullptr;
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001088
1089 // Symbols are optional.
Chris Lattner48af7d12018-07-09 19:05:38 -07001090 if (getToken().is(Token::l_bracket)) {
Chris Lattner2e595eb2018-07-10 10:08:27 -07001091 if (parseSymbolIdList())
Chris Lattner7121b802018-07-04 20:45:39 -07001092 return nullptr;
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001093 }
1094 if (!consumeIf(Token::arrow)) {
Chris Lattner7121b802018-07-04 20:45:39 -07001095 return (emitError("expected '->' or '['"), nullptr);
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001096 }
1097 if (!consumeIf(Token::l_paren)) {
1098 emitError("expected '(' at start of affine map range");
Chris Lattner7121b802018-07-04 20:45:39 -07001099 return nullptr;
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001100 }
1101
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001102 SmallVector<AffineExpr *, 4> exprs;
1103 auto parseElt = [&]() -> ParseResult {
Chris Lattner2e595eb2018-07-10 10:08:27 -07001104 auto *elt = parseAffineExpr();
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001105 ParseResult res = elt ? ParseSuccess : ParseFailure;
1106 exprs.push_back(elt);
1107 return res;
1108 };
1109
1110 // Parse a multi-dimensional affine expression (a comma-separated list of 1-d
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001111 // affine expressions); the list cannot be empty.
1112 // Grammar: multi-dim-affine-expr ::= `(` affine-expr (`,` affine-expr)* `)
1113 if (parseCommaSeparatedList(Token::r_paren, parseElt, false))
Chris Lattner7121b802018-07-04 20:45:39 -07001114 return nullptr;
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001115
Uday Bondhugula0115dbb2018-07-11 21:31:07 -07001116 // Parse optional range sizes.
Uday Bondhugula1e500b42018-07-12 18:04:04 -07001117 // range-sizes ::= (`size` `(` dim-size (`,` dim-size)* `)`)?
1118 // dim-size ::= affine-expr | `min` `(` affine-expr (`,` affine-expr)+ `)`
1119 // TODO(bondhugula): support for min of several affine expressions.
Uday Bondhugula0115dbb2018-07-11 21:31:07 -07001120 // TODO: check if sizes are non-negative whenever they are constant.
1121 SmallVector<AffineExpr *, 4> rangeSizes;
1122 if (consumeIf(Token::kw_size)) {
1123 // Location of the l_paren token (if it exists) for error reporting later.
1124 auto loc = getToken().getLoc();
1125 if (!consumeIf(Token::l_paren))
1126 return (emitError("expected '(' at start of affine map range"), nullptr);
1127
1128 auto parseRangeSize = [&]() -> ParseResult {
1129 auto *elt = parseAffineExpr();
1130 ParseResult res = elt ? ParseSuccess : ParseFailure;
1131 rangeSizes.push_back(elt);
1132 return res;
1133 };
1134
1135 setSymbolicParsing(true);
1136 if (parseCommaSeparatedList(Token::r_paren, parseRangeSize, false))
1137 return nullptr;
1138 if (exprs.size() > rangeSizes.size())
1139 return (emitError(loc, "fewer range sizes than range expressions"),
1140 nullptr);
1141 if (exprs.size() < rangeSizes.size())
1142 return (emitError(loc, "more range sizes than range expressions"),
1143 nullptr);
1144 }
1145
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001146 // Parsed a valid affine map.
Uday Bondhugula0115dbb2018-07-11 21:31:07 -07001147 return builder.getAffineMap(dims.size(), symbols.size(), exprs, rangeSizes);
MLIR Teamf85a6262018-06-27 11:03:08 -07001148}
1149
Chris Lattner2e595eb2018-07-10 10:08:27 -07001150AffineMap *Parser::parseAffineMapInline() {
1151 return AffineMapParser(state).parseAffineMapInline();
1152}
1153
MLIR Team718c82f2018-07-16 09:45:22 -07001154AffineMap *Parser::parseAffineMapReference() {
1155 if (getToken().is(Token::hash_identifier)) {
1156 // Parse affine map identifier and verify that it exists.
1157 StringRef affineMapId = getTokenSpelling().drop_front();
1158 if (getState().affineMapDefinitions.count(affineMapId) == 0)
1159 return (emitError("undefined affine map id '" + affineMapId + "'"),
1160 nullptr);
1161 consumeToken(Token::hash_identifier);
1162 return getState().affineMapDefinitions[affineMapId];
1163 }
1164 // Try to parse inline affine map.
1165 return parseAffineMapInline();
1166}
1167
MLIR Teamf85a6262018-06-27 11:03:08 -07001168//===----------------------------------------------------------------------===//
Chris Lattner78276e32018-07-07 15:48:26 -07001169// SSA
Chris Lattner4c95a502018-06-23 16:03:42 -07001170//===----------------------------------------------------------------------===//
Chris Lattnere79379a2018-06-22 10:39:19 -07001171
Chris Lattner78276e32018-07-07 15:48:26 -07001172/// Parse a SSA operand for an instruction or statement.
1173///
1174/// ssa-use ::= ssa-id | ssa-constant
1175///
1176ParseResult Parser::parseSSAUse() {
Chris Lattner48af7d12018-07-09 19:05:38 -07001177 if (getToken().is(Token::percent_identifier)) {
1178 StringRef name = getTokenSpelling().drop_front();
Chris Lattner78276e32018-07-07 15:48:26 -07001179 consumeToken(Token::percent_identifier);
1180 // TODO: Return this use.
1181 (void)name;
1182 return ParseSuccess;
1183 }
1184
1185 // TODO: Parse SSA constants.
1186
1187 return emitError("expected SSA operand");
1188}
1189
1190/// Parse a (possibly empty) list of SSA operands.
1191///
1192/// ssa-use-list ::= ssa-use (`,` ssa-use)*
1193/// ssa-use-list-opt ::= ssa-use-list?
1194///
1195ParseResult Parser::parseOptionalSSAUseList(Token::Kind endToken) {
1196 // TODO: Build and return this.
1197 return parseCommaSeparatedList(
1198 endToken, [&]() -> ParseResult { return parseSSAUse(); });
1199}
1200
1201/// Parse an SSA use with an associated type.
1202///
1203/// ssa-use-and-type ::= ssa-use `:` type
1204ParseResult Parser::parseSSAUseAndType() {
1205 if (parseSSAUse())
1206 return ParseFailure;
1207
1208 if (!consumeIf(Token::colon))
1209 return emitError("expected ':' and type for SSA operand");
1210
1211 if (!parseType())
1212 return ParseFailure;
1213
1214 return ParseSuccess;
1215}
1216
1217/// Parse a (possibly empty) list of SSA operands with types.
1218///
1219/// ssa-use-and-type-list ::= ssa-use-and-type (`,` ssa-use-and-type)*
1220///
1221ParseResult Parser::parseOptionalSSAUseAndTypeList(Token::Kind endToken) {
1222 // TODO: Build and return this.
1223 return parseCommaSeparatedList(
1224 endToken, [&]() -> ParseResult { return parseSSAUseAndType(); });
1225}
1226
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001227//===----------------------------------------------------------------------===//
1228// Operations
1229//===----------------------------------------------------------------------===//
1230
1231/// Parse the CFG or MLFunc operation.
1232///
1233/// TODO(clattner): This is a change from the MLIR spec as written, it is an
1234/// experiment that will eliminate "builtin" instructions as a thing.
1235///
1236/// operation ::=
1237/// (ssa-id `=`)? string '(' ssa-use-list? ')' attribute-dict?
1238/// `:` function-type
1239///
1240ParseResult
1241Parser::parseOperation(const CreateOperationFunction &createOpFunc) {
1242 auto loc = getToken().getLoc();
1243
1244 StringRef resultID;
1245 if (getToken().is(Token::percent_identifier)) {
1246 resultID = getTokenSpelling().drop_front();
1247 consumeToken(Token::percent_identifier);
1248 if (!consumeIf(Token::equal))
1249 return emitError("expected '=' after SSA name");
1250 }
1251
1252 if (getToken().isNot(Token::string))
1253 return emitError("expected operation name in quotes");
1254
1255 auto name = getToken().getStringValue();
1256 if (name.empty())
1257 return emitError("empty operation name is invalid");
1258
1259 consumeToken(Token::string);
1260
1261 if (!consumeIf(Token::l_paren))
1262 return emitError("expected '(' to start operand list");
1263
1264 // Parse the operand list.
1265 parseOptionalSSAUseList(Token::r_paren);
1266
1267 SmallVector<NamedAttribute, 4> attributes;
1268 if (getToken().is(Token::l_brace)) {
1269 if (parseAttributeDict(attributes))
1270 return ParseFailure;
1271 }
1272
Chris Lattner3b2ef762018-07-18 15:31:25 -07001273 if (!consumeIf(Token::colon))
1274 return emitError("expected ':' followed by instruction type");
1275
1276 auto typeLoc = getToken().getLoc();
1277 auto type = parseType();
1278 if (!type)
1279 return ParseFailure;
1280 auto fnType = dyn_cast<FunctionType>(type);
1281 if (!fnType)
1282 return emitError(typeLoc, "expected function type");
1283
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001284 // TODO: Don't drop result name and operand names on the floor.
1285 auto nameId = builder.getIdentifier(name);
1286
Chris Lattner3b2ef762018-07-18 15:31:25 -07001287 auto oper = createOpFunc(nameId, fnType->getResults(), attributes);
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001288
1289 if (!oper)
1290 return ParseFailure;
1291
1292 // We just parsed an operation. If it is a recognized one, verify that it
1293 // is structurally as we expect. If not, produce an error with a reasonable
1294 // source location.
1295 if (auto *opInfo = oper->getAbstractOperation(builder.getContext())) {
1296 if (auto error = opInfo->verifyInvariants(oper))
1297 return emitError(loc, error);
1298 }
1299
1300 return ParseSuccess;
1301}
Chris Lattnere79379a2018-06-22 10:39:19 -07001302
Chris Lattner48af7d12018-07-09 19:05:38 -07001303//===----------------------------------------------------------------------===//
1304// CFG Functions
1305//===----------------------------------------------------------------------===//
Chris Lattnere79379a2018-06-22 10:39:19 -07001306
Chris Lattner4c95a502018-06-23 16:03:42 -07001307namespace {
Chris Lattner48af7d12018-07-09 19:05:38 -07001308/// This is a specialized parser for CFGFunction's, maintaining the state
1309/// transient to their bodies.
1310class CFGFunctionParser : public Parser {
Chris Lattner158e0a3e2018-07-08 20:51:38 -07001311public:
Chris Lattner2e595eb2018-07-10 10:08:27 -07001312 CFGFunctionParser(ParserState &state, CFGFunction *function)
1313 : Parser(state), function(function), builder(function) {}
1314
1315 ParseResult parseFunctionBody();
1316
1317private:
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001318 CFGFunction *function;
1319 llvm::StringMap<std::pair<BasicBlock*, SMLoc>> blocksByName;
Chris Lattner48af7d12018-07-09 19:05:38 -07001320
1321 /// This builder intentionally shadows the builder in the base class, with a
1322 /// more specific builder type.
Chris Lattner158e0a3e2018-07-08 20:51:38 -07001323 CFGFuncBuilder builder;
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001324
Chris Lattner4c95a502018-06-23 16:03:42 -07001325 /// Get the basic block with the specified name, creating it if it doesn't
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001326 /// already exist. The location specified is the point of use, which allows
1327 /// us to diagnose references to blocks that are not defined precisely.
1328 BasicBlock *getBlockNamed(StringRef name, SMLoc loc) {
1329 auto &blockAndLoc = blocksByName[name];
1330 if (!blockAndLoc.first) {
Chris Lattner3a467cc2018-07-01 20:28:00 -07001331 blockAndLoc.first = new BasicBlock();
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001332 blockAndLoc.second = loc;
Chris Lattner4c95a502018-06-23 16:03:42 -07001333 }
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001334 return blockAndLoc.first;
Chris Lattner4c95a502018-06-23 16:03:42 -07001335 }
Chris Lattner48af7d12018-07-09 19:05:38 -07001336
Chris Lattner48af7d12018-07-09 19:05:38 -07001337 ParseResult parseBasicBlock();
1338 OperationInst *parseCFGOperation();
1339 TerminatorInst *parseTerminator();
Chris Lattner4c95a502018-06-23 16:03:42 -07001340};
1341} // end anonymous namespace
1342
Chris Lattner48af7d12018-07-09 19:05:38 -07001343ParseResult CFGFunctionParser::parseFunctionBody() {
1344 if (!consumeIf(Token::l_brace))
1345 return emitError("expected '{' in CFG function");
1346
1347 // Make sure we have at least one block.
1348 if (getToken().is(Token::r_brace))
1349 return emitError("CFG functions must have at least one basic block");
Chris Lattner4c95a502018-06-23 16:03:42 -07001350
1351 // Parse the list of blocks.
1352 while (!consumeIf(Token::r_brace))
Chris Lattner48af7d12018-07-09 19:05:38 -07001353 if (parseBasicBlock())
Chris Lattner4c95a502018-06-23 16:03:42 -07001354 return ParseFailure;
1355
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001356 // Verify that all referenced blocks were defined. Iteration over a
1357 // StringMap isn't determinstic, but this is good enough for our purposes.
Chris Lattner48af7d12018-07-09 19:05:38 -07001358 for (auto &elt : blocksByName) {
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001359 auto *bb = elt.second.first;
Chris Lattner3a467cc2018-07-01 20:28:00 -07001360 if (!bb->getFunction())
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001361 return emitError(elt.second.second,
1362 "reference to an undefined basic block '" +
1363 elt.first() + "'");
1364 }
1365
Chris Lattner48af7d12018-07-09 19:05:38 -07001366 getModule()->functionList.push_back(function);
Chris Lattner4c95a502018-06-23 16:03:42 -07001367 return ParseSuccess;
1368}
1369
1370/// Basic block declaration.
1371///
1372/// basic-block ::= bb-label instruction* terminator-stmt
1373/// bb-label ::= bb-id bb-arg-list? `:`
1374/// bb-id ::= bare-id
1375/// bb-arg-list ::= `(` ssa-id-and-type-list? `)`
1376///
Chris Lattner48af7d12018-07-09 19:05:38 -07001377ParseResult CFGFunctionParser::parseBasicBlock() {
1378 SMLoc nameLoc = getToken().getLoc();
1379 auto name = getTokenSpelling();
Chris Lattner4c95a502018-06-23 16:03:42 -07001380 if (!consumeIf(Token::bare_identifier))
1381 return emitError("expected basic block name");
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001382
Chris Lattner48af7d12018-07-09 19:05:38 -07001383 auto *block = getBlockNamed(name, nameLoc);
Chris Lattner4c95a502018-06-23 16:03:42 -07001384
1385 // If this block has already been parsed, then this is a redefinition with the
1386 // same block name.
Chris Lattner3a467cc2018-07-01 20:28:00 -07001387 if (block->getFunction())
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001388 return emitError(nameLoc, "redefinition of block '" + name.str() + "'");
1389
Chris Lattner3a467cc2018-07-01 20:28:00 -07001390 // Add the block to the function.
Chris Lattner48af7d12018-07-09 19:05:38 -07001391 function->push_back(block);
Chris Lattner4c95a502018-06-23 16:03:42 -07001392
Chris Lattner78276e32018-07-07 15:48:26 -07001393 // If an argument list is present, parse it.
1394 if (consumeIf(Token::l_paren)) {
1395 if (parseOptionalSSAUseAndTypeList(Token::r_paren))
1396 return ParseFailure;
1397
1398 // TODO: attach it.
1399 }
Chris Lattner4c95a502018-06-23 16:03:42 -07001400
1401 if (!consumeIf(Token::colon))
1402 return emitError("expected ':' after basic block name");
1403
Chris Lattner158e0a3e2018-07-08 20:51:38 -07001404 // Set the insertion point to the block we want to insert new operations into.
Chris Lattner48af7d12018-07-09 19:05:38 -07001405 builder.setInsertionPoint(block);
Chris Lattner158e0a3e2018-07-08 20:51:38 -07001406
Chris Lattner3b2ef762018-07-18 15:31:25 -07001407 auto createOpFunc = [this](Identifier name, ArrayRef<Type *> resultTypes,
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001408 ArrayRef<NamedAttribute> attrs) -> Operation * {
Chris Lattner3b2ef762018-07-18 15:31:25 -07001409 return builder.createOperation(name, {}, resultTypes, attrs);
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001410 };
1411
Chris Lattnered65a732018-06-28 20:45:33 -07001412 // Parse the list of operations that make up the body of the block.
Chris Lattner48af7d12018-07-09 19:05:38 -07001413 while (getToken().isNot(Token::kw_return, Token::kw_br)) {
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001414 if (parseOperation(createOpFunc))
Chris Lattnered65a732018-06-28 20:45:33 -07001415 return ParseFailure;
1416 }
Chris Lattner4c95a502018-06-23 16:03:42 -07001417
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001418 if (!parseTerminator())
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001419 return ParseFailure;
Chris Lattner4c95a502018-06-23 16:03:42 -07001420
1421 return ParseSuccess;
1422}
1423
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001424/// Parse the terminator instruction for a basic block.
1425///
1426/// terminator-stmt ::= `br` bb-id branch-use-list?
1427/// branch-use-list ::= `(` ssa-use-and-type-list? `)`
1428/// terminator-stmt ::=
1429/// `cond_br` ssa-use `,` bb-id branch-use-list? `,` bb-id branch-use-list?
1430/// terminator-stmt ::= `return` ssa-use-and-type-list?
1431///
Chris Lattner48af7d12018-07-09 19:05:38 -07001432TerminatorInst *CFGFunctionParser::parseTerminator() {
1433 switch (getToken().getKind()) {
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001434 default:
Chris Lattner3a467cc2018-07-01 20:28:00 -07001435 return (emitError("expected terminator at end of basic block"), nullptr);
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001436
1437 case Token::kw_return:
1438 consumeToken(Token::kw_return);
Chris Lattner48af7d12018-07-09 19:05:38 -07001439 return builder.createReturnInst();
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001440
1441 case Token::kw_br: {
1442 consumeToken(Token::kw_br);
Chris Lattner48af7d12018-07-09 19:05:38 -07001443 auto destBB = getBlockNamed(getTokenSpelling(), getToken().getLoc());
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001444 if (!consumeIf(Token::bare_identifier))
Chris Lattner3a467cc2018-07-01 20:28:00 -07001445 return (emitError("expected basic block name"), nullptr);
Chris Lattner48af7d12018-07-09 19:05:38 -07001446 return builder.createBranchInst(destBB);
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001447 }
Chris Lattner78276e32018-07-07 15:48:26 -07001448 // TODO: cond_br.
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001449 }
1450}
1451
Chris Lattner48af7d12018-07-09 19:05:38 -07001452//===----------------------------------------------------------------------===//
1453// ML Functions
1454//===----------------------------------------------------------------------===//
1455
1456namespace {
1457/// Refined parser for MLFunction bodies.
1458class MLFunctionParser : public Parser {
1459public:
Chris Lattner48af7d12018-07-09 19:05:38 -07001460 MLFunctionParser(ParserState &state, MLFunction *function)
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001461 : Parser(state), function(function), builder(function) {}
Chris Lattner48af7d12018-07-09 19:05:38 -07001462
1463 ParseResult parseFunctionBody();
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001464
1465private:
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001466 MLFunction *function;
1467
1468 /// This builder intentionally shadows the builder in the base class, with a
1469 /// more specific builder type.
1470 MLFuncBuilder builder;
1471
1472 ParseResult parseForStmt();
1473 ParseResult parseIfStmt();
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001474 ParseResult parseElseClause(IfClause *elseClause);
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001475 ParseResult parseStatements(StmtBlock *block);
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001476 ParseResult parseStmtBlock(StmtBlock *block);
Chris Lattner48af7d12018-07-09 19:05:38 -07001477};
1478} // end anonymous namespace
1479
Chris Lattner48af7d12018-07-09 19:05:38 -07001480ParseResult MLFunctionParser::parseFunctionBody() {
1481 if (!consumeIf(Token::l_brace))
1482 return emitError("expected '{' in ML function");
1483
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001484 // Parse statements in this function
1485 if (parseStatements(function))
1486 return ParseFailure;
Tatiana Shpeismanc96b5872018-06-28 17:02:32 -07001487
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001488 if (!consumeIf(Token::kw_return))
1489 emitError("ML function must end with return statement");
Tatiana Shpeismanc96b5872018-06-28 17:02:32 -07001490 // TODO: parse return statement operands
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001491
Tatiana Shpeismanc96b5872018-06-28 17:02:32 -07001492 if (!consumeIf(Token::r_brace))
1493 emitError("expected '}' in ML function");
1494
Chris Lattner48af7d12018-07-09 19:05:38 -07001495 getModule()->functionList.push_back(function);
Tatiana Shpeismanc96b5872018-06-28 17:02:32 -07001496
1497 return ParseSuccess;
1498}
1499
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001500/// For statement.
1501///
Chris Lattner48af7d12018-07-09 19:05:38 -07001502/// ml-for-stmt ::= `for` ssa-id `=` lower-bound `to` upper-bound
1503/// (`step` integer-literal)? `{` ml-stmt* `}`
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001504///
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001505ParseResult MLFunctionParser::parseForStmt() {
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001506 consumeToken(Token::kw_for);
1507
1508 //TODO: parse loop header
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001509 ForStmt *stmt = builder.createFor();
1510
1511 // If parsing of the for statement body fails
1512 // MLIR contains for statement with successfully parsed nested statements
1513 if (parseStmtBlock(static_cast<StmtBlock *>(stmt)))
1514 return ParseFailure;
1515
1516 return ParseSuccess;
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001517}
1518
1519/// If statement.
1520///
Chris Lattner48af7d12018-07-09 19:05:38 -07001521/// ml-if-head ::= `if` ml-if-cond `{` ml-stmt* `}`
1522/// | ml-if-head `else` `if` ml-if-cond `{` ml-stmt* `}`
1523/// ml-if-stmt ::= ml-if-head
1524/// | ml-if-head `else` `{` ml-stmt* `}`
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001525///
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001526ParseResult MLFunctionParser::parseIfStmt() {
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001527 consumeToken(Token::kw_if);
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001528 if (!consumeIf(Token::l_paren))
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001529 return emitError("expected (");
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001530
1531 //TODO: parse condition
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001532
1533 if (!consumeIf(Token::r_paren))
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001534 return emitError("expected )");
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001535
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001536 IfStmt *ifStmt = builder.createIf();
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001537 IfClause *thenClause = ifStmt->getThenClause();
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001538
1539 // If parsing of the then or optional else clause fails MLIR contains
1540 // if statement with successfully parsed nested statements.
1541 if (parseStmtBlock(thenClause))
1542 return ParseFailure;
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001543
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001544 if (consumeIf(Token::kw_else)) {
1545 IfClause *elseClause = ifStmt->createElseClause();
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001546 if (parseElseClause(elseClause))
1547 return ParseFailure;
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001548 }
1549
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001550 return ParseSuccess;
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001551}
1552
1553ParseResult MLFunctionParser::parseElseClause(IfClause *elseClause) {
1554 if (getToken().is(Token::kw_if)) {
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001555 builder.setInsertionPoint(elseClause);
1556 return parseIfStmt();
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001557 }
1558
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001559 return parseStmtBlock(elseClause);
1560}
1561
1562///
1563/// Parse a list of statements ending with `return` or `}`
1564///
1565ParseResult MLFunctionParser::parseStatements(StmtBlock *block) {
Chris Lattner3b2ef762018-07-18 15:31:25 -07001566 auto createOpFunc = [this](Identifier name, ArrayRef<Type *> resultTypes,
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001567 ArrayRef<NamedAttribute> attrs) -> Operation * {
1568 return builder.createOperation(name, attrs);
1569 };
1570
1571 builder.setInsertionPoint(block);
1572
1573 while (getToken().isNot(Token::kw_return, Token::r_brace)) {
1574 switch (getToken().getKind()) {
1575 default:
1576 if (parseOperation(createOpFunc))
1577 return ParseFailure;
1578 break;
1579 case Token::kw_for:
1580 if (parseForStmt())
1581 return ParseFailure;
1582 break;
1583 case Token::kw_if:
1584 if (parseIfStmt())
1585 return ParseFailure;
1586 break;
1587 } // end switch
1588 }
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001589
1590 return ParseSuccess;
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001591}
1592
1593///
1594/// Parse `{` ml-stmt* `}`
1595///
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001596ParseResult MLFunctionParser::parseStmtBlock(StmtBlock *block) {
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001597 if (!consumeIf(Token::l_brace))
1598 return emitError("expected '{' before statement list");
1599
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001600 if (parseStatements(block))
1601 return ParseFailure;
1602
1603 if (!consumeIf(Token::r_brace))
1604 return emitError("expected '}' at the end of the statement block");
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001605
1606 return ParseSuccess;
1607}
1608
Chris Lattner4c95a502018-06-23 16:03:42 -07001609//===----------------------------------------------------------------------===//
1610// Top-level entity parsing.
1611//===----------------------------------------------------------------------===//
1612
Chris Lattner2e595eb2018-07-10 10:08:27 -07001613namespace {
1614/// This parser handles entities that are only valid at the top level of the
1615/// file.
1616class ModuleParser : public Parser {
1617public:
1618 explicit ModuleParser(ParserState &state) : Parser(state) {}
1619
1620 ParseResult parseModule();
1621
1622private:
1623 ParseResult parseAffineMapDef();
1624
1625 // Functions.
1626 ParseResult parseFunctionSignature(StringRef &name, FunctionType *&type);
1627 ParseResult parseExtFunc();
1628 ParseResult parseCFGFunc();
1629 ParseResult parseMLFunc();
1630};
1631} // end anonymous namespace
1632
1633/// Affine map declaration.
1634///
1635/// affine-map-def ::= affine-map-id `=` affine-map-inline
1636///
1637ParseResult ModuleParser::parseAffineMapDef() {
1638 assert(getToken().is(Token::hash_identifier));
1639
1640 StringRef affineMapId = getTokenSpelling().drop_front();
1641
1642 // Check for redefinitions.
1643 auto *&entry = getState().affineMapDefinitions[affineMapId];
1644 if (entry)
1645 return emitError("redefinition of affine map id '" + affineMapId + "'");
1646
1647 consumeToken(Token::hash_identifier);
1648
1649 // Parse the '='
1650 if (!consumeIf(Token::equal))
1651 return emitError("expected '=' in affine map outlined definition");
1652
1653 entry = parseAffineMapInline();
1654 if (!entry)
1655 return ParseFailure;
1656
Chris Lattner2e595eb2018-07-10 10:08:27 -07001657 return ParseSuccess;
1658}
1659
1660/// Parse a function signature, starting with a name and including the parameter
1661/// list.
1662///
1663/// argument-list ::= type (`,` type)* | /*empty*/
1664/// function-signature ::= function-id `(` argument-list `)` (`->` type-list)?
1665///
1666ParseResult ModuleParser::parseFunctionSignature(StringRef &name,
1667 FunctionType *&type) {
1668 if (getToken().isNot(Token::at_identifier))
1669 return emitError("expected a function identifier like '@foo'");
1670
1671 name = getTokenSpelling().drop_front();
1672 consumeToken(Token::at_identifier);
1673
1674 if (getToken().isNot(Token::l_paren))
1675 return emitError("expected '(' in function signature");
1676
1677 SmallVector<Type *, 4> arguments;
1678 if (parseTypeList(arguments))
1679 return ParseFailure;
1680
1681 // Parse the return type if present.
1682 SmallVector<Type *, 4> results;
1683 if (consumeIf(Token::arrow)) {
1684 if (parseTypeList(results))
1685 return ParseFailure;
1686 }
1687 type = builder.getFunctionType(arguments, results);
1688 return ParseSuccess;
1689}
1690
1691/// External function declarations.
1692///
1693/// ext-func ::= `extfunc` function-signature
1694///
1695ParseResult ModuleParser::parseExtFunc() {
1696 consumeToken(Token::kw_extfunc);
1697
1698 StringRef name;
1699 FunctionType *type = nullptr;
1700 if (parseFunctionSignature(name, type))
1701 return ParseFailure;
1702
1703 // Okay, the external function definition was parsed correctly.
1704 getModule()->functionList.push_back(new ExtFunction(name, type));
1705 return ParseSuccess;
1706}
1707
1708/// CFG function declarations.
1709///
1710/// cfg-func ::= `cfgfunc` function-signature `{` basic-block+ `}`
1711///
1712ParseResult ModuleParser::parseCFGFunc() {
1713 consumeToken(Token::kw_cfgfunc);
1714
1715 StringRef name;
1716 FunctionType *type = nullptr;
1717 if (parseFunctionSignature(name, type))
1718 return ParseFailure;
1719
1720 // Okay, the CFG function signature was parsed correctly, create the function.
1721 auto function = new CFGFunction(name, type);
1722
1723 return CFGFunctionParser(getState(), function).parseFunctionBody();
1724}
1725
1726/// ML function declarations.
1727///
1728/// ml-func ::= `mlfunc` ml-func-signature `{` ml-stmt* ml-return-stmt `}`
1729///
1730ParseResult ModuleParser::parseMLFunc() {
1731 consumeToken(Token::kw_mlfunc);
1732
1733 StringRef name;
1734 FunctionType *type = nullptr;
1735
1736 // FIXME: Parse ML function signature (args + types)
1737 // by passing pointer to SmallVector<identifier> into parseFunctionSignature
1738 if (parseFunctionSignature(name, type))
1739 return ParseFailure;
1740
1741 // Okay, the ML function signature was parsed correctly, create the function.
1742 auto function = new MLFunction(name, type);
1743
1744 return MLFunctionParser(getState(), function).parseFunctionBody();
1745}
1746
Chris Lattnere79379a2018-06-22 10:39:19 -07001747/// This is the top-level module parser.
Chris Lattner2e595eb2018-07-10 10:08:27 -07001748ParseResult ModuleParser::parseModule() {
Chris Lattnere79379a2018-06-22 10:39:19 -07001749 while (1) {
Chris Lattner48af7d12018-07-09 19:05:38 -07001750 switch (getToken().getKind()) {
Chris Lattnere79379a2018-06-22 10:39:19 -07001751 default:
1752 emitError("expected a top level entity");
Chris Lattner2e595eb2018-07-10 10:08:27 -07001753 return ParseFailure;
Chris Lattnere79379a2018-06-22 10:39:19 -07001754
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001755 // If we got to the end of the file, then we're done.
Chris Lattnere79379a2018-06-22 10:39:19 -07001756 case Token::eof:
Chris Lattner2e595eb2018-07-10 10:08:27 -07001757 return ParseSuccess;
Chris Lattnere79379a2018-06-22 10:39:19 -07001758
1759 // If we got an error token, then the lexer already emitted an error, just
1760 // stop. Someday we could introduce error recovery if there was demand for
1761 // it.
1762 case Token::error:
Chris Lattner2e595eb2018-07-10 10:08:27 -07001763 return ParseFailure;
1764
1765 case Token::hash_identifier:
1766 if (parseAffineMapDef())
1767 return ParseFailure;
1768 break;
Chris Lattnere79379a2018-06-22 10:39:19 -07001769
1770 case Token::kw_extfunc:
Chris Lattner2e595eb2018-07-10 10:08:27 -07001771 if (parseExtFunc())
1772 return ParseFailure;
Chris Lattnere79379a2018-06-22 10:39:19 -07001773 break;
1774
Chris Lattner4c95a502018-06-23 16:03:42 -07001775 case Token::kw_cfgfunc:
Chris Lattner2e595eb2018-07-10 10:08:27 -07001776 if (parseCFGFunc())
1777 return ParseFailure;
MLIR Teamf85a6262018-06-27 11:03:08 -07001778 break;
Chris Lattner4c95a502018-06-23 16:03:42 -07001779
Tatiana Shpeismanc96b5872018-06-28 17:02:32 -07001780 case Token::kw_mlfunc:
Chris Lattner2e595eb2018-07-10 10:08:27 -07001781 if (parseMLFunc())
1782 return ParseFailure;
Tatiana Shpeismanc96b5872018-06-28 17:02:32 -07001783 break;
1784
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001785 // TODO: affine entity declarations, etc.
Chris Lattnere79379a2018-06-22 10:39:19 -07001786 }
1787 }
1788}
1789
1790//===----------------------------------------------------------------------===//
1791
Jacques Pienaar7b829702018-07-03 13:24:09 -07001792void mlir::defaultErrorReporter(const llvm::SMDiagnostic &error) {
1793 const auto &sourceMgr = *error.getSourceMgr();
1794 sourceMgr.PrintMessage(error.getLoc(), error.getKind(), error.getMessage());
1795}
1796
Chris Lattnere79379a2018-06-22 10:39:19 -07001797/// This parses the file specified by the indicated SourceMgr and returns an
1798/// MLIR module if it was valid. If not, it emits diagnostics and returns null.
Jacques Pienaar9c411be2018-06-24 19:17:35 -07001799Module *mlir::parseSourceFile(llvm::SourceMgr &sourceMgr, MLIRContext *context,
Jacques Pienaar7b829702018-07-03 13:24:09 -07001800 SMDiagnosticHandlerTy errorReporter) {
Chris Lattner2e595eb2018-07-10 10:08:27 -07001801 // This is the result module we are parsing into.
1802 std::unique_ptr<Module> module(new Module(context));
1803
1804 ParserState state(sourceMgr, module.get(),
Jacques Pienaar0bffd862018-07-11 13:26:23 -07001805 errorReporter ? errorReporter : defaultErrorReporter);
Chris Lattner2e595eb2018-07-10 10:08:27 -07001806 if (ModuleParser(state).parseModule())
1807 return nullptr;
Chris Lattner21e67f62018-07-06 10:46:19 -07001808
1809 // Make sure the parse module has no other structural problems detected by the
1810 // verifier.
Chris Lattner2e595eb2018-07-10 10:08:27 -07001811 module->verify();
1812 return module.release();
Chris Lattnere79379a2018-06-22 10:39:19 -07001813}