blob: 63ebeffd2960b535c8e7d457ae5cd5a343ab5beb [file] [log] [blame]
Chris Lattnere79379a2018-06-22 10:39:19 -07001//===- Parser.cpp - MLIR Parser Implementation ----------------------------===//
2//
3// Copyright 2019 The MLIR Authors.
4//
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16// =============================================================================
17//
18// This file implements the parser for the MLIR textual form.
19//
20//===----------------------------------------------------------------------===//
21
22#include "mlir/Parser.h"
23#include "Lexer.h"
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -070024#include "mlir/IR/AffineExpr.h"
MLIR Teamf85a6262018-06-27 11:03:08 -070025#include "mlir/IR/AffineMap.h"
Chris Lattner7121b802018-07-04 20:45:39 -070026#include "mlir/IR/Attributes.h"
Chris Lattner158e0a3e2018-07-08 20:51:38 -070027#include "mlir/IR/Builders.h"
Tatiana Shpeismanc96b5872018-06-28 17:02:32 -070028#include "mlir/IR/MLFunction.h"
Chris Lattner21e67f62018-07-06 10:46:19 -070029#include "mlir/IR/Module.h"
Chris Lattner85ee1512018-07-25 11:15:20 -070030#include "mlir/IR/OpImplementation.h"
Chris Lattner21e67f62018-07-06 10:46:19 -070031#include "mlir/IR/OperationSet.h"
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -070032#include "mlir/IR/Statements.h"
Chris Lattnerf7e22732018-06-22 22:03:48 -070033#include "mlir/IR/Types.h"
Chris Lattner6119d382018-07-20 18:41:34 -070034#include "llvm/ADT/DenseMap.h"
Chris Lattnere79379a2018-06-22 10:39:19 -070035#include "llvm/Support/SourceMgr.h"
36using namespace mlir;
Chris Lattner4c95a502018-06-23 16:03:42 -070037using llvm::SMLoc;
James Molloy0ff71542018-07-23 16:56:32 -070038using llvm::SourceMgr;
Chris Lattnere79379a2018-06-22 10:39:19 -070039
Chris Lattnerf7e22732018-06-22 22:03:48 -070040/// Simple enum to make code read better in cases that would otherwise return a
41/// bool value. Failure is "true" in a boolean context.
James Molloy0ff71542018-07-23 16:56:32 -070042enum ParseResult { ParseSuccess, ParseFailure };
Chris Lattnere79379a2018-06-22 10:39:19 -070043
Chris Lattner48af7d12018-07-09 19:05:38 -070044namespace {
45class Parser;
46
47/// This class refers to all of the state maintained globally by the parser,
48/// such as the current lexer position etc. The Parser base class provides
49/// methods to access this.
50class ParserState {
Chris Lattnered65a732018-06-28 20:45:33 -070051public:
Chris Lattner2e595eb2018-07-10 10:08:27 -070052 ParserState(llvm::SourceMgr &sourceMgr, Module *module,
Chris Lattner48af7d12018-07-09 19:05:38 -070053 SMDiagnosticHandlerTy errorReporter)
Chris Lattner2e595eb2018-07-10 10:08:27 -070054 : context(module->getContext()), module(module),
55 lex(sourceMgr, errorReporter), curToken(lex.lexToken()),
Chris Lattner85ee1512018-07-25 11:15:20 -070056 errorReporter(errorReporter), operationSet(OperationSet::get(context)) {
57 }
Chris Lattner2e595eb2018-07-10 10:08:27 -070058
59 // A map from affine map identifier to AffineMap.
60 llvm::StringMap<AffineMap *> affineMapDefinitions;
Chris Lattnere79379a2018-06-22 10:39:19 -070061
Chris Lattnere79379a2018-06-22 10:39:19 -070062private:
Chris Lattner48af7d12018-07-09 19:05:38 -070063 ParserState(const ParserState &) = delete;
64 void operator=(const ParserState &) = delete;
65
66 friend class Parser;
67
68 // The context we're parsing into.
Chris Lattner2e595eb2018-07-10 10:08:27 -070069 MLIRContext *const context;
70
71 // This is the module we are parsing into.
72 Module *const module;
Chris Lattnerf7e22732018-06-22 22:03:48 -070073
74 // The lexer for the source file we're parsing.
Chris Lattnere79379a2018-06-22 10:39:19 -070075 Lexer lex;
76
77 // This is the next token that hasn't been consumed yet.
78 Token curToken;
79
Jacques Pienaar9c411be2018-06-24 19:17:35 -070080 // The diagnostic error reporter.
Chris Lattner2e595eb2018-07-10 10:08:27 -070081 SMDiagnosticHandlerTy const errorReporter;
Chris Lattner85ee1512018-07-25 11:15:20 -070082
83 // The active OperationSet we're parsing with.
84 OperationSet &operationSet;
Chris Lattner48af7d12018-07-09 19:05:38 -070085};
86} // end anonymous namespace
MLIR Teamf85a6262018-06-27 11:03:08 -070087
Chris Lattner48af7d12018-07-09 19:05:38 -070088namespace {
89
Chris Lattner7f9cc272018-07-19 08:35:28 -070090typedef std::function<Operation *(Identifier, ArrayRef<SSAValue *>,
91 ArrayRef<Type *>, ArrayRef<NamedAttribute>)>
Tatiana Shpeisman565b9642018-07-16 11:47:09 -070092 CreateOperationFunction;
93
Chris Lattner48af7d12018-07-09 19:05:38 -070094/// This class implement support for parsing global entities like types and
95/// shared entities like SSA names. It is intended to be subclassed by
96/// specialized subparsers that include state, e.g. when a local symbol table.
97class Parser {
98public:
Chris Lattner2e595eb2018-07-10 10:08:27 -070099 Builder builder;
Chris Lattner48af7d12018-07-09 19:05:38 -0700100
Chris Lattner2e595eb2018-07-10 10:08:27 -0700101 Parser(ParserState &state) : builder(state.context), state(state) {}
102
103 // Helper methods to get stuff from the parser-global state.
104 ParserState &getState() const { return state; }
Chris Lattner48af7d12018-07-09 19:05:38 -0700105 MLIRContext *getContext() const { return state.context; }
Chris Lattner2e595eb2018-07-10 10:08:27 -0700106 Module *getModule() { return state.module; }
Chris Lattner85ee1512018-07-25 11:15:20 -0700107 OperationSet &getOperationSet() const { return state.operationSet; }
Chris Lattner48af7d12018-07-09 19:05:38 -0700108
109 /// Return the current token the parser is inspecting.
110 const Token &getToken() const { return state.curToken; }
111 StringRef getTokenSpelling() const { return state.curToken.getSpelling(); }
Chris Lattnere79379a2018-06-22 10:39:19 -0700112
113 /// Emit an error and return failure.
Chris Lattner4c95a502018-06-23 16:03:42 -0700114 ParseResult emitError(const Twine &message) {
Chris Lattner48af7d12018-07-09 19:05:38 -0700115 return emitError(state.curToken.getLoc(), message);
Chris Lattner4c95a502018-06-23 16:03:42 -0700116 }
117 ParseResult emitError(SMLoc loc, const Twine &message);
Chris Lattnere79379a2018-06-22 10:39:19 -0700118
119 /// Advance the current lexer onto the next token.
120 void consumeToken() {
Chris Lattner48af7d12018-07-09 19:05:38 -0700121 assert(state.curToken.isNot(Token::eof, Token::error) &&
Chris Lattnere79379a2018-06-22 10:39:19 -0700122 "shouldn't advance past EOF or errors");
Chris Lattner48af7d12018-07-09 19:05:38 -0700123 state.curToken = state.lex.lexToken();
Chris Lattnere79379a2018-06-22 10:39:19 -0700124 }
125
126 /// Advance the current lexer onto the next token, asserting what the expected
127 /// current token is. This is preferred to the above method because it leads
128 /// to more self-documenting code with better checking.
Chris Lattner8da0c282018-06-29 11:15:56 -0700129 void consumeToken(Token::Kind kind) {
Chris Lattner48af7d12018-07-09 19:05:38 -0700130 assert(state.curToken.is(kind) && "consumed an unexpected token");
Chris Lattnere79379a2018-06-22 10:39:19 -0700131 consumeToken();
132 }
133
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700134 /// If the current token has the specified kind, consume it and return true.
135 /// If not, return false.
Chris Lattner8da0c282018-06-29 11:15:56 -0700136 bool consumeIf(Token::Kind kind) {
Chris Lattner48af7d12018-07-09 19:05:38 -0700137 if (state.curToken.isNot(kind))
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700138 return false;
139 consumeToken(kind);
140 return true;
141 }
142
Chris Lattnerf7702a62018-07-23 17:30:01 -0700143 /// Consume the specified token if present and return success. On failure,
144 /// output a diagnostic and return failure.
145 ParseResult parseToken(Token::Kind expectedToken, const Twine &message);
146
Chris Lattner40746442018-07-21 14:32:09 -0700147 /// Parse a comma-separated list of elements up until the specified end token.
148 ParseResult
149 parseCommaSeparatedListUntil(Token::Kind rightToken,
150 const std::function<ParseResult()> &parseElement,
151 bool allowEmptyList = true);
152
153 /// Parse a comma separated list of elements that must have at least one entry
154 /// in it.
155 ParseResult
156 parseCommaSeparatedList(const std::function<ParseResult()> &parseElement);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700157
Chris Lattnerf7e22732018-06-22 22:03:48 -0700158 // We have two forms of parsing methods - those that return a non-null
159 // pointer on success, and those that return a ParseResult to indicate whether
160 // they returned a failure. The second class fills in by-reference arguments
161 // as the results of their action.
162
Chris Lattnere79379a2018-06-22 10:39:19 -0700163 // Type parsing.
Chris Lattnerf958bbe2018-06-29 22:08:05 -0700164 Type *parsePrimitiveType();
Chris Lattnerf7e22732018-06-22 22:03:48 -0700165 Type *parseElementType();
166 VectorType *parseVectorType();
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700167 ParseResult parseDimensionListRanked(SmallVectorImpl<int> &dimensions);
Chris Lattnerf7e22732018-06-22 22:03:48 -0700168 Type *parseTensorType();
169 Type *parseMemRefType();
170 Type *parseFunctionType();
171 Type *parseType();
Chris Lattner1604e472018-07-23 08:42:19 -0700172 ParseResult parseTypeListNoParens(SmallVectorImpl<Type *> &elements);
James Molloy0ff71542018-07-23 16:56:32 -0700173 ParseResult parseTypeList(SmallVectorImpl<Type *> &elements);
Chris Lattnere79379a2018-06-22 10:39:19 -0700174
Chris Lattner7121b802018-07-04 20:45:39 -0700175 // Attribute parsing.
176 Attribute *parseAttribute();
177 ParseResult parseAttributeDict(SmallVectorImpl<NamedAttribute> &attributes);
178
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700179 // Polyhedral structures.
Chris Lattner2e595eb2018-07-10 10:08:27 -0700180 AffineMap *parseAffineMapInline();
MLIR Team718c82f2018-07-16 09:45:22 -0700181 AffineMap *parseAffineMapReference();
MLIR Teamf85a6262018-06-27 11:03:08 -0700182
Chris Lattner48af7d12018-07-09 19:05:38 -0700183private:
184 // The Parser is subclassed and reinstantiated. Do not add additional
185 // non-trivial state here, add it to the ParserState class.
186 ParserState &state;
Chris Lattnere79379a2018-06-22 10:39:19 -0700187};
188} // end anonymous namespace
189
190//===----------------------------------------------------------------------===//
191// Helper methods.
192//===----------------------------------------------------------------------===//
193
Chris Lattner4c95a502018-06-23 16:03:42 -0700194ParseResult Parser::emitError(SMLoc loc, const Twine &message) {
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700195 // If we hit a parse error in response to a lexer error, then the lexer
Jacques Pienaar9c411be2018-06-24 19:17:35 -0700196 // already reported the error.
Chris Lattner48af7d12018-07-09 19:05:38 -0700197 if (getToken().is(Token::error))
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700198 return ParseFailure;
199
Chris Lattner48af7d12018-07-09 19:05:38 -0700200 auto &sourceMgr = state.lex.getSourceMgr();
201 state.errorReporter(sourceMgr.GetMessage(loc, SourceMgr::DK_Error, message));
Chris Lattnere79379a2018-06-22 10:39:19 -0700202 return ParseFailure;
203}
204
Chris Lattnerf7702a62018-07-23 17:30:01 -0700205/// Consume the specified token if present and return success. On failure,
206/// output a diagnostic and return failure.
207ParseResult Parser::parseToken(Token::Kind expectedToken,
208 const Twine &message) {
209 if (consumeIf(expectedToken))
210 return ParseSuccess;
211 return emitError(message);
212}
213
Chris Lattner40746442018-07-21 14:32:09 -0700214/// Parse a comma separated list of elements that must have at least one entry
215/// in it.
216ParseResult Parser::parseCommaSeparatedList(
217 const std::function<ParseResult()> &parseElement) {
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700218 // Non-empty case starts with an element.
219 if (parseElement())
220 return ParseFailure;
221
222 // Otherwise we have a list of comma separated elements.
223 while (consumeIf(Token::comma)) {
224 if (parseElement())
225 return ParseFailure;
226 }
Chris Lattner40746442018-07-21 14:32:09 -0700227 return ParseSuccess;
228}
229
230/// Parse a comma-separated list of elements, terminated with an arbitrary
231/// token. This allows empty lists if allowEmptyList is true.
232///
233/// abstract-list ::= rightToken // if allowEmptyList == true
234/// abstract-list ::= element (',' element)* rightToken
235///
236ParseResult Parser::parseCommaSeparatedListUntil(
237 Token::Kind rightToken, const std::function<ParseResult()> &parseElement,
238 bool allowEmptyList) {
239 // Handle the empty case.
240 if (getToken().is(rightToken)) {
241 if (!allowEmptyList)
242 return emitError("expected list element");
243 consumeToken(rightToken);
244 return ParseSuccess;
245 }
246
Chris Lattnerf7702a62018-07-23 17:30:01 -0700247 if (parseCommaSeparatedList(parseElement) ||
248 parseToken(rightToken, "expected ',' or '" +
249 Token::getTokenSpelling(rightToken) + "'"))
Chris Lattner40746442018-07-21 14:32:09 -0700250 return ParseFailure;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700251
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700252 return ParseSuccess;
253}
Chris Lattnere79379a2018-06-22 10:39:19 -0700254
255//===----------------------------------------------------------------------===//
256// Type Parsing
257//===----------------------------------------------------------------------===//
258
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700259/// Parse the low-level fixed dtypes in the system.
260///
Chris Lattnerf958bbe2018-06-29 22:08:05 -0700261/// primitive-type ::= `f16` | `bf16` | `f32` | `f64`
262/// primitive-type ::= integer-type
263/// primitive-type ::= `affineint`
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700264///
Chris Lattnerf958bbe2018-06-29 22:08:05 -0700265Type *Parser::parsePrimitiveType() {
Chris Lattner48af7d12018-07-09 19:05:38 -0700266 switch (getToken().getKind()) {
Chris Lattnerf7e22732018-06-22 22:03:48 -0700267 default:
268 return (emitError("expected type"), nullptr);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700269 case Token::kw_bf16:
270 consumeToken(Token::kw_bf16);
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700271 return builder.getBF16Type();
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700272 case Token::kw_f16:
273 consumeToken(Token::kw_f16);
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700274 return builder.getF16Type();
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700275 case Token::kw_f32:
276 consumeToken(Token::kw_f32);
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700277 return builder.getF32Type();
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700278 case Token::kw_f64:
279 consumeToken(Token::kw_f64);
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700280 return builder.getF64Type();
Chris Lattnerf958bbe2018-06-29 22:08:05 -0700281 case Token::kw_affineint:
282 consumeToken(Token::kw_affineint);
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700283 return builder.getAffineIntType();
Chris Lattnerf958bbe2018-06-29 22:08:05 -0700284 case Token::inttype: {
Chris Lattner48af7d12018-07-09 19:05:38 -0700285 auto width = getToken().getIntTypeBitwidth();
Chris Lattnerf958bbe2018-06-29 22:08:05 -0700286 if (!width.hasValue())
287 return (emitError("invalid integer width"), nullptr);
288 consumeToken(Token::inttype);
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700289 return builder.getIntegerType(width.getValue());
Chris Lattnerf958bbe2018-06-29 22:08:05 -0700290 }
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700291 }
292}
293
294/// Parse the element type of a tensor or memref type.
295///
296/// element-type ::= primitive-type | vector-type
297///
Chris Lattnerf7e22732018-06-22 22:03:48 -0700298Type *Parser::parseElementType() {
Chris Lattner48af7d12018-07-09 19:05:38 -0700299 if (getToken().is(Token::kw_vector))
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700300 return parseVectorType();
301
302 return parsePrimitiveType();
303}
304
305/// Parse a vector type.
306///
307/// vector-type ::= `vector` `<` const-dimension-list primitive-type `>`
308/// const-dimension-list ::= (integer-literal `x`)+
309///
Chris Lattnerf7e22732018-06-22 22:03:48 -0700310VectorType *Parser::parseVectorType() {
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700311 consumeToken(Token::kw_vector);
312
Chris Lattnerf7702a62018-07-23 17:30:01 -0700313 if (parseToken(Token::less, "expected '<' in vector type"))
314 return nullptr;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700315
Chris Lattner48af7d12018-07-09 19:05:38 -0700316 if (getToken().isNot(Token::integer))
Chris Lattnerf7e22732018-06-22 22:03:48 -0700317 return (emitError("expected dimension size in vector type"), nullptr);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700318
319 SmallVector<unsigned, 4> dimensions;
Chris Lattner48af7d12018-07-09 19:05:38 -0700320 while (getToken().is(Token::integer)) {
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700321 // Make sure this integer value is in bound and valid.
Chris Lattner48af7d12018-07-09 19:05:38 -0700322 auto dimension = getToken().getUnsignedIntegerValue();
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700323 if (!dimension.hasValue())
Chris Lattnerf7e22732018-06-22 22:03:48 -0700324 return (emitError("invalid dimension in vector type"), nullptr);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700325 dimensions.push_back(dimension.getValue());
326
327 consumeToken(Token::integer);
328
329 // Make sure we have an 'x' or something like 'xbf32'.
Chris Lattner48af7d12018-07-09 19:05:38 -0700330 if (getToken().isNot(Token::bare_identifier) ||
331 getTokenSpelling()[0] != 'x')
Chris Lattnerf7e22732018-06-22 22:03:48 -0700332 return (emitError("expected 'x' in vector dimension list"), nullptr);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700333
334 // If we had a prefix of 'x', lex the next token immediately after the 'x'.
Chris Lattner48af7d12018-07-09 19:05:38 -0700335 if (getTokenSpelling().size() != 1)
336 state.lex.resetPointer(getTokenSpelling().data() + 1);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700337
338 // Consume the 'x'.
339 consumeToken(Token::bare_identifier);
340 }
341
342 // Parse the element type.
Chris Lattnerf7e22732018-06-22 22:03:48 -0700343 auto *elementType = parsePrimitiveType();
344 if (!elementType)
345 return nullptr;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700346
Chris Lattnerf7702a62018-07-23 17:30:01 -0700347 if (parseToken(Token::greater, "expected '>' in vector type"))
348 return nullptr;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700349
Chris Lattnerf7e22732018-06-22 22:03:48 -0700350 return VectorType::get(dimensions, elementType);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700351}
352
353/// Parse a dimension list of a tensor or memref type. This populates the
354/// dimension list, returning -1 for the '?' dimensions.
355///
356/// dimension-list-ranked ::= (dimension `x`)*
357/// dimension ::= `?` | integer-literal
358///
359ParseResult Parser::parseDimensionListRanked(SmallVectorImpl<int> &dimensions) {
Chris Lattner48af7d12018-07-09 19:05:38 -0700360 while (getToken().isAny(Token::integer, Token::question)) {
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700361 if (consumeIf(Token::question)) {
362 dimensions.push_back(-1);
363 } else {
364 // Make sure this integer value is in bound and valid.
Chris Lattner48af7d12018-07-09 19:05:38 -0700365 auto dimension = getToken().getUnsignedIntegerValue();
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700366 if (!dimension.hasValue() || (int)dimension.getValue() < 0)
367 return emitError("invalid dimension");
368 dimensions.push_back((int)dimension.getValue());
369 consumeToken(Token::integer);
370 }
371
372 // Make sure we have an 'x' or something like 'xbf32'.
Chris Lattner48af7d12018-07-09 19:05:38 -0700373 if (getToken().isNot(Token::bare_identifier) ||
374 getTokenSpelling()[0] != 'x')
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700375 return emitError("expected 'x' in dimension list");
376
377 // If we had a prefix of 'x', lex the next token immediately after the 'x'.
Chris Lattner48af7d12018-07-09 19:05:38 -0700378 if (getTokenSpelling().size() != 1)
379 state.lex.resetPointer(getTokenSpelling().data() + 1);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700380
381 // Consume the 'x'.
382 consumeToken(Token::bare_identifier);
383 }
384
385 return ParseSuccess;
386}
387
388/// Parse a tensor type.
389///
390/// tensor-type ::= `tensor` `<` dimension-list element-type `>`
391/// dimension-list ::= dimension-list-ranked | `??`
392///
Chris Lattnerf7e22732018-06-22 22:03:48 -0700393Type *Parser::parseTensorType() {
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700394 consumeToken(Token::kw_tensor);
395
Chris Lattnerf7702a62018-07-23 17:30:01 -0700396 if (parseToken(Token::less, "expected '<' in tensor type"))
397 return nullptr;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700398
399 bool isUnranked;
400 SmallVector<int, 4> dimensions;
401
402 if (consumeIf(Token::questionquestion)) {
403 isUnranked = true;
404 } else {
405 isUnranked = false;
406 if (parseDimensionListRanked(dimensions))
Chris Lattnerf7e22732018-06-22 22:03:48 -0700407 return nullptr;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700408 }
409
410 // Parse the element type.
Chris Lattnerf7e22732018-06-22 22:03:48 -0700411 auto elementType = parseElementType();
412 if (!elementType)
413 return nullptr;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700414
Chris Lattnerf7702a62018-07-23 17:30:01 -0700415 if (parseToken(Token::greater, "expected '>' in tensor type"))
416 return nullptr;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700417
MLIR Team355ec862018-06-23 18:09:09 -0700418 if (isUnranked)
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700419 return builder.getTensorType(elementType);
420 return builder.getTensorType(dimensions, elementType);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700421}
422
423/// Parse a memref type.
424///
425/// memref-type ::= `memref` `<` dimension-list-ranked element-type
426/// (`,` semi-affine-map-composition)? (`,` memory-space)? `>`
427///
428/// semi-affine-map-composition ::= (semi-affine-map `,` )* semi-affine-map
429/// memory-space ::= integer-literal /* | TODO: address-space-id */
430///
Chris Lattnerf7e22732018-06-22 22:03:48 -0700431Type *Parser::parseMemRefType() {
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700432 consumeToken(Token::kw_memref);
433
Chris Lattnerf7702a62018-07-23 17:30:01 -0700434 if (parseToken(Token::less, "expected '<' in memref type"))
435 return nullptr;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700436
437 SmallVector<int, 4> dimensions;
438 if (parseDimensionListRanked(dimensions))
Chris Lattnerf7e22732018-06-22 22:03:48 -0700439 return nullptr;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700440
441 // Parse the element type.
Chris Lattnerf7e22732018-06-22 22:03:48 -0700442 auto elementType = parseElementType();
443 if (!elementType)
444 return nullptr;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700445
Chris Lattnerf7702a62018-07-23 17:30:01 -0700446 if (parseToken(Token::comma, "expected ',' in memref type"))
447 return nullptr;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700448
MLIR Team718c82f2018-07-16 09:45:22 -0700449 // Parse semi-affine-map-composition.
James Molloy0ff71542018-07-23 16:56:32 -0700450 SmallVector<AffineMap *, 2> affineMapComposition;
MLIR Team718c82f2018-07-16 09:45:22 -0700451 unsigned memorySpace;
452 bool parsedMemorySpace = false;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700453
MLIR Team718c82f2018-07-16 09:45:22 -0700454 auto parseElt = [&]() -> ParseResult {
455 if (getToken().is(Token::integer)) {
456 // Parse memory space.
457 if (parsedMemorySpace)
458 return emitError("multiple memory spaces specified in memref type");
459 auto v = getToken().getUnsignedIntegerValue();
460 if (!v.hasValue())
461 return emitError("invalid memory space in memref type");
462 memorySpace = v.getValue();
463 consumeToken(Token::integer);
464 parsedMemorySpace = true;
465 } else {
466 // Parse affine map.
467 if (parsedMemorySpace)
468 return emitError("affine map after memory space in memref type");
James Molloy0ff71542018-07-23 16:56:32 -0700469 auto *affineMap = parseAffineMapReference();
MLIR Team718c82f2018-07-16 09:45:22 -0700470 if (affineMap == nullptr)
471 return ParseFailure;
472 affineMapComposition.push_back(affineMap);
473 }
474 return ParseSuccess;
475 };
476
477 // Parse comma separated list of affine maps, followed by memory space.
Chris Lattner40746442018-07-21 14:32:09 -0700478 if (parseCommaSeparatedListUntil(Token::greater, parseElt,
479 /*allowEmptyList=*/false)) {
MLIR Team718c82f2018-07-16 09:45:22 -0700480 return nullptr;
481 }
482 // Check that MemRef type specifies at least one affine map in composition.
483 if (affineMapComposition.empty())
484 return (emitError("expected semi-affine-map in memref type"), nullptr);
485 if (!parsedMemorySpace)
486 return (emitError("expected memory space in memref type"), nullptr);
487
488 return MemRefType::get(dimensions, elementType, affineMapComposition,
489 memorySpace);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700490}
491
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700492/// Parse a function type.
493///
494/// function-type ::= type-list-parens `->` type-list
495///
Chris Lattnerf7e22732018-06-22 22:03:48 -0700496Type *Parser::parseFunctionType() {
Chris Lattner48af7d12018-07-09 19:05:38 -0700497 assert(getToken().is(Token::l_paren));
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700498
Chris Lattnerf7702a62018-07-23 17:30:01 -0700499 SmallVector<Type *, 4> arguments, results;
500 if (parseTypeList(arguments) ||
501 parseToken(Token::arrow, "expected '->' in function type") ||
502 parseTypeList(results))
Chris Lattnerf7e22732018-06-22 22:03:48 -0700503 return nullptr;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700504
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700505 return builder.getFunctionType(arguments, results);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700506}
507
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700508/// Parse an arbitrary type.
509///
510/// type ::= primitive-type
511/// | vector-type
512/// | tensor-type
513/// | memref-type
514/// | function-type
515/// element-type ::= primitive-type | vector-type
516///
Chris Lattnerf7e22732018-06-22 22:03:48 -0700517Type *Parser::parseType() {
Chris Lattner48af7d12018-07-09 19:05:38 -0700518 switch (getToken().getKind()) {
James Molloy0ff71542018-07-23 16:56:32 -0700519 case Token::kw_memref:
520 return parseMemRefType();
521 case Token::kw_tensor:
522 return parseTensorType();
523 case Token::kw_vector:
524 return parseVectorType();
525 case Token::l_paren:
526 return parseFunctionType();
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700527 default:
528 return parsePrimitiveType();
529 }
530}
531
Chris Lattner1604e472018-07-23 08:42:19 -0700532/// Parse a list of types without an enclosing parenthesis. The list must have
533/// at least one member.
534///
535/// type-list-no-parens ::= type (`,` type)*
536///
537ParseResult Parser::parseTypeListNoParens(SmallVectorImpl<Type *> &elements) {
538 auto parseElt = [&]() -> ParseResult {
539 auto elt = parseType();
540 elements.push_back(elt);
541 return elt ? ParseSuccess : ParseFailure;
542 };
543
544 return parseCommaSeparatedList(parseElt);
545}
546
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700547/// Parse a "type list", which is a singular type, or a parenthesized list of
548/// types.
549///
550/// type-list ::= type-list-parens | type
551/// type-list-parens ::= `(` `)`
Chris Lattner1604e472018-07-23 08:42:19 -0700552/// | `(` type-list-no-parens `)`
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700553///
James Molloy0ff71542018-07-23 16:56:32 -0700554ParseResult Parser::parseTypeList(SmallVectorImpl<Type *> &elements) {
Chris Lattnerf7e22732018-06-22 22:03:48 -0700555 auto parseElt = [&]() -> ParseResult {
556 auto elt = parseType();
557 elements.push_back(elt);
558 return elt ? ParseSuccess : ParseFailure;
559 };
560
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700561 // If there is no parens, then it must be a singular type.
562 if (!consumeIf(Token::l_paren))
Chris Lattnerf7e22732018-06-22 22:03:48 -0700563 return parseElt();
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700564
Chris Lattner40746442018-07-21 14:32:09 -0700565 if (parseCommaSeparatedListUntil(Token::r_paren, parseElt))
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700566 return ParseFailure;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700567
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700568 return ParseSuccess;
569}
570
Chris Lattner4c95a502018-06-23 16:03:42 -0700571//===----------------------------------------------------------------------===//
Chris Lattner7121b802018-07-04 20:45:39 -0700572// Attribute parsing.
573//===----------------------------------------------------------------------===//
574
Chris Lattner7121b802018-07-04 20:45:39 -0700575/// Attribute parsing.
576///
577/// attribute-value ::= bool-literal
578/// | integer-literal
579/// | float-literal
580/// | string-literal
581/// | `[` (attribute-value (`,` attribute-value)*)? `]`
582///
583Attribute *Parser::parseAttribute() {
Chris Lattner48af7d12018-07-09 19:05:38 -0700584 switch (getToken().getKind()) {
Chris Lattner7121b802018-07-04 20:45:39 -0700585 case Token::kw_true:
586 consumeToken(Token::kw_true);
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700587 return builder.getBoolAttr(true);
Chris Lattner7121b802018-07-04 20:45:39 -0700588 case Token::kw_false:
589 consumeToken(Token::kw_false);
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700590 return builder.getBoolAttr(false);
Chris Lattner7121b802018-07-04 20:45:39 -0700591
592 case Token::integer: {
Chris Lattner48af7d12018-07-09 19:05:38 -0700593 auto val = getToken().getUInt64IntegerValue();
Chris Lattner7121b802018-07-04 20:45:39 -0700594 if (!val.hasValue() || (int64_t)val.getValue() < 0)
595 return (emitError("integer too large for attribute"), nullptr);
596 consumeToken(Token::integer);
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700597 return builder.getIntegerAttr((int64_t)val.getValue());
Chris Lattner7121b802018-07-04 20:45:39 -0700598 }
599
600 case Token::minus: {
601 consumeToken(Token::minus);
Chris Lattner48af7d12018-07-09 19:05:38 -0700602 if (getToken().is(Token::integer)) {
603 auto val = getToken().getUInt64IntegerValue();
Chris Lattner7121b802018-07-04 20:45:39 -0700604 if (!val.hasValue() || (int64_t)-val.getValue() >= 0)
605 return (emitError("integer too large for attribute"), nullptr);
606 consumeToken(Token::integer);
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700607 return builder.getIntegerAttr((int64_t)-val.getValue());
Chris Lattner7121b802018-07-04 20:45:39 -0700608 }
609
610 return (emitError("expected constant integer or floating point value"),
611 nullptr);
612 }
613
614 case Token::string: {
Chris Lattner48af7d12018-07-09 19:05:38 -0700615 auto val = getToken().getStringValue();
Chris Lattner7121b802018-07-04 20:45:39 -0700616 consumeToken(Token::string);
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700617 return builder.getStringAttr(val);
Chris Lattner7121b802018-07-04 20:45:39 -0700618 }
619
Chris Lattner85ee1512018-07-25 11:15:20 -0700620 case Token::l_square: {
621 consumeToken(Token::l_square);
James Molloy0ff71542018-07-23 16:56:32 -0700622 SmallVector<Attribute *, 4> elements;
Chris Lattner7121b802018-07-04 20:45:39 -0700623
624 auto parseElt = [&]() -> ParseResult {
625 elements.push_back(parseAttribute());
626 return elements.back() ? ParseSuccess : ParseFailure;
627 };
628
Chris Lattner85ee1512018-07-25 11:15:20 -0700629 if (parseCommaSeparatedListUntil(Token::r_square, parseElt))
Chris Lattner7121b802018-07-04 20:45:39 -0700630 return nullptr;
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700631 return builder.getArrayAttr(elements);
Chris Lattner7121b802018-07-04 20:45:39 -0700632 }
633 default:
MLIR Teamb61885d2018-07-18 16:29:21 -0700634 // Try to parse affine map reference.
James Molloy0ff71542018-07-23 16:56:32 -0700635 auto *affineMap = parseAffineMapReference();
MLIR Teamb61885d2018-07-18 16:29:21 -0700636 if (affineMap != nullptr)
637 return builder.getAffineMapAttr(affineMap);
638
Chris Lattner7121b802018-07-04 20:45:39 -0700639 // TODO: Handle floating point.
640 return (emitError("expected constant attribute value"), nullptr);
641 }
642}
643
Chris Lattner7121b802018-07-04 20:45:39 -0700644/// Attribute dictionary.
645///
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700646/// attribute-dict ::= `{` `}`
647/// | `{` attribute-entry (`,` attribute-entry)* `}`
648/// attribute-entry ::= bare-id `:` attribute-value
Chris Lattner7121b802018-07-04 20:45:39 -0700649///
James Molloy0ff71542018-07-23 16:56:32 -0700650ParseResult
651Parser::parseAttributeDict(SmallVectorImpl<NamedAttribute> &attributes) {
Chris Lattner7121b802018-07-04 20:45:39 -0700652 consumeToken(Token::l_brace);
653
654 auto parseElt = [&]() -> ParseResult {
655 // We allow keywords as attribute names.
Chris Lattner48af7d12018-07-09 19:05:38 -0700656 if (getToken().isNot(Token::bare_identifier, Token::inttype) &&
657 !getToken().isKeyword())
Chris Lattner7121b802018-07-04 20:45:39 -0700658 return emitError("expected attribute name");
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700659 auto nameId = builder.getIdentifier(getTokenSpelling());
Chris Lattner7121b802018-07-04 20:45:39 -0700660 consumeToken();
661
Chris Lattnerf7702a62018-07-23 17:30:01 -0700662 if (parseToken(Token::colon, "expected ':' in attribute list"))
663 return ParseFailure;
Chris Lattner7121b802018-07-04 20:45:39 -0700664
665 auto attr = parseAttribute();
James Molloy0ff71542018-07-23 16:56:32 -0700666 if (!attr)
667 return ParseFailure;
Chris Lattner7121b802018-07-04 20:45:39 -0700668
669 attributes.push_back({nameId, attr});
670 return ParseSuccess;
671 };
672
Chris Lattner40746442018-07-21 14:32:09 -0700673 if (parseCommaSeparatedListUntil(Token::r_brace, parseElt))
Chris Lattner7121b802018-07-04 20:45:39 -0700674 return ParseFailure;
675
676 return ParseSuccess;
677}
678
679//===----------------------------------------------------------------------===//
MLIR Teamf85a6262018-06-27 11:03:08 -0700680// Polyhedral structures.
681//===----------------------------------------------------------------------===//
682
Chris Lattner2e595eb2018-07-10 10:08:27 -0700683/// Lower precedence ops (all at the same precedence level). LNoOp is false in
684/// the boolean sense.
685enum AffineLowPrecOp {
686 /// Null value.
687 LNoOp,
688 Add,
689 Sub
690};
MLIR Teamf85a6262018-06-27 11:03:08 -0700691
Chris Lattner2e595eb2018-07-10 10:08:27 -0700692/// Higher precedence ops - all at the same precedence level. HNoOp is false in
693/// the boolean sense.
694enum AffineHighPrecOp {
695 /// Null value.
696 HNoOp,
697 Mul,
698 FloorDiv,
699 CeilDiv,
700 Mod
701};
Chris Lattner7121b802018-07-04 20:45:39 -0700702
Chris Lattner2e595eb2018-07-10 10:08:27 -0700703namespace {
704/// This is a specialized parser for AffineMap's, maintaining the state
705/// transient to their bodies.
706class AffineMapParser : public Parser {
707public:
708 explicit AffineMapParser(ParserState &state) : Parser(state) {}
Chris Lattner7121b802018-07-04 20:45:39 -0700709
Chris Lattner2e595eb2018-07-10 10:08:27 -0700710 AffineMap *parseAffineMapInline();
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -0700711
Chris Lattner2e595eb2018-07-10 10:08:27 -0700712private:
713 unsigned getNumDims() const { return dims.size(); }
714 unsigned getNumSymbols() const { return symbols.size(); }
MLIR Teamf85a6262018-06-27 11:03:08 -0700715
Uday Bondhugula0115dbb2018-07-11 21:31:07 -0700716 /// Returns true if the only identifiers the parser accepts in affine
717 /// expressions are symbolic identifiers.
718 bool isPureSymbolic() const { return pureSymbolic; }
719 void setSymbolicParsing(bool val) { pureSymbolic = val; }
720
Chris Lattner2e595eb2018-07-10 10:08:27 -0700721 // Binary affine op parsing.
722 AffineLowPrecOp consumeIfLowPrecOp();
723 AffineHighPrecOp consumeIfHighPrecOp();
MLIR Teamf85a6262018-06-27 11:03:08 -0700724
Chris Lattner2e595eb2018-07-10 10:08:27 -0700725 // Identifier lists for polyhedral structures.
726 ParseResult parseDimIdList();
727 ParseResult parseSymbolIdList();
728 ParseResult parseDimOrSymbolId(bool isDim);
729
730 AffineExpr *parseAffineExpr();
731 AffineExpr *parseParentheticalExpr();
732 AffineExpr *parseNegateExpression(AffineExpr *lhs);
733 AffineExpr *parseIntegerExpr();
734 AffineExpr *parseBareIdExpr();
735
736 AffineExpr *getBinaryAffineOpExpr(AffineHighPrecOp op, AffineExpr *lhs,
Uday Bondhugula851b8fd2018-07-20 14:57:21 -0700737 AffineExpr *rhs, SMLoc opLoc);
Chris Lattner2e595eb2018-07-10 10:08:27 -0700738 AffineExpr *getBinaryAffineOpExpr(AffineLowPrecOp op, AffineExpr *lhs,
739 AffineExpr *rhs);
740 AffineExpr *parseAffineOperandExpr(AffineExpr *lhs);
741 AffineExpr *parseAffineLowPrecOpExpr(AffineExpr *llhs,
742 AffineLowPrecOp llhsOp);
743 AffineExpr *parseAffineHighPrecOpExpr(AffineExpr *llhs,
Uday Bondhugula851b8fd2018-07-20 14:57:21 -0700744 AffineHighPrecOp llhsOp,
745 SMLoc llhsOpLoc);
Chris Lattner2e595eb2018-07-10 10:08:27 -0700746
747private:
748 // TODO(bondhugula): could just use an vector/ArrayRef and scan the numbers.
749 llvm::StringMap<unsigned> dims;
750 llvm::StringMap<unsigned> symbols;
Uday Bondhugula0115dbb2018-07-11 21:31:07 -0700751 /// True if the parser should allow only symbolic identifiers in affine
752 /// expressions.
753 bool pureSymbolic = false;
Chris Lattner2e595eb2018-07-10 10:08:27 -0700754};
755} // end anonymous namespace
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -0700756
Uday Bondhugula851b8fd2018-07-20 14:57:21 -0700757/// Create an affine binary high precedence op expression (mul's, div's, mod).
758/// opLoc is the location of the op token to be used to report errors
759/// for non-conforming expressions.
Chris Lattner2e595eb2018-07-10 10:08:27 -0700760AffineExpr *AffineMapParser::getBinaryAffineOpExpr(AffineHighPrecOp op,
761 AffineExpr *lhs,
Chris Lattner40746442018-07-21 14:32:09 -0700762 AffineExpr *rhs,
763 SMLoc opLoc) {
Uday Bondhugula0115dbb2018-07-11 21:31:07 -0700764 // TODO: make the error location info accurate.
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700765 switch (op) {
766 case Mul:
Uday Bondhugulacbe4cca2018-07-19 13:07:16 -0700767 if (!lhs->isSymbolicOrConstant() && !rhs->isSymbolicOrConstant()) {
Uday Bondhugula851b8fd2018-07-20 14:57:21 -0700768 emitError(opLoc, "non-affine expression: at least one of the multiply "
769 "operands has to be either a constant or symbolic");
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700770 return nullptr;
771 }
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700772 return builder.getMulExpr(lhs, rhs);
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700773 case FloorDiv:
Uday Bondhugulacbe4cca2018-07-19 13:07:16 -0700774 if (!rhs->isSymbolicOrConstant()) {
Uday Bondhugula851b8fd2018-07-20 14:57:21 -0700775 emitError(opLoc, "non-affine expression: right operand of floordiv "
776 "has to be either a constant or symbolic");
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700777 return nullptr;
778 }
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700779 return builder.getFloorDivExpr(lhs, rhs);
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700780 case CeilDiv:
Uday Bondhugulacbe4cca2018-07-19 13:07:16 -0700781 if (!rhs->isSymbolicOrConstant()) {
Uday Bondhugula851b8fd2018-07-20 14:57:21 -0700782 emitError(opLoc, "non-affine expression: right operand of ceildiv "
783 "has to be either a constant or symbolic");
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700784 return nullptr;
785 }
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700786 return builder.getCeilDivExpr(lhs, rhs);
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700787 case Mod:
Uday Bondhugulacbe4cca2018-07-19 13:07:16 -0700788 if (!rhs->isSymbolicOrConstant()) {
Uday Bondhugula851b8fd2018-07-20 14:57:21 -0700789 emitError(opLoc, "non-affine expression: right operand of mod "
790 "has to be either a constant or symbolic");
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700791 return nullptr;
792 }
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700793 return builder.getModExpr(lhs, rhs);
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700794 case HNoOp:
795 llvm_unreachable("can't create affine expression for null high prec op");
796 return nullptr;
797 }
798}
799
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700800/// Create an affine binary low precedence op expression (add, sub).
Chris Lattner2e595eb2018-07-10 10:08:27 -0700801AffineExpr *AffineMapParser::getBinaryAffineOpExpr(AffineLowPrecOp op,
802 AffineExpr *lhs,
803 AffineExpr *rhs) {
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700804 switch (op) {
805 case AffineLowPrecOp::Add:
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700806 return builder.getAddExpr(lhs, rhs);
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700807 case AffineLowPrecOp::Sub:
Uday Bondhugulac1faf662018-07-19 14:08:50 -0700808 return builder.getAddExpr(
809 lhs, builder.getMulExpr(rhs, builder.getConstantExpr(-1)));
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700810 case AffineLowPrecOp::LNoOp:
811 llvm_unreachable("can't create affine expression for null low prec op");
812 return nullptr;
813 }
814}
815
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700816/// Consume this token if it is a lower precedence affine op (there are only two
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700817/// precedence levels).
Chris Lattner2e595eb2018-07-10 10:08:27 -0700818AffineLowPrecOp AffineMapParser::consumeIfLowPrecOp() {
Chris Lattner48af7d12018-07-09 19:05:38 -0700819 switch (getToken().getKind()) {
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700820 case Token::plus:
821 consumeToken(Token::plus);
822 return AffineLowPrecOp::Add;
823 case Token::minus:
824 consumeToken(Token::minus);
825 return AffineLowPrecOp::Sub;
826 default:
827 return AffineLowPrecOp::LNoOp;
828 }
829}
830
831/// Consume this token if it is a higher precedence affine op (there are only
832/// two precedence levels)
Chris Lattner2e595eb2018-07-10 10:08:27 -0700833AffineHighPrecOp AffineMapParser::consumeIfHighPrecOp() {
Chris Lattner48af7d12018-07-09 19:05:38 -0700834 switch (getToken().getKind()) {
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700835 case Token::star:
836 consumeToken(Token::star);
837 return Mul;
838 case Token::kw_floordiv:
839 consumeToken(Token::kw_floordiv);
840 return FloorDiv;
841 case Token::kw_ceildiv:
842 consumeToken(Token::kw_ceildiv);
843 return CeilDiv;
844 case Token::kw_mod:
845 consumeToken(Token::kw_mod);
846 return Mod;
847 default:
848 return HNoOp;
849 }
850}
851
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700852/// Parse a high precedence op expression list: mul, div, and mod are high
853/// precedence binary ops, i.e., parse a
854/// expr_1 op_1 expr_2 op_2 ... expr_n
855/// where op_1, op_2 are all a AffineHighPrecOp (mul, div, mod).
856/// All affine binary ops are left associative.
857/// Given llhs, returns (llhs llhsOp lhs) op rhs, or (lhs op rhs) if llhs is
858/// null. If no rhs can be found, returns (llhs llhsOp lhs) or lhs if llhs is
Uday Bondhugula851b8fd2018-07-20 14:57:21 -0700859/// null. llhsOpLoc is the location of the llhsOp token that will be used to
860/// report an error for non-conforming expressions.
861AffineExpr *AffineMapParser::parseAffineHighPrecOpExpr(AffineExpr *llhs,
862 AffineHighPrecOp llhsOp,
863 SMLoc llhsOpLoc) {
Chris Lattner2e595eb2018-07-10 10:08:27 -0700864 AffineExpr *lhs = parseAffineOperandExpr(llhs);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700865 if (!lhs)
866 return nullptr;
867
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700868 // Found an LHS. Parse the remaining expression.
Uday Bondhugula851b8fd2018-07-20 14:57:21 -0700869 auto opLoc = getToken().getLoc();
Chris Lattner2e595eb2018-07-10 10:08:27 -0700870 if (AffineHighPrecOp op = consumeIfHighPrecOp()) {
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700871 if (llhs) {
Uday Bondhugula851b8fd2018-07-20 14:57:21 -0700872 AffineExpr *expr = getBinaryAffineOpExpr(llhsOp, llhs, lhs, opLoc);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700873 if (!expr)
874 return nullptr;
Uday Bondhugula851b8fd2018-07-20 14:57:21 -0700875 return parseAffineHighPrecOpExpr(expr, op, opLoc);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700876 }
877 // No LLHS, get RHS
Uday Bondhugula851b8fd2018-07-20 14:57:21 -0700878 return parseAffineHighPrecOpExpr(lhs, op, opLoc);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700879 }
880
881 // This is the last operand in this expression.
882 if (llhs)
Uday Bondhugula851b8fd2018-07-20 14:57:21 -0700883 return getBinaryAffineOpExpr(llhsOp, llhs, lhs, llhsOpLoc);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700884
885 // No llhs, 'lhs' itself is the expression.
886 return lhs;
887}
888
889/// Parse an affine expression inside parentheses.
890///
891/// affine-expr ::= `(` affine-expr `)`
Chris Lattner2e595eb2018-07-10 10:08:27 -0700892AffineExpr *AffineMapParser::parseParentheticalExpr() {
Chris Lattnerf7702a62018-07-23 17:30:01 -0700893 if (parseToken(Token::l_paren, "expected '('"))
894 return nullptr;
Chris Lattner48af7d12018-07-09 19:05:38 -0700895 if (getToken().is(Token::r_paren))
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700896 return (emitError("no expression inside parentheses"), nullptr);
Chris Lattnerf7702a62018-07-23 17:30:01 -0700897
Chris Lattner2e595eb2018-07-10 10:08:27 -0700898 auto *expr = parseAffineExpr();
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700899 if (!expr)
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700900 return nullptr;
Chris Lattnerf7702a62018-07-23 17:30:01 -0700901 if (parseToken(Token::r_paren, "expected ')'"))
902 return nullptr;
903
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700904 return expr;
905}
906
907/// Parse the negation expression.
908///
909/// affine-expr ::= `-` affine-expr
Chris Lattner2e595eb2018-07-10 10:08:27 -0700910AffineExpr *AffineMapParser::parseNegateExpression(AffineExpr *lhs) {
Chris Lattnerf7702a62018-07-23 17:30:01 -0700911 if (parseToken(Token::minus, "expected '-'"))
912 return nullptr;
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700913
Chris Lattner2e595eb2018-07-10 10:08:27 -0700914 AffineExpr *operand = parseAffineOperandExpr(lhs);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700915 // Since negation has the highest precedence of all ops (including high
916 // precedence ops) but lower than parentheses, we are only going to use
917 // parseAffineOperandExpr instead of parseAffineExpr here.
918 if (!operand)
919 // Extra error message although parseAffineOperandExpr would have
920 // complained. Leads to a better diagnostic.
921 return (emitError("missing operand of negation"), nullptr);
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700922 auto *minusOne = builder.getConstantExpr(-1);
923 return builder.getMulExpr(minusOne, operand);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700924}
925
926/// Parse a bare id that may appear in an affine expression.
927///
928/// affine-expr ::= bare-id
Chris Lattner2e595eb2018-07-10 10:08:27 -0700929AffineExpr *AffineMapParser::parseBareIdExpr() {
Chris Lattner48af7d12018-07-09 19:05:38 -0700930 if (getToken().isNot(Token::bare_identifier))
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700931 return (emitError("expected bare identifier"), nullptr);
932
Chris Lattner48af7d12018-07-09 19:05:38 -0700933 StringRef sRef = getTokenSpelling();
Uday Bondhugula0115dbb2018-07-11 21:31:07 -0700934 // dims, symbols are all pairwise distinct.
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700935 if (dims.count(sRef)) {
Uday Bondhugula0115dbb2018-07-11 21:31:07 -0700936 if (isPureSymbolic())
937 return (emitError("identifier used is not a symbolic identifier"),
938 nullptr);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700939 consumeToken(Token::bare_identifier);
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700940 return builder.getDimExpr(dims.lookup(sRef));
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700941 }
Uday Bondhugula0115dbb2018-07-11 21:31:07 -0700942
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700943 if (symbols.count(sRef)) {
944 consumeToken(Token::bare_identifier);
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700945 return builder.getSymbolExpr(symbols.lookup(sRef));
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700946 }
Uday Bondhugula0115dbb2018-07-11 21:31:07 -0700947
948 return (emitError("use of undeclared identifier"), nullptr);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700949}
950
951/// Parse a positive integral constant appearing in an affine expression.
952///
953/// affine-expr ::= integer-literal
Chris Lattner2e595eb2018-07-10 10:08:27 -0700954AffineExpr *AffineMapParser::parseIntegerExpr() {
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700955 // No need to handle negative numbers separately here. They are naturally
956 // handled via the unary negation operator, although (FIXME) MININT_64 still
957 // not correctly handled.
Chris Lattner48af7d12018-07-09 19:05:38 -0700958 if (getToken().isNot(Token::integer))
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700959 return (emitError("expected integer"), nullptr);
960
Chris Lattner48af7d12018-07-09 19:05:38 -0700961 auto val = getToken().getUInt64IntegerValue();
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700962 if (!val.hasValue() || (int64_t)val.getValue() < 0) {
963 return (emitError("constant too large for affineint"), nullptr);
964 }
965 consumeToken(Token::integer);
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700966 return builder.getConstantExpr((int64_t)val.getValue());
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700967}
968
969/// Parses an expression that can be a valid operand of an affine expression.
Uday Bondhugula76345202018-07-09 13:47:52 -0700970/// lhs: if non-null, lhs is an affine expression that is the lhs of a binary
971/// operator, the rhs of which is being parsed. This is used to determine
972/// whether an error should be emitted for a missing right operand.
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700973// Eg: for an expression without parentheses (like i + j + k + l), each
974// of the four identifiers is an operand. For i + j*k + l, j*k is not an
975// operand expression, it's an op expression and will be parsed via
976// parseAffineHighPrecOpExpression(). However, for i + (j*k) + -l, (j*k) and -l
977// are valid operands that will be parsed by this function.
Chris Lattner2e595eb2018-07-10 10:08:27 -0700978AffineExpr *AffineMapParser::parseAffineOperandExpr(AffineExpr *lhs) {
Chris Lattner48af7d12018-07-09 19:05:38 -0700979 switch (getToken().getKind()) {
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700980 case Token::bare_identifier:
Chris Lattner2e595eb2018-07-10 10:08:27 -0700981 return parseBareIdExpr();
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700982 case Token::integer:
Chris Lattner2e595eb2018-07-10 10:08:27 -0700983 return parseIntegerExpr();
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700984 case Token::l_paren:
Chris Lattner2e595eb2018-07-10 10:08:27 -0700985 return parseParentheticalExpr();
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700986 case Token::minus:
Chris Lattner2e595eb2018-07-10 10:08:27 -0700987 return parseNegateExpression(lhs);
Uday Bondhugula76345202018-07-09 13:47:52 -0700988 case Token::kw_ceildiv:
989 case Token::kw_floordiv:
990 case Token::kw_mod:
991 case Token::plus:
992 case Token::star:
993 if (lhs)
994 emitError("missing right operand of binary operator");
995 else
996 emitError("missing left operand of binary operator");
997 return nullptr;
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700998 default:
999 if (lhs)
Uday Bondhugula76345202018-07-09 13:47:52 -07001000 emitError("missing right operand of binary operator");
Uday Bondhugula3934d4d2018-07-09 09:00:25 -07001001 else
1002 emitError("expected affine expression");
1003 return nullptr;
1004 }
1005}
1006
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001007/// Parse affine expressions that are bare-id's, integer constants,
1008/// parenthetical affine expressions, and affine op expressions that are a
1009/// composition of those.
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001010///
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001011/// All binary op's associate from left to right.
1012///
1013/// {add, sub} have lower precedence than {mul, div, and mod}.
1014///
Uday Bondhugula76345202018-07-09 13:47:52 -07001015/// Add, sub'are themselves at the same precedence level. Mul, floordiv,
1016/// ceildiv, and mod are at the same higher precedence level. Negation has
1017/// higher precedence than any binary op.
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001018///
1019/// llhs: the affine expression appearing on the left of the one being parsed.
Uday Bondhugula3934d4d2018-07-09 09:00:25 -07001020/// This function will return ((llhs llhsOp lhs) op rhs) if llhs is non null,
1021/// and lhs op rhs otherwise; if there is no rhs, llhs llhsOp lhs is returned if
1022/// llhs is non-null; otherwise lhs is returned. This is to deal with left
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001023/// associativity.
1024///
1025/// Eg: when the expression is e1 + e2*e3 + e4, with e1 as llhs, this function
Uday Bondhugula3934d4d2018-07-09 09:00:25 -07001026/// will return the affine expr equivalent of (e1 + (e2*e3)) + e4, where (e2*e3)
1027/// will be parsed using parseAffineHighPrecOpExpr().
Chris Lattner2e595eb2018-07-10 10:08:27 -07001028AffineExpr *AffineMapParser::parseAffineLowPrecOpExpr(AffineExpr *llhs,
1029 AffineLowPrecOp llhsOp) {
Uday Bondhugula76345202018-07-09 13:47:52 -07001030 AffineExpr *lhs;
Chris Lattner2e595eb2018-07-10 10:08:27 -07001031 if (!(lhs = parseAffineOperandExpr(llhs)))
Uday Bondhugula3934d4d2018-07-09 09:00:25 -07001032 return nullptr;
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001033
1034 // Found an LHS. Deal with the ops.
Chris Lattner2e595eb2018-07-10 10:08:27 -07001035 if (AffineLowPrecOp lOp = consumeIfLowPrecOp()) {
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001036 if (llhs) {
Chris Lattner158e0a3e2018-07-08 20:51:38 -07001037 AffineExpr *sum = getBinaryAffineOpExpr(llhsOp, llhs, lhs);
Chris Lattner2e595eb2018-07-10 10:08:27 -07001038 return parseAffineLowPrecOpExpr(sum, lOp);
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001039 }
1040 // No LLHS, get RHS and form the expression.
Chris Lattner2e595eb2018-07-10 10:08:27 -07001041 return parseAffineLowPrecOpExpr(lhs, lOp);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -07001042 }
Uday Bondhugula851b8fd2018-07-20 14:57:21 -07001043 auto opLoc = getToken().getLoc();
Chris Lattner2e595eb2018-07-10 10:08:27 -07001044 if (AffineHighPrecOp hOp = consumeIfHighPrecOp()) {
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001045 // We have a higher precedence op here. Get the rhs operand for the llhs
1046 // through parseAffineHighPrecOpExpr.
Uday Bondhugula851b8fd2018-07-20 14:57:21 -07001047 AffineExpr *highRes = parseAffineHighPrecOpExpr(lhs, hOp, opLoc);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -07001048 if (!highRes)
1049 return nullptr;
Chris Lattner2e595eb2018-07-10 10:08:27 -07001050
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001051 // If llhs is null, the product forms the first operand of the yet to be
Uday Bondhugula3934d4d2018-07-09 09:00:25 -07001052 // found expression. If non-null, the op to associate with llhs is llhsOp.
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001053 AffineExpr *expr =
Chris Lattner158e0a3e2018-07-08 20:51:38 -07001054 llhs ? getBinaryAffineOpExpr(llhsOp, llhs, highRes) : highRes;
Chris Lattner2e595eb2018-07-10 10:08:27 -07001055
Uday Bondhugula3934d4d2018-07-09 09:00:25 -07001056 // Recurse for subsequent low prec op's after the affine high prec op
1057 // expression.
Chris Lattner2e595eb2018-07-10 10:08:27 -07001058 if (AffineLowPrecOp nextOp = consumeIfLowPrecOp())
1059 return parseAffineLowPrecOpExpr(expr, nextOp);
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001060 return expr;
1061 }
Uday Bondhugula3934d4d2018-07-09 09:00:25 -07001062 // Last operand in the expression list.
1063 if (llhs)
1064 return getBinaryAffineOpExpr(llhsOp, llhs, lhs);
1065 // No llhs, 'lhs' itself is the expression.
1066 return lhs;
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001067}
1068
1069/// Parse an affine expression.
Uday Bondhugula3934d4d2018-07-09 09:00:25 -07001070/// affine-expr ::= `(` affine-expr `)`
1071/// | `-` affine-expr
1072/// | affine-expr `+` affine-expr
1073/// | affine-expr `-` affine-expr
1074/// | affine-expr `*` affine-expr
1075/// | affine-expr `floordiv` affine-expr
1076/// | affine-expr `ceildiv` affine-expr
1077/// | affine-expr `mod` affine-expr
1078/// | bare-id
1079/// | integer-literal
1080///
1081/// Additional conditions are checked depending on the production. For eg., one
1082/// of the operands for `*` has to be either constant/symbolic; the second
1083/// operand for floordiv, ceildiv, and mod has to be a positive integer.
Chris Lattner2e595eb2018-07-10 10:08:27 -07001084AffineExpr *AffineMapParser::parseAffineExpr() {
1085 return parseAffineLowPrecOpExpr(nullptr, AffineLowPrecOp::LNoOp);
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001086}
1087
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001088/// Parse a dim or symbol from the lists appearing before the actual expressions
Chris Lattner2e595eb2018-07-10 10:08:27 -07001089/// of the affine map. Update our state to store the dimensional/symbolic
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001090/// identifier. 'dim': whether it's the dim list or symbol list that is being
1091/// parsed.
Chris Lattner2e595eb2018-07-10 10:08:27 -07001092ParseResult AffineMapParser::parseDimOrSymbolId(bool isDim) {
Chris Lattner48af7d12018-07-09 19:05:38 -07001093 if (getToken().isNot(Token::bare_identifier))
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001094 return emitError("expected bare identifier");
Chris Lattner48af7d12018-07-09 19:05:38 -07001095 auto sRef = getTokenSpelling();
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001096 consumeToken(Token::bare_identifier);
Chris Lattner2e595eb2018-07-10 10:08:27 -07001097 if (dims.count(sRef))
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001098 return emitError("dimensional identifier name reused");
Chris Lattner2e595eb2018-07-10 10:08:27 -07001099 if (symbols.count(sRef))
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001100 return emitError("symbolic identifier name reused");
Chris Lattner2e595eb2018-07-10 10:08:27 -07001101 if (isDim)
1102 dims.insert({sRef, dims.size()});
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001103 else
Chris Lattner2e595eb2018-07-10 10:08:27 -07001104 symbols.insert({sRef, symbols.size()});
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001105 return ParseSuccess;
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001106}
1107
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001108/// Parse the list of symbolic identifiers to an affine map.
Chris Lattner2e595eb2018-07-10 10:08:27 -07001109ParseResult AffineMapParser::parseSymbolIdList() {
Chris Lattner85ee1512018-07-25 11:15:20 -07001110 if (parseToken(Token::l_square, "expected '['"))
Chris Lattnerf7702a62018-07-23 17:30:01 -07001111 return ParseFailure;
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001112
Chris Lattner2e595eb2018-07-10 10:08:27 -07001113 auto parseElt = [&]() -> ParseResult { return parseDimOrSymbolId(false); };
Chris Lattner85ee1512018-07-25 11:15:20 -07001114 return parseCommaSeparatedListUntil(Token::r_square, parseElt);
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001115}
1116
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001117/// Parse the list of dimensional identifiers to an affine map.
Chris Lattner2e595eb2018-07-10 10:08:27 -07001118ParseResult AffineMapParser::parseDimIdList() {
Chris Lattnerf7702a62018-07-23 17:30:01 -07001119 if (parseToken(Token::l_paren,
1120 "expected '(' at start of dimensional identifiers list"))
1121 return ParseFailure;
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001122
Chris Lattner2e595eb2018-07-10 10:08:27 -07001123 auto parseElt = [&]() -> ParseResult { return parseDimOrSymbolId(true); };
Chris Lattner40746442018-07-21 14:32:09 -07001124 return parseCommaSeparatedListUntil(Token::r_paren, parseElt);
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001125}
1126
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001127/// Parse an affine map definition.
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001128///
Uday Bondhugula3934d4d2018-07-09 09:00:25 -07001129/// affine-map-inline ::= dim-and-symbol-id-lists `->` multi-dim-affine-expr
1130/// (`size` `(` dim-size (`,` dim-size)* `)`)?
1131/// dim-size ::= affine-expr | `min` `(` affine-expr ( `,` affine-expr)+ `)`
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001132///
Uday Bondhugula3934d4d2018-07-09 09:00:25 -07001133/// multi-dim-affine-expr ::= `(` affine-expr (`,` affine-expr)* `)
Chris Lattner2e595eb2018-07-10 10:08:27 -07001134AffineMap *AffineMapParser::parseAffineMapInline() {
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001135 // List of dimensional identifiers.
Chris Lattner2e595eb2018-07-10 10:08:27 -07001136 if (parseDimIdList())
Chris Lattner7121b802018-07-04 20:45:39 -07001137 return nullptr;
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001138
1139 // Symbols are optional.
Chris Lattner85ee1512018-07-25 11:15:20 -07001140 if (getToken().is(Token::l_square)) {
Chris Lattner2e595eb2018-07-10 10:08:27 -07001141 if (parseSymbolIdList())
Chris Lattner7121b802018-07-04 20:45:39 -07001142 return nullptr;
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001143 }
Chris Lattnerf7702a62018-07-23 17:30:01 -07001144
1145 if (parseToken(Token::arrow, "expected '->' or '['") ||
1146 parseToken(Token::l_paren, "expected '(' at start of affine map range"))
Chris Lattner7121b802018-07-04 20:45:39 -07001147 return nullptr;
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001148
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001149 SmallVector<AffineExpr *, 4> exprs;
1150 auto parseElt = [&]() -> ParseResult {
Chris Lattner2e595eb2018-07-10 10:08:27 -07001151 auto *elt = parseAffineExpr();
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001152 ParseResult res = elt ? ParseSuccess : ParseFailure;
1153 exprs.push_back(elt);
1154 return res;
1155 };
1156
1157 // Parse a multi-dimensional affine expression (a comma-separated list of 1-d
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001158 // affine expressions); the list cannot be empty.
1159 // Grammar: multi-dim-affine-expr ::= `(` affine-expr (`,` affine-expr)* `)
Chris Lattner40746442018-07-21 14:32:09 -07001160 if (parseCommaSeparatedListUntil(Token::r_paren, parseElt, false))
Chris Lattner7121b802018-07-04 20:45:39 -07001161 return nullptr;
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001162
Uday Bondhugula0115dbb2018-07-11 21:31:07 -07001163 // Parse optional range sizes.
Uday Bondhugula1e500b42018-07-12 18:04:04 -07001164 // range-sizes ::= (`size` `(` dim-size (`,` dim-size)* `)`)?
1165 // dim-size ::= affine-expr | `min` `(` affine-expr (`,` affine-expr)+ `)`
1166 // TODO(bondhugula): support for min of several affine expressions.
Uday Bondhugula0115dbb2018-07-11 21:31:07 -07001167 // TODO: check if sizes are non-negative whenever they are constant.
1168 SmallVector<AffineExpr *, 4> rangeSizes;
1169 if (consumeIf(Token::kw_size)) {
1170 // Location of the l_paren token (if it exists) for error reporting later.
1171 auto loc = getToken().getLoc();
Chris Lattnerf7702a62018-07-23 17:30:01 -07001172 if (parseToken(Token::l_paren, "expected '(' at start of affine map range"))
1173 return nullptr;
Uday Bondhugula0115dbb2018-07-11 21:31:07 -07001174
1175 auto parseRangeSize = [&]() -> ParseResult {
1176 auto *elt = parseAffineExpr();
1177 ParseResult res = elt ? ParseSuccess : ParseFailure;
1178 rangeSizes.push_back(elt);
1179 return res;
1180 };
1181
1182 setSymbolicParsing(true);
Chris Lattner40746442018-07-21 14:32:09 -07001183 if (parseCommaSeparatedListUntil(Token::r_paren, parseRangeSize, false))
Uday Bondhugula0115dbb2018-07-11 21:31:07 -07001184 return nullptr;
1185 if (exprs.size() > rangeSizes.size())
1186 return (emitError(loc, "fewer range sizes than range expressions"),
1187 nullptr);
1188 if (exprs.size() < rangeSizes.size())
1189 return (emitError(loc, "more range sizes than range expressions"),
1190 nullptr);
1191 }
1192
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001193 // Parsed a valid affine map.
Uday Bondhugula0115dbb2018-07-11 21:31:07 -07001194 return builder.getAffineMap(dims.size(), symbols.size(), exprs, rangeSizes);
MLIR Teamf85a6262018-06-27 11:03:08 -07001195}
1196
Chris Lattner2e595eb2018-07-10 10:08:27 -07001197AffineMap *Parser::parseAffineMapInline() {
1198 return AffineMapParser(state).parseAffineMapInline();
1199}
1200
MLIR Team718c82f2018-07-16 09:45:22 -07001201AffineMap *Parser::parseAffineMapReference() {
1202 if (getToken().is(Token::hash_identifier)) {
1203 // Parse affine map identifier and verify that it exists.
1204 StringRef affineMapId = getTokenSpelling().drop_front();
1205 if (getState().affineMapDefinitions.count(affineMapId) == 0)
1206 return (emitError("undefined affine map id '" + affineMapId + "'"),
1207 nullptr);
1208 consumeToken(Token::hash_identifier);
1209 return getState().affineMapDefinitions[affineMapId];
1210 }
1211 // Try to parse inline affine map.
1212 return parseAffineMapInline();
1213}
1214
MLIR Teamf85a6262018-06-27 11:03:08 -07001215//===----------------------------------------------------------------------===//
Chris Lattner7f9cc272018-07-19 08:35:28 -07001216// FunctionParser
Chris Lattner4c95a502018-06-23 16:03:42 -07001217//===----------------------------------------------------------------------===//
Chris Lattnere79379a2018-06-22 10:39:19 -07001218
Chris Lattner7f9cc272018-07-19 08:35:28 -07001219namespace {
1220/// This class contains parser state that is common across CFG and ML functions,
1221/// notably for dealing with operations and SSA values.
1222class FunctionParser : public Parser {
1223public:
1224 FunctionParser(ParserState &state) : Parser(state) {}
1225
Chris Lattner6119d382018-07-20 18:41:34 -07001226 /// After the function is finished parsing, this function checks to see if
1227 /// there are any remaining issues.
Chris Lattner40746442018-07-21 14:32:09 -07001228 ParseResult finalizeFunction(Function *func, SMLoc loc);
Chris Lattner6119d382018-07-20 18:41:34 -07001229
1230 /// This represents a use of an SSA value in the program. The first two
1231 /// entries in the tuple are the name and result number of a reference. The
1232 /// third is the location of the reference, which is used in case this ends up
1233 /// being a use of an undefined value.
1234 struct SSAUseInfo {
1235 StringRef name; // Value name, e.g. %42 or %abc
1236 unsigned number; // Number, specified with #12
1237 SMLoc loc; // Location of first definition or use.
1238 };
Chris Lattner7f9cc272018-07-19 08:35:28 -07001239
1240 /// Given a reference to an SSA value and its type, return a reference. This
1241 /// returns null on failure.
1242 SSAValue *resolveSSAUse(SSAUseInfo useInfo, Type *type);
1243
1244 /// Register a definition of a value with the symbol table.
1245 ParseResult addDefinition(SSAUseInfo useInfo, SSAValue *value);
1246
1247 // SSA parsing productions.
1248 ParseResult parseSSAUse(SSAUseInfo &result);
Chris Lattner40746442018-07-21 14:32:09 -07001249 ParseResult parseOptionalSSAUseList(SmallVectorImpl<SSAUseInfo> &results);
James Molloy61a656c2018-07-22 15:45:24 -07001250
1251 template <typename ResultType>
1252 ResultType parseSSADefOrUseAndType(
1253 const std::function<ResultType(SSAUseInfo, Type *)> &action);
1254
1255 SSAValue *parseSSAUseAndType() {
1256 return parseSSADefOrUseAndType<SSAValue *>(
1257 [&](SSAUseInfo useInfo, Type *type) -> SSAValue * {
1258 return resolveSSAUse(useInfo, type);
1259 });
1260 }
Chris Lattner40746442018-07-21 14:32:09 -07001261
1262 template <typename ValueTy>
Chris Lattner7f9cc272018-07-19 08:35:28 -07001263 ParseResult
Chris Lattner2c402672018-07-23 11:56:17 -07001264 parseOptionalSSAUseAndTypeList(SmallVectorImpl<ValueTy *> &results,
1265 bool isParenthesized);
Chris Lattner7f9cc272018-07-19 08:35:28 -07001266
1267 // Operations
1268 ParseResult parseOperation(const CreateOperationFunction &createOpFunc);
Chris Lattner85ee1512018-07-25 11:15:20 -07001269 Operation *parseVerboseOperation(const CreateOperationFunction &createOpFunc);
1270 Operation *parseCustomOperation(const CreateOperationFunction &createOpFunc);
Chris Lattner7f9cc272018-07-19 08:35:28 -07001271
1272private:
1273 /// This keeps track of all of the SSA values we are tracking, indexed by
Chris Lattner6119d382018-07-20 18:41:34 -07001274 /// their name. This has one entry per result number.
1275 llvm::StringMap<SmallVector<std::pair<SSAValue *, SMLoc>, 1>> values;
1276
1277 /// These are all of the placeholders we've made along with the location of
1278 /// their first reference, to allow checking for use of undefined values.
1279 DenseMap<SSAValue *, SMLoc> forwardReferencePlaceholders;
1280
1281 SSAValue *createForwardReferencePlaceholder(SMLoc loc, Type *type);
1282
1283 /// Return true if this is a forward reference.
1284 bool isForwardReferencePlaceholder(SSAValue *value) {
1285 return forwardReferencePlaceholders.count(value);
1286 }
Chris Lattner7f9cc272018-07-19 08:35:28 -07001287};
1288} // end anonymous namespace
1289
Chris Lattner6119d382018-07-20 18:41:34 -07001290/// Create and remember a new placeholder for a forward reference.
1291SSAValue *FunctionParser::createForwardReferencePlaceholder(SMLoc loc,
1292 Type *type) {
1293 // Forward references are always created as instructions, even in ML
1294 // functions, because we just need something with a def/use chain.
1295 //
1296 // We create these placeholders as having an empty name, which we know cannot
1297 // be created through normal user input, allowing us to distinguish them.
1298 auto name = Identifier::get("placeholder", getContext());
1299 auto *inst = OperationInst::create(name, /*operands*/ {}, type, /*attrs*/ {},
1300 getContext());
1301 forwardReferencePlaceholders[inst->getResult(0)] = loc;
1302 return inst->getResult(0);
1303}
1304
Chris Lattner7f9cc272018-07-19 08:35:28 -07001305/// Given an unbound reference to an SSA value and its type, return a the value
1306/// it specifies. This returns null on failure.
1307SSAValue *FunctionParser::resolveSSAUse(SSAUseInfo useInfo, Type *type) {
Chris Lattner6119d382018-07-20 18:41:34 -07001308 auto &entries = values[useInfo.name];
1309
Chris Lattner7f9cc272018-07-19 08:35:28 -07001310 // If we have already seen a value of this name, return it.
Chris Lattner6119d382018-07-20 18:41:34 -07001311 if (useInfo.number < entries.size() && entries[useInfo.number].first) {
1312 auto *result = entries[useInfo.number].first;
Chris Lattner7f9cc272018-07-19 08:35:28 -07001313 // Check that the type matches the other uses.
Chris Lattner7f9cc272018-07-19 08:35:28 -07001314 if (result->getType() == type)
1315 return result;
1316
Chris Lattner6119d382018-07-20 18:41:34 -07001317 emitError(useInfo.loc, "use of value '" + useInfo.name.str() +
1318 "' expects different type than prior uses");
1319 emitError(entries[useInfo.number].second, "prior use here");
Chris Lattner7f9cc272018-07-19 08:35:28 -07001320 return nullptr;
1321 }
1322
Chris Lattner6119d382018-07-20 18:41:34 -07001323 // Make sure we have enough slots for this.
1324 if (entries.size() <= useInfo.number)
1325 entries.resize(useInfo.number + 1);
1326
1327 // If the value has already been defined and this is an overly large result
1328 // number, diagnose that.
1329 if (entries[0].first && !isForwardReferencePlaceholder(entries[0].first))
1330 return (emitError(useInfo.loc, "reference to invalid result number"),
1331 nullptr);
1332
1333 // Otherwise, this is a forward reference. Create a placeholder and remember
1334 // that we did so.
1335 auto *result = createForwardReferencePlaceholder(useInfo.loc, type);
1336 entries[useInfo.number].first = result;
1337 entries[useInfo.number].second = useInfo.loc;
1338 return result;
Chris Lattner7f9cc272018-07-19 08:35:28 -07001339}
1340
1341/// Register a definition of a value with the symbol table.
1342ParseResult FunctionParser::addDefinition(SSAUseInfo useInfo, SSAValue *value) {
Chris Lattner6119d382018-07-20 18:41:34 -07001343 auto &entries = values[useInfo.name];
Chris Lattner7f9cc272018-07-19 08:35:28 -07001344
Chris Lattner6119d382018-07-20 18:41:34 -07001345 // Make sure there is a slot for this value.
1346 if (entries.size() <= useInfo.number)
1347 entries.resize(useInfo.number + 1);
Chris Lattner7f9cc272018-07-19 08:35:28 -07001348
Chris Lattner6119d382018-07-20 18:41:34 -07001349 // If we already have an entry for this, check to see if it was a definition
1350 // or a forward reference.
1351 if (auto *existing = entries[useInfo.number].first) {
1352 if (!isForwardReferencePlaceholder(existing)) {
1353 emitError(useInfo.loc,
1354 "redefinition of SSA value '" + useInfo.name + "'");
1355 return emitError(entries[useInfo.number].second,
1356 "previously defined here");
1357 }
1358
1359 // If it was a forward reference, update everything that used it to use the
1360 // actual definition instead, delete the forward ref, and remove it from our
1361 // set of forward references we track.
1362 existing->replaceAllUsesWith(value);
1363 existing->getDefiningInst()->destroy();
1364 forwardReferencePlaceholders.erase(existing);
1365 }
1366
1367 entries[useInfo.number].first = value;
1368 entries[useInfo.number].second = useInfo.loc;
1369 return ParseSuccess;
1370}
1371
1372/// After the function is finished parsing, this function checks to see if
1373/// there are any remaining issues.
Chris Lattner40746442018-07-21 14:32:09 -07001374ParseResult FunctionParser::finalizeFunction(Function *func, SMLoc loc) {
Chris Lattner6119d382018-07-20 18:41:34 -07001375 // Check for any forward references that are left. If we find any, error out.
1376 if (!forwardReferencePlaceholders.empty()) {
1377 SmallVector<std::pair<const char *, SSAValue *>, 4> errors;
1378 // Iteration over the map isn't determinstic, so sort by source location.
1379 for (auto entry : forwardReferencePlaceholders)
1380 errors.push_back({entry.second.getPointer(), entry.first});
1381 llvm::array_pod_sort(errors.begin(), errors.end());
1382
1383 for (auto entry : errors)
1384 emitError(SMLoc::getFromPointer(entry.first),
1385 "use of undeclared SSA value name");
1386 return ParseFailure;
1387 }
1388
Chris Lattner40746442018-07-21 14:32:09 -07001389 // Run the verifier on this function. If an error is detected, report it.
1390 std::string errorString;
1391 if (func->verify(&errorString))
1392 return emitError(loc, errorString);
1393
Chris Lattner6119d382018-07-20 18:41:34 -07001394 return ParseSuccess;
Chris Lattner7f9cc272018-07-19 08:35:28 -07001395}
1396
Chris Lattner78276e32018-07-07 15:48:26 -07001397/// Parse a SSA operand for an instruction or statement.
1398///
James Molloy61a656c2018-07-22 15:45:24 -07001399/// ssa-use ::= ssa-id
Chris Lattner78276e32018-07-07 15:48:26 -07001400///
Chris Lattner7f9cc272018-07-19 08:35:28 -07001401ParseResult FunctionParser::parseSSAUse(SSAUseInfo &result) {
Chris Lattner6119d382018-07-20 18:41:34 -07001402 result.name = getTokenSpelling();
1403 result.number = 0;
1404 result.loc = getToken().getLoc();
Chris Lattnerf7702a62018-07-23 17:30:01 -07001405 if (parseToken(Token::percent_identifier, "expected SSA operand"))
1406 return ParseFailure;
Chris Lattner6119d382018-07-20 18:41:34 -07001407
1408 // If we have an affine map ID, it is a result number.
1409 if (getToken().is(Token::hash_identifier)) {
1410 if (auto value = getToken().getHashIdentifierNumber())
1411 result.number = value.getValue();
1412 else
1413 return emitError("invalid SSA value result number");
1414 consumeToken(Token::hash_identifier);
1415 }
1416
Chris Lattner7f9cc272018-07-19 08:35:28 -07001417 return ParseSuccess;
Chris Lattner78276e32018-07-07 15:48:26 -07001418}
1419
1420/// Parse a (possibly empty) list of SSA operands.
1421///
1422/// ssa-use-list ::= ssa-use (`,` ssa-use)*
1423/// ssa-use-list-opt ::= ssa-use-list?
1424///
Chris Lattner7f9cc272018-07-19 08:35:28 -07001425ParseResult
Chris Lattner40746442018-07-21 14:32:09 -07001426FunctionParser::parseOptionalSSAUseList(SmallVectorImpl<SSAUseInfo> &results) {
Chris Lattner85ee1512018-07-25 11:15:20 -07001427 if (getToken().isNot(Token::percent_identifier))
Chris Lattner40746442018-07-21 14:32:09 -07001428 return ParseSuccess;
1429 return parseCommaSeparatedList([&]() -> ParseResult {
Chris Lattner7f9cc272018-07-19 08:35:28 -07001430 SSAUseInfo result;
1431 if (parseSSAUse(result))
1432 return ParseFailure;
1433 results.push_back(result);
1434 return ParseSuccess;
1435 });
Chris Lattner78276e32018-07-07 15:48:26 -07001436}
1437
1438/// Parse an SSA use with an associated type.
1439///
1440/// ssa-use-and-type ::= ssa-use `:` type
James Molloy61a656c2018-07-22 15:45:24 -07001441template <typename ResultType>
1442ResultType FunctionParser::parseSSADefOrUseAndType(
1443 const std::function<ResultType(SSAUseInfo, Type *)> &action) {
Chris Lattner78276e32018-07-07 15:48:26 -07001444
Chris Lattnerf7702a62018-07-23 17:30:01 -07001445 SSAUseInfo useInfo;
1446 if (parseSSAUse(useInfo) ||
1447 parseToken(Token::colon, "expected ':' and type for SSA operand"))
1448 return nullptr;
Chris Lattner78276e32018-07-07 15:48:26 -07001449
Chris Lattner7f9cc272018-07-19 08:35:28 -07001450 auto *type = parseType();
1451 if (!type)
1452 return nullptr;
Chris Lattner78276e32018-07-07 15:48:26 -07001453
James Molloy61a656c2018-07-22 15:45:24 -07001454 return action(useInfo, type);
Chris Lattner78276e32018-07-07 15:48:26 -07001455}
1456
Chris Lattner2c402672018-07-23 11:56:17 -07001457/// Parse a (possibly empty) list of SSA operands, followed by a colon, then
1458/// followed by a type list. If hasParens is true, then the operands are
1459/// surrounded by parens.
Chris Lattner78276e32018-07-07 15:48:26 -07001460///
Chris Lattner2c402672018-07-23 11:56:17 -07001461/// ssa-use-and-type-list[parens]
1462/// ::= `(` ssa-use-list `)` ':' type-list-no-parens
1463///
1464/// ssa-use-and-type-list[!parens]
1465/// ::= ssa-use-list ':' type-list-no-parens
Chris Lattner78276e32018-07-07 15:48:26 -07001466///
Chris Lattner40746442018-07-21 14:32:09 -07001467template <typename ValueTy>
Chris Lattner7f9cc272018-07-19 08:35:28 -07001468ParseResult FunctionParser::parseOptionalSSAUseAndTypeList(
Chris Lattner2c402672018-07-23 11:56:17 -07001469 SmallVectorImpl<ValueTy *> &results, bool isParenthesized) {
1470
1471 // If we are in the parenthesized form and no paren exists, then we succeed
1472 // with an empty list.
1473 if (isParenthesized && !consumeIf(Token::l_paren))
Chris Lattner40746442018-07-21 14:32:09 -07001474 return ParseSuccess;
1475
Chris Lattner2c402672018-07-23 11:56:17 -07001476 SmallVector<SSAUseInfo, 4> valueIDs;
1477 if (parseOptionalSSAUseList(valueIDs))
Chris Lattner7f9cc272018-07-19 08:35:28 -07001478 return ParseFailure;
Chris Lattner2c402672018-07-23 11:56:17 -07001479
1480 if (isParenthesized && !consumeIf(Token::r_paren))
1481 return emitError("expected ')' in operand list");
1482
1483 // If there were no operands, then there is no colon or type lists.
1484 if (valueIDs.empty())
1485 return ParseSuccess;
1486
Chris Lattner2c402672018-07-23 11:56:17 -07001487 SmallVector<Type *, 4> types;
Chris Lattnerf7702a62018-07-23 17:30:01 -07001488 if (parseToken(Token::colon, "expected ':' in operand list") ||
1489 parseTypeListNoParens(types))
Chris Lattner2c402672018-07-23 11:56:17 -07001490 return ParseFailure;
1491
1492 if (valueIDs.size() != types.size())
1493 return emitError("expected " + Twine(valueIDs.size()) +
1494 " types to match operand list");
1495
1496 results.reserve(valueIDs.size());
1497 for (unsigned i = 0, e = valueIDs.size(); i != e; ++i) {
1498 if (auto *value = resolveSSAUse(valueIDs[i], types[i]))
1499 results.push_back(cast<ValueTy>(value));
1500 else
1501 return ParseFailure;
1502 }
1503
1504 return ParseSuccess;
Chris Lattner78276e32018-07-07 15:48:26 -07001505}
1506
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001507/// Parse the CFG or MLFunc operation.
1508///
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001509/// operation ::=
1510/// (ssa-id `=`)? string '(' ssa-use-list? ')' attribute-dict?
1511/// `:` function-type
1512///
1513ParseResult
Chris Lattner7f9cc272018-07-19 08:35:28 -07001514FunctionParser::parseOperation(const CreateOperationFunction &createOpFunc) {
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001515 auto loc = getToken().getLoc();
1516
1517 StringRef resultID;
1518 if (getToken().is(Token::percent_identifier)) {
Chris Lattner7f9cc272018-07-19 08:35:28 -07001519 resultID = getTokenSpelling();
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001520 consumeToken(Token::percent_identifier);
Chris Lattnerf7702a62018-07-23 17:30:01 -07001521 if (parseToken(Token::equal, "expected '=' after SSA name"))
1522 return ParseFailure;
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001523 }
1524
Chris Lattner85ee1512018-07-25 11:15:20 -07001525 Operation *op;
1526 if (getToken().is(Token::bare_identifier) || getToken().isKeyword())
1527 op = parseCustomOperation(createOpFunc);
1528 else if (getToken().is(Token::string))
1529 op = parseVerboseOperation(createOpFunc);
1530 else
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001531 return emitError("expected operation name in quotes");
1532
Chris Lattner85ee1512018-07-25 11:15:20 -07001533 // If parsing of the basic operation failed, then this whole thing fails.
Chris Lattner7f9cc272018-07-19 08:35:28 -07001534 if (!op)
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001535 return ParseFailure;
1536
1537 // We just parsed an operation. If it is a recognized one, verify that it
1538 // is structurally as we expect. If not, produce an error with a reasonable
1539 // source location.
Chris Lattner7f9cc272018-07-19 08:35:28 -07001540 if (auto *opInfo = op->getAbstractOperation(builder.getContext())) {
1541 if (auto error = opInfo->verifyInvariants(op))
Chris Lattner9361fb32018-07-24 08:34:58 -07001542 return emitError(loc, Twine("'") + op->getName().str() + "' op " + error);
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001543 }
1544
Chris Lattner7f9cc272018-07-19 08:35:28 -07001545 // If the instruction had a name, register it.
1546 if (!resultID.empty()) {
1547 // FIXME: Add result infra to handle Stmt results as well to make this
1548 // generic.
1549 if (auto *inst = dyn_cast<OperationInst>(op)) {
Chris Lattnerf8cce872018-07-20 09:28:54 -07001550 if (inst->getNumResults() == 0)
Chris Lattner7f9cc272018-07-19 08:35:28 -07001551 return emitError(loc, "cannot name an operation with no results");
1552
Chris Lattner6119d382018-07-20 18:41:34 -07001553 for (unsigned i = 0, e = inst->getNumResults(); i != e; ++i)
1554 addDefinition({resultID, i, loc}, inst->getResult(i));
Chris Lattner7f9cc272018-07-19 08:35:28 -07001555 }
1556 }
1557
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001558 return ParseSuccess;
1559}
Chris Lattnere79379a2018-06-22 10:39:19 -07001560
Chris Lattner85ee1512018-07-25 11:15:20 -07001561Operation *FunctionParser::parseVerboseOperation(
1562 const CreateOperationFunction &createOpFunc) {
1563 auto name = getToken().getStringValue();
1564 if (name.empty())
1565 return (emitError("empty operation name is invalid"), nullptr);
1566
1567 consumeToken(Token::string);
1568
1569 // Parse the operand list.
1570 SmallVector<SSAUseInfo, 8> operandInfos;
1571
1572 if (parseToken(Token::l_paren, "expected '(' to start operand list") ||
1573 parseOptionalSSAUseList(operandInfos) ||
1574 parseToken(Token::r_paren, "expected ')' to end operand list")) {
1575 return nullptr;
1576 }
1577
1578 SmallVector<NamedAttribute, 4> attributes;
1579 if (getToken().is(Token::l_brace)) {
1580 if (parseAttributeDict(attributes))
1581 return nullptr;
1582 }
1583
1584 if (parseToken(Token::colon, "expected ':' followed by instruction type"))
1585 return nullptr;
1586
1587 auto typeLoc = getToken().getLoc();
1588 auto type = parseType();
1589 if (!type)
1590 return nullptr;
1591 auto fnType = dyn_cast<FunctionType>(type);
1592 if (!fnType)
1593 return (emitError(typeLoc, "expected function type"), nullptr);
1594
1595 // Check that we have the right number of types for the operands.
1596 auto operandTypes = fnType->getInputs();
1597 if (operandTypes.size() != operandInfos.size()) {
1598 auto plural = "s"[operandInfos.size() == 1];
1599 return (emitError(typeLoc, "expected " + llvm::utostr(operandInfos.size()) +
1600 " operand type" + plural + " but had " +
1601 llvm::utostr(operandTypes.size())),
1602 nullptr);
1603 }
1604
1605 // Resolve all of the operands.
1606 SmallVector<SSAValue *, 8> operands;
1607 for (unsigned i = 0, e = operandInfos.size(); i != e; ++i) {
1608 operands.push_back(resolveSSAUse(operandInfos[i], operandTypes[i]));
1609 if (!operands.back())
1610 return nullptr;
1611 }
1612
1613 auto nameId = builder.getIdentifier(name);
1614 return createOpFunc(nameId, operands, fnType->getResults(), attributes);
1615}
1616
1617namespace {
1618class CustomOpAsmParser : public OpAsmParser {
1619public:
1620 CustomOpAsmParser(SMLoc nameLoc, StringRef opName, FunctionParser &parser)
1621 : nameLoc(nameLoc), opName(opName), parser(parser) {}
1622
1623 /// This is an internal helper to parser a colon, we don't want to expose
1624 /// this to clients.
1625 bool internalParseColon(llvm::SMLoc *loc) {
1626 if (loc)
1627 *loc = parser.getToken().getLoc();
1628 return parser.parseToken(Token::colon, "expected ':'");
1629 }
1630
1631 //===--------------------------------------------------------------------===//
1632 // High level parsing methods.
1633 //===--------------------------------------------------------------------===//
1634
1635 bool parseComma(llvm::SMLoc *loc = nullptr) override {
1636 if (loc)
1637 *loc = parser.getToken().getLoc();
1638 return parser.parseToken(Token::comma, "expected ','");
1639 }
1640
1641 bool parseColonType(Type *&result, llvm::SMLoc *loc = nullptr) override {
1642 return internalParseColon(loc) || !(result = parser.parseType());
1643 }
1644
1645 bool parseColonTypeList(SmallVectorImpl<Type *> &result,
1646 llvm::SMLoc *loc = nullptr) override {
1647 if (internalParseColon(loc))
1648 return true;
1649
1650 do {
1651 if (auto *type = parser.parseType())
1652 result.push_back(type);
1653 else
1654 return true;
1655
1656 } while (parser.consumeIf(Token::comma));
1657 return false;
1658 }
1659
1660 bool parseAttribute(Attribute *&result, llvm::SMLoc *loc = nullptr) override {
1661 if (loc)
1662 *loc = parser.getToken().getLoc();
1663 result = parser.parseAttribute();
1664 return result == nullptr;
1665 }
1666
1667 bool parseOperand(OperandType &result) override {
1668 FunctionParser::SSAUseInfo useInfo;
1669 if (parser.parseSSAUse(useInfo))
1670 return true;
1671
1672 result = {useInfo.loc, useInfo.name, useInfo.number};
1673 return false;
1674 }
1675
1676 bool parseOperandList(SmallVectorImpl<OperandType> &result,
1677 int requiredOperandCount = -1,
1678 Delimeter delimeter = Delimeter::NoDelimeter) override {
1679 auto startLoc = parser.getToken().getLoc();
1680
1681 // Handle delimeters.
1682 switch (delimeter) {
1683 case Delimeter::NoDelimeter:
1684 break;
1685 case Delimeter::ParenDelimeter:
1686 if (parser.parseToken(Token::l_paren, "expected '(' in operand list"))
1687 return true;
1688 break;
1689 case Delimeter::SquareDelimeter:
1690 if (parser.parseToken(Token::l_square, "expected '[' in operand list"))
1691 return true;
1692 break;
1693 }
1694
1695 // Check for zero operands.
1696 if (parser.getToken().is(Token::percent_identifier)) {
1697 do {
1698 OperandType operand;
1699 if (parseOperand(operand))
1700 return true;
1701 result.push_back(operand);
1702 } while (parser.consumeIf(Token::comma));
1703 }
1704
1705 // Handle delimeters.
1706 switch (delimeter) {
1707 case Delimeter::NoDelimeter:
1708 break;
1709 case Delimeter::ParenDelimeter:
1710 if (parser.parseToken(Token::r_paren, "expected ')' in operand list"))
1711 return true;
1712 break;
1713 case Delimeter::SquareDelimeter:
1714 if (parser.parseToken(Token::r_square, "expected ']' in operand list"))
1715 return true;
1716 break;
1717 }
1718
1719 if (requiredOperandCount != -1 && result.size() != requiredOperandCount)
1720 emitError(startLoc,
1721 "expected " + Twine(requiredOperandCount) + " operands");
1722 return false;
1723 }
1724
1725 //===--------------------------------------------------------------------===//
1726 // Methods for interacting with the parser
1727 //===--------------------------------------------------------------------===//
1728
1729 Builder &getBuilder() const override { return parser.builder; }
1730
1731 llvm::SMLoc getNameLoc() const override { return nameLoc; }
1732
1733 bool resolveOperand(OperandType operand, Type *type,
1734 SSAValue *&result) override {
1735 FunctionParser::SSAUseInfo operandInfo = {operand.name, operand.number,
1736 operand.location};
1737 result = parser.resolveSSAUse(operandInfo, type);
1738 return result == nullptr;
1739 }
1740
1741 /// Emit a diagnostic at the specified location.
1742 void emitError(llvm::SMLoc loc, const Twine &message) override {
1743 parser.emitError(loc, "custom op '" + Twine(opName) + "' " + message);
1744 emittedError = true;
1745 }
1746
1747 bool didEmitError() const { return emittedError; }
1748
1749private:
1750 SMLoc nameLoc;
1751 StringRef opName;
1752 FunctionParser &parser;
1753 bool emittedError = false;
1754};
1755} // end anonymous namespace.
1756
1757Operation *FunctionParser::parseCustomOperation(
1758 const CreateOperationFunction &createOpFunc) {
1759 auto opLoc = getToken().getLoc();
1760 auto opName = getTokenSpelling();
1761 CustomOpAsmParser opAsmParser(opLoc, opName, *this);
1762
1763 auto *opDefinition = getOperationSet().lookup(opName);
1764 if (!opDefinition) {
1765 opAsmParser.emitError(opLoc, "is unknown");
1766 return nullptr;
1767 }
1768
1769 consumeToken();
1770
1771 // Have the op implementation take a crack and parsing this.
1772 auto result = opDefinition->parseAssembly(&opAsmParser);
1773
1774 // If it emitted an error, we failed.
1775 if (opAsmParser.didEmitError())
1776 return nullptr;
1777
1778 // Otherwise, we succeeded. Use the state it parsed as our op information.
1779 auto nameId = builder.getIdentifier(opName);
1780 return createOpFunc(nameId, result.operands, result.types, result.attributes);
1781}
1782
Chris Lattner48af7d12018-07-09 19:05:38 -07001783//===----------------------------------------------------------------------===//
1784// CFG Functions
1785//===----------------------------------------------------------------------===//
Chris Lattnere79379a2018-06-22 10:39:19 -07001786
Chris Lattner4c95a502018-06-23 16:03:42 -07001787namespace {
Chris Lattner48af7d12018-07-09 19:05:38 -07001788/// This is a specialized parser for CFGFunction's, maintaining the state
1789/// transient to their bodies.
Chris Lattner7f9cc272018-07-19 08:35:28 -07001790class CFGFunctionParser : public FunctionParser {
Chris Lattner158e0a3e2018-07-08 20:51:38 -07001791public:
Chris Lattner2e595eb2018-07-10 10:08:27 -07001792 CFGFunctionParser(ParserState &state, CFGFunction *function)
Chris Lattner7f9cc272018-07-19 08:35:28 -07001793 : FunctionParser(state), function(function), builder(function) {}
Chris Lattner2e595eb2018-07-10 10:08:27 -07001794
1795 ParseResult parseFunctionBody();
1796
1797private:
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001798 CFGFunction *function;
James Molloy0ff71542018-07-23 16:56:32 -07001799 llvm::StringMap<std::pair<BasicBlock *, SMLoc>> blocksByName;
Chris Lattner48af7d12018-07-09 19:05:38 -07001800
1801 /// This builder intentionally shadows the builder in the base class, with a
1802 /// more specific builder type.
Chris Lattner158e0a3e2018-07-08 20:51:38 -07001803 CFGFuncBuilder builder;
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001804
Chris Lattner4c95a502018-06-23 16:03:42 -07001805 /// Get the basic block with the specified name, creating it if it doesn't
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001806 /// already exist. The location specified is the point of use, which allows
1807 /// us to diagnose references to blocks that are not defined precisely.
1808 BasicBlock *getBlockNamed(StringRef name, SMLoc loc) {
1809 auto &blockAndLoc = blocksByName[name];
1810 if (!blockAndLoc.first) {
Chris Lattner3a467cc2018-07-01 20:28:00 -07001811 blockAndLoc.first = new BasicBlock();
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001812 blockAndLoc.second = loc;
Chris Lattner4c95a502018-06-23 16:03:42 -07001813 }
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001814 return blockAndLoc.first;
Chris Lattner4c95a502018-06-23 16:03:42 -07001815 }
Chris Lattner48af7d12018-07-09 19:05:38 -07001816
James Molloy61a656c2018-07-22 15:45:24 -07001817 ParseResult
1818 parseOptionalBasicBlockArgList(SmallVectorImpl<BBArgument *> &results,
1819 BasicBlock *owner);
James Molloy4f788372018-07-24 15:01:27 -07001820 ParseResult parseBranchBlockAndUseList(BasicBlock *&block,
1821 SmallVectorImpl<CFGValue *> &values);
James Molloy61a656c2018-07-22 15:45:24 -07001822
Chris Lattner48af7d12018-07-09 19:05:38 -07001823 ParseResult parseBasicBlock();
1824 OperationInst *parseCFGOperation();
1825 TerminatorInst *parseTerminator();
Chris Lattner4c95a502018-06-23 16:03:42 -07001826};
1827} // end anonymous namespace
1828
James Molloy61a656c2018-07-22 15:45:24 -07001829/// Parse a (possibly empty) list of SSA operands with types as basic block
Chris Lattner2c402672018-07-23 11:56:17 -07001830/// arguments.
James Molloy61a656c2018-07-22 15:45:24 -07001831///
1832/// ssa-id-and-type-list ::= ssa-id-and-type (`,` ssa-id-and-type)*
1833///
1834ParseResult CFGFunctionParser::parseOptionalBasicBlockArgList(
1835 SmallVectorImpl<BBArgument *> &results, BasicBlock *owner) {
1836 if (getToken().is(Token::r_brace))
1837 return ParseSuccess;
1838
1839 return parseCommaSeparatedList([&]() -> ParseResult {
1840 auto type = parseSSADefOrUseAndType<Type *>(
1841 [&](SSAUseInfo useInfo, Type *type) -> Type * {
1842 BBArgument *arg = owner->addArgument(type);
1843 if (addDefinition(useInfo, arg) == ParseFailure)
1844 return nullptr;
1845 return type;
1846 });
1847 return type ? ParseSuccess : ParseFailure;
1848 });
1849}
1850
Chris Lattner48af7d12018-07-09 19:05:38 -07001851ParseResult CFGFunctionParser::parseFunctionBody() {
Chris Lattner40746442018-07-21 14:32:09 -07001852 auto braceLoc = getToken().getLoc();
Chris Lattnerf7702a62018-07-23 17:30:01 -07001853 if (parseToken(Token::l_brace, "expected '{' in CFG function"))
1854 return ParseFailure;
Chris Lattner48af7d12018-07-09 19:05:38 -07001855
1856 // Make sure we have at least one block.
1857 if (getToken().is(Token::r_brace))
1858 return emitError("CFG functions must have at least one basic block");
Chris Lattner4c95a502018-06-23 16:03:42 -07001859
1860 // Parse the list of blocks.
1861 while (!consumeIf(Token::r_brace))
Chris Lattner48af7d12018-07-09 19:05:38 -07001862 if (parseBasicBlock())
Chris Lattner4c95a502018-06-23 16:03:42 -07001863 return ParseFailure;
1864
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001865 // Verify that all referenced blocks were defined. Iteration over a
1866 // StringMap isn't determinstic, but this is good enough for our purposes.
Chris Lattner48af7d12018-07-09 19:05:38 -07001867 for (auto &elt : blocksByName) {
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001868 auto *bb = elt.second.first;
Chris Lattner3a467cc2018-07-01 20:28:00 -07001869 if (!bb->getFunction())
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001870 return emitError(elt.second.second,
James Molloy0ff71542018-07-23 16:56:32 -07001871 "reference to an undefined basic block '" + elt.first() +
1872 "'");
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001873 }
1874
Chris Lattner48af7d12018-07-09 19:05:38 -07001875 getModule()->functionList.push_back(function);
Chris Lattner6119d382018-07-20 18:41:34 -07001876
Chris Lattner40746442018-07-21 14:32:09 -07001877 return finalizeFunction(function, braceLoc);
Chris Lattner4c95a502018-06-23 16:03:42 -07001878}
1879
1880/// Basic block declaration.
1881///
1882/// basic-block ::= bb-label instruction* terminator-stmt
1883/// bb-label ::= bb-id bb-arg-list? `:`
1884/// bb-id ::= bare-id
1885/// bb-arg-list ::= `(` ssa-id-and-type-list? `)`
1886///
Chris Lattner48af7d12018-07-09 19:05:38 -07001887ParseResult CFGFunctionParser::parseBasicBlock() {
1888 SMLoc nameLoc = getToken().getLoc();
1889 auto name = getTokenSpelling();
Chris Lattnerf7702a62018-07-23 17:30:01 -07001890 if (parseToken(Token::bare_identifier, "expected basic block name"))
1891 return ParseFailure;
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001892
Chris Lattner48af7d12018-07-09 19:05:38 -07001893 auto *block = getBlockNamed(name, nameLoc);
Chris Lattner4c95a502018-06-23 16:03:42 -07001894
1895 // If this block has already been parsed, then this is a redefinition with the
1896 // same block name.
Chris Lattner3a467cc2018-07-01 20:28:00 -07001897 if (block->getFunction())
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001898 return emitError(nameLoc, "redefinition of block '" + name.str() + "'");
1899
Chris Lattner78276e32018-07-07 15:48:26 -07001900 // If an argument list is present, parse it.
1901 if (consumeIf(Token::l_paren)) {
James Molloy61a656c2018-07-22 15:45:24 -07001902 SmallVector<BBArgument *, 8> bbArgs;
Chris Lattnerf7702a62018-07-23 17:30:01 -07001903 if (parseOptionalBasicBlockArgList(bbArgs, block) ||
1904 parseToken(Token::r_paren, "expected ')' to end argument list"))
Chris Lattner78276e32018-07-07 15:48:26 -07001905 return ParseFailure;
Chris Lattner78276e32018-07-07 15:48:26 -07001906 }
Chris Lattner4c95a502018-06-23 16:03:42 -07001907
James Molloy61a656c2018-07-22 15:45:24 -07001908 // Add the block to the function.
1909 function->push_back(block);
1910
Chris Lattnerf7702a62018-07-23 17:30:01 -07001911 if (parseToken(Token::colon, "expected ':' after basic block name"))
1912 return ParseFailure;
Chris Lattner4c95a502018-06-23 16:03:42 -07001913
Chris Lattner158e0a3e2018-07-08 20:51:38 -07001914 // Set the insertion point to the block we want to insert new operations into.
Chris Lattner48af7d12018-07-09 19:05:38 -07001915 builder.setInsertionPoint(block);
Chris Lattner158e0a3e2018-07-08 20:51:38 -07001916
Chris Lattner7f9cc272018-07-19 08:35:28 -07001917 auto createOpFunc = [&](Identifier name, ArrayRef<SSAValue *> operands,
1918 ArrayRef<Type *> resultTypes,
1919 ArrayRef<NamedAttribute> attrs) -> Operation * {
1920 SmallVector<CFGValue *, 8> cfgOperands;
1921 cfgOperands.reserve(operands.size());
1922 for (auto *op : operands)
1923 cfgOperands.push_back(cast<CFGValue>(op));
1924 return builder.createOperation(name, cfgOperands, resultTypes, attrs);
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001925 };
1926
Chris Lattnered65a732018-06-28 20:45:33 -07001927 // Parse the list of operations that make up the body of the block.
James Molloy4f788372018-07-24 15:01:27 -07001928 while (getToken().isNot(Token::kw_return, Token::kw_br, Token::kw_cond_br)) {
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001929 if (parseOperation(createOpFunc))
Chris Lattnered65a732018-06-28 20:45:33 -07001930 return ParseFailure;
1931 }
Chris Lattner4c95a502018-06-23 16:03:42 -07001932
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001933 if (!parseTerminator())
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001934 return ParseFailure;
Chris Lattner4c95a502018-06-23 16:03:42 -07001935
1936 return ParseSuccess;
1937}
1938
James Molloy4f788372018-07-24 15:01:27 -07001939ParseResult CFGFunctionParser::parseBranchBlockAndUseList(
1940 BasicBlock *&block, SmallVectorImpl<CFGValue *> &values) {
1941 block = getBlockNamed(getTokenSpelling(), getToken().getLoc());
1942 if (parseToken(Token::bare_identifier, "expected basic block name"))
1943 return ParseFailure;
1944
1945 if (!consumeIf(Token::l_paren))
1946 return ParseSuccess;
1947 if (parseOptionalSSAUseAndTypeList(values, /*isParenthesized*/ false) ||
1948 parseToken(Token::r_paren, "expected ')' to close argument list"))
1949 return ParseFailure;
1950 return ParseSuccess;
1951}
1952
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001953/// Parse the terminator instruction for a basic block.
1954///
1955/// terminator-stmt ::= `br` bb-id branch-use-list?
Chris Lattner1604e472018-07-23 08:42:19 -07001956/// branch-use-list ::= `(` ssa-use-list `)` ':' type-list-no-parens
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001957/// terminator-stmt ::=
1958/// `cond_br` ssa-use `,` bb-id branch-use-list? `,` bb-id branch-use-list?
1959/// terminator-stmt ::= `return` ssa-use-and-type-list?
1960///
Chris Lattner48af7d12018-07-09 19:05:38 -07001961TerminatorInst *CFGFunctionParser::parseTerminator() {
1962 switch (getToken().getKind()) {
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001963 default:
Chris Lattner3a467cc2018-07-01 20:28:00 -07001964 return (emitError("expected terminator at end of basic block"), nullptr);
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001965
Chris Lattner40746442018-07-21 14:32:09 -07001966 case Token::kw_return: {
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001967 consumeToken(Token::kw_return);
Chris Lattner40746442018-07-21 14:32:09 -07001968
Chris Lattner2c402672018-07-23 11:56:17 -07001969 // Parse any operands.
1970 SmallVector<CFGValue *, 8> operands;
1971 if (parseOptionalSSAUseAndTypeList(operands, /*isParenthesized*/ false))
1972 return nullptr;
1973 return builder.createReturnInst(operands);
Chris Lattner40746442018-07-21 14:32:09 -07001974 }
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001975
1976 case Token::kw_br: {
1977 consumeToken(Token::kw_br);
James Molloy4f788372018-07-24 15:01:27 -07001978 BasicBlock *destBB;
1979 SmallVector<CFGValue *, 4> values;
1980 if (parseBranchBlockAndUseList(destBB, values))
Chris Lattnerf7702a62018-07-23 17:30:01 -07001981 return nullptr;
Chris Lattner1604e472018-07-23 08:42:19 -07001982 auto branch = builder.createBranchInst(destBB);
James Molloy4f788372018-07-24 15:01:27 -07001983 branch->addOperands(values);
Chris Lattner1604e472018-07-23 08:42:19 -07001984 return branch;
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001985 }
James Molloy4f788372018-07-24 15:01:27 -07001986
1987 case Token::kw_cond_br: {
1988 consumeToken(Token::kw_cond_br);
1989 SSAUseInfo ssaUse;
1990 if (parseSSAUse(ssaUse))
1991 return nullptr;
1992 auto *cond = resolveSSAUse(ssaUse, builder.getIntegerType(1));
1993 if (!cond)
1994 return (emitError("expected type was boolean (i1)"), nullptr);
1995 if (parseToken(Token::comma, "expected ',' in conditional branch"))
1996 return nullptr;
1997
1998 BasicBlock *trueBlock;
1999 SmallVector<CFGValue *, 4> trueOperands;
2000 if (parseBranchBlockAndUseList(trueBlock, trueOperands))
2001 return nullptr;
2002
2003 if (parseToken(Token::comma, "expected ',' in conditional branch"))
2004 return nullptr;
2005
2006 BasicBlock *falseBlock;
2007 SmallVector<CFGValue *, 4> falseOperands;
2008 if (parseBranchBlockAndUseList(falseBlock, falseOperands))
2009 return nullptr;
2010
2011 auto branch = builder.createCondBranchInst(cast<CFGValue>(cond), trueBlock,
2012 falseBlock);
2013 branch->addTrueOperands(trueOperands);
2014 branch->addFalseOperands(falseOperands);
2015 return branch;
2016 }
Chris Lattnerf6d80a02018-06-24 11:18:29 -07002017 }
2018}
2019
Chris Lattner48af7d12018-07-09 19:05:38 -07002020//===----------------------------------------------------------------------===//
2021// ML Functions
2022//===----------------------------------------------------------------------===//
2023
2024namespace {
2025/// Refined parser for MLFunction bodies.
Chris Lattner7f9cc272018-07-19 08:35:28 -07002026class MLFunctionParser : public FunctionParser {
Chris Lattner48af7d12018-07-09 19:05:38 -07002027public:
Chris Lattner48af7d12018-07-09 19:05:38 -07002028 MLFunctionParser(ParserState &state, MLFunction *function)
Chris Lattner7f9cc272018-07-19 08:35:28 -07002029 : FunctionParser(state), function(function), builder(function) {}
Chris Lattner48af7d12018-07-09 19:05:38 -07002030
2031 ParseResult parseFunctionBody();
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07002032
2033private:
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07002034 MLFunction *function;
2035
2036 /// This builder intentionally shadows the builder in the base class, with a
2037 /// more specific builder type.
2038 MLFuncBuilder builder;
2039
2040 ParseResult parseForStmt();
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002041 AffineConstantExpr *parseIntConstant();
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07002042 ParseResult parseIfStmt();
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07002043 ParseResult parseElseClause(IfClause *elseClause);
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07002044 ParseResult parseStatements(StmtBlock *block);
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07002045 ParseResult parseStmtBlock(StmtBlock *block);
Chris Lattner48af7d12018-07-09 19:05:38 -07002046};
2047} // end anonymous namespace
2048
Chris Lattner48af7d12018-07-09 19:05:38 -07002049ParseResult MLFunctionParser::parseFunctionBody() {
Chris Lattner40746442018-07-21 14:32:09 -07002050 auto braceLoc = getToken().getLoc();
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07002051 // Parse statements in this function
Tatiana Shpeismanc96b5872018-06-28 17:02:32 -07002052
Chris Lattnerf7702a62018-07-23 17:30:01 -07002053 if (parseToken(Token::l_brace, "expected '{' in ML function") ||
2054 parseStatements(function)) {
2055 return ParseFailure;
2056 }
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07002057
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002058 // TODO: store return operands in the IR.
2059 SmallVector<SSAUseInfo, 4> dummyUseInfo;
Tatiana Shpeismanc96b5872018-06-28 17:02:32 -07002060
Chris Lattnerf7702a62018-07-23 17:30:01 -07002061 if (parseToken(Token::kw_return,
2062 "ML function must end with return statement") ||
2063 parseOptionalSSAUseList(dummyUseInfo) ||
2064 parseToken(Token::r_brace, "expected '}' to end mlfunc"))
2065 return ParseFailure;
Chris Lattner40746442018-07-21 14:32:09 -07002066
Chris Lattner48af7d12018-07-09 19:05:38 -07002067 getModule()->functionList.push_back(function);
Tatiana Shpeismanc96b5872018-06-28 17:02:32 -07002068
Chris Lattner40746442018-07-21 14:32:09 -07002069 return finalizeFunction(function, braceLoc);
Tatiana Shpeismanc96b5872018-06-28 17:02:32 -07002070}
2071
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07002072/// For statement.
2073///
Chris Lattner48af7d12018-07-09 19:05:38 -07002074/// ml-for-stmt ::= `for` ssa-id `=` lower-bound `to` upper-bound
2075/// (`step` integer-literal)? `{` ml-stmt* `}`
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07002076///
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07002077ParseResult MLFunctionParser::parseForStmt() {
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07002078 consumeToken(Token::kw_for);
2079
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002080 // Parse induction variable
2081 if (getToken().isNot(Token::percent_identifier))
2082 return emitError("expected SSA identifier for the loop variable");
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07002083
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002084 // TODO: create SSA value definition from name
2085 StringRef name = getTokenSpelling().drop_front();
2086 (void)name;
2087
2088 consumeToken(Token::percent_identifier);
2089
Chris Lattnerf7702a62018-07-23 17:30:01 -07002090 if (parseToken(Token::equal, "expected ="))
2091 return ParseFailure;
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002092
2093 // Parse loop bounds
2094 AffineConstantExpr *lowerBound = parseIntConstant();
2095 if (!lowerBound)
2096 return ParseFailure;
2097
Chris Lattnerf7702a62018-07-23 17:30:01 -07002098 if (parseToken(Token::kw_to, "expected 'to' between bounds"))
2099 return ParseFailure;
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002100
2101 AffineConstantExpr *upperBound = parseIntConstant();
2102 if (!upperBound)
2103 return ParseFailure;
2104
2105 // Parse step
2106 AffineConstantExpr *step = nullptr;
2107 if (consumeIf(Token::kw_step)) {
2108 step = parseIntConstant();
2109 if (!step)
2110 return ParseFailure;
2111 }
2112
2113 // Create for statement.
2114 ForStmt *stmt = builder.createFor(lowerBound, upperBound, step);
2115
2116 // If parsing of the for statement body fails,
2117 // MLIR contains for statement with those nested statements that have been
2118 // successfully parsed.
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07002119 if (parseStmtBlock(static_cast<StmtBlock *>(stmt)))
2120 return ParseFailure;
2121
2122 return ParseSuccess;
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07002123}
2124
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002125// This method is temporary workaround to parse simple loop bounds and
2126// step.
2127// TODO: remove this method once it's no longer used.
2128AffineConstantExpr *MLFunctionParser::parseIntConstant() {
2129 if (getToken().isNot(Token::integer))
2130 return (emitError("expected non-negative integer for now"), nullptr);
2131
2132 auto val = getToken().getUInt64IntegerValue();
2133 if (!val.hasValue() || (int64_t)val.getValue() < 0) {
2134 return (emitError("constant too large for affineint"), nullptr);
2135 }
2136 consumeToken(Token::integer);
2137 return builder.getConstantExpr((int64_t)val.getValue());
2138}
2139
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07002140/// If statement.
2141///
Chris Lattner48af7d12018-07-09 19:05:38 -07002142/// ml-if-head ::= `if` ml-if-cond `{` ml-stmt* `}`
2143/// | ml-if-head `else` `if` ml-if-cond `{` ml-stmt* `}`
2144/// ml-if-stmt ::= ml-if-head
2145/// | ml-if-head `else` `{` ml-stmt* `}`
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07002146///
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07002147ParseResult MLFunctionParser::parseIfStmt() {
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07002148 consumeToken(Token::kw_if);
Chris Lattnerf7702a62018-07-23 17:30:01 -07002149 if (parseToken(Token::l_paren, "expected ("))
2150 return ParseFailure;
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07002151
James Molloy0ff71542018-07-23 16:56:32 -07002152 // TODO: parse condition
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07002153
Chris Lattnerf7702a62018-07-23 17:30:01 -07002154 if (parseToken(Token::r_paren, "expected )"))
2155 return ParseFailure;
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07002156
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07002157 IfStmt *ifStmt = builder.createIf();
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07002158 IfClause *thenClause = ifStmt->getThenClause();
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07002159
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002160 // When parsing of an if statement body fails, the IR contains
2161 // the if statement with the portion of the body that has been
2162 // successfully parsed.
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07002163 if (parseStmtBlock(thenClause))
2164 return ParseFailure;
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07002165
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07002166 if (consumeIf(Token::kw_else)) {
Chris Lattnerf7702a62018-07-23 17:30:01 -07002167 auto *elseClause = ifStmt->createElseClause();
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07002168 if (parseElseClause(elseClause))
2169 return ParseFailure;
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07002170 }
2171
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07002172 return ParseSuccess;
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07002173}
2174
2175ParseResult MLFunctionParser::parseElseClause(IfClause *elseClause) {
2176 if (getToken().is(Token::kw_if)) {
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07002177 builder.setInsertionPoint(elseClause);
2178 return parseIfStmt();
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07002179 }
2180
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07002181 return parseStmtBlock(elseClause);
2182}
2183
2184///
2185/// Parse a list of statements ending with `return` or `}`
2186///
2187ParseResult MLFunctionParser::parseStatements(StmtBlock *block) {
Chris Lattner7f9cc272018-07-19 08:35:28 -07002188 auto createOpFunc = [&](Identifier name, ArrayRef<SSAValue *> operands,
2189 ArrayRef<Type *> resultTypes,
2190 ArrayRef<NamedAttribute> attrs) -> Operation * {
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07002191 return builder.createOperation(name, attrs);
2192 };
2193
2194 builder.setInsertionPoint(block);
2195
2196 while (getToken().isNot(Token::kw_return, Token::r_brace)) {
2197 switch (getToken().getKind()) {
2198 default:
2199 if (parseOperation(createOpFunc))
2200 return ParseFailure;
2201 break;
2202 case Token::kw_for:
2203 if (parseForStmt())
2204 return ParseFailure;
2205 break;
2206 case Token::kw_if:
2207 if (parseIfStmt())
2208 return ParseFailure;
2209 break;
2210 } // end switch
2211 }
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07002212
2213 return ParseSuccess;
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07002214}
2215
2216///
2217/// Parse `{` ml-stmt* `}`
2218///
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07002219ParseResult MLFunctionParser::parseStmtBlock(StmtBlock *block) {
Chris Lattnerf7702a62018-07-23 17:30:01 -07002220 if (parseToken(Token::l_brace, "expected '{' before statement list") ||
2221 parseStatements(block) ||
2222 parseToken(Token::r_brace,
2223 "expected '}' at the end of the statement block"))
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07002224 return ParseFailure;
2225
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07002226 return ParseSuccess;
2227}
2228
Chris Lattner4c95a502018-06-23 16:03:42 -07002229//===----------------------------------------------------------------------===//
2230// Top-level entity parsing.
2231//===----------------------------------------------------------------------===//
2232
Chris Lattner2e595eb2018-07-10 10:08:27 -07002233namespace {
2234/// This parser handles entities that are only valid at the top level of the
2235/// file.
2236class ModuleParser : public Parser {
2237public:
2238 explicit ModuleParser(ParserState &state) : Parser(state) {}
2239
2240 ParseResult parseModule();
2241
2242private:
2243 ParseResult parseAffineMapDef();
2244
2245 // Functions.
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002246 ParseResult parseMLArgumentList(SmallVectorImpl<Type *> &argTypes,
2247 SmallVectorImpl<StringRef> &argNames);
2248 ParseResult parseFunctionSignature(StringRef &name, FunctionType *&type,
2249 SmallVectorImpl<StringRef> *argNames);
Chris Lattner2e595eb2018-07-10 10:08:27 -07002250 ParseResult parseExtFunc();
2251 ParseResult parseCFGFunc();
2252 ParseResult parseMLFunc();
2253};
2254} // end anonymous namespace
2255
2256/// Affine map declaration.
2257///
2258/// affine-map-def ::= affine-map-id `=` affine-map-inline
2259///
2260ParseResult ModuleParser::parseAffineMapDef() {
2261 assert(getToken().is(Token::hash_identifier));
2262
2263 StringRef affineMapId = getTokenSpelling().drop_front();
2264
2265 // Check for redefinitions.
2266 auto *&entry = getState().affineMapDefinitions[affineMapId];
2267 if (entry)
2268 return emitError("redefinition of affine map id '" + affineMapId + "'");
2269
2270 consumeToken(Token::hash_identifier);
2271
2272 // Parse the '='
Chris Lattnerf7702a62018-07-23 17:30:01 -07002273 if (parseToken(Token::equal,
2274 "expected '=' in affine map outlined definition"))
2275 return ParseFailure;
Chris Lattner2e595eb2018-07-10 10:08:27 -07002276
2277 entry = parseAffineMapInline();
2278 if (!entry)
2279 return ParseFailure;
2280
Chris Lattner2e595eb2018-07-10 10:08:27 -07002281 return ParseSuccess;
2282}
2283
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002284/// Parse a (possibly empty) list of MLFunction arguments with types.
2285///
2286/// ml-argument ::= ssa-id `:` type
2287/// ml-argument-list ::= ml-argument (`,` ml-argument)* | /*empty*/
2288///
2289ParseResult
2290ModuleParser::parseMLArgumentList(SmallVectorImpl<Type *> &argTypes,
2291 SmallVectorImpl<StringRef> &argNames) {
Chris Lattnerf7702a62018-07-23 17:30:01 -07002292 consumeToken(Token::l_paren);
2293
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002294 auto parseElt = [&]() -> ParseResult {
2295 // Parse argument name
2296 if (getToken().isNot(Token::percent_identifier))
2297 return emitError("expected SSA identifier");
2298
2299 StringRef name = getTokenSpelling().drop_front();
2300 consumeToken(Token::percent_identifier);
2301 argNames.push_back(name);
2302
Chris Lattnerf7702a62018-07-23 17:30:01 -07002303 if (parseToken(Token::colon, "expected ':'"))
2304 return ParseFailure;
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002305
2306 // Parse argument type
2307 auto elt = parseType();
2308 if (!elt)
2309 return ParseFailure;
2310 argTypes.push_back(elt);
2311
2312 return ParseSuccess;
2313 };
2314
Chris Lattner40746442018-07-21 14:32:09 -07002315 return parseCommaSeparatedListUntil(Token::r_paren, parseElt);
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002316}
2317
Chris Lattner2e595eb2018-07-10 10:08:27 -07002318/// Parse a function signature, starting with a name and including the parameter
2319/// list.
2320///
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002321/// argument-list ::= type (`,` type)* | /*empty*/ | ml-argument-list
Chris Lattner2e595eb2018-07-10 10:08:27 -07002322/// function-signature ::= function-id `(` argument-list `)` (`->` type-list)?
2323///
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002324ParseResult
2325ModuleParser::parseFunctionSignature(StringRef &name, FunctionType *&type,
2326 SmallVectorImpl<StringRef> *argNames) {
Chris Lattner2e595eb2018-07-10 10:08:27 -07002327 if (getToken().isNot(Token::at_identifier))
2328 return emitError("expected a function identifier like '@foo'");
2329
2330 name = getTokenSpelling().drop_front();
2331 consumeToken(Token::at_identifier);
2332
2333 if (getToken().isNot(Token::l_paren))
2334 return emitError("expected '(' in function signature");
2335
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002336 SmallVector<Type *, 4> argTypes;
2337 ParseResult parseResult;
2338
2339 if (argNames)
2340 parseResult = parseMLArgumentList(argTypes, *argNames);
2341 else
2342 parseResult = parseTypeList(argTypes);
2343
2344 if (parseResult)
Chris Lattner2e595eb2018-07-10 10:08:27 -07002345 return ParseFailure;
2346
2347 // Parse the return type if present.
2348 SmallVector<Type *, 4> results;
2349 if (consumeIf(Token::arrow)) {
2350 if (parseTypeList(results))
2351 return ParseFailure;
2352 }
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002353 type = builder.getFunctionType(argTypes, results);
Chris Lattner2e595eb2018-07-10 10:08:27 -07002354 return ParseSuccess;
2355}
2356
2357/// External function declarations.
2358///
2359/// ext-func ::= `extfunc` function-signature
2360///
2361ParseResult ModuleParser::parseExtFunc() {
2362 consumeToken(Token::kw_extfunc);
2363
2364 StringRef name;
2365 FunctionType *type = nullptr;
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002366 if (parseFunctionSignature(name, type, /*arguments*/ nullptr))
Chris Lattner2e595eb2018-07-10 10:08:27 -07002367 return ParseFailure;
2368
2369 // Okay, the external function definition was parsed correctly.
2370 getModule()->functionList.push_back(new ExtFunction(name, type));
2371 return ParseSuccess;
2372}
2373
2374/// CFG function declarations.
2375///
2376/// cfg-func ::= `cfgfunc` function-signature `{` basic-block+ `}`
2377///
2378ParseResult ModuleParser::parseCFGFunc() {
2379 consumeToken(Token::kw_cfgfunc);
2380
2381 StringRef name;
2382 FunctionType *type = nullptr;
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002383 if (parseFunctionSignature(name, type, /*arguments*/ nullptr))
Chris Lattner2e595eb2018-07-10 10:08:27 -07002384 return ParseFailure;
2385
2386 // Okay, the CFG function signature was parsed correctly, create the function.
2387 auto function = new CFGFunction(name, type);
2388
2389 return CFGFunctionParser(getState(), function).parseFunctionBody();
2390}
2391
2392/// ML function declarations.
2393///
2394/// ml-func ::= `mlfunc` ml-func-signature `{` ml-stmt* ml-return-stmt `}`
2395///
2396ParseResult ModuleParser::parseMLFunc() {
2397 consumeToken(Token::kw_mlfunc);
2398
2399 StringRef name;
2400 FunctionType *type = nullptr;
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002401 SmallVector<StringRef, 4> argNames;
Chris Lattner2e595eb2018-07-10 10:08:27 -07002402 // FIXME: Parse ML function signature (args + types)
2403 // by passing pointer to SmallVector<identifier> into parseFunctionSignature
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07002404
2405 if (parseFunctionSignature(name, type, &argNames))
Chris Lattner2e595eb2018-07-10 10:08:27 -07002406 return ParseFailure;
2407
2408 // Okay, the ML function signature was parsed correctly, create the function.
2409 auto function = new MLFunction(name, type);
2410
2411 return MLFunctionParser(getState(), function).parseFunctionBody();
2412}
2413
Chris Lattnere79379a2018-06-22 10:39:19 -07002414/// This is the top-level module parser.
Chris Lattner2e595eb2018-07-10 10:08:27 -07002415ParseResult ModuleParser::parseModule() {
Chris Lattnere79379a2018-06-22 10:39:19 -07002416 while (1) {
Chris Lattner48af7d12018-07-09 19:05:38 -07002417 switch (getToken().getKind()) {
Chris Lattnere79379a2018-06-22 10:39:19 -07002418 default:
2419 emitError("expected a top level entity");
Chris Lattner2e595eb2018-07-10 10:08:27 -07002420 return ParseFailure;
Chris Lattnere79379a2018-06-22 10:39:19 -07002421
Uday Bondhugula015cbb12018-07-03 20:16:08 -07002422 // If we got to the end of the file, then we're done.
Chris Lattnere79379a2018-06-22 10:39:19 -07002423 case Token::eof:
Chris Lattner2e595eb2018-07-10 10:08:27 -07002424 return ParseSuccess;
Chris Lattnere79379a2018-06-22 10:39:19 -07002425
2426 // If we got an error token, then the lexer already emitted an error, just
2427 // stop. Someday we could introduce error recovery if there was demand for
2428 // it.
2429 case Token::error:
Chris Lattner2e595eb2018-07-10 10:08:27 -07002430 return ParseFailure;
2431
2432 case Token::hash_identifier:
2433 if (parseAffineMapDef())
2434 return ParseFailure;
2435 break;
Chris Lattnere79379a2018-06-22 10:39:19 -07002436
2437 case Token::kw_extfunc:
Chris Lattner2e595eb2018-07-10 10:08:27 -07002438 if (parseExtFunc())
2439 return ParseFailure;
Chris Lattnere79379a2018-06-22 10:39:19 -07002440 break;
2441
Chris Lattner4c95a502018-06-23 16:03:42 -07002442 case Token::kw_cfgfunc:
Chris Lattner2e595eb2018-07-10 10:08:27 -07002443 if (parseCFGFunc())
2444 return ParseFailure;
MLIR Teamf85a6262018-06-27 11:03:08 -07002445 break;
Chris Lattner4c95a502018-06-23 16:03:42 -07002446
Tatiana Shpeismanc96b5872018-06-28 17:02:32 -07002447 case Token::kw_mlfunc:
Chris Lattner2e595eb2018-07-10 10:08:27 -07002448 if (parseMLFunc())
2449 return ParseFailure;
Tatiana Shpeismanc96b5872018-06-28 17:02:32 -07002450 break;
2451
Uday Bondhugula015cbb12018-07-03 20:16:08 -07002452 // TODO: affine entity declarations, etc.
Chris Lattnere79379a2018-06-22 10:39:19 -07002453 }
2454 }
2455}
2456
2457//===----------------------------------------------------------------------===//
2458
Jacques Pienaar7b829702018-07-03 13:24:09 -07002459void mlir::defaultErrorReporter(const llvm::SMDiagnostic &error) {
2460 const auto &sourceMgr = *error.getSourceMgr();
2461 sourceMgr.PrintMessage(error.getLoc(), error.getKind(), error.getMessage());
2462}
2463
Chris Lattnere79379a2018-06-22 10:39:19 -07002464/// This parses the file specified by the indicated SourceMgr and returns an
2465/// MLIR module if it was valid. If not, it emits diagnostics and returns null.
Jacques Pienaar9c411be2018-06-24 19:17:35 -07002466Module *mlir::parseSourceFile(llvm::SourceMgr &sourceMgr, MLIRContext *context,
Jacques Pienaar7b829702018-07-03 13:24:09 -07002467 SMDiagnosticHandlerTy errorReporter) {
Chris Lattner2e595eb2018-07-10 10:08:27 -07002468 // This is the result module we are parsing into.
2469 std::unique_ptr<Module> module(new Module(context));
2470
2471 ParserState state(sourceMgr, module.get(),
Jacques Pienaar0bffd862018-07-11 13:26:23 -07002472 errorReporter ? errorReporter : defaultErrorReporter);
Chris Lattner2e595eb2018-07-10 10:08:27 -07002473 if (ModuleParser(state).parseModule())
2474 return nullptr;
Chris Lattner21e67f62018-07-06 10:46:19 -07002475
2476 // Make sure the parse module has no other structural problems detected by the
2477 // verifier.
Chris Lattner2e595eb2018-07-10 10:08:27 -07002478 module->verify();
2479 return module.release();
Chris Lattnere79379a2018-06-22 10:39:19 -07002480}