blob: 3c8fc894e02a6334fd432575250e57e62edd4680 [file] [log] [blame]
Chris Lattnere79379a2018-06-22 10:39:19 -07001//===- Parser.cpp - MLIR Parser Implementation ----------------------------===//
2//
3// Copyright 2019 The MLIR Authors.
4//
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16// =============================================================================
17//
18// This file implements the parser for the MLIR textual form.
19//
20//===----------------------------------------------------------------------===//
21
22#include "mlir/Parser.h"
23#include "Lexer.h"
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -070024#include "mlir/IR/AffineExpr.h"
MLIR Teamf85a6262018-06-27 11:03:08 -070025#include "mlir/IR/AffineMap.h"
Chris Lattner7121b802018-07-04 20:45:39 -070026#include "mlir/IR/Attributes.h"
Chris Lattner158e0a3e2018-07-08 20:51:38 -070027#include "mlir/IR/Builders.h"
Tatiana Shpeismanc96b5872018-06-28 17:02:32 -070028#include "mlir/IR/MLFunction.h"
Chris Lattner21e67f62018-07-06 10:46:19 -070029#include "mlir/IR/Module.h"
30#include "mlir/IR/OperationSet.h"
Chris Lattnerf7e22732018-06-22 22:03:48 -070031#include "mlir/IR/Types.h"
Chris Lattnere79379a2018-06-22 10:39:19 -070032#include "llvm/Support/SourceMgr.h"
33using namespace mlir;
34using llvm::SourceMgr;
Chris Lattner4c95a502018-06-23 16:03:42 -070035using llvm::SMLoc;
Chris Lattnere79379a2018-06-22 10:39:19 -070036
Chris Lattnerf7e22732018-06-22 22:03:48 -070037/// Simple enum to make code read better in cases that would otherwise return a
38/// bool value. Failure is "true" in a boolean context.
Chris Lattnere79379a2018-06-22 10:39:19 -070039enum ParseResult {
40 ParseSuccess,
41 ParseFailure
42};
43
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()),
56 errorReporter(std::move(errorReporter)) {}
57
58 // A map from affine map identifier to AffineMap.
59 llvm::StringMap<AffineMap *> affineMapDefinitions;
Chris Lattnere79379a2018-06-22 10:39:19 -070060
Chris Lattnere79379a2018-06-22 10:39:19 -070061private:
Chris Lattner48af7d12018-07-09 19:05:38 -070062 ParserState(const ParserState &) = delete;
63 void operator=(const ParserState &) = delete;
64
65 friend class Parser;
66
67 // The context we're parsing into.
Chris Lattner2e595eb2018-07-10 10:08:27 -070068 MLIRContext *const context;
69
70 // This is the module we are parsing into.
71 Module *const module;
Chris Lattnerf7e22732018-06-22 22:03:48 -070072
73 // The lexer for the source file we're parsing.
Chris Lattnere79379a2018-06-22 10:39:19 -070074 Lexer lex;
75
76 // This is the next token that hasn't been consumed yet.
77 Token curToken;
78
Jacques Pienaar9c411be2018-06-24 19:17:35 -070079 // The diagnostic error reporter.
Chris Lattner2e595eb2018-07-10 10:08:27 -070080 SMDiagnosticHandlerTy const errorReporter;
Chris Lattner48af7d12018-07-09 19:05:38 -070081};
82} // end anonymous namespace
MLIR Teamf85a6262018-06-27 11:03:08 -070083
Chris Lattner48af7d12018-07-09 19:05:38 -070084namespace {
85
86/// This class implement support for parsing global entities like types and
87/// shared entities like SSA names. It is intended to be subclassed by
88/// specialized subparsers that include state, e.g. when a local symbol table.
89class Parser {
90public:
Chris Lattner2e595eb2018-07-10 10:08:27 -070091 Builder builder;
Chris Lattner48af7d12018-07-09 19:05:38 -070092
Chris Lattner2e595eb2018-07-10 10:08:27 -070093 Parser(ParserState &state) : builder(state.context), state(state) {}
94
95 // Helper methods to get stuff from the parser-global state.
96 ParserState &getState() const { return state; }
Chris Lattner48af7d12018-07-09 19:05:38 -070097 MLIRContext *getContext() const { return state.context; }
Chris Lattner2e595eb2018-07-10 10:08:27 -070098 Module *getModule() { return state.module; }
Chris Lattner48af7d12018-07-09 19:05:38 -070099
100 /// Return the current token the parser is inspecting.
101 const Token &getToken() const { return state.curToken; }
102 StringRef getTokenSpelling() const { return state.curToken.getSpelling(); }
Chris Lattnere79379a2018-06-22 10:39:19 -0700103
104 /// Emit an error and return failure.
Chris Lattner4c95a502018-06-23 16:03:42 -0700105 ParseResult emitError(const Twine &message) {
Chris Lattner48af7d12018-07-09 19:05:38 -0700106 return emitError(state.curToken.getLoc(), message);
Chris Lattner4c95a502018-06-23 16:03:42 -0700107 }
108 ParseResult emitError(SMLoc loc, const Twine &message);
Chris Lattnere79379a2018-06-22 10:39:19 -0700109
110 /// Advance the current lexer onto the next token.
111 void consumeToken() {
Chris Lattner48af7d12018-07-09 19:05:38 -0700112 assert(state.curToken.isNot(Token::eof, Token::error) &&
Chris Lattnere79379a2018-06-22 10:39:19 -0700113 "shouldn't advance past EOF or errors");
Chris Lattner48af7d12018-07-09 19:05:38 -0700114 state.curToken = state.lex.lexToken();
Chris Lattnere79379a2018-06-22 10:39:19 -0700115 }
116
117 /// Advance the current lexer onto the next token, asserting what the expected
118 /// current token is. This is preferred to the above method because it leads
119 /// to more self-documenting code with better checking.
Chris Lattner8da0c282018-06-29 11:15:56 -0700120 void consumeToken(Token::Kind kind) {
Chris Lattner48af7d12018-07-09 19:05:38 -0700121 assert(state.curToken.is(kind) && "consumed an unexpected token");
Chris Lattnere79379a2018-06-22 10:39:19 -0700122 consumeToken();
123 }
124
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700125 /// If the current token has the specified kind, consume it and return true.
126 /// If not, return false.
Chris Lattner8da0c282018-06-29 11:15:56 -0700127 bool consumeIf(Token::Kind kind) {
Chris Lattner48af7d12018-07-09 19:05:38 -0700128 if (state.curToken.isNot(kind))
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700129 return false;
130 consumeToken(kind);
131 return true;
132 }
133
Chris Lattner8da0c282018-06-29 11:15:56 -0700134 ParseResult parseCommaSeparatedList(Token::Kind rightToken,
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700135 const std::function<ParseResult()> &parseElement,
136 bool allowEmptyList = true);
137
Chris Lattnerf7e22732018-06-22 22:03:48 -0700138 // We have two forms of parsing methods - those that return a non-null
139 // pointer on success, and those that return a ParseResult to indicate whether
140 // they returned a failure. The second class fills in by-reference arguments
141 // as the results of their action.
142
Chris Lattnere79379a2018-06-22 10:39:19 -0700143 // Type parsing.
Chris Lattnerf958bbe2018-06-29 22:08:05 -0700144 Type *parsePrimitiveType();
Chris Lattnerf7e22732018-06-22 22:03:48 -0700145 Type *parseElementType();
146 VectorType *parseVectorType();
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700147 ParseResult parseDimensionListRanked(SmallVectorImpl<int> &dimensions);
Chris Lattnerf7e22732018-06-22 22:03:48 -0700148 Type *parseTensorType();
149 Type *parseMemRefType();
150 Type *parseFunctionType();
151 Type *parseType();
152 ParseResult parseTypeList(SmallVectorImpl<Type*> &elements);
Chris Lattnere79379a2018-06-22 10:39:19 -0700153
Chris Lattner7121b802018-07-04 20:45:39 -0700154 // Attribute parsing.
155 Attribute *parseAttribute();
156 ParseResult parseAttributeDict(SmallVectorImpl<NamedAttribute> &attributes);
157
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700158 // Polyhedral structures.
Chris Lattner2e595eb2018-07-10 10:08:27 -0700159 AffineMap *parseAffineMapInline();
MLIR Teamf85a6262018-06-27 11:03:08 -0700160
Chris Lattner78276e32018-07-07 15:48:26 -0700161 // SSA
162 ParseResult parseSSAUse();
163 ParseResult parseOptionalSSAUseList(Token::Kind endToken);
164 ParseResult parseSSAUseAndType();
165 ParseResult parseOptionalSSAUseAndTypeList(Token::Kind endToken);
166
Chris Lattner48af7d12018-07-09 19:05:38 -0700167private:
168 // The Parser is subclassed and reinstantiated. Do not add additional
169 // non-trivial state here, add it to the ParserState class.
170 ParserState &state;
Chris Lattnere79379a2018-06-22 10:39:19 -0700171};
172} // end anonymous namespace
173
174//===----------------------------------------------------------------------===//
175// Helper methods.
176//===----------------------------------------------------------------------===//
177
Chris Lattner4c95a502018-06-23 16:03:42 -0700178ParseResult Parser::emitError(SMLoc loc, const Twine &message) {
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700179 // If we hit a parse error in response to a lexer error, then the lexer
Jacques Pienaar9c411be2018-06-24 19:17:35 -0700180 // already reported the error.
Chris Lattner48af7d12018-07-09 19:05:38 -0700181 if (getToken().is(Token::error))
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700182 return ParseFailure;
183
Chris Lattner48af7d12018-07-09 19:05:38 -0700184 auto &sourceMgr = state.lex.getSourceMgr();
185 state.errorReporter(sourceMgr.GetMessage(loc, SourceMgr::DK_Error, message));
Chris Lattnere79379a2018-06-22 10:39:19 -0700186 return ParseFailure;
187}
188
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700189/// Parse a comma-separated list of elements, terminated with an arbitrary
190/// token. This allows empty lists if allowEmptyList is true.
191///
192/// abstract-list ::= rightToken // if allowEmptyList == true
193/// abstract-list ::= element (',' element)* rightToken
194///
195ParseResult Parser::
Chris Lattner8da0c282018-06-29 11:15:56 -0700196parseCommaSeparatedList(Token::Kind rightToken,
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700197 const std::function<ParseResult()> &parseElement,
198 bool allowEmptyList) {
199 // Handle the empty case.
Chris Lattner48af7d12018-07-09 19:05:38 -0700200 if (getToken().is(rightToken)) {
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700201 if (!allowEmptyList)
202 return emitError("expected list element");
203 consumeToken(rightToken);
204 return ParseSuccess;
205 }
206
207 // Non-empty case starts with an element.
208 if (parseElement())
209 return ParseFailure;
210
211 // Otherwise we have a list of comma separated elements.
212 while (consumeIf(Token::comma)) {
213 if (parseElement())
214 return ParseFailure;
215 }
216
217 // Consume the end character.
218 if (!consumeIf(rightToken))
Chris Lattner8da0c282018-06-29 11:15:56 -0700219 return emitError("expected ',' or '" + Token::getTokenSpelling(rightToken) +
220 "'");
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700221
222 return ParseSuccess;
223}
Chris Lattnere79379a2018-06-22 10:39:19 -0700224
225//===----------------------------------------------------------------------===//
226// Type Parsing
227//===----------------------------------------------------------------------===//
228
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700229/// Parse the low-level fixed dtypes in the system.
230///
Chris Lattnerf958bbe2018-06-29 22:08:05 -0700231/// primitive-type ::= `f16` | `bf16` | `f32` | `f64`
232/// primitive-type ::= integer-type
233/// primitive-type ::= `affineint`
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700234///
Chris Lattnerf958bbe2018-06-29 22:08:05 -0700235Type *Parser::parsePrimitiveType() {
Chris Lattner48af7d12018-07-09 19:05:38 -0700236 switch (getToken().getKind()) {
Chris Lattnerf7e22732018-06-22 22:03:48 -0700237 default:
238 return (emitError("expected type"), nullptr);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700239 case Token::kw_bf16:
240 consumeToken(Token::kw_bf16);
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700241 return builder.getBF16Type();
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700242 case Token::kw_f16:
243 consumeToken(Token::kw_f16);
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700244 return builder.getF16Type();
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700245 case Token::kw_f32:
246 consumeToken(Token::kw_f32);
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700247 return builder.getF32Type();
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700248 case Token::kw_f64:
249 consumeToken(Token::kw_f64);
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700250 return builder.getF64Type();
Chris Lattnerf958bbe2018-06-29 22:08:05 -0700251 case Token::kw_affineint:
252 consumeToken(Token::kw_affineint);
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700253 return builder.getAffineIntType();
Chris Lattnerf958bbe2018-06-29 22:08:05 -0700254 case Token::inttype: {
Chris Lattner48af7d12018-07-09 19:05:38 -0700255 auto width = getToken().getIntTypeBitwidth();
Chris Lattnerf958bbe2018-06-29 22:08:05 -0700256 if (!width.hasValue())
257 return (emitError("invalid integer width"), nullptr);
258 consumeToken(Token::inttype);
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700259 return builder.getIntegerType(width.getValue());
Chris Lattnerf958bbe2018-06-29 22:08:05 -0700260 }
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700261 }
262}
263
264/// Parse the element type of a tensor or memref type.
265///
266/// element-type ::= primitive-type | vector-type
267///
Chris Lattnerf7e22732018-06-22 22:03:48 -0700268Type *Parser::parseElementType() {
Chris Lattner48af7d12018-07-09 19:05:38 -0700269 if (getToken().is(Token::kw_vector))
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700270 return parseVectorType();
271
272 return parsePrimitiveType();
273}
274
275/// Parse a vector type.
276///
277/// vector-type ::= `vector` `<` const-dimension-list primitive-type `>`
278/// const-dimension-list ::= (integer-literal `x`)+
279///
Chris Lattnerf7e22732018-06-22 22:03:48 -0700280VectorType *Parser::parseVectorType() {
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700281 consumeToken(Token::kw_vector);
282
283 if (!consumeIf(Token::less))
Chris Lattnerf7e22732018-06-22 22:03:48 -0700284 return (emitError("expected '<' in vector type"), nullptr);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700285
Chris Lattner48af7d12018-07-09 19:05:38 -0700286 if (getToken().isNot(Token::integer))
Chris Lattnerf7e22732018-06-22 22:03:48 -0700287 return (emitError("expected dimension size in vector type"), nullptr);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700288
289 SmallVector<unsigned, 4> dimensions;
Chris Lattner48af7d12018-07-09 19:05:38 -0700290 while (getToken().is(Token::integer)) {
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700291 // Make sure this integer value is in bound and valid.
Chris Lattner48af7d12018-07-09 19:05:38 -0700292 auto dimension = getToken().getUnsignedIntegerValue();
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700293 if (!dimension.hasValue())
Chris Lattnerf7e22732018-06-22 22:03:48 -0700294 return (emitError("invalid dimension in vector type"), nullptr);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700295 dimensions.push_back(dimension.getValue());
296
297 consumeToken(Token::integer);
298
299 // Make sure we have an 'x' or something like 'xbf32'.
Chris Lattner48af7d12018-07-09 19:05:38 -0700300 if (getToken().isNot(Token::bare_identifier) ||
301 getTokenSpelling()[0] != 'x')
Chris Lattnerf7e22732018-06-22 22:03:48 -0700302 return (emitError("expected 'x' in vector dimension list"), nullptr);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700303
304 // If we had a prefix of 'x', lex the next token immediately after the 'x'.
Chris Lattner48af7d12018-07-09 19:05:38 -0700305 if (getTokenSpelling().size() != 1)
306 state.lex.resetPointer(getTokenSpelling().data() + 1);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700307
308 // Consume the 'x'.
309 consumeToken(Token::bare_identifier);
310 }
311
312 // Parse the element type.
Chris Lattnerf7e22732018-06-22 22:03:48 -0700313 auto *elementType = parsePrimitiveType();
314 if (!elementType)
315 return nullptr;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700316
317 if (!consumeIf(Token::greater))
Chris Lattnerf7e22732018-06-22 22:03:48 -0700318 return (emitError("expected '>' in vector type"), nullptr);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700319
Chris Lattnerf7e22732018-06-22 22:03:48 -0700320 return VectorType::get(dimensions, elementType);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700321}
322
323/// Parse a dimension list of a tensor or memref type. This populates the
324/// dimension list, returning -1 for the '?' dimensions.
325///
326/// dimension-list-ranked ::= (dimension `x`)*
327/// dimension ::= `?` | integer-literal
328///
329ParseResult Parser::parseDimensionListRanked(SmallVectorImpl<int> &dimensions) {
Chris Lattner48af7d12018-07-09 19:05:38 -0700330 while (getToken().isAny(Token::integer, Token::question)) {
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700331 if (consumeIf(Token::question)) {
332 dimensions.push_back(-1);
333 } else {
334 // Make sure this integer value is in bound and valid.
Chris Lattner48af7d12018-07-09 19:05:38 -0700335 auto dimension = getToken().getUnsignedIntegerValue();
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700336 if (!dimension.hasValue() || (int)dimension.getValue() < 0)
337 return emitError("invalid dimension");
338 dimensions.push_back((int)dimension.getValue());
339 consumeToken(Token::integer);
340 }
341
342 // Make sure we have an 'x' or something like 'xbf32'.
Chris Lattner48af7d12018-07-09 19:05:38 -0700343 if (getToken().isNot(Token::bare_identifier) ||
344 getTokenSpelling()[0] != 'x')
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700345 return emitError("expected 'x' in dimension list");
346
347 // If we had a prefix of 'x', lex the next token immediately after the 'x'.
Chris Lattner48af7d12018-07-09 19:05:38 -0700348 if (getTokenSpelling().size() != 1)
349 state.lex.resetPointer(getTokenSpelling().data() + 1);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700350
351 // Consume the 'x'.
352 consumeToken(Token::bare_identifier);
353 }
354
355 return ParseSuccess;
356}
357
358/// Parse a tensor type.
359///
360/// tensor-type ::= `tensor` `<` dimension-list element-type `>`
361/// dimension-list ::= dimension-list-ranked | `??`
362///
Chris Lattnerf7e22732018-06-22 22:03:48 -0700363Type *Parser::parseTensorType() {
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700364 consumeToken(Token::kw_tensor);
365
366 if (!consumeIf(Token::less))
Chris Lattnerf7e22732018-06-22 22:03:48 -0700367 return (emitError("expected '<' in tensor type"), nullptr);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700368
369 bool isUnranked;
370 SmallVector<int, 4> dimensions;
371
372 if (consumeIf(Token::questionquestion)) {
373 isUnranked = true;
374 } else {
375 isUnranked = false;
376 if (parseDimensionListRanked(dimensions))
Chris Lattnerf7e22732018-06-22 22:03:48 -0700377 return nullptr;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700378 }
379
380 // Parse the element type.
Chris Lattnerf7e22732018-06-22 22:03:48 -0700381 auto elementType = parseElementType();
382 if (!elementType)
383 return nullptr;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700384
385 if (!consumeIf(Token::greater))
Chris Lattnerf7e22732018-06-22 22:03:48 -0700386 return (emitError("expected '>' in tensor type"), nullptr);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700387
MLIR Team355ec862018-06-23 18:09:09 -0700388 if (isUnranked)
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700389 return builder.getTensorType(elementType);
390 return builder.getTensorType(dimensions, elementType);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700391}
392
393/// Parse a memref type.
394///
395/// memref-type ::= `memref` `<` dimension-list-ranked element-type
396/// (`,` semi-affine-map-composition)? (`,` memory-space)? `>`
397///
398/// semi-affine-map-composition ::= (semi-affine-map `,` )* semi-affine-map
399/// memory-space ::= integer-literal /* | TODO: address-space-id */
400///
Chris Lattnerf7e22732018-06-22 22:03:48 -0700401Type *Parser::parseMemRefType() {
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700402 consumeToken(Token::kw_memref);
403
404 if (!consumeIf(Token::less))
Chris Lattnerf7e22732018-06-22 22:03:48 -0700405 return (emitError("expected '<' in memref type"), nullptr);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700406
407 SmallVector<int, 4> dimensions;
408 if (parseDimensionListRanked(dimensions))
Chris Lattnerf7e22732018-06-22 22:03:48 -0700409 return nullptr;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700410
411 // Parse the element type.
Chris Lattnerf7e22732018-06-22 22:03:48 -0700412 auto elementType = parseElementType();
413 if (!elementType)
414 return nullptr;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700415
416 // TODO: Parse semi-affine-map-composition.
417 // TODO: Parse memory-space.
418
419 if (!consumeIf(Token::greater))
Chris Lattnerf7e22732018-06-22 22:03:48 -0700420 return (emitError("expected '>' in memref type"), nullptr);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700421
Chris Lattnerf7e22732018-06-22 22:03:48 -0700422 // FIXME: Add an IR representation for memref types.
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700423 return builder.getIntegerType(1);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700424}
425
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700426/// Parse a function type.
427///
428/// function-type ::= type-list-parens `->` type-list
429///
Chris Lattnerf7e22732018-06-22 22:03:48 -0700430Type *Parser::parseFunctionType() {
Chris Lattner48af7d12018-07-09 19:05:38 -0700431 assert(getToken().is(Token::l_paren));
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700432
Chris Lattnerf7e22732018-06-22 22:03:48 -0700433 SmallVector<Type*, 4> arguments;
434 if (parseTypeList(arguments))
435 return nullptr;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700436
437 if (!consumeIf(Token::arrow))
Chris Lattnerf7e22732018-06-22 22:03:48 -0700438 return (emitError("expected '->' in function type"), nullptr);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700439
Chris Lattnerf7e22732018-06-22 22:03:48 -0700440 SmallVector<Type*, 4> results;
441 if (parseTypeList(results))
442 return nullptr;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700443
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700444 return builder.getFunctionType(arguments, results);
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700445}
446
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700447/// Parse an arbitrary type.
448///
449/// type ::= primitive-type
450/// | vector-type
451/// | tensor-type
452/// | memref-type
453/// | function-type
454/// element-type ::= primitive-type | vector-type
455///
Chris Lattnerf7e22732018-06-22 22:03:48 -0700456Type *Parser::parseType() {
Chris Lattner48af7d12018-07-09 19:05:38 -0700457 switch (getToken().getKind()) {
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700458 case Token::kw_memref: return parseMemRefType();
459 case Token::kw_tensor: return parseTensorType();
460 case Token::kw_vector: return parseVectorType();
461 case Token::l_paren: return parseFunctionType();
462 default:
463 return parsePrimitiveType();
464 }
465}
466
467/// Parse a "type list", which is a singular type, or a parenthesized list of
468/// types.
469///
470/// type-list ::= type-list-parens | type
471/// type-list-parens ::= `(` `)`
472/// | `(` type (`,` type)* `)`
473///
Chris Lattnerf7e22732018-06-22 22:03:48 -0700474ParseResult Parser::parseTypeList(SmallVectorImpl<Type*> &elements) {
475 auto parseElt = [&]() -> ParseResult {
476 auto elt = parseType();
477 elements.push_back(elt);
478 return elt ? ParseSuccess : ParseFailure;
479 };
480
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700481 // If there is no parens, then it must be a singular type.
482 if (!consumeIf(Token::l_paren))
Chris Lattnerf7e22732018-06-22 22:03:48 -0700483 return parseElt();
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700484
Chris Lattnerf7e22732018-06-22 22:03:48 -0700485 if (parseCommaSeparatedList(Token::r_paren, parseElt))
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700486 return ParseFailure;
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700487
Chris Lattnerbb8fafc2018-06-22 15:52:02 -0700488 return ParseSuccess;
489}
490
Chris Lattner4c95a502018-06-23 16:03:42 -0700491//===----------------------------------------------------------------------===//
Chris Lattner7121b802018-07-04 20:45:39 -0700492// Attribute parsing.
493//===----------------------------------------------------------------------===//
494
495
496/// Attribute parsing.
497///
498/// attribute-value ::= bool-literal
499/// | integer-literal
500/// | float-literal
501/// | string-literal
502/// | `[` (attribute-value (`,` attribute-value)*)? `]`
503///
504Attribute *Parser::parseAttribute() {
Chris Lattner48af7d12018-07-09 19:05:38 -0700505 switch (getToken().getKind()) {
Chris Lattner7121b802018-07-04 20:45:39 -0700506 case Token::kw_true:
507 consumeToken(Token::kw_true);
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700508 return builder.getBoolAttr(true);
Chris Lattner7121b802018-07-04 20:45:39 -0700509 case Token::kw_false:
510 consumeToken(Token::kw_false);
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700511 return builder.getBoolAttr(false);
Chris Lattner7121b802018-07-04 20:45:39 -0700512
513 case Token::integer: {
Chris Lattner48af7d12018-07-09 19:05:38 -0700514 auto val = getToken().getUInt64IntegerValue();
Chris Lattner7121b802018-07-04 20:45:39 -0700515 if (!val.hasValue() || (int64_t)val.getValue() < 0)
516 return (emitError("integer too large for attribute"), nullptr);
517 consumeToken(Token::integer);
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700518 return builder.getIntegerAttr((int64_t)val.getValue());
Chris Lattner7121b802018-07-04 20:45:39 -0700519 }
520
521 case Token::minus: {
522 consumeToken(Token::minus);
Chris Lattner48af7d12018-07-09 19:05:38 -0700523 if (getToken().is(Token::integer)) {
524 auto val = getToken().getUInt64IntegerValue();
Chris Lattner7121b802018-07-04 20:45:39 -0700525 if (!val.hasValue() || (int64_t)-val.getValue() >= 0)
526 return (emitError("integer too large for attribute"), nullptr);
527 consumeToken(Token::integer);
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700528 return builder.getIntegerAttr((int64_t)-val.getValue());
Chris Lattner7121b802018-07-04 20:45:39 -0700529 }
530
531 return (emitError("expected constant integer or floating point value"),
532 nullptr);
533 }
534
535 case Token::string: {
Chris Lattner48af7d12018-07-09 19:05:38 -0700536 auto val = getToken().getStringValue();
Chris Lattner7121b802018-07-04 20:45:39 -0700537 consumeToken(Token::string);
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700538 return builder.getStringAttr(val);
Chris Lattner7121b802018-07-04 20:45:39 -0700539 }
540
541 case Token::l_bracket: {
542 consumeToken(Token::l_bracket);
543 SmallVector<Attribute*, 4> elements;
544
545 auto parseElt = [&]() -> ParseResult {
546 elements.push_back(parseAttribute());
547 return elements.back() ? ParseSuccess : ParseFailure;
548 };
549
550 if (parseCommaSeparatedList(Token::r_bracket, parseElt))
551 return nullptr;
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700552 return builder.getArrayAttr(elements);
Chris Lattner7121b802018-07-04 20:45:39 -0700553 }
554 default:
555 // TODO: Handle floating point.
556 return (emitError("expected constant attribute value"), nullptr);
557 }
558}
559
Chris Lattner7121b802018-07-04 20:45:39 -0700560/// Attribute dictionary.
561///
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700562/// attribute-dict ::= `{` `}`
563/// | `{` attribute-entry (`,` attribute-entry)* `}`
564/// attribute-entry ::= bare-id `:` attribute-value
Chris Lattner7121b802018-07-04 20:45:39 -0700565///
566ParseResult Parser::parseAttributeDict(
567 SmallVectorImpl<NamedAttribute> &attributes) {
568 consumeToken(Token::l_brace);
569
570 auto parseElt = [&]() -> ParseResult {
571 // We allow keywords as attribute names.
Chris Lattner48af7d12018-07-09 19:05:38 -0700572 if (getToken().isNot(Token::bare_identifier, Token::inttype) &&
573 !getToken().isKeyword())
Chris Lattner7121b802018-07-04 20:45:39 -0700574 return emitError("expected attribute name");
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700575 auto nameId = builder.getIdentifier(getTokenSpelling());
Chris Lattner7121b802018-07-04 20:45:39 -0700576 consumeToken();
577
578 if (!consumeIf(Token::colon))
579 return emitError("expected ':' in attribute list");
580
581 auto attr = parseAttribute();
582 if (!attr) return ParseFailure;
583
584 attributes.push_back({nameId, attr});
585 return ParseSuccess;
586 };
587
588 if (parseCommaSeparatedList(Token::r_brace, parseElt))
589 return ParseFailure;
590
591 return ParseSuccess;
592}
593
594//===----------------------------------------------------------------------===//
MLIR Teamf85a6262018-06-27 11:03:08 -0700595// Polyhedral structures.
596//===----------------------------------------------------------------------===//
597
Chris Lattner2e595eb2018-07-10 10:08:27 -0700598/// Lower precedence ops (all at the same precedence level). LNoOp is false in
599/// the boolean sense.
600enum AffineLowPrecOp {
601 /// Null value.
602 LNoOp,
603 Add,
604 Sub
605};
MLIR Teamf85a6262018-06-27 11:03:08 -0700606
Chris Lattner2e595eb2018-07-10 10:08:27 -0700607/// Higher precedence ops - all at the same precedence level. HNoOp is false in
608/// the boolean sense.
609enum AffineHighPrecOp {
610 /// Null value.
611 HNoOp,
612 Mul,
613 FloorDiv,
614 CeilDiv,
615 Mod
616};
Chris Lattner7121b802018-07-04 20:45:39 -0700617
Chris Lattner2e595eb2018-07-10 10:08:27 -0700618namespace {
619/// This is a specialized parser for AffineMap's, maintaining the state
620/// transient to their bodies.
621class AffineMapParser : public Parser {
622public:
623 explicit AffineMapParser(ParserState &state) : Parser(state) {}
Chris Lattner7121b802018-07-04 20:45:39 -0700624
Chris Lattner2e595eb2018-07-10 10:08:27 -0700625 AffineMap *parseAffineMapInline();
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -0700626
Chris Lattner2e595eb2018-07-10 10:08:27 -0700627private:
628 unsigned getNumDims() const { return dims.size(); }
629 unsigned getNumSymbols() const { return symbols.size(); }
MLIR Teamf85a6262018-06-27 11:03:08 -0700630
Chris Lattner2e595eb2018-07-10 10:08:27 -0700631 // Binary affine op parsing.
632 AffineLowPrecOp consumeIfLowPrecOp();
633 AffineHighPrecOp consumeIfHighPrecOp();
MLIR Teamf85a6262018-06-27 11:03:08 -0700634
Chris Lattner2e595eb2018-07-10 10:08:27 -0700635 // Identifier lists for polyhedral structures.
636 ParseResult parseDimIdList();
637 ParseResult parseSymbolIdList();
638 ParseResult parseDimOrSymbolId(bool isDim);
639
640 AffineExpr *parseAffineExpr();
641 AffineExpr *parseParentheticalExpr();
642 AffineExpr *parseNegateExpression(AffineExpr *lhs);
643 AffineExpr *parseIntegerExpr();
644 AffineExpr *parseBareIdExpr();
645
646 AffineExpr *getBinaryAffineOpExpr(AffineHighPrecOp op, AffineExpr *lhs,
647 AffineExpr *rhs);
648 AffineExpr *getBinaryAffineOpExpr(AffineLowPrecOp op, AffineExpr *lhs,
649 AffineExpr *rhs);
650 AffineExpr *parseAffineOperandExpr(AffineExpr *lhs);
651 AffineExpr *parseAffineLowPrecOpExpr(AffineExpr *llhs,
652 AffineLowPrecOp llhsOp);
653 AffineExpr *parseAffineHighPrecOpExpr(AffineExpr *llhs,
654 AffineHighPrecOp llhsOp);
655
656private:
657 // TODO(bondhugula): could just use an vector/ArrayRef and scan the numbers.
658 llvm::StringMap<unsigned> dims;
659 llvm::StringMap<unsigned> symbols;
660};
661} // end anonymous namespace
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -0700662
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700663/// Create an affine binary high precedence op expression (mul's, div's, mod)
Chris Lattner2e595eb2018-07-10 10:08:27 -0700664AffineExpr *AffineMapParser::getBinaryAffineOpExpr(AffineHighPrecOp op,
665 AffineExpr *lhs,
666 AffineExpr *rhs) {
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700667 switch (op) {
668 case Mul:
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700669 if (!lhs->isSymbolic() && !rhs->isSymbolic()) {
670 emitError("non-affine expression: at least one of the multiply "
671 "operands has to be either a constant or symbolic");
672 return nullptr;
673 }
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700674 return builder.getMulExpr(lhs, rhs);
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700675 case FloorDiv:
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700676 if (!rhs->isSymbolic()) {
677 emitError("non-affine expression: right operand of floordiv "
678 "has to be either a constant or symbolic");
679 return nullptr;
680 }
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700681 return builder.getFloorDivExpr(lhs, rhs);
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700682 case CeilDiv:
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700683 if (!rhs->isSymbolic()) {
684 emitError("non-affine expression: right operand of ceildiv "
685 "has to be either a constant or symbolic");
686 return nullptr;
687 }
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700688 return builder.getCeilDivExpr(lhs, rhs);
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700689 case Mod:
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700690 if (!rhs->isSymbolic()) {
691 emitError("non-affine expression: right operand of mod "
692 "has to be either a constant or symbolic");
693 return nullptr;
694 }
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700695 return builder.getModExpr(lhs, rhs);
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700696 case HNoOp:
697 llvm_unreachable("can't create affine expression for null high prec op");
698 return nullptr;
699 }
700}
701
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700702/// Create an affine binary low precedence op expression (add, sub).
Chris Lattner2e595eb2018-07-10 10:08:27 -0700703AffineExpr *AffineMapParser::getBinaryAffineOpExpr(AffineLowPrecOp op,
704 AffineExpr *lhs,
705 AffineExpr *rhs) {
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700706 switch (op) {
707 case AffineLowPrecOp::Add:
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700708 return builder.getAddExpr(lhs, rhs);
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700709 case AffineLowPrecOp::Sub:
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700710 return builder.getSubExpr(lhs, rhs);
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700711 case AffineLowPrecOp::LNoOp:
712 llvm_unreachable("can't create affine expression for null low prec op");
713 return nullptr;
714 }
715}
716
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700717/// Consume this token if it is a lower precedence affine op (there are only two
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700718/// precedence levels).
Chris Lattner2e595eb2018-07-10 10:08:27 -0700719AffineLowPrecOp AffineMapParser::consumeIfLowPrecOp() {
Chris Lattner48af7d12018-07-09 19:05:38 -0700720 switch (getToken().getKind()) {
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700721 case Token::plus:
722 consumeToken(Token::plus);
723 return AffineLowPrecOp::Add;
724 case Token::minus:
725 consumeToken(Token::minus);
726 return AffineLowPrecOp::Sub;
727 default:
728 return AffineLowPrecOp::LNoOp;
729 }
730}
731
732/// Consume this token if it is a higher precedence affine op (there are only
733/// two precedence levels)
Chris Lattner2e595eb2018-07-10 10:08:27 -0700734AffineHighPrecOp AffineMapParser::consumeIfHighPrecOp() {
Chris Lattner48af7d12018-07-09 19:05:38 -0700735 switch (getToken().getKind()) {
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700736 case Token::star:
737 consumeToken(Token::star);
738 return Mul;
739 case Token::kw_floordiv:
740 consumeToken(Token::kw_floordiv);
741 return FloorDiv;
742 case Token::kw_ceildiv:
743 consumeToken(Token::kw_ceildiv);
744 return CeilDiv;
745 case Token::kw_mod:
746 consumeToken(Token::kw_mod);
747 return Mod;
748 default:
749 return HNoOp;
750 }
751}
752
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700753/// Parse a high precedence op expression list: mul, div, and mod are high
754/// precedence binary ops, i.e., parse a
755/// expr_1 op_1 expr_2 op_2 ... expr_n
756/// where op_1, op_2 are all a AffineHighPrecOp (mul, div, mod).
757/// All affine binary ops are left associative.
758/// Given llhs, returns (llhs llhsOp lhs) op rhs, or (lhs op rhs) if llhs is
759/// null. If no rhs can be found, returns (llhs llhsOp lhs) or lhs if llhs is
760/// null.
761AffineExpr *
Chris Lattner2e595eb2018-07-10 10:08:27 -0700762AffineMapParser::parseAffineHighPrecOpExpr(AffineExpr *llhs,
763 AffineHighPrecOp llhsOp) {
764 AffineExpr *lhs = parseAffineOperandExpr(llhs);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700765 if (!lhs)
766 return nullptr;
767
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700768 // Found an LHS. Parse the remaining expression.
Chris Lattner2e595eb2018-07-10 10:08:27 -0700769 if (AffineHighPrecOp op = consumeIfHighPrecOp()) {
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700770 if (llhs) {
771 AffineExpr *expr = getBinaryAffineOpExpr(llhsOp, llhs, lhs);
772 if (!expr)
773 return nullptr;
Chris Lattner2e595eb2018-07-10 10:08:27 -0700774 return parseAffineHighPrecOpExpr(expr, op);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700775 }
776 // No LLHS, get RHS
Chris Lattner2e595eb2018-07-10 10:08:27 -0700777 return parseAffineHighPrecOpExpr(lhs, op);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700778 }
779
780 // This is the last operand in this expression.
781 if (llhs)
782 return getBinaryAffineOpExpr(llhsOp, llhs, lhs);
783
784 // No llhs, 'lhs' itself is the expression.
785 return lhs;
786}
787
788/// Parse an affine expression inside parentheses.
789///
790/// affine-expr ::= `(` affine-expr `)`
Chris Lattner2e595eb2018-07-10 10:08:27 -0700791AffineExpr *AffineMapParser::parseParentheticalExpr() {
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700792 if (!consumeIf(Token::l_paren))
793 return (emitError("expected '('"), nullptr);
Chris Lattner48af7d12018-07-09 19:05:38 -0700794 if (getToken().is(Token::r_paren))
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700795 return (emitError("no expression inside parentheses"), nullptr);
Chris Lattner2e595eb2018-07-10 10:08:27 -0700796 auto *expr = parseAffineExpr();
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700797 if (!expr)
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700798 return nullptr;
799 if (!consumeIf(Token::r_paren))
800 return (emitError("expected ')'"), nullptr);
801 return expr;
802}
803
804/// Parse the negation expression.
805///
806/// affine-expr ::= `-` affine-expr
Chris Lattner2e595eb2018-07-10 10:08:27 -0700807AffineExpr *AffineMapParser::parseNegateExpression(AffineExpr *lhs) {
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700808 if (!consumeIf(Token::minus))
809 return (emitError("expected '-'"), nullptr);
810
Chris Lattner2e595eb2018-07-10 10:08:27 -0700811 AffineExpr *operand = parseAffineOperandExpr(lhs);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700812 // Since negation has the highest precedence of all ops (including high
813 // precedence ops) but lower than parentheses, we are only going to use
814 // parseAffineOperandExpr instead of parseAffineExpr here.
815 if (!operand)
816 // Extra error message although parseAffineOperandExpr would have
817 // complained. Leads to a better diagnostic.
818 return (emitError("missing operand of negation"), nullptr);
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700819 auto *minusOne = builder.getConstantExpr(-1);
820 return builder.getMulExpr(minusOne, operand);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700821}
822
823/// Parse a bare id that may appear in an affine expression.
824///
825/// affine-expr ::= bare-id
Chris Lattner2e595eb2018-07-10 10:08:27 -0700826AffineExpr *AffineMapParser::parseBareIdExpr() {
Chris Lattner48af7d12018-07-09 19:05:38 -0700827 if (getToken().isNot(Token::bare_identifier))
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700828 return (emitError("expected bare identifier"), nullptr);
829
Chris Lattner48af7d12018-07-09 19:05:38 -0700830 StringRef sRef = getTokenSpelling();
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700831 if (dims.count(sRef)) {
832 consumeToken(Token::bare_identifier);
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700833 return builder.getDimExpr(dims.lookup(sRef));
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700834 }
835 if (symbols.count(sRef)) {
836 consumeToken(Token::bare_identifier);
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700837 return builder.getSymbolExpr(symbols.lookup(sRef));
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700838 }
839 return (emitError("identifier is neither dimensional nor symbolic"), nullptr);
840}
841
842/// Parse a positive integral constant appearing in an affine expression.
843///
844/// affine-expr ::= integer-literal
Chris Lattner2e595eb2018-07-10 10:08:27 -0700845AffineExpr *AffineMapParser::parseIntegerExpr() {
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700846 // No need to handle negative numbers separately here. They are naturally
847 // handled via the unary negation operator, although (FIXME) MININT_64 still
848 // not correctly handled.
Chris Lattner48af7d12018-07-09 19:05:38 -0700849 if (getToken().isNot(Token::integer))
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700850 return (emitError("expected integer"), nullptr);
851
Chris Lattner48af7d12018-07-09 19:05:38 -0700852 auto val = getToken().getUInt64IntegerValue();
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700853 if (!val.hasValue() || (int64_t)val.getValue() < 0) {
854 return (emitError("constant too large for affineint"), nullptr);
855 }
856 consumeToken(Token::integer);
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700857 return builder.getConstantExpr((int64_t)val.getValue());
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700858}
859
860/// Parses an expression that can be a valid operand of an affine expression.
Uday Bondhugula76345202018-07-09 13:47:52 -0700861/// lhs: if non-null, lhs is an affine expression that is the lhs of a binary
862/// operator, the rhs of which is being parsed. This is used to determine
863/// whether an error should be emitted for a missing right operand.
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700864// Eg: for an expression without parentheses (like i + j + k + l), each
865// of the four identifiers is an operand. For i + j*k + l, j*k is not an
866// operand expression, it's an op expression and will be parsed via
867// parseAffineHighPrecOpExpression(). However, for i + (j*k) + -l, (j*k) and -l
868// are valid operands that will be parsed by this function.
Chris Lattner2e595eb2018-07-10 10:08:27 -0700869AffineExpr *AffineMapParser::parseAffineOperandExpr(AffineExpr *lhs) {
Chris Lattner48af7d12018-07-09 19:05:38 -0700870 switch (getToken().getKind()) {
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700871 case Token::bare_identifier:
Chris Lattner2e595eb2018-07-10 10:08:27 -0700872 return parseBareIdExpr();
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700873 case Token::integer:
Chris Lattner2e595eb2018-07-10 10:08:27 -0700874 return parseIntegerExpr();
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700875 case Token::l_paren:
Chris Lattner2e595eb2018-07-10 10:08:27 -0700876 return parseParentheticalExpr();
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700877 case Token::minus:
Chris Lattner2e595eb2018-07-10 10:08:27 -0700878 return parseNegateExpression(lhs);
Uday Bondhugula76345202018-07-09 13:47:52 -0700879 case Token::kw_ceildiv:
880 case Token::kw_floordiv:
881 case Token::kw_mod:
882 case Token::plus:
883 case Token::star:
884 if (lhs)
885 emitError("missing right operand of binary operator");
886 else
887 emitError("missing left operand of binary operator");
888 return nullptr;
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700889 default:
890 if (lhs)
Uday Bondhugula76345202018-07-09 13:47:52 -0700891 emitError("missing right operand of binary operator");
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700892 else
893 emitError("expected affine expression");
894 return nullptr;
895 }
896}
897
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700898/// Parse affine expressions that are bare-id's, integer constants,
899/// parenthetical affine expressions, and affine op expressions that are a
900/// composition of those.
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -0700901///
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700902/// All binary op's associate from left to right.
903///
904/// {add, sub} have lower precedence than {mul, div, and mod}.
905///
Uday Bondhugula76345202018-07-09 13:47:52 -0700906/// Add, sub'are themselves at the same precedence level. Mul, floordiv,
907/// ceildiv, and mod are at the same higher precedence level. Negation has
908/// higher precedence than any binary op.
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700909///
910/// llhs: the affine expression appearing on the left of the one being parsed.
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700911/// This function will return ((llhs llhsOp lhs) op rhs) if llhs is non null,
912/// and lhs op rhs otherwise; if there is no rhs, llhs llhsOp lhs is returned if
913/// llhs is non-null; otherwise lhs is returned. This is to deal with left
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700914/// associativity.
915///
916/// Eg: when the expression is e1 + e2*e3 + e4, with e1 as llhs, this function
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700917/// will return the affine expr equivalent of (e1 + (e2*e3)) + e4, where (e2*e3)
918/// will be parsed using parseAffineHighPrecOpExpr().
Chris Lattner2e595eb2018-07-10 10:08:27 -0700919AffineExpr *AffineMapParser::parseAffineLowPrecOpExpr(AffineExpr *llhs,
920 AffineLowPrecOp llhsOp) {
Uday Bondhugula76345202018-07-09 13:47:52 -0700921 AffineExpr *lhs;
Chris Lattner2e595eb2018-07-10 10:08:27 -0700922 if (!(lhs = parseAffineOperandExpr(llhs)))
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700923 return nullptr;
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700924
925 // Found an LHS. Deal with the ops.
Chris Lattner2e595eb2018-07-10 10:08:27 -0700926 if (AffineLowPrecOp lOp = consumeIfLowPrecOp()) {
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700927 if (llhs) {
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700928 AffineExpr *sum = getBinaryAffineOpExpr(llhsOp, llhs, lhs);
Chris Lattner2e595eb2018-07-10 10:08:27 -0700929 return parseAffineLowPrecOpExpr(sum, lOp);
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700930 }
931 // No LLHS, get RHS and form the expression.
Chris Lattner2e595eb2018-07-10 10:08:27 -0700932 return parseAffineLowPrecOpExpr(lhs, lOp);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700933 }
Chris Lattner2e595eb2018-07-10 10:08:27 -0700934 if (AffineHighPrecOp hOp = consumeIfHighPrecOp()) {
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700935 // We have a higher precedence op here. Get the rhs operand for the llhs
936 // through parseAffineHighPrecOpExpr.
Chris Lattner2e595eb2018-07-10 10:08:27 -0700937 AffineExpr *highRes = parseAffineHighPrecOpExpr(lhs, hOp);
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700938 if (!highRes)
939 return nullptr;
Chris Lattner2e595eb2018-07-10 10:08:27 -0700940
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700941 // If llhs is null, the product forms the first operand of the yet to be
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700942 // found expression. If non-null, the op to associate with llhs is llhsOp.
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700943 AffineExpr *expr =
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700944 llhs ? getBinaryAffineOpExpr(llhsOp, llhs, highRes) : highRes;
Chris Lattner2e595eb2018-07-10 10:08:27 -0700945
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700946 // Recurse for subsequent low prec op's after the affine high prec op
947 // expression.
Chris Lattner2e595eb2018-07-10 10:08:27 -0700948 if (AffineLowPrecOp nextOp = consumeIfLowPrecOp())
949 return parseAffineLowPrecOpExpr(expr, nextOp);
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700950 return expr;
951 }
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700952 // Last operand in the expression list.
953 if (llhs)
954 return getBinaryAffineOpExpr(llhsOp, llhs, lhs);
955 // No llhs, 'lhs' itself is the expression.
956 return lhs;
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700957}
958
959/// Parse an affine expression.
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700960/// affine-expr ::= `(` affine-expr `)`
961/// | `-` affine-expr
962/// | affine-expr `+` affine-expr
963/// | affine-expr `-` affine-expr
964/// | affine-expr `*` affine-expr
965/// | affine-expr `floordiv` affine-expr
966/// | affine-expr `ceildiv` affine-expr
967/// | affine-expr `mod` affine-expr
968/// | bare-id
969/// | integer-literal
970///
971/// Additional conditions are checked depending on the production. For eg., one
972/// of the operands for `*` has to be either constant/symbolic; the second
973/// operand for floordiv, ceildiv, and mod has to be a positive integer.
Chris Lattner2e595eb2018-07-10 10:08:27 -0700974AffineExpr *AffineMapParser::parseAffineExpr() {
975 return parseAffineLowPrecOpExpr(nullptr, AffineLowPrecOp::LNoOp);
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -0700976}
977
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700978/// Parse a dim or symbol from the lists appearing before the actual expressions
Chris Lattner2e595eb2018-07-10 10:08:27 -0700979/// of the affine map. Update our state to store the dimensional/symbolic
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700980/// identifier. 'dim': whether it's the dim list or symbol list that is being
981/// parsed.
Chris Lattner2e595eb2018-07-10 10:08:27 -0700982ParseResult AffineMapParser::parseDimOrSymbolId(bool isDim) {
Chris Lattner48af7d12018-07-09 19:05:38 -0700983 if (getToken().isNot(Token::bare_identifier))
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700984 return emitError("expected bare identifier");
Chris Lattner48af7d12018-07-09 19:05:38 -0700985 auto sRef = getTokenSpelling();
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -0700986 consumeToken(Token::bare_identifier);
Chris Lattner2e595eb2018-07-10 10:08:27 -0700987 if (dims.count(sRef))
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700988 return emitError("dimensional identifier name reused");
Chris Lattner2e595eb2018-07-10 10:08:27 -0700989 if (symbols.count(sRef))
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700990 return emitError("symbolic identifier name reused");
Chris Lattner2e595eb2018-07-10 10:08:27 -0700991 if (isDim)
992 dims.insert({sRef, dims.size()});
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700993 else
Chris Lattner2e595eb2018-07-10 10:08:27 -0700994 symbols.insert({sRef, symbols.size()});
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700995 return ParseSuccess;
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -0700996}
997
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700998/// Parse the list of symbolic identifiers to an affine map.
Chris Lattner2e595eb2018-07-10 10:08:27 -0700999ParseResult AffineMapParser::parseSymbolIdList() {
1000 if (!consumeIf(Token::l_bracket))
1001 return emitError("expected '['");
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001002
Chris Lattner2e595eb2018-07-10 10:08:27 -07001003 auto parseElt = [&]() -> ParseResult { return parseDimOrSymbolId(false); };
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001004 return parseCommaSeparatedList(Token::r_bracket, parseElt);
1005}
1006
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001007/// Parse the list of dimensional identifiers to an affine map.
Chris Lattner2e595eb2018-07-10 10:08:27 -07001008ParseResult AffineMapParser::parseDimIdList() {
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001009 if (!consumeIf(Token::l_paren))
1010 return emitError("expected '(' at start of dimensional identifiers list");
1011
Chris Lattner2e595eb2018-07-10 10:08:27 -07001012 auto parseElt = [&]() -> ParseResult { return parseDimOrSymbolId(true); };
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001013 return parseCommaSeparatedList(Token::r_paren, parseElt);
1014}
1015
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001016/// Parse an affine map definition.
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001017///
Uday Bondhugula3934d4d2018-07-09 09:00:25 -07001018/// affine-map-inline ::= dim-and-symbol-id-lists `->` multi-dim-affine-expr
1019/// (`size` `(` dim-size (`,` dim-size)* `)`)?
1020/// dim-size ::= affine-expr | `min` `(` affine-expr ( `,` affine-expr)+ `)`
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001021///
Uday Bondhugula3934d4d2018-07-09 09:00:25 -07001022/// multi-dim-affine-expr ::= `(` affine-expr (`,` affine-expr)* `)
1023// TODO(bondhugula): parse range size information.
Chris Lattner2e595eb2018-07-10 10:08:27 -07001024AffineMap *AffineMapParser::parseAffineMapInline() {
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001025 // List of dimensional identifiers.
Chris Lattner2e595eb2018-07-10 10:08:27 -07001026 if (parseDimIdList())
Chris Lattner7121b802018-07-04 20:45:39 -07001027 return nullptr;
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001028
1029 // Symbols are optional.
Chris Lattner48af7d12018-07-09 19:05:38 -07001030 if (getToken().is(Token::l_bracket)) {
Chris Lattner2e595eb2018-07-10 10:08:27 -07001031 if (parseSymbolIdList())
Chris Lattner7121b802018-07-04 20:45:39 -07001032 return nullptr;
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001033 }
1034 if (!consumeIf(Token::arrow)) {
Chris Lattner7121b802018-07-04 20:45:39 -07001035 return (emitError("expected '->' or '['"), nullptr);
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001036 }
1037 if (!consumeIf(Token::l_paren)) {
1038 emitError("expected '(' at start of affine map range");
Chris Lattner7121b802018-07-04 20:45:39 -07001039 return nullptr;
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001040 }
1041
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001042 SmallVector<AffineExpr *, 4> exprs;
1043 auto parseElt = [&]() -> ParseResult {
Chris Lattner2e595eb2018-07-10 10:08:27 -07001044 auto *elt = parseAffineExpr();
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001045 ParseResult res = elt ? ParseSuccess : ParseFailure;
1046 exprs.push_back(elt);
1047 return res;
1048 };
1049
1050 // Parse a multi-dimensional affine expression (a comma-separated list of 1-d
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001051 // affine expressions); the list cannot be empty.
1052 // Grammar: multi-dim-affine-expr ::= `(` affine-expr (`,` affine-expr)* `)
1053 if (parseCommaSeparatedList(Token::r_paren, parseElt, false))
Chris Lattner7121b802018-07-04 20:45:39 -07001054 return nullptr;
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001055
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001056 // Parsed a valid affine map.
Chris Lattner1ac20cb2018-07-10 10:59:53 -07001057 return builder.getAffineMap(dims.size(), symbols.size(), exprs);
MLIR Teamf85a6262018-06-27 11:03:08 -07001058}
1059
Chris Lattner2e595eb2018-07-10 10:08:27 -07001060AffineMap *Parser::parseAffineMapInline() {
1061 return AffineMapParser(state).parseAffineMapInline();
1062}
1063
MLIR Teamf85a6262018-06-27 11:03:08 -07001064//===----------------------------------------------------------------------===//
Chris Lattner78276e32018-07-07 15:48:26 -07001065// SSA
Chris Lattner4c95a502018-06-23 16:03:42 -07001066//===----------------------------------------------------------------------===//
Chris Lattnere79379a2018-06-22 10:39:19 -07001067
Chris Lattner78276e32018-07-07 15:48:26 -07001068/// Parse a SSA operand for an instruction or statement.
1069///
1070/// ssa-use ::= ssa-id | ssa-constant
1071///
1072ParseResult Parser::parseSSAUse() {
Chris Lattner48af7d12018-07-09 19:05:38 -07001073 if (getToken().is(Token::percent_identifier)) {
1074 StringRef name = getTokenSpelling().drop_front();
Chris Lattner78276e32018-07-07 15:48:26 -07001075 consumeToken(Token::percent_identifier);
1076 // TODO: Return this use.
1077 (void)name;
1078 return ParseSuccess;
1079 }
1080
1081 // TODO: Parse SSA constants.
1082
1083 return emitError("expected SSA operand");
1084}
1085
1086/// Parse a (possibly empty) list of SSA operands.
1087///
1088/// ssa-use-list ::= ssa-use (`,` ssa-use)*
1089/// ssa-use-list-opt ::= ssa-use-list?
1090///
1091ParseResult Parser::parseOptionalSSAUseList(Token::Kind endToken) {
1092 // TODO: Build and return this.
1093 return parseCommaSeparatedList(
1094 endToken, [&]() -> ParseResult { return parseSSAUse(); });
1095}
1096
1097/// Parse an SSA use with an associated type.
1098///
1099/// ssa-use-and-type ::= ssa-use `:` type
1100ParseResult Parser::parseSSAUseAndType() {
1101 if (parseSSAUse())
1102 return ParseFailure;
1103
1104 if (!consumeIf(Token::colon))
1105 return emitError("expected ':' and type for SSA operand");
1106
1107 if (!parseType())
1108 return ParseFailure;
1109
1110 return ParseSuccess;
1111}
1112
1113/// Parse a (possibly empty) list of SSA operands with types.
1114///
1115/// ssa-use-and-type-list ::= ssa-use-and-type (`,` ssa-use-and-type)*
1116///
1117ParseResult Parser::parseOptionalSSAUseAndTypeList(Token::Kind endToken) {
1118 // TODO: Build and return this.
1119 return parseCommaSeparatedList(
1120 endToken, [&]() -> ParseResult { return parseSSAUseAndType(); });
1121}
1122
Chris Lattnere79379a2018-06-22 10:39:19 -07001123
Chris Lattner48af7d12018-07-09 19:05:38 -07001124//===----------------------------------------------------------------------===//
1125// CFG Functions
1126//===----------------------------------------------------------------------===//
Chris Lattnere79379a2018-06-22 10:39:19 -07001127
Chris Lattner4c95a502018-06-23 16:03:42 -07001128namespace {
Chris Lattner48af7d12018-07-09 19:05:38 -07001129/// This is a specialized parser for CFGFunction's, maintaining the state
1130/// transient to their bodies.
1131class CFGFunctionParser : public Parser {
Chris Lattner158e0a3e2018-07-08 20:51:38 -07001132public:
Chris Lattner2e595eb2018-07-10 10:08:27 -07001133 CFGFunctionParser(ParserState &state, CFGFunction *function)
1134 : Parser(state), function(function), builder(function) {}
1135
1136 ParseResult parseFunctionBody();
1137
1138private:
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001139 CFGFunction *function;
1140 llvm::StringMap<std::pair<BasicBlock*, SMLoc>> blocksByName;
Chris Lattner48af7d12018-07-09 19:05:38 -07001141
1142 /// This builder intentionally shadows the builder in the base class, with a
1143 /// more specific builder type.
Chris Lattner158e0a3e2018-07-08 20:51:38 -07001144 CFGFuncBuilder builder;
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001145
Chris Lattner4c95a502018-06-23 16:03:42 -07001146 /// Get the basic block with the specified name, creating it if it doesn't
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001147 /// already exist. The location specified is the point of use, which allows
1148 /// us to diagnose references to blocks that are not defined precisely.
1149 BasicBlock *getBlockNamed(StringRef name, SMLoc loc) {
1150 auto &blockAndLoc = blocksByName[name];
1151 if (!blockAndLoc.first) {
Chris Lattner3a467cc2018-07-01 20:28:00 -07001152 blockAndLoc.first = new BasicBlock();
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001153 blockAndLoc.second = loc;
Chris Lattner4c95a502018-06-23 16:03:42 -07001154 }
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001155 return blockAndLoc.first;
Chris Lattner4c95a502018-06-23 16:03:42 -07001156 }
Chris Lattner48af7d12018-07-09 19:05:38 -07001157
Chris Lattner48af7d12018-07-09 19:05:38 -07001158 ParseResult parseBasicBlock();
1159 OperationInst *parseCFGOperation();
1160 TerminatorInst *parseTerminator();
Chris Lattner4c95a502018-06-23 16:03:42 -07001161};
1162} // end anonymous namespace
1163
Chris Lattner48af7d12018-07-09 19:05:38 -07001164ParseResult CFGFunctionParser::parseFunctionBody() {
1165 if (!consumeIf(Token::l_brace))
1166 return emitError("expected '{' in CFG function");
1167
1168 // Make sure we have at least one block.
1169 if (getToken().is(Token::r_brace))
1170 return emitError("CFG functions must have at least one basic block");
Chris Lattner4c95a502018-06-23 16:03:42 -07001171
1172 // Parse the list of blocks.
1173 while (!consumeIf(Token::r_brace))
Chris Lattner48af7d12018-07-09 19:05:38 -07001174 if (parseBasicBlock())
Chris Lattner4c95a502018-06-23 16:03:42 -07001175 return ParseFailure;
1176
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001177 // Verify that all referenced blocks were defined. Iteration over a
1178 // StringMap isn't determinstic, but this is good enough for our purposes.
Chris Lattner48af7d12018-07-09 19:05:38 -07001179 for (auto &elt : blocksByName) {
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001180 auto *bb = elt.second.first;
Chris Lattner3a467cc2018-07-01 20:28:00 -07001181 if (!bb->getFunction())
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001182 return emitError(elt.second.second,
1183 "reference to an undefined basic block '" +
1184 elt.first() + "'");
1185 }
1186
Chris Lattner48af7d12018-07-09 19:05:38 -07001187 getModule()->functionList.push_back(function);
Chris Lattner4c95a502018-06-23 16:03:42 -07001188 return ParseSuccess;
1189}
1190
1191/// Basic block declaration.
1192///
1193/// basic-block ::= bb-label instruction* terminator-stmt
1194/// bb-label ::= bb-id bb-arg-list? `:`
1195/// bb-id ::= bare-id
1196/// bb-arg-list ::= `(` ssa-id-and-type-list? `)`
1197///
Chris Lattner48af7d12018-07-09 19:05:38 -07001198ParseResult CFGFunctionParser::parseBasicBlock() {
1199 SMLoc nameLoc = getToken().getLoc();
1200 auto name = getTokenSpelling();
Chris Lattner4c95a502018-06-23 16:03:42 -07001201 if (!consumeIf(Token::bare_identifier))
1202 return emitError("expected basic block name");
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001203
Chris Lattner48af7d12018-07-09 19:05:38 -07001204 auto *block = getBlockNamed(name, nameLoc);
Chris Lattner4c95a502018-06-23 16:03:42 -07001205
1206 // If this block has already been parsed, then this is a redefinition with the
1207 // same block name.
Chris Lattner3a467cc2018-07-01 20:28:00 -07001208 if (block->getFunction())
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001209 return emitError(nameLoc, "redefinition of block '" + name.str() + "'");
1210
Chris Lattner3a467cc2018-07-01 20:28:00 -07001211 // Add the block to the function.
Chris Lattner48af7d12018-07-09 19:05:38 -07001212 function->push_back(block);
Chris Lattner4c95a502018-06-23 16:03:42 -07001213
Chris Lattner78276e32018-07-07 15:48:26 -07001214 // If an argument list is present, parse it.
1215 if (consumeIf(Token::l_paren)) {
1216 if (parseOptionalSSAUseAndTypeList(Token::r_paren))
1217 return ParseFailure;
1218
1219 // TODO: attach it.
1220 }
Chris Lattner4c95a502018-06-23 16:03:42 -07001221
1222 if (!consumeIf(Token::colon))
1223 return emitError("expected ':' after basic block name");
1224
Chris Lattner158e0a3e2018-07-08 20:51:38 -07001225 // Set the insertion point to the block we want to insert new operations into.
Chris Lattner48af7d12018-07-09 19:05:38 -07001226 builder.setInsertionPoint(block);
Chris Lattner158e0a3e2018-07-08 20:51:38 -07001227
Chris Lattnered65a732018-06-28 20:45:33 -07001228 // Parse the list of operations that make up the body of the block.
Chris Lattner48af7d12018-07-09 19:05:38 -07001229 while (getToken().isNot(Token::kw_return, Token::kw_br)) {
1230 auto loc = getToken().getLoc();
1231 auto *inst = parseCFGOperation();
Chris Lattner3a467cc2018-07-01 20:28:00 -07001232 if (!inst)
Chris Lattnered65a732018-06-28 20:45:33 -07001233 return ParseFailure;
Chris Lattner3a467cc2018-07-01 20:28:00 -07001234
Chris Lattner21e67f62018-07-06 10:46:19 -07001235 // We just parsed an operation. If it is a recognized one, verify that it
1236 // is structurally as we expect. If not, produce an error with a reasonable
1237 // source location.
Chris Lattner158e0a3e2018-07-08 20:51:38 -07001238 if (auto *opInfo = inst->getAbstractOperation(builder.getContext()))
Chris Lattner21e67f62018-07-06 10:46:19 -07001239 if (auto error = opInfo->verifyInvariants(inst))
1240 return emitError(loc, error);
Chris Lattnered65a732018-06-28 20:45:33 -07001241 }
Chris Lattner4c95a502018-06-23 16:03:42 -07001242
Chris Lattner48af7d12018-07-09 19:05:38 -07001243 auto *term = parseTerminator();
Chris Lattner3a467cc2018-07-01 20:28:00 -07001244 if (!term)
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001245 return ParseFailure;
Chris Lattner4c95a502018-06-23 16:03:42 -07001246
1247 return ParseSuccess;
1248}
1249
Chris Lattnered65a732018-06-28 20:45:33 -07001250/// Parse the CFG operation.
1251///
1252/// TODO(clattner): This is a change from the MLIR spec as written, it is an
1253/// experiment that will eliminate "builtin" instructions as a thing.
1254///
1255/// cfg-operation ::=
1256/// (ssa-id `=`)? string '(' ssa-use-list? ')' attribute-dict?
1257/// `:` function-type
1258///
Chris Lattner48af7d12018-07-09 19:05:38 -07001259OperationInst *CFGFunctionParser::parseCFGOperation() {
Chris Lattner78276e32018-07-07 15:48:26 -07001260 StringRef resultID;
Chris Lattner48af7d12018-07-09 19:05:38 -07001261 if (getToken().is(Token::percent_identifier)) {
1262 resultID = getTokenSpelling().drop_front();
Chris Lattner78276e32018-07-07 15:48:26 -07001263 consumeToken();
1264 if (!consumeIf(Token::equal))
1265 return (emitError("expected '=' after SSA name"), nullptr);
1266 }
Chris Lattnered65a732018-06-28 20:45:33 -07001267
Chris Lattner48af7d12018-07-09 19:05:38 -07001268 if (getToken().isNot(Token::string))
Chris Lattner3a467cc2018-07-01 20:28:00 -07001269 return (emitError("expected operation name in quotes"), nullptr);
Chris Lattnered65a732018-06-28 20:45:33 -07001270
Chris Lattner48af7d12018-07-09 19:05:38 -07001271 auto name = getToken().getStringValue();
Chris Lattnered65a732018-06-28 20:45:33 -07001272 if (name.empty())
Chris Lattner3a467cc2018-07-01 20:28:00 -07001273 return (emitError("empty operation name is invalid"), nullptr);
Chris Lattnered65a732018-06-28 20:45:33 -07001274
1275 consumeToken(Token::string);
1276
1277 if (!consumeIf(Token::l_paren))
Chris Lattner7121b802018-07-04 20:45:39 -07001278 return (emitError("expected '(' to start operand list"), nullptr);
Chris Lattnered65a732018-06-28 20:45:33 -07001279
Chris Lattner78276e32018-07-07 15:48:26 -07001280 // Parse the operand list.
1281 parseOptionalSSAUseList(Token::r_paren);
Chris Lattner7121b802018-07-04 20:45:39 -07001282
1283 SmallVector<NamedAttribute, 4> attributes;
Chris Lattner48af7d12018-07-09 19:05:38 -07001284 if (getToken().is(Token::l_brace)) {
Chris Lattner7121b802018-07-04 20:45:39 -07001285 if (parseAttributeDict(attributes))
1286 return nullptr;
1287 }
Chris Lattnered65a732018-06-28 20:45:33 -07001288
Chris Lattner78276e32018-07-07 15:48:26 -07001289 // TODO: Don't drop result name and operand names on the floor.
Chris Lattner1ac20cb2018-07-10 10:59:53 -07001290 auto nameId = builder.getIdentifier(name);
Chris Lattner48af7d12018-07-09 19:05:38 -07001291 return builder.createOperation(nameId, attributes);
Chris Lattnered65a732018-06-28 20:45:33 -07001292}
1293
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001294/// Parse the terminator instruction for a basic block.
1295///
1296/// terminator-stmt ::= `br` bb-id branch-use-list?
1297/// branch-use-list ::= `(` ssa-use-and-type-list? `)`
1298/// terminator-stmt ::=
1299/// `cond_br` ssa-use `,` bb-id branch-use-list? `,` bb-id branch-use-list?
1300/// terminator-stmt ::= `return` ssa-use-and-type-list?
1301///
Chris Lattner48af7d12018-07-09 19:05:38 -07001302TerminatorInst *CFGFunctionParser::parseTerminator() {
1303 switch (getToken().getKind()) {
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001304 default:
Chris Lattner3a467cc2018-07-01 20:28:00 -07001305 return (emitError("expected terminator at end of basic block"), nullptr);
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001306
1307 case Token::kw_return:
1308 consumeToken(Token::kw_return);
Chris Lattner48af7d12018-07-09 19:05:38 -07001309 return builder.createReturnInst();
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001310
1311 case Token::kw_br: {
1312 consumeToken(Token::kw_br);
Chris Lattner48af7d12018-07-09 19:05:38 -07001313 auto destBB = getBlockNamed(getTokenSpelling(), getToken().getLoc());
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001314 if (!consumeIf(Token::bare_identifier))
Chris Lattner3a467cc2018-07-01 20:28:00 -07001315 return (emitError("expected basic block name"), nullptr);
Chris Lattner48af7d12018-07-09 19:05:38 -07001316 return builder.createBranchInst(destBB);
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001317 }
Chris Lattner78276e32018-07-07 15:48:26 -07001318 // TODO: cond_br.
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001319 }
1320}
1321
Chris Lattner48af7d12018-07-09 19:05:38 -07001322//===----------------------------------------------------------------------===//
1323// ML Functions
1324//===----------------------------------------------------------------------===//
1325
1326namespace {
1327/// Refined parser for MLFunction bodies.
1328class MLFunctionParser : public Parser {
1329public:
1330 MLFunction *function;
1331
1332 /// This builder intentionally shadows the builder in the base class, with a
1333 /// more specific builder type.
1334 // TODO: MLFuncBuilder builder;
1335
1336 MLFunctionParser(ParserState &state, MLFunction *function)
1337 : Parser(state), function(function) {}
1338
1339 ParseResult parseFunctionBody();
1340 Statement *parseStatement(ParentType parent);
1341 ForStmt *parseForStmt(ParentType parent);
1342 IfStmt *parseIfStmt(ParentType parent);
1343 ParseResult parseNestedStatements(NodeStmt *parent);
1344};
1345} // end anonymous namespace
1346
Chris Lattner48af7d12018-07-09 19:05:38 -07001347ParseResult MLFunctionParser::parseFunctionBody() {
1348 if (!consumeIf(Token::l_brace))
1349 return emitError("expected '{' in ML function");
1350
Tatiana Shpeismanc96b5872018-06-28 17:02:32 -07001351 // Make sure we have at least one statement.
Chris Lattner48af7d12018-07-09 19:05:38 -07001352 if (getToken().is(Token::r_brace))
Tatiana Shpeismanc96b5872018-06-28 17:02:32 -07001353 return emitError("ML function must end with return statement");
1354
1355 // Parse the list of instructions.
1356 while (!consumeIf(Token::kw_return)) {
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001357 auto *stmt = parseStatement(function);
Tatiana Shpeismanc96b5872018-06-28 17:02:32 -07001358 if (!stmt)
1359 return ParseFailure;
1360 function->stmtList.push_back(stmt);
1361 }
1362
1363 // TODO: parse return statement operands
1364 if (!consumeIf(Token::r_brace))
1365 emitError("expected '}' in ML function");
1366
Chris Lattner48af7d12018-07-09 19:05:38 -07001367 getModule()->functionList.push_back(function);
Tatiana Shpeismanc96b5872018-06-28 17:02:32 -07001368
1369 return ParseSuccess;
1370}
1371
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001372/// Statement.
Tatiana Shpeismanc96b5872018-06-28 17:02:32 -07001373///
Chris Lattner48af7d12018-07-09 19:05:38 -07001374/// ml-stmt ::= instruction | ml-for-stmt | ml-if-stmt
1375///
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001376/// TODO: fix terminology in MLSpec document. ML functions
1377/// contain operation statements, not instructions.
1378///
Chris Lattner48af7d12018-07-09 19:05:38 -07001379Statement *MLFunctionParser::parseStatement(ParentType parent) {
1380 switch (getToken().getKind()) {
Tatiana Shpeismanc96b5872018-06-28 17:02:32 -07001381 default:
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001382 //TODO: parse OperationStmt
1383 return (emitError("expected statement"), nullptr);
Tatiana Shpeismanc96b5872018-06-28 17:02:32 -07001384
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001385 case Token::kw_for:
1386 return parseForStmt(parent);
1387
1388 case Token::kw_if:
1389 return parseIfStmt(parent);
Tatiana Shpeismanc96b5872018-06-28 17:02:32 -07001390 }
1391}
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001392
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001393/// For statement.
1394///
Chris Lattner48af7d12018-07-09 19:05:38 -07001395/// ml-for-stmt ::= `for` ssa-id `=` lower-bound `to` upper-bound
1396/// (`step` integer-literal)? `{` ml-stmt* `}`
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001397///
Chris Lattner48af7d12018-07-09 19:05:38 -07001398ForStmt *MLFunctionParser::parseForStmt(ParentType parent) {
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001399 consumeToken(Token::kw_for);
1400
1401 //TODO: parse loop header
1402 ForStmt *stmt = new ForStmt(parent);
1403 if (parseNestedStatements(stmt)) {
1404 delete stmt;
1405 return nullptr;
1406 }
1407 return stmt;
1408}
1409
1410/// If statement.
1411///
Chris Lattner48af7d12018-07-09 19:05:38 -07001412/// ml-if-head ::= `if` ml-if-cond `{` ml-stmt* `}`
1413/// | ml-if-head `else` `if` ml-if-cond `{` ml-stmt* `}`
1414/// ml-if-stmt ::= ml-if-head
1415/// | ml-if-head `else` `{` ml-stmt* `}`
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001416///
Chris Lattner48af7d12018-07-09 19:05:38 -07001417IfStmt *
1418MLFunctionParser::parseIfStmt(PointerUnion<MLFunction *, NodeStmt *> parent) {
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001419 consumeToken(Token::kw_if);
1420
1421 //TODO: parse condition
1422 IfStmt *stmt = new IfStmt(parent);
1423 if (parseNestedStatements(stmt)) {
1424 delete stmt;
1425 return nullptr;
1426 }
1427
1428 int clauseNum = 0;
1429 while (consumeIf(Token::kw_else)) {
1430 if (consumeIf(Token::kw_if)) {
1431 //TODO: parse condition
1432 }
1433 ElseClause * clause = new ElseClause(stmt, clauseNum);
1434 ++clauseNum;
1435 if (parseNestedStatements(clause)) {
1436 delete clause;
1437 return nullptr;
1438 }
1439 }
1440
1441 return stmt;
1442}
1443
1444///
1445/// Parse `{` ml-stmt* `}`
1446///
Chris Lattner48af7d12018-07-09 19:05:38 -07001447ParseResult MLFunctionParser::parseNestedStatements(NodeStmt *parent) {
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001448 if (!consumeIf(Token::l_brace))
1449 return emitError("expected '{' before statement list");
1450
1451 if (consumeIf(Token::r_brace)) {
1452 // TODO: parse OperationStmt
1453 return ParseSuccess;
1454 }
1455
1456 while (!consumeIf(Token::r_brace)) {
1457 auto *stmt = parseStatement(parent);
1458 if (!stmt)
1459 return ParseFailure;
1460 parent->children.push_back(stmt);
1461 }
1462
1463 return ParseSuccess;
1464}
1465
Chris Lattner4c95a502018-06-23 16:03:42 -07001466//===----------------------------------------------------------------------===//
1467// Top-level entity parsing.
1468//===----------------------------------------------------------------------===//
1469
Chris Lattner2e595eb2018-07-10 10:08:27 -07001470namespace {
1471/// This parser handles entities that are only valid at the top level of the
1472/// file.
1473class ModuleParser : public Parser {
1474public:
1475 explicit ModuleParser(ParserState &state) : Parser(state) {}
1476
1477 ParseResult parseModule();
1478
1479private:
1480 ParseResult parseAffineMapDef();
1481
1482 // Functions.
1483 ParseResult parseFunctionSignature(StringRef &name, FunctionType *&type);
1484 ParseResult parseExtFunc();
1485 ParseResult parseCFGFunc();
1486 ParseResult parseMLFunc();
1487};
1488} // end anonymous namespace
1489
1490/// Affine map declaration.
1491///
1492/// affine-map-def ::= affine-map-id `=` affine-map-inline
1493///
1494ParseResult ModuleParser::parseAffineMapDef() {
1495 assert(getToken().is(Token::hash_identifier));
1496
1497 StringRef affineMapId = getTokenSpelling().drop_front();
1498
1499 // Check for redefinitions.
1500 auto *&entry = getState().affineMapDefinitions[affineMapId];
1501 if (entry)
1502 return emitError("redefinition of affine map id '" + affineMapId + "'");
1503
1504 consumeToken(Token::hash_identifier);
1505
1506 // Parse the '='
1507 if (!consumeIf(Token::equal))
1508 return emitError("expected '=' in affine map outlined definition");
1509
1510 entry = parseAffineMapInline();
1511 if (!entry)
1512 return ParseFailure;
1513
1514 getModule()->affineMapList.push_back(entry);
1515 return ParseSuccess;
1516}
1517
1518/// Parse a function signature, starting with a name and including the parameter
1519/// list.
1520///
1521/// argument-list ::= type (`,` type)* | /*empty*/
1522/// function-signature ::= function-id `(` argument-list `)` (`->` type-list)?
1523///
1524ParseResult ModuleParser::parseFunctionSignature(StringRef &name,
1525 FunctionType *&type) {
1526 if (getToken().isNot(Token::at_identifier))
1527 return emitError("expected a function identifier like '@foo'");
1528
1529 name = getTokenSpelling().drop_front();
1530 consumeToken(Token::at_identifier);
1531
1532 if (getToken().isNot(Token::l_paren))
1533 return emitError("expected '(' in function signature");
1534
1535 SmallVector<Type *, 4> arguments;
1536 if (parseTypeList(arguments))
1537 return ParseFailure;
1538
1539 // Parse the return type if present.
1540 SmallVector<Type *, 4> results;
1541 if (consumeIf(Token::arrow)) {
1542 if (parseTypeList(results))
1543 return ParseFailure;
1544 }
1545 type = builder.getFunctionType(arguments, results);
1546 return ParseSuccess;
1547}
1548
1549/// External function declarations.
1550///
1551/// ext-func ::= `extfunc` function-signature
1552///
1553ParseResult ModuleParser::parseExtFunc() {
1554 consumeToken(Token::kw_extfunc);
1555
1556 StringRef name;
1557 FunctionType *type = nullptr;
1558 if (parseFunctionSignature(name, type))
1559 return ParseFailure;
1560
1561 // Okay, the external function definition was parsed correctly.
1562 getModule()->functionList.push_back(new ExtFunction(name, type));
1563 return ParseSuccess;
1564}
1565
1566/// CFG function declarations.
1567///
1568/// cfg-func ::= `cfgfunc` function-signature `{` basic-block+ `}`
1569///
1570ParseResult ModuleParser::parseCFGFunc() {
1571 consumeToken(Token::kw_cfgfunc);
1572
1573 StringRef name;
1574 FunctionType *type = nullptr;
1575 if (parseFunctionSignature(name, type))
1576 return ParseFailure;
1577
1578 // Okay, the CFG function signature was parsed correctly, create the function.
1579 auto function = new CFGFunction(name, type);
1580
1581 return CFGFunctionParser(getState(), function).parseFunctionBody();
1582}
1583
1584/// ML function declarations.
1585///
1586/// ml-func ::= `mlfunc` ml-func-signature `{` ml-stmt* ml-return-stmt `}`
1587///
1588ParseResult ModuleParser::parseMLFunc() {
1589 consumeToken(Token::kw_mlfunc);
1590
1591 StringRef name;
1592 FunctionType *type = nullptr;
1593
1594 // FIXME: Parse ML function signature (args + types)
1595 // by passing pointer to SmallVector<identifier> into parseFunctionSignature
1596 if (parseFunctionSignature(name, type))
1597 return ParseFailure;
1598
1599 // Okay, the ML function signature was parsed correctly, create the function.
1600 auto function = new MLFunction(name, type);
1601
1602 return MLFunctionParser(getState(), function).parseFunctionBody();
1603}
1604
Chris Lattnere79379a2018-06-22 10:39:19 -07001605/// This is the top-level module parser.
Chris Lattner2e595eb2018-07-10 10:08:27 -07001606ParseResult ModuleParser::parseModule() {
Chris Lattnere79379a2018-06-22 10:39:19 -07001607 while (1) {
Chris Lattner48af7d12018-07-09 19:05:38 -07001608 switch (getToken().getKind()) {
Chris Lattnere79379a2018-06-22 10:39:19 -07001609 default:
1610 emitError("expected a top level entity");
Chris Lattner2e595eb2018-07-10 10:08:27 -07001611 return ParseFailure;
Chris Lattnere79379a2018-06-22 10:39:19 -07001612
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001613 // If we got to the end of the file, then we're done.
Chris Lattnere79379a2018-06-22 10:39:19 -07001614 case Token::eof:
Chris Lattner2e595eb2018-07-10 10:08:27 -07001615 return ParseSuccess;
Chris Lattnere79379a2018-06-22 10:39:19 -07001616
1617 // If we got an error token, then the lexer already emitted an error, just
1618 // stop. Someday we could introduce error recovery if there was demand for
1619 // it.
1620 case Token::error:
Chris Lattner2e595eb2018-07-10 10:08:27 -07001621 return ParseFailure;
1622
1623 case Token::hash_identifier:
1624 if (parseAffineMapDef())
1625 return ParseFailure;
1626 break;
Chris Lattnere79379a2018-06-22 10:39:19 -07001627
1628 case Token::kw_extfunc:
Chris Lattner2e595eb2018-07-10 10:08:27 -07001629 if (parseExtFunc())
1630 return ParseFailure;
Chris Lattnere79379a2018-06-22 10:39:19 -07001631 break;
1632
Chris Lattner4c95a502018-06-23 16:03:42 -07001633 case Token::kw_cfgfunc:
Chris Lattner2e595eb2018-07-10 10:08:27 -07001634 if (parseCFGFunc())
1635 return ParseFailure;
MLIR Teamf85a6262018-06-27 11:03:08 -07001636 break;
Chris Lattner4c95a502018-06-23 16:03:42 -07001637
Tatiana Shpeismanc96b5872018-06-28 17:02:32 -07001638 case Token::kw_mlfunc:
Chris Lattner2e595eb2018-07-10 10:08:27 -07001639 if (parseMLFunc())
1640 return ParseFailure;
Tatiana Shpeismanc96b5872018-06-28 17:02:32 -07001641 break;
1642
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001643 // TODO: affine entity declarations, etc.
Chris Lattnere79379a2018-06-22 10:39:19 -07001644 }
1645 }
1646}
1647
1648//===----------------------------------------------------------------------===//
1649
Jacques Pienaar7b829702018-07-03 13:24:09 -07001650void mlir::defaultErrorReporter(const llvm::SMDiagnostic &error) {
1651 const auto &sourceMgr = *error.getSourceMgr();
1652 sourceMgr.PrintMessage(error.getLoc(), error.getKind(), error.getMessage());
1653}
1654
Chris Lattnere79379a2018-06-22 10:39:19 -07001655/// This parses the file specified by the indicated SourceMgr and returns an
1656/// MLIR module if it was valid. If not, it emits diagnostics and returns null.
Jacques Pienaar9c411be2018-06-24 19:17:35 -07001657Module *mlir::parseSourceFile(llvm::SourceMgr &sourceMgr, MLIRContext *context,
Jacques Pienaar7b829702018-07-03 13:24:09 -07001658 SMDiagnosticHandlerTy errorReporter) {
Chris Lattner2e595eb2018-07-10 10:08:27 -07001659 // This is the result module we are parsing into.
1660 std::unique_ptr<Module> module(new Module(context));
1661
1662 ParserState state(sourceMgr, module.get(),
Chris Lattner48af7d12018-07-09 19:05:38 -07001663 errorReporter ? std::move(errorReporter)
1664 : defaultErrorReporter);
Chris Lattner2e595eb2018-07-10 10:08:27 -07001665 if (ModuleParser(state).parseModule())
1666 return nullptr;
Chris Lattner21e67f62018-07-06 10:46:19 -07001667
1668 // Make sure the parse module has no other structural problems detected by the
1669 // verifier.
Chris Lattner2e595eb2018-07-10 10:08:27 -07001670 module->verify();
1671 return module.release();
Chris Lattnere79379a2018-06-22 10:39:19 -07001672}