blob: 7fbbf9b5b8a1e7312e1a310f17751efde95bace9 [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 Lattner7f9cc272018-07-19 08:35:28 -070087typedef std::function<Operation *(Identifier, ArrayRef<SSAValue *>,
88 ArrayRef<Type *>, 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 Lattner48af7d12018-07-09 19:05:38 -0700168private:
169 // The Parser is subclassed and reinstantiated. Do not add additional
170 // non-trivial state here, add it to the ParserState class.
171 ParserState &state;
Chris Lattnere79379a2018-06-22 10:39:19 -0700172};
173} // end anonymous namespace
174
175//===----------------------------------------------------------------------===//
176// Helper methods.
177//===----------------------------------------------------------------------===//
178
Chris Lattner4c95a502018-06-23 16:03:42 -0700179ParseResult Parser::emitError(SMLoc loc, const Twine &message) {
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700180 // If we hit a parse error in response to a lexer error, then the lexer
Jacques Pienaar9c411be2018-06-24 19:17:35 -0700181 // already reported the error.
Chris Lattner48af7d12018-07-09 19:05:38 -0700182 if (getToken().is(Token::error))
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700183 return ParseFailure;
184
Chris Lattner48af7d12018-07-09 19:05:38 -0700185 auto &sourceMgr = state.lex.getSourceMgr();
186 state.errorReporter(sourceMgr.GetMessage(loc, SourceMgr::DK_Error, message));
Chris Lattnere79379a2018-06-22 10:39:19 -0700187 return ParseFailure;
188}
189
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700190/// Parse a comma-separated list of elements, terminated with an arbitrary
191/// token. This allows empty lists if allowEmptyList is true.
192///
193/// abstract-list ::= rightToken // if allowEmptyList == true
194/// abstract-list ::= element (',' element)* rightToken
195///
196ParseResult Parser::
Chris Lattner8da0c282018-06-29 11:15:56 -0700197parseCommaSeparatedList(Token::Kind rightToken,
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700198 const std::function<ParseResult()> &parseElement,
199 bool allowEmptyList) {
200 // Handle the empty case.
Chris Lattner48af7d12018-07-09 19:05:38 -0700201 if (getToken().is(rightToken)) {
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700202 if (!allowEmptyList)
203 return emitError("expected list element");
204 consumeToken(rightToken);
205 return ParseSuccess;
206 }
207
208 // Non-empty case starts with an element.
209 if (parseElement())
210 return ParseFailure;
211
212 // Otherwise we have a list of comma separated elements.
213 while (consumeIf(Token::comma)) {
214 if (parseElement())
215 return ParseFailure;
216 }
217
218 // Consume the end character.
219 if (!consumeIf(rightToken))
Chris Lattner8da0c282018-06-29 11:15:56 -0700220 return emitError("expected ',' or '" + Token::getTokenSpelling(rightToken) +
221 "'");
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700222
223 return ParseSuccess;
224}
Chris Lattnere79379a2018-06-22 10:39:19 -0700225
226//===----------------------------------------------------------------------===//
227// Type Parsing
228//===----------------------------------------------------------------------===//
229
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700230/// Parse the low-level fixed dtypes in the system.
231///
Chris Lattnerf958bbe2018-06-29 22:08:05 -0700232/// primitive-type ::= `f16` | `bf16` | `f32` | `f64`
233/// primitive-type ::= integer-type
234/// primitive-type ::= `affineint`
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700235///
Chris Lattnerf958bbe2018-06-29 22:08:05 -0700236Type *Parser::parsePrimitiveType() {
Chris Lattner48af7d12018-07-09 19:05:38 -0700237 switch (getToken().getKind()) {
Chris Lattnerf7e22732018-06-22 22:03:48 -0700238 default:
239 return (emitError("expected type"), nullptr);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700240 case Token::kw_bf16:
241 consumeToken(Token::kw_bf16);
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700242 return builder.getBF16Type();
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700243 case Token::kw_f16:
244 consumeToken(Token::kw_f16);
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700245 return builder.getF16Type();
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700246 case Token::kw_f32:
247 consumeToken(Token::kw_f32);
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700248 return builder.getF32Type();
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700249 case Token::kw_f64:
250 consumeToken(Token::kw_f64);
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700251 return builder.getF64Type();
Chris Lattnerf958bbe2018-06-29 22:08:05 -0700252 case Token::kw_affineint:
253 consumeToken(Token::kw_affineint);
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700254 return builder.getAffineIntType();
Chris Lattnerf958bbe2018-06-29 22:08:05 -0700255 case Token::inttype: {
Chris Lattner48af7d12018-07-09 19:05:38 -0700256 auto width = getToken().getIntTypeBitwidth();
Chris Lattnerf958bbe2018-06-29 22:08:05 -0700257 if (!width.hasValue())
258 return (emitError("invalid integer width"), nullptr);
259 consumeToken(Token::inttype);
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700260 return builder.getIntegerType(width.getValue());
Chris Lattnerf958bbe2018-06-29 22:08:05 -0700261 }
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700262 }
263}
264
265/// Parse the element type of a tensor or memref type.
266///
267/// element-type ::= primitive-type | vector-type
268///
Chris Lattnerf7e22732018-06-22 22:03:48 -0700269Type *Parser::parseElementType() {
Chris Lattner48af7d12018-07-09 19:05:38 -0700270 if (getToken().is(Token::kw_vector))
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700271 return parseVectorType();
272
273 return parsePrimitiveType();
274}
275
276/// Parse a vector type.
277///
278/// vector-type ::= `vector` `<` const-dimension-list primitive-type `>`
279/// const-dimension-list ::= (integer-literal `x`)+
280///
Chris Lattnerf7e22732018-06-22 22:03:48 -0700281VectorType *Parser::parseVectorType() {
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700282 consumeToken(Token::kw_vector);
283
284 if (!consumeIf(Token::less))
Chris Lattnerf7e22732018-06-22 22:03:48 -0700285 return (emitError("expected '<' in vector type"), nullptr);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700286
Chris Lattner48af7d12018-07-09 19:05:38 -0700287 if (getToken().isNot(Token::integer))
Chris Lattnerf7e22732018-06-22 22:03:48 -0700288 return (emitError("expected dimension size in vector type"), nullptr);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700289
290 SmallVector<unsigned, 4> dimensions;
Chris Lattner48af7d12018-07-09 19:05:38 -0700291 while (getToken().is(Token::integer)) {
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700292 // Make sure this integer value is in bound and valid.
Chris Lattner48af7d12018-07-09 19:05:38 -0700293 auto dimension = getToken().getUnsignedIntegerValue();
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700294 if (!dimension.hasValue())
Chris Lattnerf7e22732018-06-22 22:03:48 -0700295 return (emitError("invalid dimension in vector type"), nullptr);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700296 dimensions.push_back(dimension.getValue());
297
298 consumeToken(Token::integer);
299
300 // Make sure we have an 'x' or something like 'xbf32'.
Chris Lattner48af7d12018-07-09 19:05:38 -0700301 if (getToken().isNot(Token::bare_identifier) ||
302 getTokenSpelling()[0] != 'x')
Chris Lattnerf7e22732018-06-22 22:03:48 -0700303 return (emitError("expected 'x' in vector dimension list"), nullptr);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700304
305 // If we had a prefix of 'x', lex the next token immediately after the 'x'.
Chris Lattner48af7d12018-07-09 19:05:38 -0700306 if (getTokenSpelling().size() != 1)
307 state.lex.resetPointer(getTokenSpelling().data() + 1);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700308
309 // Consume the 'x'.
310 consumeToken(Token::bare_identifier);
311 }
312
313 // Parse the element type.
Chris Lattnerf7e22732018-06-22 22:03:48 -0700314 auto *elementType = parsePrimitiveType();
315 if (!elementType)
316 return nullptr;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700317
318 if (!consumeIf(Token::greater))
Chris Lattnerf7e22732018-06-22 22:03:48 -0700319 return (emitError("expected '>' in vector type"), nullptr);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700320
Chris Lattnerf7e22732018-06-22 22:03:48 -0700321 return VectorType::get(dimensions, elementType);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700322}
323
324/// Parse a dimension list of a tensor or memref type. This populates the
325/// dimension list, returning -1 for the '?' dimensions.
326///
327/// dimension-list-ranked ::= (dimension `x`)*
328/// dimension ::= `?` | integer-literal
329///
330ParseResult Parser::parseDimensionListRanked(SmallVectorImpl<int> &dimensions) {
Chris Lattner48af7d12018-07-09 19:05:38 -0700331 while (getToken().isAny(Token::integer, Token::question)) {
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700332 if (consumeIf(Token::question)) {
333 dimensions.push_back(-1);
334 } else {
335 // Make sure this integer value is in bound and valid.
Chris Lattner48af7d12018-07-09 19:05:38 -0700336 auto dimension = getToken().getUnsignedIntegerValue();
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700337 if (!dimension.hasValue() || (int)dimension.getValue() < 0)
338 return emitError("invalid dimension");
339 dimensions.push_back((int)dimension.getValue());
340 consumeToken(Token::integer);
341 }
342
343 // Make sure we have an 'x' or something like 'xbf32'.
Chris Lattner48af7d12018-07-09 19:05:38 -0700344 if (getToken().isNot(Token::bare_identifier) ||
345 getTokenSpelling()[0] != 'x')
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700346 return emitError("expected 'x' in dimension list");
347
348 // If we had a prefix of 'x', lex the next token immediately after the 'x'.
Chris Lattner48af7d12018-07-09 19:05:38 -0700349 if (getTokenSpelling().size() != 1)
350 state.lex.resetPointer(getTokenSpelling().data() + 1);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700351
352 // Consume the 'x'.
353 consumeToken(Token::bare_identifier);
354 }
355
356 return ParseSuccess;
357}
358
359/// Parse a tensor type.
360///
361/// tensor-type ::= `tensor` `<` dimension-list element-type `>`
362/// dimension-list ::= dimension-list-ranked | `??`
363///
Chris Lattnerf7e22732018-06-22 22:03:48 -0700364Type *Parser::parseTensorType() {
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700365 consumeToken(Token::kw_tensor);
366
367 if (!consumeIf(Token::less))
Chris Lattnerf7e22732018-06-22 22:03:48 -0700368 return (emitError("expected '<' in tensor type"), nullptr);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700369
370 bool isUnranked;
371 SmallVector<int, 4> dimensions;
372
373 if (consumeIf(Token::questionquestion)) {
374 isUnranked = true;
375 } else {
376 isUnranked = false;
377 if (parseDimensionListRanked(dimensions))
Chris Lattnerf7e22732018-06-22 22:03:48 -0700378 return nullptr;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700379 }
380
381 // Parse the element type.
Chris Lattnerf7e22732018-06-22 22:03:48 -0700382 auto elementType = parseElementType();
383 if (!elementType)
384 return nullptr;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700385
386 if (!consumeIf(Token::greater))
Chris Lattnerf7e22732018-06-22 22:03:48 -0700387 return (emitError("expected '>' in tensor type"), nullptr);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700388
MLIR Team355ec862018-06-23 18:09:09 -0700389 if (isUnranked)
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700390 return builder.getTensorType(elementType);
391 return builder.getTensorType(dimensions, elementType);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700392}
393
394/// Parse a memref type.
395///
396/// memref-type ::= `memref` `<` dimension-list-ranked element-type
397/// (`,` semi-affine-map-composition)? (`,` memory-space)? `>`
398///
399/// semi-affine-map-composition ::= (semi-affine-map `,` )* semi-affine-map
400/// memory-space ::= integer-literal /* | TODO: address-space-id */
401///
Chris Lattnerf7e22732018-06-22 22:03:48 -0700402Type *Parser::parseMemRefType() {
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700403 consumeToken(Token::kw_memref);
404
405 if (!consumeIf(Token::less))
Chris Lattnerf7e22732018-06-22 22:03:48 -0700406 return (emitError("expected '<' in memref type"), nullptr);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700407
408 SmallVector<int, 4> dimensions;
409 if (parseDimensionListRanked(dimensions))
Chris Lattnerf7e22732018-06-22 22:03:48 -0700410 return nullptr;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700411
412 // Parse the element type.
Chris Lattnerf7e22732018-06-22 22:03:48 -0700413 auto elementType = parseElementType();
414 if (!elementType)
415 return nullptr;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700416
MLIR Team718c82f2018-07-16 09:45:22 -0700417 if (!consumeIf(Token::comma))
418 return (emitError("expected ',' in memref type"), nullptr);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700419
MLIR Team718c82f2018-07-16 09:45:22 -0700420 // Parse semi-affine-map-composition.
421 SmallVector<AffineMap*, 2> affineMapComposition;
422 unsigned memorySpace;
423 bool parsedMemorySpace = false;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700424
MLIR Team718c82f2018-07-16 09:45:22 -0700425 auto parseElt = [&]() -> ParseResult {
426 if (getToken().is(Token::integer)) {
427 // Parse memory space.
428 if (parsedMemorySpace)
429 return emitError("multiple memory spaces specified in memref type");
430 auto v = getToken().getUnsignedIntegerValue();
431 if (!v.hasValue())
432 return emitError("invalid memory space in memref type");
433 memorySpace = v.getValue();
434 consumeToken(Token::integer);
435 parsedMemorySpace = true;
436 } else {
437 // Parse affine map.
438 if (parsedMemorySpace)
439 return emitError("affine map after memory space in memref type");
440 auto* affineMap = parseAffineMapReference();
441 if (affineMap == nullptr)
442 return ParseFailure;
443 affineMapComposition.push_back(affineMap);
444 }
445 return ParseSuccess;
446 };
447
448 // Parse comma separated list of affine maps, followed by memory space.
449 if (parseCommaSeparatedList(Token::greater, parseElt,
450 /*allowEmptyList=*/false)) {
451 return nullptr;
452 }
453 // Check that MemRef type specifies at least one affine map in composition.
454 if (affineMapComposition.empty())
455 return (emitError("expected semi-affine-map in memref type"), nullptr);
456 if (!parsedMemorySpace)
457 return (emitError("expected memory space in memref type"), nullptr);
458
459 return MemRefType::get(dimensions, elementType, affineMapComposition,
460 memorySpace);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700461}
462
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700463/// Parse a function type.
464///
465/// function-type ::= type-list-parens `->` type-list
466///
Chris Lattnerf7e22732018-06-22 22:03:48 -0700467Type *Parser::parseFunctionType() {
Chris Lattner48af7d12018-07-09 19:05:38 -0700468 assert(getToken().is(Token::l_paren));
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700469
Chris Lattnerf7e22732018-06-22 22:03:48 -0700470 SmallVector<Type*, 4> arguments;
471 if (parseTypeList(arguments))
472 return nullptr;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700473
474 if (!consumeIf(Token::arrow))
Chris Lattnerf7e22732018-06-22 22:03:48 -0700475 return (emitError("expected '->' in function type"), nullptr);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700476
Chris Lattnerf7e22732018-06-22 22:03:48 -0700477 SmallVector<Type*, 4> results;
478 if (parseTypeList(results))
479 return nullptr;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700480
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700481 return builder.getFunctionType(arguments, results);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700482}
483
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700484/// Parse an arbitrary type.
485///
486/// type ::= primitive-type
487/// | vector-type
488/// | tensor-type
489/// | memref-type
490/// | function-type
491/// element-type ::= primitive-type | vector-type
492///
Chris Lattnerf7e22732018-06-22 22:03:48 -0700493Type *Parser::parseType() {
Chris Lattner48af7d12018-07-09 19:05:38 -0700494 switch (getToken().getKind()) {
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700495 case Token::kw_memref: return parseMemRefType();
496 case Token::kw_tensor: return parseTensorType();
497 case Token::kw_vector: return parseVectorType();
498 case Token::l_paren: return parseFunctionType();
499 default:
500 return parsePrimitiveType();
501 }
502}
503
504/// Parse a "type list", which is a singular type, or a parenthesized list of
505/// types.
506///
507/// type-list ::= type-list-parens | type
508/// type-list-parens ::= `(` `)`
509/// | `(` type (`,` type)* `)`
510///
Chris Lattnerf7e22732018-06-22 22:03:48 -0700511ParseResult Parser::parseTypeList(SmallVectorImpl<Type*> &elements) {
512 auto parseElt = [&]() -> ParseResult {
513 auto elt = parseType();
514 elements.push_back(elt);
515 return elt ? ParseSuccess : ParseFailure;
516 };
517
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700518 // If there is no parens, then it must be a singular type.
519 if (!consumeIf(Token::l_paren))
Chris Lattnerf7e22732018-06-22 22:03:48 -0700520 return parseElt();
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700521
Chris Lattnerf7e22732018-06-22 22:03:48 -0700522 if (parseCommaSeparatedList(Token::r_paren, parseElt))
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700523 return ParseFailure;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700524
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700525 return ParseSuccess;
526}
527
Chris Lattner4c95a502018-06-23 16:03:42 -0700528//===----------------------------------------------------------------------===//
Chris Lattner7121b802018-07-04 20:45:39 -0700529// Attribute parsing.
530//===----------------------------------------------------------------------===//
531
532
533/// Attribute parsing.
534///
535/// attribute-value ::= bool-literal
536/// | integer-literal
537/// | float-literal
538/// | string-literal
539/// | `[` (attribute-value (`,` attribute-value)*)? `]`
540///
541Attribute *Parser::parseAttribute() {
Chris Lattner48af7d12018-07-09 19:05:38 -0700542 switch (getToken().getKind()) {
Chris Lattner7121b802018-07-04 20:45:39 -0700543 case Token::kw_true:
544 consumeToken(Token::kw_true);
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700545 return builder.getBoolAttr(true);
Chris Lattner7121b802018-07-04 20:45:39 -0700546 case Token::kw_false:
547 consumeToken(Token::kw_false);
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700548 return builder.getBoolAttr(false);
Chris Lattner7121b802018-07-04 20:45:39 -0700549
550 case Token::integer: {
Chris Lattner48af7d12018-07-09 19:05:38 -0700551 auto val = getToken().getUInt64IntegerValue();
Chris Lattner7121b802018-07-04 20:45:39 -0700552 if (!val.hasValue() || (int64_t)val.getValue() < 0)
553 return (emitError("integer too large for attribute"), nullptr);
554 consumeToken(Token::integer);
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700555 return builder.getIntegerAttr((int64_t)val.getValue());
Chris Lattner7121b802018-07-04 20:45:39 -0700556 }
557
558 case Token::minus: {
559 consumeToken(Token::minus);
Chris Lattner48af7d12018-07-09 19:05:38 -0700560 if (getToken().is(Token::integer)) {
561 auto val = getToken().getUInt64IntegerValue();
Chris Lattner7121b802018-07-04 20:45:39 -0700562 if (!val.hasValue() || (int64_t)-val.getValue() >= 0)
563 return (emitError("integer too large for attribute"), nullptr);
564 consumeToken(Token::integer);
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700565 return builder.getIntegerAttr((int64_t)-val.getValue());
Chris Lattner7121b802018-07-04 20:45:39 -0700566 }
567
568 return (emitError("expected constant integer or floating point value"),
569 nullptr);
570 }
571
572 case Token::string: {
Chris Lattner48af7d12018-07-09 19:05:38 -0700573 auto val = getToken().getStringValue();
Chris Lattner7121b802018-07-04 20:45:39 -0700574 consumeToken(Token::string);
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700575 return builder.getStringAttr(val);
Chris Lattner7121b802018-07-04 20:45:39 -0700576 }
577
578 case Token::l_bracket: {
579 consumeToken(Token::l_bracket);
580 SmallVector<Attribute*, 4> elements;
581
582 auto parseElt = [&]() -> ParseResult {
583 elements.push_back(parseAttribute());
584 return elements.back() ? ParseSuccess : ParseFailure;
585 };
586
587 if (parseCommaSeparatedList(Token::r_bracket, parseElt))
588 return nullptr;
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700589 return builder.getArrayAttr(elements);
Chris Lattner7121b802018-07-04 20:45:39 -0700590 }
591 default:
MLIR Teamb61885d2018-07-18 16:29:21 -0700592 // Try to parse affine map reference.
593 auto* affineMap = parseAffineMapReference();
594 if (affineMap != nullptr)
595 return builder.getAffineMapAttr(affineMap);
596
Chris Lattner7121b802018-07-04 20:45:39 -0700597 // TODO: Handle floating point.
598 return (emitError("expected constant attribute value"), nullptr);
599 }
600}
601
Chris Lattner7121b802018-07-04 20:45:39 -0700602/// Attribute dictionary.
603///
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700604/// attribute-dict ::= `{` `}`
605/// | `{` attribute-entry (`,` attribute-entry)* `}`
606/// attribute-entry ::= bare-id `:` attribute-value
Chris Lattner7121b802018-07-04 20:45:39 -0700607///
608ParseResult Parser::parseAttributeDict(
609 SmallVectorImpl<NamedAttribute> &attributes) {
610 consumeToken(Token::l_brace);
611
612 auto parseElt = [&]() -> ParseResult {
613 // We allow keywords as attribute names.
Chris Lattner48af7d12018-07-09 19:05:38 -0700614 if (getToken().isNot(Token::bare_identifier, Token::inttype) &&
615 !getToken().isKeyword())
Chris Lattner7121b802018-07-04 20:45:39 -0700616 return emitError("expected attribute name");
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700617 auto nameId = builder.getIdentifier(getTokenSpelling());
Chris Lattner7121b802018-07-04 20:45:39 -0700618 consumeToken();
619
620 if (!consumeIf(Token::colon))
621 return emitError("expected ':' in attribute list");
622
623 auto attr = parseAttribute();
624 if (!attr) return ParseFailure;
625
626 attributes.push_back({nameId, attr});
627 return ParseSuccess;
628 };
629
630 if (parseCommaSeparatedList(Token::r_brace, parseElt))
631 return ParseFailure;
632
633 return ParseSuccess;
634}
635
636//===----------------------------------------------------------------------===//
MLIR Teamf85a6262018-06-27 11:03:08 -0700637// Polyhedral structures.
638//===----------------------------------------------------------------------===//
639
Chris Lattner2e595eb2018-07-10 10:08:27 -0700640/// Lower precedence ops (all at the same precedence level). LNoOp is false in
641/// the boolean sense.
642enum AffineLowPrecOp {
643 /// Null value.
644 LNoOp,
645 Add,
646 Sub
647};
MLIR Teamf85a6262018-06-27 11:03:08 -0700648
Chris Lattner2e595eb2018-07-10 10:08:27 -0700649/// Higher precedence ops - all at the same precedence level. HNoOp is false in
650/// the boolean sense.
651enum AffineHighPrecOp {
652 /// Null value.
653 HNoOp,
654 Mul,
655 FloorDiv,
656 CeilDiv,
657 Mod
658};
Chris Lattner7121b802018-07-04 20:45:39 -0700659
Chris Lattner2e595eb2018-07-10 10:08:27 -0700660namespace {
661/// This is a specialized parser for AffineMap's, maintaining the state
662/// transient to their bodies.
663class AffineMapParser : public Parser {
664public:
665 explicit AffineMapParser(ParserState &state) : Parser(state) {}
Chris Lattner7121b802018-07-04 20:45:39 -0700666
Chris Lattner2e595eb2018-07-10 10:08:27 -0700667 AffineMap *parseAffineMapInline();
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -0700668
Chris Lattner2e595eb2018-07-10 10:08:27 -0700669private:
670 unsigned getNumDims() const { return dims.size(); }
671 unsigned getNumSymbols() const { return symbols.size(); }
MLIR Teamf85a6262018-06-27 11:03:08 -0700672
Uday Bondhugula0115dbb2018-07-11 21:31:07 -0700673 /// Returns true if the only identifiers the parser accepts in affine
674 /// expressions are symbolic identifiers.
675 bool isPureSymbolic() const { return pureSymbolic; }
676 void setSymbolicParsing(bool val) { pureSymbolic = val; }
677
Chris Lattner2e595eb2018-07-10 10:08:27 -0700678 // Binary affine op parsing.
679 AffineLowPrecOp consumeIfLowPrecOp();
680 AffineHighPrecOp consumeIfHighPrecOp();
MLIR Teamf85a6262018-06-27 11:03:08 -0700681
Chris Lattner2e595eb2018-07-10 10:08:27 -0700682 // Identifier lists for polyhedral structures.
683 ParseResult parseDimIdList();
684 ParseResult parseSymbolIdList();
685 ParseResult parseDimOrSymbolId(bool isDim);
686
687 AffineExpr *parseAffineExpr();
688 AffineExpr *parseParentheticalExpr();
689 AffineExpr *parseNegateExpression(AffineExpr *lhs);
690 AffineExpr *parseIntegerExpr();
691 AffineExpr *parseBareIdExpr();
692
693 AffineExpr *getBinaryAffineOpExpr(AffineHighPrecOp op, AffineExpr *lhs,
694 AffineExpr *rhs);
695 AffineExpr *getBinaryAffineOpExpr(AffineLowPrecOp op, AffineExpr *lhs,
696 AffineExpr *rhs);
697 AffineExpr *parseAffineOperandExpr(AffineExpr *lhs);
698 AffineExpr *parseAffineLowPrecOpExpr(AffineExpr *llhs,
699 AffineLowPrecOp llhsOp);
700 AffineExpr *parseAffineHighPrecOpExpr(AffineExpr *llhs,
701 AffineHighPrecOp llhsOp);
702
703private:
704 // TODO(bondhugula): could just use an vector/ArrayRef and scan the numbers.
705 llvm::StringMap<unsigned> dims;
706 llvm::StringMap<unsigned> symbols;
Uday Bondhugula0115dbb2018-07-11 21:31:07 -0700707 /// True if the parser should allow only symbolic identifiers in affine
708 /// expressions.
709 bool pureSymbolic = false;
Chris Lattner2e595eb2018-07-10 10:08:27 -0700710};
711} // end anonymous namespace
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -0700712
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700713/// Create an affine binary high precedence op expression (mul's, div's, mod)
Chris Lattner2e595eb2018-07-10 10:08:27 -0700714AffineExpr *AffineMapParser::getBinaryAffineOpExpr(AffineHighPrecOp op,
715 AffineExpr *lhs,
716 AffineExpr *rhs) {
Uday Bondhugula0115dbb2018-07-11 21:31:07 -0700717 // TODO: make the error location info accurate.
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700718 switch (op) {
719 case Mul:
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700720 if (!lhs->isSymbolic() && !rhs->isSymbolic()) {
721 emitError("non-affine expression: at least one of the multiply "
722 "operands has to be either a constant or symbolic");
723 return nullptr;
724 }
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700725 return builder.getMulExpr(lhs, rhs);
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700726 case FloorDiv:
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700727 if (!rhs->isSymbolic()) {
728 emitError("non-affine expression: right operand of floordiv "
729 "has to be either a constant or symbolic");
730 return nullptr;
731 }
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700732 return builder.getFloorDivExpr(lhs, rhs);
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700733 case CeilDiv:
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700734 if (!rhs->isSymbolic()) {
735 emitError("non-affine expression: right operand of ceildiv "
736 "has to be either a constant or symbolic");
737 return nullptr;
738 }
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700739 return builder.getCeilDivExpr(lhs, rhs);
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700740 case Mod:
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700741 if (!rhs->isSymbolic()) {
742 emitError("non-affine expression: right operand of mod "
743 "has to be either a constant or symbolic");
744 return nullptr;
745 }
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700746 return builder.getModExpr(lhs, rhs);
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700747 case HNoOp:
748 llvm_unreachable("can't create affine expression for null high prec op");
749 return nullptr;
750 }
751}
752
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700753/// Create an affine binary low precedence op expression (add, sub).
Chris Lattner2e595eb2018-07-10 10:08:27 -0700754AffineExpr *AffineMapParser::getBinaryAffineOpExpr(AffineLowPrecOp op,
755 AffineExpr *lhs,
756 AffineExpr *rhs) {
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700757 switch (op) {
758 case AffineLowPrecOp::Add:
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700759 return builder.getAddExpr(lhs, rhs);
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700760 case AffineLowPrecOp::Sub:
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700761 return builder.getSubExpr(lhs, rhs);
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700762 case AffineLowPrecOp::LNoOp:
763 llvm_unreachable("can't create affine expression for null low prec op");
764 return nullptr;
765 }
766}
767
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700768/// Consume this token if it is a lower precedence affine op (there are only two
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700769/// precedence levels).
Chris Lattner2e595eb2018-07-10 10:08:27 -0700770AffineLowPrecOp AffineMapParser::consumeIfLowPrecOp() {
Chris Lattner48af7d12018-07-09 19:05:38 -0700771 switch (getToken().getKind()) {
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700772 case Token::plus:
773 consumeToken(Token::plus);
774 return AffineLowPrecOp::Add;
775 case Token::minus:
776 consumeToken(Token::minus);
777 return AffineLowPrecOp::Sub;
778 default:
779 return AffineLowPrecOp::LNoOp;
780 }
781}
782
783/// Consume this token if it is a higher precedence affine op (there are only
784/// two precedence levels)
Chris Lattner2e595eb2018-07-10 10:08:27 -0700785AffineHighPrecOp AffineMapParser::consumeIfHighPrecOp() {
Chris Lattner48af7d12018-07-09 19:05:38 -0700786 switch (getToken().getKind()) {
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700787 case Token::star:
788 consumeToken(Token::star);
789 return Mul;
790 case Token::kw_floordiv:
791 consumeToken(Token::kw_floordiv);
792 return FloorDiv;
793 case Token::kw_ceildiv:
794 consumeToken(Token::kw_ceildiv);
795 return CeilDiv;
796 case Token::kw_mod:
797 consumeToken(Token::kw_mod);
798 return Mod;
799 default:
800 return HNoOp;
801 }
802}
803
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700804/// Parse a high precedence op expression list: mul, div, and mod are high
805/// precedence binary ops, i.e., parse a
806/// expr_1 op_1 expr_2 op_2 ... expr_n
807/// where op_1, op_2 are all a AffineHighPrecOp (mul, div, mod).
808/// All affine binary ops are left associative.
809/// Given llhs, returns (llhs llhsOp lhs) op rhs, or (lhs op rhs) if llhs is
810/// null. If no rhs can be found, returns (llhs llhsOp lhs) or lhs if llhs is
811/// null.
812AffineExpr *
Chris Lattner2e595eb2018-07-10 10:08:27 -0700813AffineMapParser::parseAffineHighPrecOpExpr(AffineExpr *llhs,
814 AffineHighPrecOp llhsOp) {
815 AffineExpr *lhs = parseAffineOperandExpr(llhs);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700816 if (!lhs)
817 return nullptr;
818
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700819 // Found an LHS. Parse the remaining expression.
Chris Lattner2e595eb2018-07-10 10:08:27 -0700820 if (AffineHighPrecOp op = consumeIfHighPrecOp()) {
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700821 if (llhs) {
822 AffineExpr *expr = getBinaryAffineOpExpr(llhsOp, llhs, lhs);
823 if (!expr)
824 return nullptr;
Chris Lattner2e595eb2018-07-10 10:08:27 -0700825 return parseAffineHighPrecOpExpr(expr, op);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700826 }
827 // No LLHS, get RHS
Chris Lattner2e595eb2018-07-10 10:08:27 -0700828 return parseAffineHighPrecOpExpr(lhs, op);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700829 }
830
831 // This is the last operand in this expression.
832 if (llhs)
833 return getBinaryAffineOpExpr(llhsOp, llhs, lhs);
834
835 // No llhs, 'lhs' itself is the expression.
836 return lhs;
837}
838
839/// Parse an affine expression inside parentheses.
840///
841/// affine-expr ::= `(` affine-expr `)`
Chris Lattner2e595eb2018-07-10 10:08:27 -0700842AffineExpr *AffineMapParser::parseParentheticalExpr() {
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700843 if (!consumeIf(Token::l_paren))
844 return (emitError("expected '('"), nullptr);
Chris Lattner48af7d12018-07-09 19:05:38 -0700845 if (getToken().is(Token::r_paren))
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700846 return (emitError("no expression inside parentheses"), nullptr);
Chris Lattner2e595eb2018-07-10 10:08:27 -0700847 auto *expr = parseAffineExpr();
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700848 if (!expr)
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700849 return nullptr;
850 if (!consumeIf(Token::r_paren))
851 return (emitError("expected ')'"), nullptr);
852 return expr;
853}
854
855/// Parse the negation expression.
856///
857/// affine-expr ::= `-` affine-expr
Chris Lattner2e595eb2018-07-10 10:08:27 -0700858AffineExpr *AffineMapParser::parseNegateExpression(AffineExpr *lhs) {
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700859 if (!consumeIf(Token::minus))
860 return (emitError("expected '-'"), nullptr);
861
Chris Lattner2e595eb2018-07-10 10:08:27 -0700862 AffineExpr *operand = parseAffineOperandExpr(lhs);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700863 // Since negation has the highest precedence of all ops (including high
864 // precedence ops) but lower than parentheses, we are only going to use
865 // parseAffineOperandExpr instead of parseAffineExpr here.
866 if (!operand)
867 // Extra error message although parseAffineOperandExpr would have
868 // complained. Leads to a better diagnostic.
869 return (emitError("missing operand of negation"), nullptr);
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700870 auto *minusOne = builder.getConstantExpr(-1);
871 return builder.getMulExpr(minusOne, operand);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700872}
873
874/// Parse a bare id that may appear in an affine expression.
875///
876/// affine-expr ::= bare-id
Chris Lattner2e595eb2018-07-10 10:08:27 -0700877AffineExpr *AffineMapParser::parseBareIdExpr() {
Chris Lattner48af7d12018-07-09 19:05:38 -0700878 if (getToken().isNot(Token::bare_identifier))
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700879 return (emitError("expected bare identifier"), nullptr);
880
Chris Lattner48af7d12018-07-09 19:05:38 -0700881 StringRef sRef = getTokenSpelling();
Uday Bondhugula0115dbb2018-07-11 21:31:07 -0700882 // dims, symbols are all pairwise distinct.
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700883 if (dims.count(sRef)) {
Uday Bondhugula0115dbb2018-07-11 21:31:07 -0700884 if (isPureSymbolic())
885 return (emitError("identifier used is not a symbolic identifier"),
886 nullptr);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700887 consumeToken(Token::bare_identifier);
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700888 return builder.getDimExpr(dims.lookup(sRef));
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700889 }
Uday Bondhugula0115dbb2018-07-11 21:31:07 -0700890
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700891 if (symbols.count(sRef)) {
892 consumeToken(Token::bare_identifier);
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700893 return builder.getSymbolExpr(symbols.lookup(sRef));
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700894 }
Uday Bondhugula0115dbb2018-07-11 21:31:07 -0700895
896 return (emitError("use of undeclared identifier"), nullptr);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700897}
898
899/// Parse a positive integral constant appearing in an affine expression.
900///
901/// affine-expr ::= integer-literal
Chris Lattner2e595eb2018-07-10 10:08:27 -0700902AffineExpr *AffineMapParser::parseIntegerExpr() {
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700903 // No need to handle negative numbers separately here. They are naturally
904 // handled via the unary negation operator, although (FIXME) MININT_64 still
905 // not correctly handled.
Chris Lattner48af7d12018-07-09 19:05:38 -0700906 if (getToken().isNot(Token::integer))
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700907 return (emitError("expected integer"), nullptr);
908
Chris Lattner48af7d12018-07-09 19:05:38 -0700909 auto val = getToken().getUInt64IntegerValue();
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700910 if (!val.hasValue() || (int64_t)val.getValue() < 0) {
911 return (emitError("constant too large for affineint"), nullptr);
912 }
913 consumeToken(Token::integer);
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700914 return builder.getConstantExpr((int64_t)val.getValue());
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700915}
916
917/// Parses an expression that can be a valid operand of an affine expression.
Uday Bondhugula76345202018-07-09 13:47:52 -0700918/// lhs: if non-null, lhs is an affine expression that is the lhs of a binary
919/// operator, the rhs of which is being parsed. This is used to determine
920/// whether an error should be emitted for a missing right operand.
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700921// Eg: for an expression without parentheses (like i + j + k + l), each
922// of the four identifiers is an operand. For i + j*k + l, j*k is not an
923// operand expression, it's an op expression and will be parsed via
924// parseAffineHighPrecOpExpression(). However, for i + (j*k) + -l, (j*k) and -l
925// are valid operands that will be parsed by this function.
Chris Lattner2e595eb2018-07-10 10:08:27 -0700926AffineExpr *AffineMapParser::parseAffineOperandExpr(AffineExpr *lhs) {
Chris Lattner48af7d12018-07-09 19:05:38 -0700927 switch (getToken().getKind()) {
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700928 case Token::bare_identifier:
Chris Lattner2e595eb2018-07-10 10:08:27 -0700929 return parseBareIdExpr();
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700930 case Token::integer:
Chris Lattner2e595eb2018-07-10 10:08:27 -0700931 return parseIntegerExpr();
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700932 case Token::l_paren:
Chris Lattner2e595eb2018-07-10 10:08:27 -0700933 return parseParentheticalExpr();
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700934 case Token::minus:
Chris Lattner2e595eb2018-07-10 10:08:27 -0700935 return parseNegateExpression(lhs);
Uday Bondhugula76345202018-07-09 13:47:52 -0700936 case Token::kw_ceildiv:
937 case Token::kw_floordiv:
938 case Token::kw_mod:
939 case Token::plus:
940 case Token::star:
941 if (lhs)
942 emitError("missing right operand of binary operator");
943 else
944 emitError("missing left operand of binary operator");
945 return nullptr;
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700946 default:
947 if (lhs)
Uday Bondhugula76345202018-07-09 13:47:52 -0700948 emitError("missing right operand of binary operator");
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700949 else
950 emitError("expected affine expression");
951 return nullptr;
952 }
953}
954
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700955/// Parse affine expressions that are bare-id's, integer constants,
956/// parenthetical affine expressions, and affine op expressions that are a
957/// composition of those.
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -0700958///
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700959/// All binary op's associate from left to right.
960///
961/// {add, sub} have lower precedence than {mul, div, and mod}.
962///
Uday Bondhugula76345202018-07-09 13:47:52 -0700963/// Add, sub'are themselves at the same precedence level. Mul, floordiv,
964/// ceildiv, and mod are at the same higher precedence level. Negation has
965/// higher precedence than any binary op.
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700966///
967/// llhs: the affine expression appearing on the left of the one being parsed.
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700968/// This function will return ((llhs llhsOp lhs) op rhs) if llhs is non null,
969/// and lhs op rhs otherwise; if there is no rhs, llhs llhsOp lhs is returned if
970/// llhs is non-null; otherwise lhs is returned. This is to deal with left
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700971/// associativity.
972///
973/// Eg: when the expression is e1 + e2*e3 + e4, with e1 as llhs, this function
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700974/// will return the affine expr equivalent of (e1 + (e2*e3)) + e4, where (e2*e3)
975/// will be parsed using parseAffineHighPrecOpExpr().
Chris Lattner2e595eb2018-07-10 10:08:27 -0700976AffineExpr *AffineMapParser::parseAffineLowPrecOpExpr(AffineExpr *llhs,
977 AffineLowPrecOp llhsOp) {
Uday Bondhugula76345202018-07-09 13:47:52 -0700978 AffineExpr *lhs;
Chris Lattner2e595eb2018-07-10 10:08:27 -0700979 if (!(lhs = parseAffineOperandExpr(llhs)))
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700980 return nullptr;
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700981
982 // Found an LHS. Deal with the ops.
Chris Lattner2e595eb2018-07-10 10:08:27 -0700983 if (AffineLowPrecOp lOp = consumeIfLowPrecOp()) {
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700984 if (llhs) {
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700985 AffineExpr *sum = getBinaryAffineOpExpr(llhsOp, llhs, lhs);
Chris Lattner2e595eb2018-07-10 10:08:27 -0700986 return parseAffineLowPrecOpExpr(sum, lOp);
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700987 }
988 // No LLHS, get RHS and form the expression.
Chris Lattner2e595eb2018-07-10 10:08:27 -0700989 return parseAffineLowPrecOpExpr(lhs, lOp);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700990 }
Chris Lattner2e595eb2018-07-10 10:08:27 -0700991 if (AffineHighPrecOp hOp = consumeIfHighPrecOp()) {
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700992 // We have a higher precedence op here. Get the rhs operand for the llhs
993 // through parseAffineHighPrecOpExpr.
Chris Lattner2e595eb2018-07-10 10:08:27 -0700994 AffineExpr *highRes = parseAffineHighPrecOpExpr(lhs, hOp);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700995 if (!highRes)
996 return nullptr;
Chris Lattner2e595eb2018-07-10 10:08:27 -0700997
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700998 // If llhs is null, the product forms the first operand of the yet to be
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700999 // found expression. If non-null, the op to associate with llhs is llhsOp.
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001000 AffineExpr *expr =
Chris Lattner158e0a3e2018-07-08 20:51:38 -07001001 llhs ? getBinaryAffineOpExpr(llhsOp, llhs, highRes) : highRes;
Chris Lattner2e595eb2018-07-10 10:08:27 -07001002
Uday Bondhugula3934d4d2018-07-09 09:00:25 -07001003 // Recurse for subsequent low prec op's after the affine high prec op
1004 // expression.
Chris Lattner2e595eb2018-07-10 10:08:27 -07001005 if (AffineLowPrecOp nextOp = consumeIfLowPrecOp())
1006 return parseAffineLowPrecOpExpr(expr, nextOp);
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001007 return expr;
1008 }
Uday Bondhugula3934d4d2018-07-09 09:00:25 -07001009 // Last operand in the expression list.
1010 if (llhs)
1011 return getBinaryAffineOpExpr(llhsOp, llhs, lhs);
1012 // No llhs, 'lhs' itself is the expression.
1013 return lhs;
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001014}
1015
1016/// Parse an affine expression.
Uday Bondhugula3934d4d2018-07-09 09:00:25 -07001017/// affine-expr ::= `(` affine-expr `)`
1018/// | `-` affine-expr
1019/// | affine-expr `+` affine-expr
1020/// | affine-expr `-` affine-expr
1021/// | affine-expr `*` affine-expr
1022/// | affine-expr `floordiv` affine-expr
1023/// | affine-expr `ceildiv` affine-expr
1024/// | affine-expr `mod` affine-expr
1025/// | bare-id
1026/// | integer-literal
1027///
1028/// Additional conditions are checked depending on the production. For eg., one
1029/// of the operands for `*` has to be either constant/symbolic; the second
1030/// operand for floordiv, ceildiv, and mod has to be a positive integer.
Chris Lattner2e595eb2018-07-10 10:08:27 -07001031AffineExpr *AffineMapParser::parseAffineExpr() {
1032 return parseAffineLowPrecOpExpr(nullptr, AffineLowPrecOp::LNoOp);
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001033}
1034
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001035/// Parse a dim or symbol from the lists appearing before the actual expressions
Chris Lattner2e595eb2018-07-10 10:08:27 -07001036/// of the affine map. Update our state to store the dimensional/symbolic
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001037/// identifier. 'dim': whether it's the dim list or symbol list that is being
1038/// parsed.
Chris Lattner2e595eb2018-07-10 10:08:27 -07001039ParseResult AffineMapParser::parseDimOrSymbolId(bool isDim) {
Chris Lattner48af7d12018-07-09 19:05:38 -07001040 if (getToken().isNot(Token::bare_identifier))
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001041 return emitError("expected bare identifier");
Chris Lattner48af7d12018-07-09 19:05:38 -07001042 auto sRef = getTokenSpelling();
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001043 consumeToken(Token::bare_identifier);
Chris Lattner2e595eb2018-07-10 10:08:27 -07001044 if (dims.count(sRef))
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001045 return emitError("dimensional identifier name reused");
Chris Lattner2e595eb2018-07-10 10:08:27 -07001046 if (symbols.count(sRef))
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001047 return emitError("symbolic identifier name reused");
Chris Lattner2e595eb2018-07-10 10:08:27 -07001048 if (isDim)
1049 dims.insert({sRef, dims.size()});
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001050 else
Chris Lattner2e595eb2018-07-10 10:08:27 -07001051 symbols.insert({sRef, symbols.size()});
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001052 return ParseSuccess;
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001053}
1054
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001055/// Parse the list of symbolic identifiers to an affine map.
Chris Lattner2e595eb2018-07-10 10:08:27 -07001056ParseResult AffineMapParser::parseSymbolIdList() {
1057 if (!consumeIf(Token::l_bracket))
1058 return emitError("expected '['");
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001059
Chris Lattner2e595eb2018-07-10 10:08:27 -07001060 auto parseElt = [&]() -> ParseResult { return parseDimOrSymbolId(false); };
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001061 return parseCommaSeparatedList(Token::r_bracket, parseElt);
1062}
1063
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001064/// Parse the list of dimensional identifiers to an affine map.
Chris Lattner2e595eb2018-07-10 10:08:27 -07001065ParseResult AffineMapParser::parseDimIdList() {
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001066 if (!consumeIf(Token::l_paren))
1067 return emitError("expected '(' at start of dimensional identifiers list");
1068
Chris Lattner2e595eb2018-07-10 10:08:27 -07001069 auto parseElt = [&]() -> ParseResult { return parseDimOrSymbolId(true); };
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001070 return parseCommaSeparatedList(Token::r_paren, parseElt);
1071}
1072
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001073/// Parse an affine map definition.
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001074///
Uday Bondhugula3934d4d2018-07-09 09:00:25 -07001075/// affine-map-inline ::= dim-and-symbol-id-lists `->` multi-dim-affine-expr
1076/// (`size` `(` dim-size (`,` dim-size)* `)`)?
1077/// dim-size ::= affine-expr | `min` `(` affine-expr ( `,` affine-expr)+ `)`
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001078///
Uday Bondhugula3934d4d2018-07-09 09:00:25 -07001079/// multi-dim-affine-expr ::= `(` affine-expr (`,` affine-expr)* `)
Chris Lattner2e595eb2018-07-10 10:08:27 -07001080AffineMap *AffineMapParser::parseAffineMapInline() {
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001081 // List of dimensional identifiers.
Chris Lattner2e595eb2018-07-10 10:08:27 -07001082 if (parseDimIdList())
Chris Lattner7121b802018-07-04 20:45:39 -07001083 return nullptr;
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001084
1085 // Symbols are optional.
Chris Lattner48af7d12018-07-09 19:05:38 -07001086 if (getToken().is(Token::l_bracket)) {
Chris Lattner2e595eb2018-07-10 10:08:27 -07001087 if (parseSymbolIdList())
Chris Lattner7121b802018-07-04 20:45:39 -07001088 return nullptr;
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001089 }
1090 if (!consumeIf(Token::arrow)) {
Chris Lattner7121b802018-07-04 20:45:39 -07001091 return (emitError("expected '->' or '['"), nullptr);
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001092 }
1093 if (!consumeIf(Token::l_paren)) {
1094 emitError("expected '(' at start of affine map range");
Chris Lattner7121b802018-07-04 20:45:39 -07001095 return nullptr;
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001096 }
1097
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001098 SmallVector<AffineExpr *, 4> exprs;
1099 auto parseElt = [&]() -> ParseResult {
Chris Lattner2e595eb2018-07-10 10:08:27 -07001100 auto *elt = parseAffineExpr();
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001101 ParseResult res = elt ? ParseSuccess : ParseFailure;
1102 exprs.push_back(elt);
1103 return res;
1104 };
1105
1106 // Parse a multi-dimensional affine expression (a comma-separated list of 1-d
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001107 // affine expressions); the list cannot be empty.
1108 // Grammar: multi-dim-affine-expr ::= `(` affine-expr (`,` affine-expr)* `)
1109 if (parseCommaSeparatedList(Token::r_paren, parseElt, false))
Chris Lattner7121b802018-07-04 20:45:39 -07001110 return nullptr;
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001111
Uday Bondhugula0115dbb2018-07-11 21:31:07 -07001112 // Parse optional range sizes.
Uday Bondhugula1e500b42018-07-12 18:04:04 -07001113 // range-sizes ::= (`size` `(` dim-size (`,` dim-size)* `)`)?
1114 // dim-size ::= affine-expr | `min` `(` affine-expr (`,` affine-expr)+ `)`
1115 // TODO(bondhugula): support for min of several affine expressions.
Uday Bondhugula0115dbb2018-07-11 21:31:07 -07001116 // TODO: check if sizes are non-negative whenever they are constant.
1117 SmallVector<AffineExpr *, 4> rangeSizes;
1118 if (consumeIf(Token::kw_size)) {
1119 // Location of the l_paren token (if it exists) for error reporting later.
1120 auto loc = getToken().getLoc();
1121 if (!consumeIf(Token::l_paren))
1122 return (emitError("expected '(' at start of affine map range"), nullptr);
1123
1124 auto parseRangeSize = [&]() -> ParseResult {
1125 auto *elt = parseAffineExpr();
1126 ParseResult res = elt ? ParseSuccess : ParseFailure;
1127 rangeSizes.push_back(elt);
1128 return res;
1129 };
1130
1131 setSymbolicParsing(true);
1132 if (parseCommaSeparatedList(Token::r_paren, parseRangeSize, false))
1133 return nullptr;
1134 if (exprs.size() > rangeSizes.size())
1135 return (emitError(loc, "fewer range sizes than range expressions"),
1136 nullptr);
1137 if (exprs.size() < rangeSizes.size())
1138 return (emitError(loc, "more range sizes than range expressions"),
1139 nullptr);
1140 }
1141
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001142 // Parsed a valid affine map.
Uday Bondhugula0115dbb2018-07-11 21:31:07 -07001143 return builder.getAffineMap(dims.size(), symbols.size(), exprs, rangeSizes);
MLIR Teamf85a6262018-06-27 11:03:08 -07001144}
1145
Chris Lattner2e595eb2018-07-10 10:08:27 -07001146AffineMap *Parser::parseAffineMapInline() {
1147 return AffineMapParser(state).parseAffineMapInline();
1148}
1149
MLIR Team718c82f2018-07-16 09:45:22 -07001150AffineMap *Parser::parseAffineMapReference() {
1151 if (getToken().is(Token::hash_identifier)) {
1152 // Parse affine map identifier and verify that it exists.
1153 StringRef affineMapId = getTokenSpelling().drop_front();
1154 if (getState().affineMapDefinitions.count(affineMapId) == 0)
1155 return (emitError("undefined affine map id '" + affineMapId + "'"),
1156 nullptr);
1157 consumeToken(Token::hash_identifier);
1158 return getState().affineMapDefinitions[affineMapId];
1159 }
1160 // Try to parse inline affine map.
1161 return parseAffineMapInline();
1162}
1163
MLIR Teamf85a6262018-06-27 11:03:08 -07001164//===----------------------------------------------------------------------===//
Chris Lattner7f9cc272018-07-19 08:35:28 -07001165// FunctionParser
Chris Lattner4c95a502018-06-23 16:03:42 -07001166//===----------------------------------------------------------------------===//
Chris Lattnere79379a2018-06-22 10:39:19 -07001167
Chris Lattner7f9cc272018-07-19 08:35:28 -07001168namespace {
1169/// This class contains parser state that is common across CFG and ML functions,
1170/// notably for dealing with operations and SSA values.
1171class FunctionParser : public Parser {
1172public:
1173 FunctionParser(ParserState &state) : Parser(state) {}
1174
1175 /// This represents a use of an SSA value in the program. This tracks
1176 /// location information in case this ends up being a use of an undefined
1177 /// value.
1178 typedef std::pair<StringRef, SMLoc> SSAUseInfo;
1179
1180 /// Given a reference to an SSA value and its type, return a reference. This
1181 /// returns null on failure.
1182 SSAValue *resolveSSAUse(SSAUseInfo useInfo, Type *type);
1183
1184 /// Register a definition of a value with the symbol table.
1185 ParseResult addDefinition(SSAUseInfo useInfo, SSAValue *value);
1186
1187 // SSA parsing productions.
1188 ParseResult parseSSAUse(SSAUseInfo &result);
1189 ParseResult parseOptionalSSAUseList(Token::Kind endToken,
1190 SmallVectorImpl<SSAUseInfo> &results);
1191 SSAValue *parseSSAUseAndType();
1192 ParseResult
1193 parseOptionalSSAUseAndTypeList(Token::Kind endToken,
1194 SmallVectorImpl<SSAValue *> &results);
1195
1196 // Operations
1197 ParseResult parseOperation(const CreateOperationFunction &createOpFunc);
1198
1199private:
1200 /// This keeps track of all of the SSA values we are tracking, indexed by
1201 /// their name (either an identifier or a number).
1202 llvm::StringMap<std::pair<SSAValue *, SMLoc>> values;
1203};
1204} // end anonymous namespace
1205
1206/// Given an unbound reference to an SSA value and its type, return a the value
1207/// it specifies. This returns null on failure.
1208SSAValue *FunctionParser::resolveSSAUse(SSAUseInfo useInfo, Type *type) {
1209 // If we have already seen a value of this name, return it.
1210 auto it = values.find(useInfo.first);
1211 if (it != values.end()) {
1212 // Check that the type matches the other uses.
1213 auto result = it->second.first;
1214 if (result->getType() == type)
1215 return result;
1216
1217 emitError(useInfo.second, "use of value '" + useInfo.first.str() +
1218 "' expects different type than prior uses");
1219 emitError(it->second.second, "prior use here");
1220 return nullptr;
1221 }
1222
1223 // Otherwise we have a forward reference.
1224 // TODO: Handle forward references.
1225 emitError(useInfo.second, "undeclared or forward reference");
1226 return nullptr;
1227}
1228
1229/// Register a definition of a value with the symbol table.
1230ParseResult FunctionParser::addDefinition(SSAUseInfo useInfo, SSAValue *value) {
1231
1232 // If this is the first definition of this thing, then we are trivially done.
1233 auto insertInfo = values.insert({useInfo.first, {value, useInfo.second}});
1234 if (insertInfo.second)
1235 return ParseSuccess;
1236
1237 // If we already had a value, replace it with the new one and remove the
1238 // placeholder, only if it was a forward ref.
1239 // TODO: Handle forward references.
1240 emitError(useInfo.second, "redefinition of SSA value " + useInfo.first.str());
1241 return ParseFailure;
1242}
1243
Chris Lattner78276e32018-07-07 15:48:26 -07001244/// Parse a SSA operand for an instruction or statement.
1245///
1246/// ssa-use ::= ssa-id | ssa-constant
Chris Lattner7f9cc272018-07-19 08:35:28 -07001247/// TODO: SSA Constants.
Chris Lattner78276e32018-07-07 15:48:26 -07001248///
Chris Lattner7f9cc272018-07-19 08:35:28 -07001249ParseResult FunctionParser::parseSSAUse(SSAUseInfo &result) {
1250 result.first = getTokenSpelling();
1251 result.second = getToken().getLoc();
1252 if (!consumeIf(Token::percent_identifier))
1253 return emitError("expected SSA operand");
1254 return ParseSuccess;
Chris Lattner78276e32018-07-07 15:48:26 -07001255}
1256
1257/// Parse a (possibly empty) list of SSA operands.
1258///
1259/// ssa-use-list ::= ssa-use (`,` ssa-use)*
1260/// ssa-use-list-opt ::= ssa-use-list?
1261///
Chris Lattner7f9cc272018-07-19 08:35:28 -07001262ParseResult
1263FunctionParser::parseOptionalSSAUseList(Token::Kind endToken,
1264 SmallVectorImpl<SSAUseInfo> &results) {
1265 return parseCommaSeparatedList(endToken, [&]() -> ParseResult {
1266 SSAUseInfo result;
1267 if (parseSSAUse(result))
1268 return ParseFailure;
1269 results.push_back(result);
1270 return ParseSuccess;
1271 });
Chris Lattner78276e32018-07-07 15:48:26 -07001272}
1273
1274/// Parse an SSA use with an associated type.
1275///
1276/// ssa-use-and-type ::= ssa-use `:` type
Chris Lattner7f9cc272018-07-19 08:35:28 -07001277SSAValue *FunctionParser::parseSSAUseAndType() {
1278 SSAUseInfo useInfo;
1279 if (parseSSAUse(useInfo))
1280 return nullptr;
Chris Lattner78276e32018-07-07 15:48:26 -07001281
1282 if (!consumeIf(Token::colon))
Chris Lattner7f9cc272018-07-19 08:35:28 -07001283 return (emitError("expected ':' and type for SSA operand"), nullptr);
Chris Lattner78276e32018-07-07 15:48:26 -07001284
Chris Lattner7f9cc272018-07-19 08:35:28 -07001285 auto *type = parseType();
1286 if (!type)
1287 return nullptr;
Chris Lattner78276e32018-07-07 15:48:26 -07001288
Chris Lattner7f9cc272018-07-19 08:35:28 -07001289 return resolveSSAUse(useInfo, type);
Chris Lattner78276e32018-07-07 15:48:26 -07001290}
1291
1292/// Parse a (possibly empty) list of SSA operands with types.
1293///
1294/// ssa-use-and-type-list ::= ssa-use-and-type (`,` ssa-use-and-type)*
1295///
Chris Lattner7f9cc272018-07-19 08:35:28 -07001296ParseResult FunctionParser::parseOptionalSSAUseAndTypeList(
1297 Token::Kind endToken, SmallVectorImpl<SSAValue *> &results) {
1298 return parseCommaSeparatedList(endToken, [&]() -> ParseResult {
1299 if (auto *value = parseSSAUseAndType()) {
1300 results.push_back(value);
1301 return ParseSuccess;
1302 }
1303 return ParseFailure;
1304 });
Chris Lattner78276e32018-07-07 15:48:26 -07001305}
1306
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001307/// Parse the CFG or MLFunc operation.
1308///
1309/// TODO(clattner): This is a change from the MLIR spec as written, it is an
1310/// experiment that will eliminate "builtin" instructions as a thing.
1311///
1312/// operation ::=
1313/// (ssa-id `=`)? string '(' ssa-use-list? ')' attribute-dict?
1314/// `:` function-type
1315///
1316ParseResult
Chris Lattner7f9cc272018-07-19 08:35:28 -07001317FunctionParser::parseOperation(const CreateOperationFunction &createOpFunc) {
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001318 auto loc = getToken().getLoc();
1319
1320 StringRef resultID;
1321 if (getToken().is(Token::percent_identifier)) {
Chris Lattner7f9cc272018-07-19 08:35:28 -07001322 resultID = getTokenSpelling();
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001323 consumeToken(Token::percent_identifier);
1324 if (!consumeIf(Token::equal))
1325 return emitError("expected '=' after SSA name");
1326 }
1327
1328 if (getToken().isNot(Token::string))
1329 return emitError("expected operation name in quotes");
1330
1331 auto name = getToken().getStringValue();
1332 if (name.empty())
1333 return emitError("empty operation name is invalid");
1334
1335 consumeToken(Token::string);
1336
1337 if (!consumeIf(Token::l_paren))
1338 return emitError("expected '(' to start operand list");
1339
1340 // Parse the operand list.
Chris Lattner7f9cc272018-07-19 08:35:28 -07001341 SmallVector<SSAUseInfo, 8> operandInfos;
1342 parseOptionalSSAUseList(Token::r_paren, operandInfos);
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001343
1344 SmallVector<NamedAttribute, 4> attributes;
1345 if (getToken().is(Token::l_brace)) {
1346 if (parseAttributeDict(attributes))
1347 return ParseFailure;
1348 }
1349
Chris Lattner3b2ef762018-07-18 15:31:25 -07001350 if (!consumeIf(Token::colon))
1351 return emitError("expected ':' followed by instruction type");
1352
1353 auto typeLoc = getToken().getLoc();
1354 auto type = parseType();
1355 if (!type)
1356 return ParseFailure;
1357 auto fnType = dyn_cast<FunctionType>(type);
1358 if (!fnType)
1359 return emitError(typeLoc, "expected function type");
1360
Chris Lattner7f9cc272018-07-19 08:35:28 -07001361 // Check that we have the right number of types for the operands.
1362 auto operandTypes = fnType->getInputs();
1363 if (operandTypes.size() != operandInfos.size()) {
1364 auto plural = "s"[operandInfos.size() == 1];
1365 return emitError(typeLoc, "expected " + llvm::utostr(operandInfos.size()) +
1366 " type" + plural +
1367 " in operand list but had " +
1368 llvm::utostr(operandTypes.size()));
1369 }
1370
1371 // Resolve all of the operands.
1372 SmallVector<SSAValue *, 8> operands;
1373 for (unsigned i = 0, e = operandInfos.size(); i != e; ++i) {
1374 operands.push_back(resolveSSAUse(operandInfos[i], operandTypes[i]));
1375 if (!operands.back())
1376 return ParseFailure;
1377 }
1378
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001379 auto nameId = builder.getIdentifier(name);
Chris Lattner7f9cc272018-07-19 08:35:28 -07001380 auto op = createOpFunc(nameId, operands, fnType->getResults(), attributes);
1381 if (!op)
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001382 return ParseFailure;
1383
1384 // We just parsed an operation. If it is a recognized one, verify that it
1385 // is structurally as we expect. If not, produce an error with a reasonable
1386 // source location.
Chris Lattner7f9cc272018-07-19 08:35:28 -07001387 if (auto *opInfo = op->getAbstractOperation(builder.getContext())) {
1388 if (auto error = opInfo->verifyInvariants(op))
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001389 return emitError(loc, error);
1390 }
1391
Chris Lattner7f9cc272018-07-19 08:35:28 -07001392 // If the instruction had a name, register it.
1393 if (!resultID.empty()) {
1394 // FIXME: Add result infra to handle Stmt results as well to make this
1395 // generic.
1396 if (auto *inst = dyn_cast<OperationInst>(op)) {
1397 if (inst->getResults().empty())
1398 return emitError(loc, "cannot name an operation with no results");
1399
1400 // TODO: This should be getResult(0)
1401 addDefinition({resultID, loc}, &inst->getResults()[0]);
1402 }
1403 }
1404
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001405 return ParseSuccess;
1406}
Chris Lattnere79379a2018-06-22 10:39:19 -07001407
Chris Lattner48af7d12018-07-09 19:05:38 -07001408//===----------------------------------------------------------------------===//
1409// CFG Functions
1410//===----------------------------------------------------------------------===//
Chris Lattnere79379a2018-06-22 10:39:19 -07001411
Chris Lattner4c95a502018-06-23 16:03:42 -07001412namespace {
Chris Lattner48af7d12018-07-09 19:05:38 -07001413/// This is a specialized parser for CFGFunction's, maintaining the state
1414/// transient to their bodies.
Chris Lattner7f9cc272018-07-19 08:35:28 -07001415class CFGFunctionParser : public FunctionParser {
Chris Lattner158e0a3e2018-07-08 20:51:38 -07001416public:
Chris Lattner2e595eb2018-07-10 10:08:27 -07001417 CFGFunctionParser(ParserState &state, CFGFunction *function)
Chris Lattner7f9cc272018-07-19 08:35:28 -07001418 : FunctionParser(state), function(function), builder(function) {}
Chris Lattner2e595eb2018-07-10 10:08:27 -07001419
1420 ParseResult parseFunctionBody();
1421
1422private:
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001423 CFGFunction *function;
1424 llvm::StringMap<std::pair<BasicBlock*, SMLoc>> blocksByName;
Chris Lattner48af7d12018-07-09 19:05:38 -07001425
1426 /// This builder intentionally shadows the builder in the base class, with a
1427 /// more specific builder type.
Chris Lattner158e0a3e2018-07-08 20:51:38 -07001428 CFGFuncBuilder builder;
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001429
Chris Lattner4c95a502018-06-23 16:03:42 -07001430 /// Get the basic block with the specified name, creating it if it doesn't
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001431 /// already exist. The location specified is the point of use, which allows
1432 /// us to diagnose references to blocks that are not defined precisely.
1433 BasicBlock *getBlockNamed(StringRef name, SMLoc loc) {
1434 auto &blockAndLoc = blocksByName[name];
1435 if (!blockAndLoc.first) {
Chris Lattner3a467cc2018-07-01 20:28:00 -07001436 blockAndLoc.first = new BasicBlock();
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001437 blockAndLoc.second = loc;
Chris Lattner4c95a502018-06-23 16:03:42 -07001438 }
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001439 return blockAndLoc.first;
Chris Lattner4c95a502018-06-23 16:03:42 -07001440 }
Chris Lattner48af7d12018-07-09 19:05:38 -07001441
Chris Lattner48af7d12018-07-09 19:05:38 -07001442 ParseResult parseBasicBlock();
1443 OperationInst *parseCFGOperation();
1444 TerminatorInst *parseTerminator();
Chris Lattner4c95a502018-06-23 16:03:42 -07001445};
1446} // end anonymous namespace
1447
Chris Lattner48af7d12018-07-09 19:05:38 -07001448ParseResult CFGFunctionParser::parseFunctionBody() {
1449 if (!consumeIf(Token::l_brace))
1450 return emitError("expected '{' in CFG function");
1451
1452 // Make sure we have at least one block.
1453 if (getToken().is(Token::r_brace))
1454 return emitError("CFG functions must have at least one basic block");
Chris Lattner4c95a502018-06-23 16:03:42 -07001455
1456 // Parse the list of blocks.
1457 while (!consumeIf(Token::r_brace))
Chris Lattner48af7d12018-07-09 19:05:38 -07001458 if (parseBasicBlock())
Chris Lattner4c95a502018-06-23 16:03:42 -07001459 return ParseFailure;
1460
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001461 // Verify that all referenced blocks were defined. Iteration over a
1462 // StringMap isn't determinstic, but this is good enough for our purposes.
Chris Lattner48af7d12018-07-09 19:05:38 -07001463 for (auto &elt : blocksByName) {
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001464 auto *bb = elt.second.first;
Chris Lattner3a467cc2018-07-01 20:28:00 -07001465 if (!bb->getFunction())
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001466 return emitError(elt.second.second,
1467 "reference to an undefined basic block '" +
1468 elt.first() + "'");
1469 }
1470
Chris Lattner48af7d12018-07-09 19:05:38 -07001471 getModule()->functionList.push_back(function);
Chris Lattner4c95a502018-06-23 16:03:42 -07001472 return ParseSuccess;
1473}
1474
1475/// Basic block declaration.
1476///
1477/// basic-block ::= bb-label instruction* terminator-stmt
1478/// bb-label ::= bb-id bb-arg-list? `:`
1479/// bb-id ::= bare-id
1480/// bb-arg-list ::= `(` ssa-id-and-type-list? `)`
1481///
Chris Lattner48af7d12018-07-09 19:05:38 -07001482ParseResult CFGFunctionParser::parseBasicBlock() {
1483 SMLoc nameLoc = getToken().getLoc();
1484 auto name = getTokenSpelling();
Chris Lattner4c95a502018-06-23 16:03:42 -07001485 if (!consumeIf(Token::bare_identifier))
1486 return emitError("expected basic block name");
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001487
Chris Lattner48af7d12018-07-09 19:05:38 -07001488 auto *block = getBlockNamed(name, nameLoc);
Chris Lattner4c95a502018-06-23 16:03:42 -07001489
1490 // If this block has already been parsed, then this is a redefinition with the
1491 // same block name.
Chris Lattner3a467cc2018-07-01 20:28:00 -07001492 if (block->getFunction())
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001493 return emitError(nameLoc, "redefinition of block '" + name.str() + "'");
1494
Chris Lattner3a467cc2018-07-01 20:28:00 -07001495 // Add the block to the function.
Chris Lattner48af7d12018-07-09 19:05:38 -07001496 function->push_back(block);
Chris Lattner4c95a502018-06-23 16:03:42 -07001497
Chris Lattner78276e32018-07-07 15:48:26 -07001498 // If an argument list is present, parse it.
1499 if (consumeIf(Token::l_paren)) {
Chris Lattner7f9cc272018-07-19 08:35:28 -07001500 SmallVector<SSAValue *, 8> bbArgs;
1501 if (parseOptionalSSAUseAndTypeList(Token::r_paren, bbArgs))
Chris Lattner78276e32018-07-07 15:48:26 -07001502 return ParseFailure;
1503
1504 // TODO: attach it.
1505 }
Chris Lattner4c95a502018-06-23 16:03:42 -07001506
1507 if (!consumeIf(Token::colon))
1508 return emitError("expected ':' after basic block name");
1509
Chris Lattner158e0a3e2018-07-08 20:51:38 -07001510 // Set the insertion point to the block we want to insert new operations into.
Chris Lattner48af7d12018-07-09 19:05:38 -07001511 builder.setInsertionPoint(block);
Chris Lattner158e0a3e2018-07-08 20:51:38 -07001512
Chris Lattner7f9cc272018-07-19 08:35:28 -07001513 auto createOpFunc = [&](Identifier name, ArrayRef<SSAValue *> operands,
1514 ArrayRef<Type *> resultTypes,
1515 ArrayRef<NamedAttribute> attrs) -> Operation * {
1516 SmallVector<CFGValue *, 8> cfgOperands;
1517 cfgOperands.reserve(operands.size());
1518 for (auto *op : operands)
1519 cfgOperands.push_back(cast<CFGValue>(op));
1520 return builder.createOperation(name, cfgOperands, resultTypes, attrs);
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001521 };
1522
Chris Lattnered65a732018-06-28 20:45:33 -07001523 // Parse the list of operations that make up the body of the block.
Chris Lattner48af7d12018-07-09 19:05:38 -07001524 while (getToken().isNot(Token::kw_return, Token::kw_br)) {
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001525 if (parseOperation(createOpFunc))
Chris Lattnered65a732018-06-28 20:45:33 -07001526 return ParseFailure;
1527 }
Chris Lattner4c95a502018-06-23 16:03:42 -07001528
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001529 if (!parseTerminator())
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001530 return ParseFailure;
Chris Lattner4c95a502018-06-23 16:03:42 -07001531
1532 return ParseSuccess;
1533}
1534
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001535/// Parse the terminator instruction for a basic block.
1536///
1537/// terminator-stmt ::= `br` bb-id branch-use-list?
1538/// branch-use-list ::= `(` ssa-use-and-type-list? `)`
1539/// terminator-stmt ::=
1540/// `cond_br` ssa-use `,` bb-id branch-use-list? `,` bb-id branch-use-list?
1541/// terminator-stmt ::= `return` ssa-use-and-type-list?
1542///
Chris Lattner48af7d12018-07-09 19:05:38 -07001543TerminatorInst *CFGFunctionParser::parseTerminator() {
1544 switch (getToken().getKind()) {
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001545 default:
Chris Lattner3a467cc2018-07-01 20:28:00 -07001546 return (emitError("expected terminator at end of basic block"), nullptr);
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001547
1548 case Token::kw_return:
1549 consumeToken(Token::kw_return);
Chris Lattner48af7d12018-07-09 19:05:38 -07001550 return builder.createReturnInst();
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001551
1552 case Token::kw_br: {
1553 consumeToken(Token::kw_br);
Chris Lattner48af7d12018-07-09 19:05:38 -07001554 auto destBB = getBlockNamed(getTokenSpelling(), getToken().getLoc());
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001555 if (!consumeIf(Token::bare_identifier))
Chris Lattner3a467cc2018-07-01 20:28:00 -07001556 return (emitError("expected basic block name"), nullptr);
Chris Lattner48af7d12018-07-09 19:05:38 -07001557 return builder.createBranchInst(destBB);
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001558 }
Chris Lattner78276e32018-07-07 15:48:26 -07001559 // TODO: cond_br.
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001560 }
1561}
1562
Chris Lattner48af7d12018-07-09 19:05:38 -07001563//===----------------------------------------------------------------------===//
1564// ML Functions
1565//===----------------------------------------------------------------------===//
1566
1567namespace {
1568/// Refined parser for MLFunction bodies.
Chris Lattner7f9cc272018-07-19 08:35:28 -07001569class MLFunctionParser : public FunctionParser {
Chris Lattner48af7d12018-07-09 19:05:38 -07001570public:
Chris Lattner48af7d12018-07-09 19:05:38 -07001571 MLFunctionParser(ParserState &state, MLFunction *function)
Chris Lattner7f9cc272018-07-19 08:35:28 -07001572 : FunctionParser(state), function(function), builder(function) {}
Chris Lattner48af7d12018-07-09 19:05:38 -07001573
1574 ParseResult parseFunctionBody();
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001575
1576private:
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001577 MLFunction *function;
1578
1579 /// This builder intentionally shadows the builder in the base class, with a
1580 /// more specific builder type.
1581 MLFuncBuilder builder;
1582
1583 ParseResult parseForStmt();
1584 ParseResult parseIfStmt();
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001585 ParseResult parseElseClause(IfClause *elseClause);
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001586 ParseResult parseStatements(StmtBlock *block);
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001587 ParseResult parseStmtBlock(StmtBlock *block);
Chris Lattner48af7d12018-07-09 19:05:38 -07001588};
1589} // end anonymous namespace
1590
Chris Lattner48af7d12018-07-09 19:05:38 -07001591ParseResult MLFunctionParser::parseFunctionBody() {
1592 if (!consumeIf(Token::l_brace))
1593 return emitError("expected '{' in ML function");
1594
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001595 // Parse statements in this function
1596 if (parseStatements(function))
1597 return ParseFailure;
Tatiana Shpeismanc96b5872018-06-28 17:02:32 -07001598
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001599 if (!consumeIf(Token::kw_return))
1600 emitError("ML function must end with return statement");
Tatiana Shpeismanc96b5872018-06-28 17:02:32 -07001601 // TODO: parse return statement operands
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001602
Tatiana Shpeismanc96b5872018-06-28 17:02:32 -07001603 if (!consumeIf(Token::r_brace))
1604 emitError("expected '}' in ML function");
1605
Chris Lattner48af7d12018-07-09 19:05:38 -07001606 getModule()->functionList.push_back(function);
Tatiana Shpeismanc96b5872018-06-28 17:02:32 -07001607
1608 return ParseSuccess;
1609}
1610
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001611/// For statement.
1612///
Chris Lattner48af7d12018-07-09 19:05:38 -07001613/// ml-for-stmt ::= `for` ssa-id `=` lower-bound `to` upper-bound
1614/// (`step` integer-literal)? `{` ml-stmt* `}`
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001615///
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001616ParseResult MLFunctionParser::parseForStmt() {
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001617 consumeToken(Token::kw_for);
1618
1619 //TODO: parse loop header
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001620 ForStmt *stmt = builder.createFor();
1621
1622 // If parsing of the for statement body fails
1623 // MLIR contains for statement with successfully parsed nested statements
1624 if (parseStmtBlock(static_cast<StmtBlock *>(stmt)))
1625 return ParseFailure;
1626
1627 return ParseSuccess;
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001628}
1629
1630/// If statement.
1631///
Chris Lattner48af7d12018-07-09 19:05:38 -07001632/// ml-if-head ::= `if` ml-if-cond `{` ml-stmt* `}`
1633/// | ml-if-head `else` `if` ml-if-cond `{` ml-stmt* `}`
1634/// ml-if-stmt ::= ml-if-head
1635/// | ml-if-head `else` `{` ml-stmt* `}`
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001636///
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001637ParseResult MLFunctionParser::parseIfStmt() {
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001638 consumeToken(Token::kw_if);
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001639 if (!consumeIf(Token::l_paren))
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001640 return emitError("expected (");
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001641
1642 //TODO: parse condition
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001643
1644 if (!consumeIf(Token::r_paren))
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001645 return emitError("expected )");
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001646
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001647 IfStmt *ifStmt = builder.createIf();
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001648 IfClause *thenClause = ifStmt->getThenClause();
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001649
1650 // If parsing of the then or optional else clause fails MLIR contains
1651 // if statement with successfully parsed nested statements.
1652 if (parseStmtBlock(thenClause))
1653 return ParseFailure;
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001654
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001655 if (consumeIf(Token::kw_else)) {
1656 IfClause *elseClause = ifStmt->createElseClause();
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001657 if (parseElseClause(elseClause))
1658 return ParseFailure;
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001659 }
1660
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001661 return ParseSuccess;
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001662}
1663
1664ParseResult MLFunctionParser::parseElseClause(IfClause *elseClause) {
1665 if (getToken().is(Token::kw_if)) {
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001666 builder.setInsertionPoint(elseClause);
1667 return parseIfStmt();
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001668 }
1669
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001670 return parseStmtBlock(elseClause);
1671}
1672
1673///
1674/// Parse a list of statements ending with `return` or `}`
1675///
1676ParseResult MLFunctionParser::parseStatements(StmtBlock *block) {
Chris Lattner7f9cc272018-07-19 08:35:28 -07001677 auto createOpFunc = [&](Identifier name, ArrayRef<SSAValue *> operands,
1678 ArrayRef<Type *> resultTypes,
1679 ArrayRef<NamedAttribute> attrs) -> Operation * {
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001680 return builder.createOperation(name, attrs);
1681 };
1682
1683 builder.setInsertionPoint(block);
1684
1685 while (getToken().isNot(Token::kw_return, Token::r_brace)) {
1686 switch (getToken().getKind()) {
1687 default:
1688 if (parseOperation(createOpFunc))
1689 return ParseFailure;
1690 break;
1691 case Token::kw_for:
1692 if (parseForStmt())
1693 return ParseFailure;
1694 break;
1695 case Token::kw_if:
1696 if (parseIfStmt())
1697 return ParseFailure;
1698 break;
1699 } // end switch
1700 }
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001701
1702 return ParseSuccess;
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001703}
1704
1705///
1706/// Parse `{` ml-stmt* `}`
1707///
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001708ParseResult MLFunctionParser::parseStmtBlock(StmtBlock *block) {
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001709 if (!consumeIf(Token::l_brace))
1710 return emitError("expected '{' before statement list");
1711
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001712 if (parseStatements(block))
1713 return ParseFailure;
1714
1715 if (!consumeIf(Token::r_brace))
1716 return emitError("expected '}' at the end of the statement block");
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001717
1718 return ParseSuccess;
1719}
1720
Chris Lattner4c95a502018-06-23 16:03:42 -07001721//===----------------------------------------------------------------------===//
1722// Top-level entity parsing.
1723//===----------------------------------------------------------------------===//
1724
Chris Lattner2e595eb2018-07-10 10:08:27 -07001725namespace {
1726/// This parser handles entities that are only valid at the top level of the
1727/// file.
1728class ModuleParser : public Parser {
1729public:
1730 explicit ModuleParser(ParserState &state) : Parser(state) {}
1731
1732 ParseResult parseModule();
1733
1734private:
1735 ParseResult parseAffineMapDef();
1736
1737 // Functions.
1738 ParseResult parseFunctionSignature(StringRef &name, FunctionType *&type);
1739 ParseResult parseExtFunc();
1740 ParseResult parseCFGFunc();
1741 ParseResult parseMLFunc();
1742};
1743} // end anonymous namespace
1744
1745/// Affine map declaration.
1746///
1747/// affine-map-def ::= affine-map-id `=` affine-map-inline
1748///
1749ParseResult ModuleParser::parseAffineMapDef() {
1750 assert(getToken().is(Token::hash_identifier));
1751
1752 StringRef affineMapId = getTokenSpelling().drop_front();
1753
1754 // Check for redefinitions.
1755 auto *&entry = getState().affineMapDefinitions[affineMapId];
1756 if (entry)
1757 return emitError("redefinition of affine map id '" + affineMapId + "'");
1758
1759 consumeToken(Token::hash_identifier);
1760
1761 // Parse the '='
1762 if (!consumeIf(Token::equal))
1763 return emitError("expected '=' in affine map outlined definition");
1764
1765 entry = parseAffineMapInline();
1766 if (!entry)
1767 return ParseFailure;
1768
Chris Lattner2e595eb2018-07-10 10:08:27 -07001769 return ParseSuccess;
1770}
1771
1772/// Parse a function signature, starting with a name and including the parameter
1773/// list.
1774///
1775/// argument-list ::= type (`,` type)* | /*empty*/
1776/// function-signature ::= function-id `(` argument-list `)` (`->` type-list)?
1777///
1778ParseResult ModuleParser::parseFunctionSignature(StringRef &name,
1779 FunctionType *&type) {
1780 if (getToken().isNot(Token::at_identifier))
1781 return emitError("expected a function identifier like '@foo'");
1782
1783 name = getTokenSpelling().drop_front();
1784 consumeToken(Token::at_identifier);
1785
1786 if (getToken().isNot(Token::l_paren))
1787 return emitError("expected '(' in function signature");
1788
1789 SmallVector<Type *, 4> arguments;
1790 if (parseTypeList(arguments))
1791 return ParseFailure;
1792
1793 // Parse the return type if present.
1794 SmallVector<Type *, 4> results;
1795 if (consumeIf(Token::arrow)) {
1796 if (parseTypeList(results))
1797 return ParseFailure;
1798 }
1799 type = builder.getFunctionType(arguments, results);
1800 return ParseSuccess;
1801}
1802
1803/// External function declarations.
1804///
1805/// ext-func ::= `extfunc` function-signature
1806///
1807ParseResult ModuleParser::parseExtFunc() {
1808 consumeToken(Token::kw_extfunc);
1809
1810 StringRef name;
1811 FunctionType *type = nullptr;
1812 if (parseFunctionSignature(name, type))
1813 return ParseFailure;
1814
1815 // Okay, the external function definition was parsed correctly.
1816 getModule()->functionList.push_back(new ExtFunction(name, type));
1817 return ParseSuccess;
1818}
1819
1820/// CFG function declarations.
1821///
1822/// cfg-func ::= `cfgfunc` function-signature `{` basic-block+ `}`
1823///
1824ParseResult ModuleParser::parseCFGFunc() {
1825 consumeToken(Token::kw_cfgfunc);
1826
1827 StringRef name;
1828 FunctionType *type = nullptr;
1829 if (parseFunctionSignature(name, type))
1830 return ParseFailure;
1831
1832 // Okay, the CFG function signature was parsed correctly, create the function.
1833 auto function = new CFGFunction(name, type);
1834
1835 return CFGFunctionParser(getState(), function).parseFunctionBody();
1836}
1837
1838/// ML function declarations.
1839///
1840/// ml-func ::= `mlfunc` ml-func-signature `{` ml-stmt* ml-return-stmt `}`
1841///
1842ParseResult ModuleParser::parseMLFunc() {
1843 consumeToken(Token::kw_mlfunc);
1844
1845 StringRef name;
1846 FunctionType *type = nullptr;
1847
1848 // FIXME: Parse ML function signature (args + types)
1849 // by passing pointer to SmallVector<identifier> into parseFunctionSignature
1850 if (parseFunctionSignature(name, type))
1851 return ParseFailure;
1852
1853 // Okay, the ML function signature was parsed correctly, create the function.
1854 auto function = new MLFunction(name, type);
1855
1856 return MLFunctionParser(getState(), function).parseFunctionBody();
1857}
1858
Chris Lattnere79379a2018-06-22 10:39:19 -07001859/// This is the top-level module parser.
Chris Lattner2e595eb2018-07-10 10:08:27 -07001860ParseResult ModuleParser::parseModule() {
Chris Lattnere79379a2018-06-22 10:39:19 -07001861 while (1) {
Chris Lattner48af7d12018-07-09 19:05:38 -07001862 switch (getToken().getKind()) {
Chris Lattnere79379a2018-06-22 10:39:19 -07001863 default:
1864 emitError("expected a top level entity");
Chris Lattner2e595eb2018-07-10 10:08:27 -07001865 return ParseFailure;
Chris Lattnere79379a2018-06-22 10:39:19 -07001866
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001867 // If we got to the end of the file, then we're done.
Chris Lattnere79379a2018-06-22 10:39:19 -07001868 case Token::eof:
Chris Lattner2e595eb2018-07-10 10:08:27 -07001869 return ParseSuccess;
Chris Lattnere79379a2018-06-22 10:39:19 -07001870
1871 // If we got an error token, then the lexer already emitted an error, just
1872 // stop. Someday we could introduce error recovery if there was demand for
1873 // it.
1874 case Token::error:
Chris Lattner2e595eb2018-07-10 10:08:27 -07001875 return ParseFailure;
1876
1877 case Token::hash_identifier:
1878 if (parseAffineMapDef())
1879 return ParseFailure;
1880 break;
Chris Lattnere79379a2018-06-22 10:39:19 -07001881
1882 case Token::kw_extfunc:
Chris Lattner2e595eb2018-07-10 10:08:27 -07001883 if (parseExtFunc())
1884 return ParseFailure;
Chris Lattnere79379a2018-06-22 10:39:19 -07001885 break;
1886
Chris Lattner4c95a502018-06-23 16:03:42 -07001887 case Token::kw_cfgfunc:
Chris Lattner2e595eb2018-07-10 10:08:27 -07001888 if (parseCFGFunc())
1889 return ParseFailure;
MLIR Teamf85a6262018-06-27 11:03:08 -07001890 break;
Chris Lattner4c95a502018-06-23 16:03:42 -07001891
Tatiana Shpeismanc96b5872018-06-28 17:02:32 -07001892 case Token::kw_mlfunc:
Chris Lattner2e595eb2018-07-10 10:08:27 -07001893 if (parseMLFunc())
1894 return ParseFailure;
Tatiana Shpeismanc96b5872018-06-28 17:02:32 -07001895 break;
1896
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001897 // TODO: affine entity declarations, etc.
Chris Lattnere79379a2018-06-22 10:39:19 -07001898 }
1899 }
1900}
1901
1902//===----------------------------------------------------------------------===//
1903
Jacques Pienaar7b829702018-07-03 13:24:09 -07001904void mlir::defaultErrorReporter(const llvm::SMDiagnostic &error) {
1905 const auto &sourceMgr = *error.getSourceMgr();
1906 sourceMgr.PrintMessage(error.getLoc(), error.getKind(), error.getMessage());
1907}
1908
Chris Lattnere79379a2018-06-22 10:39:19 -07001909/// This parses the file specified by the indicated SourceMgr and returns an
1910/// MLIR module if it was valid. If not, it emits diagnostics and returns null.
Jacques Pienaar9c411be2018-06-24 19:17:35 -07001911Module *mlir::parseSourceFile(llvm::SourceMgr &sourceMgr, MLIRContext *context,
Jacques Pienaar7b829702018-07-03 13:24:09 -07001912 SMDiagnosticHandlerTy errorReporter) {
Chris Lattner2e595eb2018-07-10 10:08:27 -07001913 // This is the result module we are parsing into.
1914 std::unique_ptr<Module> module(new Module(context));
1915
1916 ParserState state(sourceMgr, module.get(),
Jacques Pienaar0bffd862018-07-11 13:26:23 -07001917 errorReporter ? errorReporter : defaultErrorReporter);
Chris Lattner2e595eb2018-07-10 10:08:27 -07001918 if (ModuleParser(state).parseModule())
1919 return nullptr;
Chris Lattner21e67f62018-07-06 10:46:19 -07001920
1921 // Make sure the parse module has no other structural problems detected by the
1922 // verifier.
Chris Lattner2e595eb2018-07-10 10:08:27 -07001923 module->verify();
1924 return module.release();
Chris Lattnere79379a2018-06-22 10:39:19 -07001925}