1 //===- Parser.cpp - MLIR Parser Implementation ----------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the parser for the MLIR textual form.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "mlir/Parser.h"
14 #include "Lexer.h"
15 #include "mlir/Analysis/Verifier.h"
16 #include "mlir/IR/AffineExpr.h"
17 #include "mlir/IR/AffineMap.h"
18 #include "mlir/IR/Attributes.h"
19 #include "mlir/IR/Builders.h"
20 #include "mlir/IR/Dialect.h"
21 #include "mlir/IR/DialectImplementation.h"
22 #include "mlir/IR/IntegerSet.h"
23 #include "mlir/IR/Location.h"
24 #include "mlir/IR/MLIRContext.h"
25 #include "mlir/IR/Module.h"
26 #include "mlir/IR/OpImplementation.h"
27 #include "mlir/IR/StandardTypes.h"
28 #include "mlir/Support/STLExtras.h"
29 #include "llvm/ADT/APInt.h"
30 #include "llvm/ADT/DenseMap.h"
31 #include "llvm/ADT/StringExtras.h"
32 #include "llvm/ADT/StringSet.h"
33 #include "llvm/ADT/bit.h"
34 #include "llvm/Support/PrettyStackTrace.h"
35 #include "llvm/Support/SMLoc.h"
36 #include "llvm/Support/SourceMgr.h"
37 #include <algorithm>
38 using namespace mlir;
39 using llvm::MemoryBuffer;
40 using llvm::SMLoc;
41 using llvm::SourceMgr;
42 
43 namespace {
44 class Parser;
45 
46 //===----------------------------------------------------------------------===//
47 // SymbolState
48 //===----------------------------------------------------------------------===//
49 
50 /// This class contains record of any parsed top-level symbols.
51 struct SymbolState {
52   // A map from attribute alias identifier to Attribute.
53   llvm::StringMap<Attribute> attributeAliasDefinitions;
54 
55   // A map from type alias identifier to Type.
56   llvm::StringMap<Type> typeAliasDefinitions;
57 
58   /// A set of locations into the main parser memory buffer for each of the
59   /// active nested parsers. Given that some nested parsers, i.e. custom dialect
60   /// parsers, operate on a temporary memory buffer, this provides an anchor
61   /// point for emitting diagnostics.
62   SmallVector<llvm::SMLoc, 1> nestedParserLocs;
63 
64   /// The top-level lexer that contains the original memory buffer provided by
65   /// the user. This is used by nested parsers to get a properly encoded source
66   /// location.
67   Lexer *topLevelLexer = nullptr;
68 };
69 
70 //===----------------------------------------------------------------------===//
71 // ParserState
72 //===----------------------------------------------------------------------===//
73 
74 /// This class refers to all of the state maintained globally by the parser,
75 /// such as the current lexer position etc.
76 struct ParserState {
77   ParserState(const llvm::SourceMgr &sourceMgr, MLIRContext *ctx,
78               SymbolState &symbols)
79       : context(ctx), lex(sourceMgr, ctx), curToken(lex.lexToken()),
80         symbols(symbols), parserDepth(symbols.nestedParserLocs.size()) {
81     // Set the top level lexer for the symbol state if one doesn't exist.
82     if (!symbols.topLevelLexer)
83       symbols.topLevelLexer = &lex;
84   }
85   ~ParserState() {
86     // Reset the top level lexer if it refers the lexer in our state.
87     if (symbols.topLevelLexer == &lex)
88       symbols.topLevelLexer = nullptr;
89   }
90   ParserState(const ParserState &) = delete;
91   void operator=(const ParserState &) = delete;
92 
93   /// The context we're parsing into.
94   MLIRContext *const context;
95 
96   /// The lexer for the source file we're parsing.
97   Lexer lex;
98 
99   /// This is the next token that hasn't been consumed yet.
100   Token curToken;
101 
102   /// The current state for symbol parsing.
103   SymbolState &symbols;
104 
105   /// The depth of this parser in the nested parsing stack.
106   size_t parserDepth;
107 };
108 
109 //===----------------------------------------------------------------------===//
110 // Parser
111 //===----------------------------------------------------------------------===//
112 
113 /// This class implement support for parsing global entities like types and
114 /// shared entities like SSA names.  It is intended to be subclassed by
115 /// specialized subparsers that include state, e.g. when a local symbol table.
116 class Parser {
117 public:
118   Builder builder;
119 
120   Parser(ParserState &state) : builder(state.context), state(state) {}
121 
122   // Helper methods to get stuff from the parser-global state.
123   ParserState &getState() const { return state; }
124   MLIRContext *getContext() const { return state.context; }
125   const llvm::SourceMgr &getSourceMgr() { return state.lex.getSourceMgr(); }
126 
127   /// Parse a comma-separated list of elements up until the specified end token.
128   ParseResult
129   parseCommaSeparatedListUntil(Token::Kind rightToken,
130                                const std::function<ParseResult()> &parseElement,
131                                bool allowEmptyList = true);
132 
133   /// Parse a comma separated list of elements that must have at least one entry
134   /// in it.
135   ParseResult
136   parseCommaSeparatedList(const std::function<ParseResult()> &parseElement);
137 
138   ParseResult parsePrettyDialectSymbolName(StringRef &prettyName);
139 
140   // We have two forms of parsing methods - those that return a non-null
141   // pointer on success, and those that return a ParseResult to indicate whether
142   // they returned a failure.  The second class fills in by-reference arguments
143   // as the results of their action.
144 
145   //===--------------------------------------------------------------------===//
146   // Error Handling
147   //===--------------------------------------------------------------------===//
148 
149   /// Emit an error and return failure.
150   InFlightDiagnostic emitError(const Twine &message = {}) {
151     return emitError(state.curToken.getLoc(), message);
152   }
153   InFlightDiagnostic emitError(SMLoc loc, const Twine &message = {});
154 
155   /// Encode the specified source location information into an attribute for
156   /// attachment to the IR.
157   Location getEncodedSourceLocation(llvm::SMLoc loc) {
158     // If there are no active nested parsers, we can get the encoded source
159     // location directly.
160     if (state.parserDepth == 0)
161       return state.lex.getEncodedSourceLocation(loc);
162     // Otherwise, we need to re-encode it to point to the top level buffer.
163     return state.symbols.topLevelLexer->getEncodedSourceLocation(
164         remapLocationToTopLevelBuffer(loc));
165   }
166 
167   /// Remaps the given SMLoc to the top level lexer of the parser. This is used
168   /// to adjust locations of potentially nested parsers to ensure that they can
169   /// be emitted properly as diagnostics.
170   llvm::SMLoc remapLocationToTopLevelBuffer(llvm::SMLoc loc) {
171     // If there are no active nested parsers, we can return location directly.
172     SymbolState &symbols = state.symbols;
173     if (state.parserDepth == 0)
174       return loc;
175     assert(symbols.topLevelLexer && "expected valid top-level lexer");
176 
177     // Otherwise, we need to remap the location to the main parser. This is
178     // simply offseting the location onto the location of the last nested
179     // parser.
180     size_t offset = loc.getPointer() - state.lex.getBufferBegin();
181     auto *rawLoc =
182         symbols.nestedParserLocs[state.parserDepth - 1].getPointer() + offset;
183     return llvm::SMLoc::getFromPointer(rawLoc);
184   }
185 
186   //===--------------------------------------------------------------------===//
187   // Token Parsing
188   //===--------------------------------------------------------------------===//
189 
190   /// Return the current token the parser is inspecting.
191   const Token &getToken() const { return state.curToken; }
192   StringRef getTokenSpelling() const { return state.curToken.getSpelling(); }
193 
194   /// If the current token has the specified kind, consume it and return true.
195   /// If not, return false.
196   bool consumeIf(Token::Kind kind) {
197     if (state.curToken.isNot(kind))
198       return false;
199     consumeToken(kind);
200     return true;
201   }
202 
203   /// Advance the current lexer onto the next token.
204   void consumeToken() {
205     assert(state.curToken.isNot(Token::eof, Token::error) &&
206            "shouldn't advance past EOF or errors");
207     state.curToken = state.lex.lexToken();
208   }
209 
210   /// Advance the current lexer onto the next token, asserting what the expected
211   /// current token is.  This is preferred to the above method because it leads
212   /// to more self-documenting code with better checking.
213   void consumeToken(Token::Kind kind) {
214     assert(state.curToken.is(kind) && "consumed an unexpected token");
215     consumeToken();
216   }
217 
218   /// Consume the specified token if present and return success.  On failure,
219   /// output a diagnostic and return failure.
220   ParseResult parseToken(Token::Kind expectedToken, const Twine &message);
221 
222   //===--------------------------------------------------------------------===//
223   // Type Parsing
224   //===--------------------------------------------------------------------===//
225 
226   ParseResult parseFunctionResultTypes(SmallVectorImpl<Type> &elements);
227   ParseResult parseTypeListNoParens(SmallVectorImpl<Type> &elements);
228   ParseResult parseTypeListParens(SmallVectorImpl<Type> &elements);
229 
230   /// Parse an arbitrary type.
231   Type parseType();
232 
233   /// Parse a complex type.
234   Type parseComplexType();
235 
236   /// Parse an extended type.
237   Type parseExtendedType();
238 
239   /// Parse a function type.
240   Type parseFunctionType();
241 
242   /// Parse a memref type.
243   Type parseMemRefType();
244 
245   /// Parse a non function type.
246   Type parseNonFunctionType();
247 
248   /// Parse a tensor type.
249   Type parseTensorType();
250 
251   /// Parse a tuple type.
252   Type parseTupleType();
253 
254   /// Parse a vector type.
255   VectorType parseVectorType();
256   ParseResult parseDimensionListRanked(SmallVectorImpl<int64_t> &dimensions,
257                                        bool allowDynamic = true);
258   ParseResult parseXInDimensionList();
259 
260   /// Parse strided layout specification.
261   ParseResult parseStridedLayout(int64_t &offset,
262                                  SmallVectorImpl<int64_t> &strides);
263 
264   // Parse a brace-delimiter list of comma-separated integers with `?` as an
265   // unknown marker.
266   ParseResult parseStrideList(SmallVectorImpl<int64_t> &dimensions);
267 
268   //===--------------------------------------------------------------------===//
269   // Attribute Parsing
270   //===--------------------------------------------------------------------===//
271 
272   /// Parse an arbitrary attribute with an optional type.
273   Attribute parseAttribute(Type type = {});
274 
275   /// Parse an attribute dictionary.
276   ParseResult parseAttributeDict(SmallVectorImpl<NamedAttribute> &attributes);
277 
278   /// Parse an extended attribute.
279   Attribute parseExtendedAttr(Type type);
280 
281   /// Parse a float attribute.
282   Attribute parseFloatAttr(Type type, bool isNegative);
283 
284   /// Parse a decimal or a hexadecimal literal, which can be either an integer
285   /// or a float attribute.
286   Attribute parseDecOrHexAttr(Type type, bool isNegative);
287 
288   /// Parse an opaque elements attribute.
289   Attribute parseOpaqueElementsAttr(Type attrType);
290 
291   /// Parse a dense elements attribute.
292   Attribute parseDenseElementsAttr(Type attrType);
293   ShapedType parseElementsLiteralType(Type type);
294 
295   /// Parse a sparse elements attribute.
296   Attribute parseSparseElementsAttr(Type attrType);
297 
298   //===--------------------------------------------------------------------===//
299   // Location Parsing
300   //===--------------------------------------------------------------------===//
301 
302   /// Parse an inline location.
303   ParseResult parseLocation(LocationAttr &loc);
304 
305   /// Parse a raw location instance.
306   ParseResult parseLocationInstance(LocationAttr &loc);
307 
308   /// Parse a callsite location instance.
309   ParseResult parseCallSiteLocation(LocationAttr &loc);
310 
311   /// Parse a fused location instance.
312   ParseResult parseFusedLocation(LocationAttr &loc);
313 
314   /// Parse a name or FileLineCol location instance.
315   ParseResult parseNameOrFileLineColLocation(LocationAttr &loc);
316 
317   /// Parse an optional trailing location.
318   ///
319   ///   trailing-location     ::= (`loc` `(` location `)`)?
320   ///
321   ParseResult parseOptionalTrailingLocation(Location &loc) {
322     // If there is a 'loc' we parse a trailing location.
323     if (!getToken().is(Token::kw_loc))
324       return success();
325 
326     // Parse the location.
327     LocationAttr directLoc;
328     if (parseLocation(directLoc))
329       return failure();
330     loc = directLoc;
331     return success();
332   }
333 
334   //===--------------------------------------------------------------------===//
335   // Affine Parsing
336   //===--------------------------------------------------------------------===//
337 
338   /// Parse a reference to either an affine map, or an integer set.
339   ParseResult parseAffineMapOrIntegerSetReference(AffineMap &map,
340                                                   IntegerSet &set);
341   ParseResult parseAffineMapReference(AffineMap &map);
342   ParseResult parseIntegerSetReference(IntegerSet &set);
343 
344   /// Parse an AffineMap where the dim and symbol identifiers are SSA ids.
345   ParseResult
346   parseAffineMapOfSSAIds(AffineMap &map,
347                          function_ref<ParseResult(bool)> parseElement,
348                          OpAsmParser::Delimiter delimiter);
349 
350 private:
351   /// The Parser is subclassed and reinstantiated.  Do not add additional
352   /// non-trivial state here, add it to the ParserState class.
353   ParserState &state;
354 };
355 } // end anonymous namespace
356 
357 //===----------------------------------------------------------------------===//
358 // Helper methods.
359 //===----------------------------------------------------------------------===//
360 
361 /// Parse a comma separated list of elements that must have at least one entry
362 /// in it.
363 ParseResult Parser::parseCommaSeparatedList(
364     const std::function<ParseResult()> &parseElement) {
365   // Non-empty case starts with an element.
366   if (parseElement())
367     return failure();
368 
369   // Otherwise we have a list of comma separated elements.
370   while (consumeIf(Token::comma)) {
371     if (parseElement())
372       return failure();
373   }
374   return success();
375 }
376 
377 /// Parse a comma-separated list of elements, terminated with an arbitrary
378 /// token.  This allows empty lists if allowEmptyList is true.
379 ///
380 ///   abstract-list ::= rightToken                  // if allowEmptyList == true
381 ///   abstract-list ::= element (',' element)* rightToken
382 ///
383 ParseResult Parser::parseCommaSeparatedListUntil(
384     Token::Kind rightToken, const std::function<ParseResult()> &parseElement,
385     bool allowEmptyList) {
386   // Handle the empty case.
387   if (getToken().is(rightToken)) {
388     if (!allowEmptyList)
389       return emitError("expected list element");
390     consumeToken(rightToken);
391     return success();
392   }
393 
394   if (parseCommaSeparatedList(parseElement) ||
395       parseToken(rightToken, "expected ',' or '" +
396                                  Token::getTokenSpelling(rightToken) + "'"))
397     return failure();
398 
399   return success();
400 }
401 
402 //===----------------------------------------------------------------------===//
403 // DialectAsmParser
404 //===----------------------------------------------------------------------===//
405 
406 namespace {
407 /// This class provides the main implementation of the DialectAsmParser that
408 /// allows for dialects to parse attributes and types. This allows for dialect
409 /// hooking into the main MLIR parsing logic.
410 class CustomDialectAsmParser : public DialectAsmParser {
411 public:
412   CustomDialectAsmParser(StringRef fullSpec, Parser &parser)
413       : fullSpec(fullSpec), nameLoc(parser.getToken().getLoc()),
414         parser(parser) {}
415   ~CustomDialectAsmParser() override {}
416 
417   /// Emit a diagnostic at the specified location and return failure.
418   InFlightDiagnostic emitError(llvm::SMLoc loc, const Twine &message) override {
419     return parser.emitError(loc, message);
420   }
421 
422   /// Return a builder which provides useful access to MLIRContext, global
423   /// objects like types and attributes.
424   Builder &getBuilder() const override { return parser.builder; }
425 
426   /// Get the location of the next token and store it into the argument.  This
427   /// always succeeds.
428   llvm::SMLoc getCurrentLocation() override {
429     return parser.getToken().getLoc();
430   }
431 
432   /// Return the location of the original name token.
433   llvm::SMLoc getNameLoc() const override { return nameLoc; }
434 
435   /// Re-encode the given source location as an MLIR location and return it.
436   Location getEncodedSourceLoc(llvm::SMLoc loc) override {
437     return parser.getEncodedSourceLocation(loc);
438   }
439 
440   /// Returns the full specification of the symbol being parsed. This allows
441   /// for using a separate parser if necessary.
442   StringRef getFullSymbolSpec() const override { return fullSpec; }
443 
444   /// Parse a floating point value from the stream.
445   ParseResult parseFloat(double &result) override {
446     bool negative = parser.consumeIf(Token::minus);
447     Token curTok = parser.getToken();
448 
449     // Check for a floating point value.
450     if (curTok.is(Token::floatliteral)) {
451       auto val = curTok.getFloatingPointValue();
452       if (!val.hasValue())
453         return emitError(curTok.getLoc(), "floating point value too large");
454       parser.consumeToken(Token::floatliteral);
455       result = negative ? -*val : *val;
456       return success();
457     }
458 
459     // TODO(riverriddle) support hex floating point values.
460     return emitError(getCurrentLocation(), "expected floating point literal");
461   }
462 
463   /// Parse an optional integer value from the stream.
464   OptionalParseResult parseOptionalInteger(uint64_t &result) override {
465     Token curToken = parser.getToken();
466     if (curToken.isNot(Token::integer, Token::minus))
467       return llvm::None;
468 
469     bool negative = parser.consumeIf(Token::minus);
470     Token curTok = parser.getToken();
471     if (parser.parseToken(Token::integer, "expected integer value"))
472       return failure();
473 
474     auto val = curTok.getUInt64IntegerValue();
475     if (!val)
476       return emitError(curTok.getLoc(), "integer value too large");
477     result = negative ? -*val : *val;
478     return success();
479   }
480 
481   //===--------------------------------------------------------------------===//
482   // Token Parsing
483   //===--------------------------------------------------------------------===//
484 
485   /// Parse a `->` token.
486   ParseResult parseArrow() override {
487     return parser.parseToken(Token::arrow, "expected '->'");
488   }
489 
490   /// Parses a `->` if present.
491   ParseResult parseOptionalArrow() override {
492     return success(parser.consumeIf(Token::arrow));
493   }
494 
495   /// Parse a '{' token.
496   ParseResult parseLBrace() override {
497     return parser.parseToken(Token::l_brace, "expected '{'");
498   }
499 
500   /// Parse a '{' token if present
501   ParseResult parseOptionalLBrace() override {
502     return success(parser.consumeIf(Token::l_brace));
503   }
504 
505   /// Parse a `}` token.
506   ParseResult parseRBrace() override {
507     return parser.parseToken(Token::r_brace, "expected '}'");
508   }
509 
510   /// Parse a `}` token if present
511   ParseResult parseOptionalRBrace() override {
512     return success(parser.consumeIf(Token::r_brace));
513   }
514 
515   /// Parse a `:` token.
516   ParseResult parseColon() override {
517     return parser.parseToken(Token::colon, "expected ':'");
518   }
519 
520   /// Parse a `:` token if present.
521   ParseResult parseOptionalColon() override {
522     return success(parser.consumeIf(Token::colon));
523   }
524 
525   /// Parse a `,` token.
526   ParseResult parseComma() override {
527     return parser.parseToken(Token::comma, "expected ','");
528   }
529 
530   /// Parse a `,` token if present.
531   ParseResult parseOptionalComma() override {
532     return success(parser.consumeIf(Token::comma));
533   }
534 
535   /// Parses a `...` if present.
536   ParseResult parseOptionalEllipsis() override {
537     return success(parser.consumeIf(Token::ellipsis));
538   }
539 
540   /// Parse a `=` token.
541   ParseResult parseEqual() override {
542     return parser.parseToken(Token::equal, "expected '='");
543   }
544 
545   /// Parse a '<' token.
546   ParseResult parseLess() override {
547     return parser.parseToken(Token::less, "expected '<'");
548   }
549 
550   /// Parse a `<` token if present.
551   ParseResult parseOptionalLess() override {
552     return success(parser.consumeIf(Token::less));
553   }
554 
555   /// Parse a '>' token.
556   ParseResult parseGreater() override {
557     return parser.parseToken(Token::greater, "expected '>'");
558   }
559 
560   /// Parse a `>` token if present.
561   ParseResult parseOptionalGreater() override {
562     return success(parser.consumeIf(Token::greater));
563   }
564 
565   /// Parse a `(` token.
566   ParseResult parseLParen() override {
567     return parser.parseToken(Token::l_paren, "expected '('");
568   }
569 
570   /// Parses a '(' if present.
571   ParseResult parseOptionalLParen() override {
572     return success(parser.consumeIf(Token::l_paren));
573   }
574 
575   /// Parse a `)` token.
576   ParseResult parseRParen() override {
577     return parser.parseToken(Token::r_paren, "expected ')'");
578   }
579 
580   /// Parses a ')' if present.
581   ParseResult parseOptionalRParen() override {
582     return success(parser.consumeIf(Token::r_paren));
583   }
584 
585   /// Parse a `[` token.
586   ParseResult parseLSquare() override {
587     return parser.parseToken(Token::l_square, "expected '['");
588   }
589 
590   /// Parses a '[' if present.
591   ParseResult parseOptionalLSquare() override {
592     return success(parser.consumeIf(Token::l_square));
593   }
594 
595   /// Parse a `]` token.
596   ParseResult parseRSquare() override {
597     return parser.parseToken(Token::r_square, "expected ']'");
598   }
599 
600   /// Parses a ']' if present.
601   ParseResult parseOptionalRSquare() override {
602     return success(parser.consumeIf(Token::r_square));
603   }
604 
605   /// Parses a '?' if present.
606   ParseResult parseOptionalQuestion() override {
607     return success(parser.consumeIf(Token::question));
608   }
609 
610   /// Parses a '*' if present.
611   ParseResult parseOptionalStar() override {
612     return success(parser.consumeIf(Token::star));
613   }
614 
615   /// Returns if the current token corresponds to a keyword.
616   bool isCurrentTokenAKeyword() const {
617     return parser.getToken().is(Token::bare_identifier) ||
618            parser.getToken().isKeyword();
619   }
620 
621   /// Parse the given keyword if present.
622   ParseResult parseOptionalKeyword(StringRef keyword) override {
623     // Check that the current token has the same spelling.
624     if (!isCurrentTokenAKeyword() || parser.getTokenSpelling() != keyword)
625       return failure();
626     parser.consumeToken();
627     return success();
628   }
629 
630   /// Parse a keyword, if present, into 'keyword'.
631   ParseResult parseOptionalKeyword(StringRef *keyword) override {
632     // Check that the current token is a keyword.
633     if (!isCurrentTokenAKeyword())
634       return failure();
635 
636     *keyword = parser.getTokenSpelling();
637     parser.consumeToken();
638     return success();
639   }
640 
641   //===--------------------------------------------------------------------===//
642   // Attribute Parsing
643   //===--------------------------------------------------------------------===//
644 
645   /// Parse an arbitrary attribute and return it in result.
646   ParseResult parseAttribute(Attribute &result, Type type) override {
647     result = parser.parseAttribute(type);
648     return success(static_cast<bool>(result));
649   }
650 
651   /// Parse an affine map instance into 'map'.
652   ParseResult parseAffineMap(AffineMap &map) override {
653     return parser.parseAffineMapReference(map);
654   }
655 
656   /// Parse an integer set instance into 'set'.
657   ParseResult printIntegerSet(IntegerSet &set) override {
658     return parser.parseIntegerSetReference(set);
659   }
660 
661   //===--------------------------------------------------------------------===//
662   // Type Parsing
663   //===--------------------------------------------------------------------===//
664 
665   ParseResult parseType(Type &result) override {
666     result = parser.parseType();
667     return success(static_cast<bool>(result));
668   }
669 
670   ParseResult parseDimensionList(SmallVectorImpl<int64_t> &dimensions,
671                                  bool allowDynamic) override {
672     return parser.parseDimensionListRanked(dimensions, allowDynamic);
673   }
674 
675 private:
676   /// The full symbol specification.
677   StringRef fullSpec;
678 
679   /// The source location of the dialect symbol.
680   SMLoc nameLoc;
681 
682   /// The main parser.
683   Parser &parser;
684 };
685 } // namespace
686 
687 /// Parse the body of a pretty dialect symbol, which starts and ends with <>'s,
688 /// and may be recursive.  Return with the 'prettyName' StringRef encompassing
689 /// the entire pretty name.
690 ///
691 ///   pretty-dialect-sym-body ::= '<' pretty-dialect-sym-contents+ '>'
692 ///   pretty-dialect-sym-contents ::= pretty-dialect-sym-body
693 ///                                  | '(' pretty-dialect-sym-contents+ ')'
694 ///                                  | '[' pretty-dialect-sym-contents+ ']'
695 ///                                  | '{' pretty-dialect-sym-contents+ '}'
696 ///                                  | '[^[<({>\])}\0]+'
697 ///
698 ParseResult Parser::parsePrettyDialectSymbolName(StringRef &prettyName) {
699   // Pretty symbol names are a relatively unstructured format that contains a
700   // series of properly nested punctuation, with anything else in the middle.
701   // Scan ahead to find it and consume it if successful, otherwise emit an
702   // error.
703   auto *curPtr = getTokenSpelling().data();
704 
705   SmallVector<char, 8> nestedPunctuation;
706 
707   // Scan over the nested punctuation, bailing out on error and consuming until
708   // we find the end.  We know that we're currently looking at the '<', so we
709   // can go until we find the matching '>' character.
710   assert(*curPtr == '<');
711   do {
712     char c = *curPtr++;
713     switch (c) {
714     case '\0':
715       // This also handles the EOF case.
716       return emitError("unexpected nul or EOF in pretty dialect name");
717     case '<':
718     case '[':
719     case '(':
720     case '{':
721       nestedPunctuation.push_back(c);
722       continue;
723 
724     case '-':
725       // The sequence `->` is treated as special token.
726       if (*curPtr == '>')
727         ++curPtr;
728       continue;
729 
730     case '>':
731       if (nestedPunctuation.pop_back_val() != '<')
732         return emitError("unbalanced '>' character in pretty dialect name");
733       break;
734     case ']':
735       if (nestedPunctuation.pop_back_val() != '[')
736         return emitError("unbalanced ']' character in pretty dialect name");
737       break;
738     case ')':
739       if (nestedPunctuation.pop_back_val() != '(')
740         return emitError("unbalanced ')' character in pretty dialect name");
741       break;
742     case '}':
743       if (nestedPunctuation.pop_back_val() != '{')
744         return emitError("unbalanced '}' character in pretty dialect name");
745       break;
746 
747     default:
748       continue;
749     }
750   } while (!nestedPunctuation.empty());
751 
752   // Ok, we succeeded, remember where we stopped, reset the lexer to know it is
753   // consuming all this stuff, and return.
754   state.lex.resetPointer(curPtr);
755 
756   unsigned length = curPtr - prettyName.begin();
757   prettyName = StringRef(prettyName.begin(), length);
758   consumeToken();
759   return success();
760 }
761 
762 /// Parse an extended dialect symbol.
763 template <typename Symbol, typename SymbolAliasMap, typename CreateFn>
764 static Symbol parseExtendedSymbol(Parser &p, Token::Kind identifierTok,
765                                   SymbolAliasMap &aliases,
766                                   CreateFn &&createSymbol) {
767   // Parse the dialect namespace.
768   StringRef identifier = p.getTokenSpelling().drop_front();
769   auto loc = p.getToken().getLoc();
770   p.consumeToken(identifierTok);
771 
772   // If there is no '<' token following this, and if the typename contains no
773   // dot, then we are parsing a symbol alias.
774   if (p.getToken().isNot(Token::less) && !identifier.contains('.')) {
775     // Check for an alias for this type.
776     auto aliasIt = aliases.find(identifier);
777     if (aliasIt == aliases.end())
778       return (p.emitError("undefined symbol alias id '" + identifier + "'"),
779               nullptr);
780     return aliasIt->second;
781   }
782 
783   // Otherwise, we are parsing a dialect-specific symbol.  If the name contains
784   // a dot, then this is the "pretty" form.  If not, it is the verbose form that
785   // looks like <"...">.
786   std::string symbolData;
787   auto dialectName = identifier;
788 
789   // Handle the verbose form, where "identifier" is a simple dialect name.
790   if (!identifier.contains('.')) {
791     // Consume the '<'.
792     if (p.parseToken(Token::less, "expected '<' in dialect type"))
793       return nullptr;
794 
795     // Parse the symbol specific data.
796     if (p.getToken().isNot(Token::string))
797       return (p.emitError("expected string literal data in dialect symbol"),
798               nullptr);
799     symbolData = p.getToken().getStringValue();
800     loc = llvm::SMLoc::getFromPointer(p.getToken().getLoc().getPointer() + 1);
801     p.consumeToken(Token::string);
802 
803     // Consume the '>'.
804     if (p.parseToken(Token::greater, "expected '>' in dialect symbol"))
805       return nullptr;
806   } else {
807     // Ok, the dialect name is the part of the identifier before the dot, the
808     // part after the dot is the dialect's symbol, or the start thereof.
809     auto dotHalves = identifier.split('.');
810     dialectName = dotHalves.first;
811     auto prettyName = dotHalves.second;
812     loc = llvm::SMLoc::getFromPointer(prettyName.data());
813 
814     // If the dialect's symbol is followed immediately by a <, then lex the body
815     // of it into prettyName.
816     if (p.getToken().is(Token::less) &&
817         prettyName.bytes_end() == p.getTokenSpelling().bytes_begin()) {
818       if (p.parsePrettyDialectSymbolName(prettyName))
819         return nullptr;
820     }
821 
822     symbolData = prettyName.str();
823   }
824 
825   // Record the name location of the type remapped to the top level buffer.
826   llvm::SMLoc locInTopLevelBuffer = p.remapLocationToTopLevelBuffer(loc);
827   p.getState().symbols.nestedParserLocs.push_back(locInTopLevelBuffer);
828 
829   // Call into the provided symbol construction function.
830   Symbol sym = createSymbol(dialectName, symbolData, loc);
831 
832   // Pop the last parser location.
833   p.getState().symbols.nestedParserLocs.pop_back();
834   return sym;
835 }
836 
837 /// Parses a symbol, of type 'T', and returns it if parsing was successful. If
838 /// parsing failed, nullptr is returned. The number of bytes read from the input
839 /// string is returned in 'numRead'.
840 template <typename T, typename ParserFn>
841 static T parseSymbol(StringRef inputStr, MLIRContext *context,
842                      SymbolState &symbolState, ParserFn &&parserFn,
843                      size_t *numRead = nullptr) {
844   SourceMgr sourceMgr;
845   auto memBuffer = MemoryBuffer::getMemBuffer(
846       inputStr, /*BufferName=*/"<mlir_parser_buffer>",
847       /*RequiresNullTerminator=*/false);
848   sourceMgr.AddNewSourceBuffer(std::move(memBuffer), SMLoc());
849   ParserState state(sourceMgr, context, symbolState);
850   Parser parser(state);
851 
852   Token startTok = parser.getToken();
853   T symbol = parserFn(parser);
854   if (!symbol)
855     return T();
856 
857   // If 'numRead' is valid, then provide the number of bytes that were read.
858   Token endTok = parser.getToken();
859   if (numRead) {
860     *numRead = static_cast<size_t>(endTok.getLoc().getPointer() -
861                                    startTok.getLoc().getPointer());
862 
863     // Otherwise, ensure that all of the tokens were parsed.
864   } else if (startTok.getLoc() != endTok.getLoc() && endTok.isNot(Token::eof)) {
865     parser.emitError(endTok.getLoc(), "encountered unexpected token");
866     return T();
867   }
868   return symbol;
869 }
870 
871 //===----------------------------------------------------------------------===//
872 // Error Handling
873 //===----------------------------------------------------------------------===//
874 
875 InFlightDiagnostic Parser::emitError(SMLoc loc, const Twine &message) {
876   auto diag = mlir::emitError(getEncodedSourceLocation(loc), message);
877 
878   // If we hit a parse error in response to a lexer error, then the lexer
879   // already reported the error.
880   if (getToken().is(Token::error))
881     diag.abandon();
882   return diag;
883 }
884 
885 //===----------------------------------------------------------------------===//
886 // Token Parsing
887 //===----------------------------------------------------------------------===//
888 
889 /// Consume the specified token if present and return success.  On failure,
890 /// output a diagnostic and return failure.
891 ParseResult Parser::parseToken(Token::Kind expectedToken,
892                                const Twine &message) {
893   if (consumeIf(expectedToken))
894     return success();
895   return emitError(message);
896 }
897 
898 //===----------------------------------------------------------------------===//
899 // Type Parsing
900 //===----------------------------------------------------------------------===//
901 
902 /// Parse an arbitrary type.
903 ///
904 ///   type ::= function-type
905 ///          | non-function-type
906 ///
907 Type Parser::parseType() {
908   if (getToken().is(Token::l_paren))
909     return parseFunctionType();
910   return parseNonFunctionType();
911 }
912 
913 /// Parse a function result type.
914 ///
915 ///   function-result-type ::= type-list-parens
916 ///                          | non-function-type
917 ///
918 ParseResult Parser::parseFunctionResultTypes(SmallVectorImpl<Type> &elements) {
919   if (getToken().is(Token::l_paren))
920     return parseTypeListParens(elements);
921 
922   Type t = parseNonFunctionType();
923   if (!t)
924     return failure();
925   elements.push_back(t);
926   return success();
927 }
928 
929 /// Parse a list of types without an enclosing parenthesis.  The list must have
930 /// at least one member.
931 ///
932 ///   type-list-no-parens ::=  type (`,` type)*
933 ///
934 ParseResult Parser::parseTypeListNoParens(SmallVectorImpl<Type> &elements) {
935   auto parseElt = [&]() -> ParseResult {
936     auto elt = parseType();
937     elements.push_back(elt);
938     return elt ? success() : failure();
939   };
940 
941   return parseCommaSeparatedList(parseElt);
942 }
943 
944 /// Parse a parenthesized list of types.
945 ///
946 ///   type-list-parens ::= `(` `)`
947 ///                      | `(` type-list-no-parens `)`
948 ///
949 ParseResult Parser::parseTypeListParens(SmallVectorImpl<Type> &elements) {
950   if (parseToken(Token::l_paren, "expected '('"))
951     return failure();
952 
953   // Handle empty lists.
954   if (getToken().is(Token::r_paren))
955     return consumeToken(), success();
956 
957   if (parseTypeListNoParens(elements) ||
958       parseToken(Token::r_paren, "expected ')'"))
959     return failure();
960   return success();
961 }
962 
963 /// Parse a complex type.
964 ///
965 ///   complex-type ::= `complex` `<` type `>`
966 ///
967 Type Parser::parseComplexType() {
968   consumeToken(Token::kw_complex);
969 
970   // Parse the '<'.
971   if (parseToken(Token::less, "expected '<' in complex type"))
972     return nullptr;
973 
974   llvm::SMLoc elementTypeLoc = getToken().getLoc();
975   auto elementType = parseType();
976   if (!elementType ||
977       parseToken(Token::greater, "expected '>' in complex type"))
978     return nullptr;
979   if (!elementType.isa<FloatType>() && !elementType.isa<IntegerType>())
980     return emitError(elementTypeLoc, "invalid element type for complex"),
981            nullptr;
982 
983   return ComplexType::get(elementType);
984 }
985 
986 /// Parse an extended type.
987 ///
988 ///   extended-type ::= (dialect-type | type-alias)
989 ///   dialect-type  ::= `!` dialect-namespace `<` `"` type-data `"` `>`
990 ///   dialect-type  ::= `!` alias-name pretty-dialect-attribute-body?
991 ///   type-alias    ::= `!` alias-name
992 ///
993 Type Parser::parseExtendedType() {
994   return parseExtendedSymbol<Type>(
995       *this, Token::exclamation_identifier, state.symbols.typeAliasDefinitions,
996       [&](StringRef dialectName, StringRef symbolData,
997           llvm::SMLoc loc) -> Type {
998         // If we found a registered dialect, then ask it to parse the type.
999         if (auto *dialect = state.context->getRegisteredDialect(dialectName)) {
1000           return parseSymbol<Type>(
1001               symbolData, state.context, state.symbols, [&](Parser &parser) {
1002                 CustomDialectAsmParser customParser(symbolData, parser);
1003                 return dialect->parseType(customParser);
1004               });
1005         }
1006 
1007         // Otherwise, form a new opaque type.
1008         return OpaqueType::getChecked(
1009             Identifier::get(dialectName, state.context), symbolData,
1010             state.context, getEncodedSourceLocation(loc));
1011       });
1012 }
1013 
1014 /// Parse a function type.
1015 ///
1016 ///   function-type ::= type-list-parens `->` function-result-type
1017 ///
1018 Type Parser::parseFunctionType() {
1019   assert(getToken().is(Token::l_paren));
1020 
1021   SmallVector<Type, 4> arguments, results;
1022   if (parseTypeListParens(arguments) ||
1023       parseToken(Token::arrow, "expected '->' in function type") ||
1024       parseFunctionResultTypes(results))
1025     return nullptr;
1026 
1027   return builder.getFunctionType(arguments, results);
1028 }
1029 
1030 /// Parse the offset and strides from a strided layout specification.
1031 ///
1032 ///   strided-layout ::= `offset:` dimension `,` `strides: ` stride-list
1033 ///
1034 ParseResult Parser::parseStridedLayout(int64_t &offset,
1035                                        SmallVectorImpl<int64_t> &strides) {
1036   // Parse offset.
1037   consumeToken(Token::kw_offset);
1038   if (!consumeIf(Token::colon))
1039     return emitError("expected colon after `offset` keyword");
1040   auto maybeOffset = getToken().getUnsignedIntegerValue();
1041   bool question = getToken().is(Token::question);
1042   if (!maybeOffset && !question)
1043     return emitError("invalid offset");
1044   offset = maybeOffset ? static_cast<int64_t>(maybeOffset.getValue())
1045                        : MemRefType::getDynamicStrideOrOffset();
1046   consumeToken();
1047 
1048   if (!consumeIf(Token::comma))
1049     return emitError("expected comma after offset value");
1050 
1051   // Parse stride list.
1052   if (!consumeIf(Token::kw_strides))
1053     return emitError("expected `strides` keyword after offset specification");
1054   if (!consumeIf(Token::colon))
1055     return emitError("expected colon after `strides` keyword");
1056   if (failed(parseStrideList(strides)))
1057     return emitError("invalid braces-enclosed stride list");
1058   if (llvm::any_of(strides, [](int64_t st) { return st == 0; }))
1059     return emitError("invalid memref stride");
1060 
1061   return success();
1062 }
1063 
1064 /// Parse a memref type.
1065 ///
1066 ///   memref-type ::= ranked-memref-type | unranked-memref-type
1067 ///
1068 ///   ranked-memref-type ::= `memref` `<` dimension-list-ranked type
1069 ///                          (`,` semi-affine-map-composition)? (`,`
1070 ///                          memory-space)? `>`
1071 ///
1072 ///   unranked-memref-type ::= `memref` `<*x` type (`,` memory-space)? `>`
1073 ///
1074 ///   semi-affine-map-composition ::= (semi-affine-map `,` )* semi-affine-map
1075 ///   memory-space ::= integer-literal /* | TODO: address-space-id */
1076 ///
1077 Type Parser::parseMemRefType() {
1078   consumeToken(Token::kw_memref);
1079 
1080   if (parseToken(Token::less, "expected '<' in memref type"))
1081     return nullptr;
1082 
1083   bool isUnranked;
1084   SmallVector<int64_t, 4> dimensions;
1085 
1086   if (consumeIf(Token::star)) {
1087     // This is an unranked memref type.
1088     isUnranked = true;
1089     if (parseXInDimensionList())
1090       return nullptr;
1091 
1092   } else {
1093     isUnranked = false;
1094     if (parseDimensionListRanked(dimensions))
1095       return nullptr;
1096   }
1097 
1098   // Parse the element type.
1099   auto typeLoc = getToken().getLoc();
1100   auto elementType = parseType();
1101   if (!elementType)
1102     return nullptr;
1103 
1104   // Check that memref is formed from allowed types.
1105   if (!elementType.isIntOrFloat() && !elementType.isa<VectorType>() &&
1106       !elementType.isa<ComplexType>())
1107     return emitError(typeLoc, "invalid memref element type"), nullptr;
1108 
1109   // Parse semi-affine-map-composition.
1110   SmallVector<AffineMap, 2> affineMapComposition;
1111   Optional<unsigned> memorySpace;
1112   unsigned numDims = dimensions.size();
1113 
1114   auto parseElt = [&]() -> ParseResult {
1115     // Check for the memory space.
1116     if (getToken().is(Token::integer)) {
1117       if (memorySpace)
1118         return emitError("multiple memory spaces specified in memref type");
1119       memorySpace = getToken().getUnsignedIntegerValue();
1120       if (!memorySpace.hasValue())
1121         return emitError("invalid memory space in memref type");
1122       consumeToken(Token::integer);
1123       return success();
1124     }
1125     if (isUnranked)
1126       return emitError("cannot have affine map for unranked memref type");
1127     if (memorySpace)
1128       return emitError("expected memory space to be last in memref type");
1129 
1130     AffineMap map;
1131     llvm::SMLoc mapLoc = getToken().getLoc();
1132     if (getToken().is(Token::kw_offset)) {
1133       int64_t offset;
1134       SmallVector<int64_t, 4> strides;
1135       if (failed(parseStridedLayout(offset, strides)))
1136         return failure();
1137       // Construct strided affine map.
1138       map = makeStridedLinearLayoutMap(strides, offset, state.context);
1139     } else {
1140       // Parse an affine map attribute.
1141       auto affineMap = parseAttribute();
1142       if (!affineMap)
1143         return failure();
1144       auto affineMapAttr = affineMap.dyn_cast<AffineMapAttr>();
1145       if (!affineMapAttr)
1146         return emitError("expected affine map in memref type");
1147       map = affineMapAttr.getValue();
1148     }
1149 
1150     if (map.getNumDims() != numDims) {
1151       size_t i = affineMapComposition.size();
1152       return emitError(mapLoc, "memref affine map dimension mismatch between ")
1153              << (i == 0 ? Twine("memref rank") : "affine map " + Twine(i))
1154              << " and affine map" << i + 1 << ": " << numDims
1155              << " != " << map.getNumDims();
1156     }
1157     numDims = map.getNumResults();
1158     affineMapComposition.push_back(map);
1159     return success();
1160   };
1161 
1162   // Parse a list of mappings and address space if present.
1163   if (!consumeIf(Token::greater)) {
1164     // Parse comma separated list of affine maps, followed by memory space.
1165     if (parseToken(Token::comma, "expected ',' or '>' in memref type") ||
1166         parseCommaSeparatedListUntil(Token::greater, parseElt,
1167                                      /*allowEmptyList=*/false)) {
1168       return nullptr;
1169     }
1170   }
1171 
1172   if (isUnranked)
1173     return UnrankedMemRefType::get(elementType, memorySpace.getValueOr(0));
1174 
1175   return MemRefType::get(dimensions, elementType, affineMapComposition,
1176                          memorySpace.getValueOr(0));
1177 }
1178 
1179 /// Parse any type except the function type.
1180 ///
1181 ///   non-function-type ::= integer-type
1182 ///                       | index-type
1183 ///                       | float-type
1184 ///                       | extended-type
1185 ///                       | vector-type
1186 ///                       | tensor-type
1187 ///                       | memref-type
1188 ///                       | complex-type
1189 ///                       | tuple-type
1190 ///                       | none-type
1191 ///
1192 ///   index-type ::= `index`
1193 ///   float-type ::= `f16` | `bf16` | `f32` | `f64`
1194 ///   none-type ::= `none`
1195 ///
1196 Type Parser::parseNonFunctionType() {
1197   switch (getToken().getKind()) {
1198   default:
1199     return (emitError("expected non-function type"), nullptr);
1200   case Token::kw_memref:
1201     return parseMemRefType();
1202   case Token::kw_tensor:
1203     return parseTensorType();
1204   case Token::kw_complex:
1205     return parseComplexType();
1206   case Token::kw_tuple:
1207     return parseTupleType();
1208   case Token::kw_vector:
1209     return parseVectorType();
1210   // integer-type
1211   case Token::inttype: {
1212     auto width = getToken().getIntTypeBitwidth();
1213     if (!width.hasValue())
1214       return (emitError("invalid integer width"), nullptr);
1215     if (width.getValue() > IntegerType::kMaxWidth) {
1216       emitError(getToken().getLoc(), "integer bitwidth is limited to ")
1217           << IntegerType::kMaxWidth << " bits";
1218       return nullptr;
1219     }
1220 
1221     IntegerType::SignednessSemantics signSemantics = IntegerType::Signless;
1222     if (Optional<bool> signedness = getToken().getIntTypeSignedness())
1223       signSemantics = *signedness ? IntegerType::Signed : IntegerType::Unsigned;
1224 
1225     auto loc = getEncodedSourceLocation(getToken().getLoc());
1226     consumeToken(Token::inttype);
1227     return IntegerType::getChecked(width.getValue(), signSemantics, loc);
1228   }
1229 
1230   // float-type
1231   case Token::kw_bf16:
1232     consumeToken(Token::kw_bf16);
1233     return builder.getBF16Type();
1234   case Token::kw_f16:
1235     consumeToken(Token::kw_f16);
1236     return builder.getF16Type();
1237   case Token::kw_f32:
1238     consumeToken(Token::kw_f32);
1239     return builder.getF32Type();
1240   case Token::kw_f64:
1241     consumeToken(Token::kw_f64);
1242     return builder.getF64Type();
1243 
1244   // index-type
1245   case Token::kw_index:
1246     consumeToken(Token::kw_index);
1247     return builder.getIndexType();
1248 
1249   // none-type
1250   case Token::kw_none:
1251     consumeToken(Token::kw_none);
1252     return builder.getNoneType();
1253 
1254   // extended type
1255   case Token::exclamation_identifier:
1256     return parseExtendedType();
1257   }
1258 }
1259 
1260 /// Parse a tensor type.
1261 ///
1262 ///   tensor-type ::= `tensor` `<` dimension-list type `>`
1263 ///   dimension-list ::= dimension-list-ranked | `*x`
1264 ///
1265 Type Parser::parseTensorType() {
1266   consumeToken(Token::kw_tensor);
1267 
1268   if (parseToken(Token::less, "expected '<' in tensor type"))
1269     return nullptr;
1270 
1271   bool isUnranked;
1272   SmallVector<int64_t, 4> dimensions;
1273 
1274   if (consumeIf(Token::star)) {
1275     // This is an unranked tensor type.
1276     isUnranked = true;
1277 
1278     if (parseXInDimensionList())
1279       return nullptr;
1280 
1281   } else {
1282     isUnranked = false;
1283     if (parseDimensionListRanked(dimensions))
1284       return nullptr;
1285   }
1286 
1287   // Parse the element type.
1288   auto elementTypeLoc = getToken().getLoc();
1289   auto elementType = parseType();
1290   if (!elementType || parseToken(Token::greater, "expected '>' in tensor type"))
1291     return nullptr;
1292   if (!TensorType::isValidElementType(elementType))
1293     return emitError(elementTypeLoc, "invalid tensor element type"), nullptr;
1294 
1295   if (isUnranked)
1296     return UnrankedTensorType::get(elementType);
1297   return RankedTensorType::get(dimensions, elementType);
1298 }
1299 
1300 /// Parse a tuple type.
1301 ///
1302 ///   tuple-type ::= `tuple` `<` (type (`,` type)*)? `>`
1303 ///
1304 Type Parser::parseTupleType() {
1305   consumeToken(Token::kw_tuple);
1306 
1307   // Parse the '<'.
1308   if (parseToken(Token::less, "expected '<' in tuple type"))
1309     return nullptr;
1310 
1311   // Check for an empty tuple by directly parsing '>'.
1312   if (consumeIf(Token::greater))
1313     return TupleType::get(getContext());
1314 
1315   // Parse the element types and the '>'.
1316   SmallVector<Type, 4> types;
1317   if (parseTypeListNoParens(types) ||
1318       parseToken(Token::greater, "expected '>' in tuple type"))
1319     return nullptr;
1320 
1321   return TupleType::get(types, getContext());
1322 }
1323 
1324 /// Parse a vector type.
1325 ///
1326 ///   vector-type ::= `vector` `<` non-empty-static-dimension-list type `>`
1327 ///   non-empty-static-dimension-list ::= decimal-literal `x`
1328 ///                                       static-dimension-list
1329 ///   static-dimension-list ::= (decimal-literal `x`)*
1330 ///
1331 VectorType Parser::parseVectorType() {
1332   consumeToken(Token::kw_vector);
1333 
1334   if (parseToken(Token::less, "expected '<' in vector type"))
1335     return nullptr;
1336 
1337   SmallVector<int64_t, 4> dimensions;
1338   if (parseDimensionListRanked(dimensions, /*allowDynamic=*/false))
1339     return nullptr;
1340   if (dimensions.empty())
1341     return (emitError("expected dimension size in vector type"), nullptr);
1342   if (any_of(dimensions, [](int64_t i) { return i <= 0; }))
1343     return emitError(getToken().getLoc(),
1344                      "vector types must have positive constant sizes"),
1345            nullptr;
1346 
1347   // Parse the element type.
1348   auto typeLoc = getToken().getLoc();
1349   auto elementType = parseType();
1350   if (!elementType || parseToken(Token::greater, "expected '>' in vector type"))
1351     return nullptr;
1352   if (!VectorType::isValidElementType(elementType))
1353     return emitError(typeLoc, "vector elements must be int or float type"),
1354            nullptr;
1355 
1356   return VectorType::get(dimensions, elementType);
1357 }
1358 
1359 /// Parse a dimension list of a tensor or memref type.  This populates the
1360 /// dimension list, using -1 for the `?` dimensions if `allowDynamic` is set and
1361 /// errors out on `?` otherwise.
1362 ///
1363 ///   dimension-list-ranked ::= (dimension `x`)*
1364 ///   dimension ::= `?` | decimal-literal
1365 ///
1366 /// When `allowDynamic` is not set, this is used to parse:
1367 ///
1368 ///   static-dimension-list ::= (decimal-literal `x`)*
1369 ParseResult
1370 Parser::parseDimensionListRanked(SmallVectorImpl<int64_t> &dimensions,
1371                                  bool allowDynamic) {
1372   while (getToken().isAny(Token::integer, Token::question)) {
1373     if (consumeIf(Token::question)) {
1374       if (!allowDynamic)
1375         return emitError("expected static shape");
1376       dimensions.push_back(-1);
1377     } else {
1378       // Hexadecimal integer literals (starting with `0x`) are not allowed in
1379       // aggregate type declarations.  Therefore, `0xf32` should be processed as
1380       // a sequence of separate elements `0`, `x`, `f32`.
1381       if (getTokenSpelling().size() > 1 && getTokenSpelling()[1] == 'x') {
1382         // We can get here only if the token is an integer literal.  Hexadecimal
1383         // integer literals can only start with `0x` (`1x` wouldn't lex as a
1384         // literal, just `1` would, at which point we don't get into this
1385         // branch).
1386         assert(getTokenSpelling()[0] == '0' && "invalid integer literal");
1387         dimensions.push_back(0);
1388         state.lex.resetPointer(getTokenSpelling().data() + 1);
1389         consumeToken();
1390       } else {
1391         // Make sure this integer value is in bound and valid.
1392         auto dimension = getToken().getUnsignedIntegerValue();
1393         if (!dimension.hasValue())
1394           return emitError("invalid dimension");
1395         dimensions.push_back((int64_t)dimension.getValue());
1396         consumeToken(Token::integer);
1397       }
1398     }
1399 
1400     // Make sure we have an 'x' or something like 'xbf32'.
1401     if (parseXInDimensionList())
1402       return failure();
1403   }
1404 
1405   return success();
1406 }
1407 
1408 /// Parse an 'x' token in a dimension list, handling the case where the x is
1409 /// juxtaposed with an element type, as in "xf32", leaving the "f32" as the next
1410 /// token.
1411 ParseResult Parser::parseXInDimensionList() {
1412   if (getToken().isNot(Token::bare_identifier) || getTokenSpelling()[0] != 'x')
1413     return emitError("expected 'x' in dimension list");
1414 
1415   // If we had a prefix of 'x', lex the next token immediately after the 'x'.
1416   if (getTokenSpelling().size() != 1)
1417     state.lex.resetPointer(getTokenSpelling().data() + 1);
1418 
1419   // Consume the 'x'.
1420   consumeToken(Token::bare_identifier);
1421 
1422   return success();
1423 }
1424 
1425 // Parse a comma-separated list of dimensions, possibly empty:
1426 //   stride-list ::= `[` (dimension (`,` dimension)*)? `]`
1427 ParseResult Parser::parseStrideList(SmallVectorImpl<int64_t> &dimensions) {
1428   if (!consumeIf(Token::l_square))
1429     return failure();
1430   // Empty list early exit.
1431   if (consumeIf(Token::r_square))
1432     return success();
1433   while (true) {
1434     if (consumeIf(Token::question)) {
1435       dimensions.push_back(MemRefType::getDynamicStrideOrOffset());
1436     } else {
1437       // This must be an integer value.
1438       int64_t val;
1439       if (getToken().getSpelling().getAsInteger(10, val))
1440         return emitError("invalid integer value: ") << getToken().getSpelling();
1441       // Make sure it is not the one value for `?`.
1442       if (ShapedType::isDynamic(val))
1443         return emitError("invalid integer value: ")
1444                << getToken().getSpelling()
1445                << ", use `?` to specify a dynamic dimension";
1446       dimensions.push_back(val);
1447       consumeToken(Token::integer);
1448     }
1449     if (!consumeIf(Token::comma))
1450       break;
1451   }
1452   if (!consumeIf(Token::r_square))
1453     return failure();
1454   return success();
1455 }
1456 
1457 //===----------------------------------------------------------------------===//
1458 // Attribute parsing.
1459 //===----------------------------------------------------------------------===//
1460 
1461 /// Return the symbol reference referred to by the given token, that is known to
1462 /// be an @-identifier.
1463 static std::string extractSymbolReference(Token tok) {
1464   assert(tok.is(Token::at_identifier) && "expected valid @-identifier");
1465   StringRef nameStr = tok.getSpelling().drop_front();
1466 
1467   // Check to see if the reference is a string literal, or a bare identifier.
1468   if (nameStr.front() == '"')
1469     return tok.getStringValue();
1470   return std::string(nameStr);
1471 }
1472 
1473 /// Parse an arbitrary attribute.
1474 ///
1475 ///  attribute-value ::= `unit`
1476 ///                    | bool-literal
1477 ///                    | integer-literal (`:` (index-type | integer-type))?
1478 ///                    | float-literal (`:` float-type)?
1479 ///                    | string-literal (`:` type)?
1480 ///                    | type
1481 ///                    | `[` (attribute-value (`,` attribute-value)*)? `]`
1482 ///                    | `{` (attribute-entry (`,` attribute-entry)*)? `}`
1483 ///                    | symbol-ref-id (`::` symbol-ref-id)*
1484 ///                    | `dense` `<` attribute-value `>` `:`
1485 ///                      (tensor-type | vector-type)
1486 ///                    | `sparse` `<` attribute-value `,` attribute-value `>`
1487 ///                      `:` (tensor-type | vector-type)
1488 ///                    | `opaque` `<` dialect-namespace  `,` hex-string-literal
1489 ///                      `>` `:` (tensor-type | vector-type)
1490 ///                    | extended-attribute
1491 ///
1492 Attribute Parser::parseAttribute(Type type) {
1493   switch (getToken().getKind()) {
1494   // Parse an AffineMap or IntegerSet attribute.
1495   case Token::kw_affine_map: {
1496     consumeToken(Token::kw_affine_map);
1497 
1498     AffineMap map;
1499     if (parseToken(Token::less, "expected '<' in affine map") ||
1500         parseAffineMapReference(map) ||
1501         parseToken(Token::greater, "expected '>' in affine map"))
1502       return Attribute();
1503     return AffineMapAttr::get(map);
1504   }
1505   case Token::kw_affine_set: {
1506     consumeToken(Token::kw_affine_set);
1507 
1508     IntegerSet set;
1509     if (parseToken(Token::less, "expected '<' in integer set") ||
1510         parseIntegerSetReference(set) ||
1511         parseToken(Token::greater, "expected '>' in integer set"))
1512       return Attribute();
1513     return IntegerSetAttr::get(set);
1514   }
1515 
1516   // Parse an array attribute.
1517   case Token::l_square: {
1518     consumeToken(Token::l_square);
1519 
1520     SmallVector<Attribute, 4> elements;
1521     auto parseElt = [&]() -> ParseResult {
1522       elements.push_back(parseAttribute());
1523       return elements.back() ? success() : failure();
1524     };
1525 
1526     if (parseCommaSeparatedListUntil(Token::r_square, parseElt))
1527       return nullptr;
1528     return builder.getArrayAttr(elements);
1529   }
1530 
1531   // Parse a boolean attribute.
1532   case Token::kw_false:
1533     consumeToken(Token::kw_false);
1534     return builder.getBoolAttr(false);
1535   case Token::kw_true:
1536     consumeToken(Token::kw_true);
1537     return builder.getBoolAttr(true);
1538 
1539   // Parse a dense elements attribute.
1540   case Token::kw_dense:
1541     return parseDenseElementsAttr(type);
1542 
1543   // Parse a dictionary attribute.
1544   case Token::l_brace: {
1545     SmallVector<NamedAttribute, 4> elements;
1546     if (parseAttributeDict(elements))
1547       return nullptr;
1548     return builder.getDictionaryAttr(elements);
1549   }
1550 
1551   // Parse an extended attribute, i.e. alias or dialect attribute.
1552   case Token::hash_identifier:
1553     return parseExtendedAttr(type);
1554 
1555   // Parse floating point and integer attributes.
1556   case Token::floatliteral:
1557     return parseFloatAttr(type, /*isNegative=*/false);
1558   case Token::integer:
1559     return parseDecOrHexAttr(type, /*isNegative=*/false);
1560   case Token::minus: {
1561     consumeToken(Token::minus);
1562     if (getToken().is(Token::integer))
1563       return parseDecOrHexAttr(type, /*isNegative=*/true);
1564     if (getToken().is(Token::floatliteral))
1565       return parseFloatAttr(type, /*isNegative=*/true);
1566 
1567     return (emitError("expected constant integer or floating point value"),
1568             nullptr);
1569   }
1570 
1571   // Parse a location attribute.
1572   case Token::kw_loc: {
1573     LocationAttr attr;
1574     return failed(parseLocation(attr)) ? Attribute() : attr;
1575   }
1576 
1577   // Parse an opaque elements attribute.
1578   case Token::kw_opaque:
1579     return parseOpaqueElementsAttr(type);
1580 
1581   // Parse a sparse elements attribute.
1582   case Token::kw_sparse:
1583     return parseSparseElementsAttr(type);
1584 
1585   // Parse a string attribute.
1586   case Token::string: {
1587     auto val = getToken().getStringValue();
1588     consumeToken(Token::string);
1589     // Parse the optional trailing colon type if one wasn't explicitly provided.
1590     if (!type && consumeIf(Token::colon) && !(type = parseType()))
1591       return Attribute();
1592 
1593     return type ? StringAttr::get(val, type)
1594                 : StringAttr::get(val, getContext());
1595   }
1596 
1597   // Parse a symbol reference attribute.
1598   case Token::at_identifier: {
1599     std::string nameStr = extractSymbolReference(getToken());
1600     consumeToken(Token::at_identifier);
1601 
1602     // Parse any nested references.
1603     std::vector<FlatSymbolRefAttr> nestedRefs;
1604     while (getToken().is(Token::colon)) {
1605       // Check for the '::' prefix.
1606       const char *curPointer = getToken().getLoc().getPointer();
1607       consumeToken(Token::colon);
1608       if (!consumeIf(Token::colon)) {
1609         state.lex.resetPointer(curPointer);
1610         consumeToken();
1611         break;
1612       }
1613       // Parse the reference itself.
1614       auto curLoc = getToken().getLoc();
1615       if (getToken().isNot(Token::at_identifier)) {
1616         emitError(curLoc, "expected nested symbol reference identifier");
1617         return Attribute();
1618       }
1619 
1620       std::string nameStr = extractSymbolReference(getToken());
1621       consumeToken(Token::at_identifier);
1622       nestedRefs.push_back(SymbolRefAttr::get(nameStr, getContext()));
1623     }
1624 
1625     return builder.getSymbolRefAttr(nameStr, nestedRefs);
1626   }
1627 
1628   // Parse a 'unit' attribute.
1629   case Token::kw_unit:
1630     consumeToken(Token::kw_unit);
1631     return builder.getUnitAttr();
1632 
1633   default:
1634     // Parse a type attribute.
1635     if (Type type = parseType())
1636       return TypeAttr::get(type);
1637     return nullptr;
1638   }
1639 }
1640 
1641 /// Attribute dictionary.
1642 ///
1643 ///   attribute-dict ::= `{` `}`
1644 ///                    | `{` attribute-entry (`,` attribute-entry)* `}`
1645 ///   attribute-entry ::= (bare-id | string-literal) `=` attribute-value
1646 ///
1647 ParseResult
1648 Parser::parseAttributeDict(SmallVectorImpl<NamedAttribute> &attributes) {
1649   if (parseToken(Token::l_brace, "expected '{' in attribute dictionary"))
1650     return failure();
1651 
1652   auto parseElt = [&]() -> ParseResult {
1653     // The name of an attribute can either be a bare identifier, or a string.
1654     Optional<Identifier> nameId;
1655     if (getToken().is(Token::string))
1656       nameId = builder.getIdentifier(getToken().getStringValue());
1657     else if (getToken().isAny(Token::bare_identifier, Token::inttype) ||
1658              getToken().isKeyword())
1659       nameId = builder.getIdentifier(getTokenSpelling());
1660     else
1661       return emitError("expected attribute name");
1662     consumeToken();
1663 
1664     // Try to parse the '=' for the attribute value.
1665     if (!consumeIf(Token::equal)) {
1666       // If there is no '=', we treat this as a unit attribute.
1667       attributes.push_back({*nameId, builder.getUnitAttr()});
1668       return success();
1669     }
1670 
1671     auto attr = parseAttribute();
1672     if (!attr)
1673       return failure();
1674 
1675     attributes.push_back({*nameId, attr});
1676     return success();
1677   };
1678 
1679   if (parseCommaSeparatedListUntil(Token::r_brace, parseElt))
1680     return failure();
1681 
1682   return success();
1683 }
1684 
1685 /// Parse an extended attribute.
1686 ///
1687 ///   extended-attribute ::= (dialect-attribute | attribute-alias)
1688 ///   dialect-attribute  ::= `#` dialect-namespace `<` `"` attr-data `"` `>`
1689 ///   dialect-attribute  ::= `#` alias-name pretty-dialect-sym-body?
1690 ///   attribute-alias    ::= `#` alias-name
1691 ///
1692 Attribute Parser::parseExtendedAttr(Type type) {
1693   Attribute attr = parseExtendedSymbol<Attribute>(
1694       *this, Token::hash_identifier, state.symbols.attributeAliasDefinitions,
1695       [&](StringRef dialectName, StringRef symbolData,
1696           llvm::SMLoc loc) -> Attribute {
1697         // Parse an optional trailing colon type.
1698         Type attrType = type;
1699         if (consumeIf(Token::colon) && !(attrType = parseType()))
1700           return Attribute();
1701 
1702         // If we found a registered dialect, then ask it to parse the attribute.
1703         if (auto *dialect = state.context->getRegisteredDialect(dialectName)) {
1704           return parseSymbol<Attribute>(
1705               symbolData, state.context, state.symbols, [&](Parser &parser) {
1706                 CustomDialectAsmParser customParser(symbolData, parser);
1707                 return dialect->parseAttribute(customParser, attrType);
1708               });
1709         }
1710 
1711         // Otherwise, form a new opaque attribute.
1712         return OpaqueAttr::getChecked(
1713             Identifier::get(dialectName, state.context), symbolData,
1714             attrType ? attrType : NoneType::get(state.context),
1715             getEncodedSourceLocation(loc));
1716       });
1717 
1718   // Ensure that the attribute has the same type as requested.
1719   if (attr && type && attr.getType() != type) {
1720     emitError("attribute type different than expected: expected ")
1721         << type << ", but got " << attr.getType();
1722     return nullptr;
1723   }
1724   return attr;
1725 }
1726 
1727 /// Parse a float attribute.
1728 Attribute Parser::parseFloatAttr(Type type, bool isNegative) {
1729   auto val = getToken().getFloatingPointValue();
1730   if (!val.hasValue())
1731     return (emitError("floating point value too large for attribute"), nullptr);
1732   consumeToken(Token::floatliteral);
1733   if (!type) {
1734     // Default to F64 when no type is specified.
1735     if (!consumeIf(Token::colon))
1736       type = builder.getF64Type();
1737     else if (!(type = parseType()))
1738       return nullptr;
1739   }
1740   if (!type.isa<FloatType>())
1741     return (emitError("floating point value not valid for specified type"),
1742             nullptr);
1743   return FloatAttr::get(type, isNegative ? -val.getValue() : val.getValue());
1744 }
1745 
1746 /// Construct a float attribute bitwise equivalent to the integer literal.
1747 static Optional<APFloat> buildHexadecimalFloatLiteral(Parser *p, FloatType type,
1748                                                       uint64_t value) {
1749   // FIXME: bfloat is currently stored as a double internally because it doesn't
1750   // have valid APFloat semantics.
1751   if (type.isF64() || type.isBF16())
1752     return APFloat(type.getFloatSemantics(), APInt(/*numBits=*/64, value));
1753 
1754   APInt apInt(type.getWidth(), value);
1755   if (apInt != value) {
1756     p->emitError("hexadecimal float constant out of range for type");
1757     return llvm::None;
1758   }
1759   return APFloat(type.getFloatSemantics(), apInt);
1760 }
1761 
1762 /// Parse a decimal or a hexadecimal literal, which can be either an integer
1763 /// or a float attribute.
1764 Attribute Parser::parseDecOrHexAttr(Type type, bool isNegative) {
1765   auto val = getToken().getUInt64IntegerValue();
1766   if (!val.hasValue())
1767     return (emitError("integer constant out of range for attribute"), nullptr);
1768 
1769   // Remember if the literal is hexadecimal.
1770   StringRef spelling = getToken().getSpelling();
1771   auto loc = state.curToken.getLoc();
1772   bool isHex = spelling.size() > 1 && spelling[1] == 'x';
1773 
1774   consumeToken(Token::integer);
1775   if (!type) {
1776     // Default to i64 if not type is specified.
1777     if (!consumeIf(Token::colon))
1778       type = builder.getIntegerType(64);
1779     else if (!(type = parseType()))
1780       return nullptr;
1781   }
1782 
1783   if (auto floatType = type.dyn_cast<FloatType>()) {
1784     if (isNegative)
1785       return emitError(
1786                  loc,
1787                  "hexadecimal float literal should not have a leading minus"),
1788              nullptr;
1789     if (!isHex) {
1790       emitError(loc, "unexpected decimal integer literal for a float attribute")
1791               .attachNote()
1792           << "add a trailing dot to make the literal a float";
1793       return nullptr;
1794     }
1795 
1796     // Construct a float attribute bitwise equivalent to the integer literal.
1797     Optional<APFloat> apVal =
1798         buildHexadecimalFloatLiteral(this, floatType, *val);
1799     return apVal ? FloatAttr::get(floatType, *apVal) : Attribute();
1800   }
1801 
1802   if (!type.isa<IntegerType>() && !type.isa<IndexType>())
1803     return emitError(loc, "integer literal not valid for specified type"),
1804            nullptr;
1805 
1806   if (isNegative && type.isUnsignedInteger()) {
1807     emitError(loc,
1808               "negative integer literal not valid for unsigned integer type");
1809     return nullptr;
1810   }
1811 
1812   // Parse the integer literal.
1813   int width = type.isIndex() ? 64 : type.getIntOrFloatBitWidth();
1814   APInt apInt(width, *val, isNegative);
1815   if (apInt != *val)
1816     return emitError(loc, "integer constant out of range for attribute"),
1817            nullptr;
1818 
1819   // Otherwise construct an integer attribute.
1820   if (isNegative ? (int64_t)-val.getValue() >= 0 : (int64_t)val.getValue() < 0)
1821     return emitError(loc, "integer constant out of range for attribute"),
1822            nullptr;
1823 
1824   return builder.getIntegerAttr(type, isNegative ? -apInt : apInt);
1825 }
1826 
1827 /// Parse elements values stored within a hex etring. On success, the values are
1828 /// stored into 'result'.
1829 static ParseResult parseElementAttrHexValues(Parser &parser, Token tok,
1830                                              std::string &result) {
1831   std::string val = tok.getStringValue();
1832   if (val.size() < 2 || val[0] != '0' || val[1] != 'x')
1833     return parser.emitError(tok.getLoc(),
1834                             "elements hex string should start with '0x'");
1835 
1836   StringRef hexValues = StringRef(val).drop_front(2);
1837   if (!llvm::all_of(hexValues, llvm::isHexDigit))
1838     return parser.emitError(tok.getLoc(),
1839                             "elements hex string only contains hex digits");
1840 
1841   result = llvm::fromHex(hexValues);
1842   return success();
1843 }
1844 
1845 /// Parse an opaque elements attribute.
1846 Attribute Parser::parseOpaqueElementsAttr(Type attrType) {
1847   consumeToken(Token::kw_opaque);
1848   if (parseToken(Token::less, "expected '<' after 'opaque'"))
1849     return nullptr;
1850 
1851   if (getToken().isNot(Token::string))
1852     return (emitError("expected dialect namespace"), nullptr);
1853 
1854   auto name = getToken().getStringValue();
1855   auto *dialect = builder.getContext()->getRegisteredDialect(name);
1856   // TODO(shpeisman): Allow for having an unknown dialect on an opaque
1857   // attribute. Otherwise, it can't be roundtripped without having the dialect
1858   // registered.
1859   if (!dialect)
1860     return (emitError("no registered dialect with namespace '" + name + "'"),
1861             nullptr);
1862   consumeToken(Token::string);
1863 
1864   if (parseToken(Token::comma, "expected ','"))
1865     return nullptr;
1866 
1867   Token hexTok = getToken();
1868   if (parseToken(Token::string, "elements hex string should start with '0x'") ||
1869       parseToken(Token::greater, "expected '>'"))
1870     return nullptr;
1871   auto type = parseElementsLiteralType(attrType);
1872   if (!type)
1873     return nullptr;
1874 
1875   std::string data;
1876   if (parseElementAttrHexValues(*this, hexTok, data))
1877     return nullptr;
1878   return OpaqueElementsAttr::get(dialect, type, data);
1879 }
1880 
1881 namespace {
1882 class TensorLiteralParser {
1883 public:
1884   TensorLiteralParser(Parser &p) : p(p) {}
1885 
1886   /// Parse the elements of a tensor literal. If 'allowHex' is true, the parser
1887   /// may also parse a tensor literal that is store as a hex string.
1888   ParseResult parse(bool allowHex);
1889 
1890   /// Build a dense attribute instance with the parsed elements and the given
1891   /// shaped type.
1892   DenseElementsAttr getAttr(llvm::SMLoc loc, ShapedType type);
1893 
1894   ArrayRef<int64_t> getShape() const { return shape; }
1895 
1896 private:
1897   enum class ElementKind { Boolean, Integer, Float };
1898 
1899   /// Return a string to represent the given element kind.
1900   const char *getElementKindStr(ElementKind kind) {
1901     switch (kind) {
1902     case ElementKind::Boolean:
1903       return "'boolean'";
1904     case ElementKind::Integer:
1905       return "'integer'";
1906     case ElementKind::Float:
1907       return "'float'";
1908     }
1909     llvm_unreachable("unknown element kind");
1910   }
1911 
1912   /// Build a Dense Integer attribute for the given type.
1913   DenseElementsAttr getIntAttr(llvm::SMLoc loc, ShapedType type,
1914                                IntegerType eltTy);
1915 
1916   /// Build a Dense Float attribute for the given type.
1917   DenseElementsAttr getFloatAttr(llvm::SMLoc loc, ShapedType type,
1918                                  FloatType eltTy);
1919 
1920   /// Build a Dense attribute with hex data for the given type.
1921   DenseElementsAttr getHexAttr(llvm::SMLoc loc, ShapedType type);
1922 
1923   /// Parse a single element, returning failure if it isn't a valid element
1924   /// literal. For example:
1925   /// parseElement(1) -> Success, 1
1926   /// parseElement([1]) -> Failure
1927   ParseResult parseElement();
1928 
1929   /// Parse a list of either lists or elements, returning the dimensions of the
1930   /// parsed sub-tensors in dims. For example:
1931   ///   parseList([1, 2, 3]) -> Success, [3]
1932   ///   parseList([[1, 2], [3, 4]]) -> Success, [2, 2]
1933   ///   parseList([[1, 2], 3]) -> Failure
1934   ///   parseList([[1, [2, 3]], [4, [5]]]) -> Failure
1935   ParseResult parseList(SmallVectorImpl<int64_t> &dims);
1936 
1937   /// Parse a literal that was printed as a hex string.
1938   ParseResult parseHexElements();
1939 
1940   Parser &p;
1941 
1942   /// The shape inferred from the parsed elements.
1943   SmallVector<int64_t, 4> shape;
1944 
1945   /// Storage used when parsing elements, this is a pair of <is_negated, token>.
1946   std::vector<std::pair<bool, Token>> storage;
1947 
1948   /// A flag that indicates the type of elements that have been parsed.
1949   Optional<ElementKind> knownEltKind;
1950 
1951   /// Storage used when parsing elements that were stored as hex values.
1952   Optional<Token> hexStorage;
1953 };
1954 } // namespace
1955 
1956 /// Parse the elements of a tensor literal. If 'allowHex' is true, the parser
1957 /// may also parse a tensor literal that is store as a hex string.
1958 ParseResult TensorLiteralParser::parse(bool allowHex) {
1959   // If hex is allowed, check for a string literal.
1960   if (allowHex && p.getToken().is(Token::string)) {
1961     hexStorage = p.getToken();
1962     p.consumeToken(Token::string);
1963     return success();
1964   }
1965   // Otherwise, parse a list or an individual element.
1966   if (p.getToken().is(Token::l_square))
1967     return parseList(shape);
1968   return parseElement();
1969 }
1970 
1971 /// Build a dense attribute instance with the parsed elements and the given
1972 /// shaped type.
1973 DenseElementsAttr TensorLiteralParser::getAttr(llvm::SMLoc loc,
1974                                                ShapedType type) {
1975   // Check to see if we parsed the literal from a hex string.
1976   if (hexStorage.hasValue())
1977     return getHexAttr(loc, type);
1978 
1979   // Check that the parsed storage size has the same number of elements to the
1980   // type, or is a known splat.
1981   if (!shape.empty() && getShape() != type.getShape()) {
1982     p.emitError(loc) << "inferred shape of elements literal ([" << getShape()
1983                      << "]) does not match type ([" << type.getShape() << "])";
1984     return nullptr;
1985   }
1986 
1987   // If the type is an integer, build a set of APInt values from the storage
1988   // with the correct bitwidth.
1989   if (auto intTy = type.getElementType().dyn_cast<IntegerType>())
1990     return getIntAttr(loc, type, intTy);
1991 
1992   // Otherwise, this must be a floating point type.
1993   auto floatTy = type.getElementType().dyn_cast<FloatType>();
1994   if (!floatTy) {
1995     p.emitError(loc) << "expected floating-point or integer element type, got "
1996                      << type.getElementType();
1997     return nullptr;
1998   }
1999   return getFloatAttr(loc, type, floatTy);
2000 }
2001 
2002 /// Build a Dense Integer attribute for the given type.
2003 DenseElementsAttr TensorLiteralParser::getIntAttr(llvm::SMLoc loc,
2004                                                   ShapedType type,
2005                                                   IntegerType eltTy) {
2006   std::vector<APInt> intElements;
2007   intElements.reserve(storage.size());
2008   auto isUintType = type.getElementType().isUnsignedInteger();
2009   for (const auto &signAndToken : storage) {
2010     bool isNegative = signAndToken.first;
2011     const Token &token = signAndToken.second;
2012     auto tokenLoc = token.getLoc();
2013 
2014     if (isNegative && isUintType) {
2015       p.emitError(tokenLoc)
2016           << "expected unsigned integer elements, but parsed negative value";
2017       return nullptr;
2018     }
2019 
2020     // Check to see if floating point values were parsed.
2021     if (token.is(Token::floatliteral)) {
2022       p.emitError(tokenLoc)
2023           << "expected integer elements, but parsed floating-point";
2024       return nullptr;
2025     }
2026 
2027     assert(token.isAny(Token::integer, Token::kw_true, Token::kw_false) &&
2028            "unexpected token type");
2029     if (token.isAny(Token::kw_true, Token::kw_false)) {
2030       if (!eltTy.isInteger(1))
2031         p.emitError(tokenLoc)
2032             << "expected i1 type for 'true' or 'false' values";
2033       APInt apInt(eltTy.getWidth(), token.is(Token::kw_true),
2034                   /*isSigned=*/false);
2035       intElements.push_back(apInt);
2036       continue;
2037     }
2038 
2039     // Create APInt values for each element with the correct bitwidth.
2040     auto val = token.getUInt64IntegerValue();
2041     if (!val.hasValue() || (isNegative ? (int64_t)-val.getValue() >= 0
2042                                        : (int64_t)val.getValue() < 0)) {
2043       p.emitError(tokenLoc, "integer constant out of range for attribute");
2044       return nullptr;
2045     }
2046     APInt apInt(eltTy.getWidth(), val.getValue(), isNegative);
2047     if (apInt != val.getValue())
2048       return (p.emitError(tokenLoc, "integer constant out of range for type"),
2049               nullptr);
2050     intElements.push_back(isNegative ? -apInt : apInt);
2051   }
2052 
2053   return DenseElementsAttr::get(type, intElements);
2054 }
2055 
2056 /// Build a Dense Float attribute for the given type.
2057 DenseElementsAttr TensorLiteralParser::getFloatAttr(llvm::SMLoc loc,
2058                                                     ShapedType type,
2059                                                     FloatType eltTy) {
2060   std::vector<APFloat> floatValues;
2061   floatValues.reserve(storage.size());
2062   for (const auto &signAndToken : storage) {
2063     bool isNegative = signAndToken.first;
2064     const Token &token = signAndToken.second;
2065 
2066     // Handle hexadecimal float literals.
2067     if (token.is(Token::integer) && token.getSpelling().startswith("0x")) {
2068       if (isNegative) {
2069         p.emitError(token.getLoc())
2070             << "hexadecimal float literal should not have a leading minus";
2071         return nullptr;
2072       }
2073       auto val = token.getUInt64IntegerValue();
2074       if (!val.hasValue()) {
2075         p.emitError("hexadecimal float constant out of range for attribute");
2076         return nullptr;
2077       }
2078       Optional<APFloat> apVal = buildHexadecimalFloatLiteral(&p, eltTy, *val);
2079       if (!apVal)
2080         return nullptr;
2081       floatValues.push_back(*apVal);
2082       continue;
2083     }
2084 
2085     // Check to see if any decimal integers or booleans were parsed.
2086     if (!token.is(Token::floatliteral)) {
2087       p.emitError() << "expected floating-point elements, but parsed integer";
2088       return nullptr;
2089     }
2090 
2091     // Build the float values from tokens.
2092     auto val = token.getFloatingPointValue();
2093     if (!val.hasValue()) {
2094       p.emitError("floating point value too large for attribute");
2095       return nullptr;
2096     }
2097     // Treat BF16 as double because it is not supported in LLVM's APFloat.
2098     APFloat apVal(isNegative ? -*val : *val);
2099     if (!eltTy.isBF16() && !eltTy.isF64()) {
2100       bool unused;
2101       apVal.convert(eltTy.getFloatSemantics(), APFloat::rmNearestTiesToEven,
2102                     &unused);
2103     }
2104     floatValues.push_back(apVal);
2105   }
2106 
2107   return DenseElementsAttr::get(type, floatValues);
2108 }
2109 
2110 /// Build a Dense attribute with hex data for the given type.
2111 DenseElementsAttr TensorLiteralParser::getHexAttr(llvm::SMLoc loc,
2112                                                   ShapedType type) {
2113   Type elementType = type.getElementType();
2114   if (!elementType.isa<FloatType>() && !elementType.isa<IntegerType>()) {
2115     p.emitError(loc) << "expected floating-point or integer element type, got "
2116                      << elementType;
2117     return nullptr;
2118   }
2119 
2120   std::string data;
2121   if (parseElementAttrHexValues(p, hexStorage.getValue(), data))
2122     return nullptr;
2123 
2124   // Check that the size of the hex data correpsonds to the size of the type, or
2125   // a splat of the type.
2126   // TODO: bf16 is currently stored as a double, this should be removed when
2127   // APFloat properly supports it.
2128   int64_t elementWidth =
2129       elementType.isBF16() ? 64 : elementType.getIntOrFloatBitWidth();
2130   if (static_cast<int64_t>(data.size() * CHAR_BIT) !=
2131       (type.getNumElements() * elementWidth)) {
2132     p.emitError(loc) << "elements hex data size is invalid for provided type: "
2133                      << type;
2134     return nullptr;
2135   }
2136 
2137   return DenseElementsAttr::getFromRawBuffer(
2138       type, ArrayRef<char>(data.data(), data.size()), /*isSplatBuffer=*/false);
2139 }
2140 
2141 ParseResult TensorLiteralParser::parseElement() {
2142   switch (p.getToken().getKind()) {
2143   // Parse a boolean element.
2144   case Token::kw_true:
2145   case Token::kw_false:
2146   case Token::floatliteral:
2147   case Token::integer:
2148     storage.emplace_back(/*isNegative=*/false, p.getToken());
2149     p.consumeToken();
2150     break;
2151 
2152   // Parse a signed integer or a negative floating-point element.
2153   case Token::minus:
2154     p.consumeToken(Token::minus);
2155     if (!p.getToken().isAny(Token::floatliteral, Token::integer))
2156       return p.emitError("expected integer or floating point literal");
2157     storage.emplace_back(/*isNegative=*/true, p.getToken());
2158     p.consumeToken();
2159     break;
2160 
2161   default:
2162     return p.emitError("expected element literal of primitive type");
2163   }
2164 
2165   return success();
2166 }
2167 
2168 /// Parse a list of either lists or elements, returning the dimensions of the
2169 /// parsed sub-tensors in dims. For example:
2170 ///   parseList([1, 2, 3]) -> Success, [3]
2171 ///   parseList([[1, 2], [3, 4]]) -> Success, [2, 2]
2172 ///   parseList([[1, 2], 3]) -> Failure
2173 ///   parseList([[1, [2, 3]], [4, [5]]]) -> Failure
2174 ParseResult TensorLiteralParser::parseList(SmallVectorImpl<int64_t> &dims) {
2175   p.consumeToken(Token::l_square);
2176 
2177   auto checkDims = [&](const SmallVectorImpl<int64_t> &prevDims,
2178                        const SmallVectorImpl<int64_t> &newDims) -> ParseResult {
2179     if (prevDims == newDims)
2180       return success();
2181     return p.emitError("tensor literal is invalid; ranks are not consistent "
2182                        "between elements");
2183   };
2184 
2185   bool first = true;
2186   SmallVector<int64_t, 4> newDims;
2187   unsigned size = 0;
2188   auto parseCommaSeparatedList = [&]() -> ParseResult {
2189     SmallVector<int64_t, 4> thisDims;
2190     if (p.getToken().getKind() == Token::l_square) {
2191       if (parseList(thisDims))
2192         return failure();
2193     } else if (parseElement()) {
2194       return failure();
2195     }
2196     ++size;
2197     if (!first)
2198       return checkDims(newDims, thisDims);
2199     newDims = thisDims;
2200     first = false;
2201     return success();
2202   };
2203   if (p.parseCommaSeparatedListUntil(Token::r_square, parseCommaSeparatedList))
2204     return failure();
2205 
2206   // Return the sublists' dimensions with 'size' prepended.
2207   dims.clear();
2208   dims.push_back(size);
2209   dims.append(newDims.begin(), newDims.end());
2210   return success();
2211 }
2212 
2213 /// Parse a dense elements attribute.
2214 Attribute Parser::parseDenseElementsAttr(Type attrType) {
2215   consumeToken(Token::kw_dense);
2216   if (parseToken(Token::less, "expected '<' after 'dense'"))
2217     return nullptr;
2218 
2219   // Parse the literal data.
2220   TensorLiteralParser literalParser(*this);
2221   if (literalParser.parse(/*allowHex=*/true))
2222     return nullptr;
2223 
2224   if (parseToken(Token::greater, "expected '>'"))
2225     return nullptr;
2226 
2227   auto typeLoc = getToken().getLoc();
2228   auto type = parseElementsLiteralType(attrType);
2229   if (!type)
2230     return nullptr;
2231   return literalParser.getAttr(typeLoc, type);
2232 }
2233 
2234 /// Shaped type for elements attribute.
2235 ///
2236 ///   elements-literal-type ::= vector-type | ranked-tensor-type
2237 ///
2238 /// This method also checks the type has static shape.
2239 ShapedType Parser::parseElementsLiteralType(Type type) {
2240   // If the user didn't provide a type, parse the colon type for the literal.
2241   if (!type) {
2242     if (parseToken(Token::colon, "expected ':'"))
2243       return nullptr;
2244     if (!(type = parseType()))
2245       return nullptr;
2246   }
2247 
2248   if (!type.isa<RankedTensorType>() && !type.isa<VectorType>()) {
2249     emitError("elements literal must be a ranked tensor or vector type");
2250     return nullptr;
2251   }
2252 
2253   auto sType = type.cast<ShapedType>();
2254   if (!sType.hasStaticShape())
2255     return (emitError("elements literal type must have static shape"), nullptr);
2256 
2257   return sType;
2258 }
2259 
2260 /// Parse a sparse elements attribute.
2261 Attribute Parser::parseSparseElementsAttr(Type attrType) {
2262   consumeToken(Token::kw_sparse);
2263   if (parseToken(Token::less, "Expected '<' after 'sparse'"))
2264     return nullptr;
2265 
2266   /// Parse the indices. We don't allow hex values here as we may need to use
2267   /// the inferred shape.
2268   auto indicesLoc = getToken().getLoc();
2269   TensorLiteralParser indiceParser(*this);
2270   if (indiceParser.parse(/*allowHex=*/false))
2271     return nullptr;
2272 
2273   if (parseToken(Token::comma, "expected ','"))
2274     return nullptr;
2275 
2276   /// Parse the values.
2277   auto valuesLoc = getToken().getLoc();
2278   TensorLiteralParser valuesParser(*this);
2279   if (valuesParser.parse(/*allowHex=*/true))
2280     return nullptr;
2281 
2282   if (parseToken(Token::greater, "expected '>'"))
2283     return nullptr;
2284 
2285   auto type = parseElementsLiteralType(attrType);
2286   if (!type)
2287     return nullptr;
2288 
2289   // If the indices are a splat, i.e. the literal parser parsed an element and
2290   // not a list, we set the shape explicitly. The indices are represented by a
2291   // 2-dimensional shape where the second dimension is the rank of the type.
2292   // Given that the parsed indices is a splat, we know that we only have one
2293   // indice and thus one for the first dimension.
2294   auto indiceEltType = builder.getIntegerType(64);
2295   ShapedType indicesType;
2296   if (indiceParser.getShape().empty()) {
2297     indicesType = RankedTensorType::get({1, type.getRank()}, indiceEltType);
2298   } else {
2299     // Otherwise, set the shape to the one parsed by the literal parser.
2300     indicesType = RankedTensorType::get(indiceParser.getShape(), indiceEltType);
2301   }
2302   auto indices = indiceParser.getAttr(indicesLoc, indicesType);
2303 
2304   // If the values are a splat, set the shape explicitly based on the number of
2305   // indices. The number of indices is encoded in the first dimension of the
2306   // indice shape type.
2307   auto valuesEltType = type.getElementType();
2308   ShapedType valuesType =
2309       valuesParser.getShape().empty()
2310           ? RankedTensorType::get({indicesType.getDimSize(0)}, valuesEltType)
2311           : RankedTensorType::get(valuesParser.getShape(), valuesEltType);
2312   auto values = valuesParser.getAttr(valuesLoc, valuesType);
2313 
2314   /// Sanity check.
2315   if (valuesType.getRank() != 1)
2316     return (emitError("expected 1-d tensor for values"), nullptr);
2317 
2318   auto sameShape = (indicesType.getRank() == 1) ||
2319                    (type.getRank() == indicesType.getDimSize(1));
2320   auto sameElementNum = indicesType.getDimSize(0) == valuesType.getDimSize(0);
2321   if (!sameShape || !sameElementNum) {
2322     emitError() << "expected shape ([" << type.getShape()
2323                 << "]); inferred shape of indices literal (["
2324                 << indicesType.getShape()
2325                 << "]); inferred shape of values literal (["
2326                 << valuesType.getShape() << "])";
2327     return nullptr;
2328   }
2329 
2330   // Build the sparse elements attribute by the indices and values.
2331   return SparseElementsAttr::get(type, indices, values);
2332 }
2333 
2334 //===----------------------------------------------------------------------===//
2335 // Location parsing.
2336 //===----------------------------------------------------------------------===//
2337 
2338 /// Parse a location.
2339 ///
2340 ///   location           ::= `loc` inline-location
2341 ///   inline-location    ::= '(' location-inst ')'
2342 ///
2343 ParseResult Parser::parseLocation(LocationAttr &loc) {
2344   // Check for 'loc' identifier.
2345   if (parseToken(Token::kw_loc, "expected 'loc' keyword"))
2346     return emitError();
2347 
2348   // Parse the inline-location.
2349   if (parseToken(Token::l_paren, "expected '(' in inline location") ||
2350       parseLocationInstance(loc) ||
2351       parseToken(Token::r_paren, "expected ')' in inline location"))
2352     return failure();
2353   return success();
2354 }
2355 
2356 /// Specific location instances.
2357 ///
2358 /// location-inst ::= filelinecol-location |
2359 ///                   name-location |
2360 ///                   callsite-location |
2361 ///                   fused-location |
2362 ///                   unknown-location
2363 /// filelinecol-location ::= string-literal ':' integer-literal
2364 ///                                         ':' integer-literal
2365 /// name-location ::= string-literal
2366 /// callsite-location ::= 'callsite' '(' location-inst 'at' location-inst ')'
2367 /// fused-location ::= fused ('<' attribute-value '>')?
2368 ///                    '[' location-inst (location-inst ',')* ']'
2369 /// unknown-location ::= 'unknown'
2370 ///
2371 ParseResult Parser::parseCallSiteLocation(LocationAttr &loc) {
2372   consumeToken(Token::bare_identifier);
2373 
2374   // Parse the '('.
2375   if (parseToken(Token::l_paren, "expected '(' in callsite location"))
2376     return failure();
2377 
2378   // Parse the callee location.
2379   LocationAttr calleeLoc;
2380   if (parseLocationInstance(calleeLoc))
2381     return failure();
2382 
2383   // Parse the 'at'.
2384   if (getToken().isNot(Token::bare_identifier) ||
2385       getToken().getSpelling() != "at")
2386     return emitError("expected 'at' in callsite location");
2387   consumeToken(Token::bare_identifier);
2388 
2389   // Parse the caller location.
2390   LocationAttr callerLoc;
2391   if (parseLocationInstance(callerLoc))
2392     return failure();
2393 
2394   // Parse the ')'.
2395   if (parseToken(Token::r_paren, "expected ')' in callsite location"))
2396     return failure();
2397 
2398   // Return the callsite location.
2399   loc = CallSiteLoc::get(calleeLoc, callerLoc);
2400   return success();
2401 }
2402 
2403 ParseResult Parser::parseFusedLocation(LocationAttr &loc) {
2404   consumeToken(Token::bare_identifier);
2405 
2406   // Try to parse the optional metadata.
2407   Attribute metadata;
2408   if (consumeIf(Token::less)) {
2409     metadata = parseAttribute();
2410     if (!metadata)
2411       return emitError("expected valid attribute metadata");
2412     // Parse the '>' token.
2413     if (parseToken(Token::greater,
2414                    "expected '>' after fused location metadata"))
2415       return failure();
2416   }
2417 
2418   SmallVector<Location, 4> locations;
2419   auto parseElt = [&] {
2420     LocationAttr newLoc;
2421     if (parseLocationInstance(newLoc))
2422       return failure();
2423     locations.push_back(newLoc);
2424     return success();
2425   };
2426 
2427   if (parseToken(Token::l_square, "expected '[' in fused location") ||
2428       parseCommaSeparatedList(parseElt) ||
2429       parseToken(Token::r_square, "expected ']' in fused location"))
2430     return failure();
2431 
2432   // Return the fused location.
2433   loc = FusedLoc::get(locations, metadata, getContext());
2434   return success();
2435 }
2436 
2437 ParseResult Parser::parseNameOrFileLineColLocation(LocationAttr &loc) {
2438   auto *ctx = getContext();
2439   auto str = getToken().getStringValue();
2440   consumeToken(Token::string);
2441 
2442   // If the next token is ':' this is a filelinecol location.
2443   if (consumeIf(Token::colon)) {
2444     // Parse the line number.
2445     if (getToken().isNot(Token::integer))
2446       return emitError("expected integer line number in FileLineColLoc");
2447     auto line = getToken().getUnsignedIntegerValue();
2448     if (!line.hasValue())
2449       return emitError("expected integer line number in FileLineColLoc");
2450     consumeToken(Token::integer);
2451 
2452     // Parse the ':'.
2453     if (parseToken(Token::colon, "expected ':' in FileLineColLoc"))
2454       return failure();
2455 
2456     // Parse the column number.
2457     if (getToken().isNot(Token::integer))
2458       return emitError("expected integer column number in FileLineColLoc");
2459     auto column = getToken().getUnsignedIntegerValue();
2460     if (!column.hasValue())
2461       return emitError("expected integer column number in FileLineColLoc");
2462     consumeToken(Token::integer);
2463 
2464     loc = FileLineColLoc::get(str, line.getValue(), column.getValue(), ctx);
2465     return success();
2466   }
2467 
2468   // Otherwise, this is a NameLoc.
2469 
2470   // Check for a child location.
2471   if (consumeIf(Token::l_paren)) {
2472     auto childSourceLoc = getToken().getLoc();
2473 
2474     // Parse the child location.
2475     LocationAttr childLoc;
2476     if (parseLocationInstance(childLoc))
2477       return failure();
2478 
2479     // The child must not be another NameLoc.
2480     if (childLoc.isa<NameLoc>())
2481       return emitError(childSourceLoc,
2482                        "child of NameLoc cannot be another NameLoc");
2483     loc = NameLoc::get(Identifier::get(str, ctx), childLoc);
2484 
2485     // Parse the closing ')'.
2486     if (parseToken(Token::r_paren,
2487                    "expected ')' after child location of NameLoc"))
2488       return failure();
2489   } else {
2490     loc = NameLoc::get(Identifier::get(str, ctx), ctx);
2491   }
2492 
2493   return success();
2494 }
2495 
2496 ParseResult Parser::parseLocationInstance(LocationAttr &loc) {
2497   // Handle either name or filelinecol locations.
2498   if (getToken().is(Token::string))
2499     return parseNameOrFileLineColLocation(loc);
2500 
2501   // Bare tokens required for other cases.
2502   if (!getToken().is(Token::bare_identifier))
2503     return emitError("expected location instance");
2504 
2505   // Check for the 'callsite' signifying a callsite location.
2506   if (getToken().getSpelling() == "callsite")
2507     return parseCallSiteLocation(loc);
2508 
2509   // If the token is 'fused', then this is a fused location.
2510   if (getToken().getSpelling() == "fused")
2511     return parseFusedLocation(loc);
2512 
2513   // Check for a 'unknown' for an unknown location.
2514   if (getToken().getSpelling() == "unknown") {
2515     consumeToken(Token::bare_identifier);
2516     loc = UnknownLoc::get(getContext());
2517     return success();
2518   }
2519 
2520   return emitError("expected location instance");
2521 }
2522 
2523 //===----------------------------------------------------------------------===//
2524 // Affine parsing.
2525 //===----------------------------------------------------------------------===//
2526 
2527 /// Lower precedence ops (all at the same precedence level). LNoOp is false in
2528 /// the boolean sense.
2529 enum AffineLowPrecOp {
2530   /// Null value.
2531   LNoOp,
2532   Add,
2533   Sub
2534 };
2535 
2536 /// Higher precedence ops - all at the same precedence level. HNoOp is false
2537 /// in the boolean sense.
2538 enum AffineHighPrecOp {
2539   /// Null value.
2540   HNoOp,
2541   Mul,
2542   FloorDiv,
2543   CeilDiv,
2544   Mod
2545 };
2546 
2547 namespace {
2548 /// This is a specialized parser for affine structures (affine maps, affine
2549 /// expressions, and integer sets), maintaining the state transient to their
2550 /// bodies.
2551 class AffineParser : public Parser {
2552 public:
2553   AffineParser(ParserState &state, bool allowParsingSSAIds = false,
2554                function_ref<ParseResult(bool)> parseElement = nullptr)
2555       : Parser(state), allowParsingSSAIds(allowParsingSSAIds),
2556         parseElement(parseElement), numDimOperands(0), numSymbolOperands(0) {}
2557 
2558   AffineMap parseAffineMapRange(unsigned numDims, unsigned numSymbols);
2559   ParseResult parseAffineMapOrIntegerSetInline(AffineMap &map, IntegerSet &set);
2560   IntegerSet parseIntegerSetConstraints(unsigned numDims, unsigned numSymbols);
2561   ParseResult parseAffineMapOfSSAIds(AffineMap &map,
2562                                      OpAsmParser::Delimiter delimiter);
2563   void getDimsAndSymbolSSAIds(SmallVectorImpl<StringRef> &dimAndSymbolSSAIds,
2564                               unsigned &numDims);
2565 
2566 private:
2567   // Binary affine op parsing.
2568   AffineLowPrecOp consumeIfLowPrecOp();
2569   AffineHighPrecOp consumeIfHighPrecOp();
2570 
2571   // Identifier lists for polyhedral structures.
2572   ParseResult parseDimIdList(unsigned &numDims);
2573   ParseResult parseSymbolIdList(unsigned &numSymbols);
2574   ParseResult parseDimAndOptionalSymbolIdList(unsigned &numDims,
2575                                               unsigned &numSymbols);
2576   ParseResult parseIdentifierDefinition(AffineExpr idExpr);
2577 
2578   AffineExpr parseAffineExpr();
2579   AffineExpr parseParentheticalExpr();
2580   AffineExpr parseNegateExpression(AffineExpr lhs);
2581   AffineExpr parseIntegerExpr();
2582   AffineExpr parseBareIdExpr();
2583   AffineExpr parseSSAIdExpr(bool isSymbol);
2584   AffineExpr parseSymbolSSAIdExpr();
2585 
2586   AffineExpr getAffineBinaryOpExpr(AffineHighPrecOp op, AffineExpr lhs,
2587                                    AffineExpr rhs, SMLoc opLoc);
2588   AffineExpr getAffineBinaryOpExpr(AffineLowPrecOp op, AffineExpr lhs,
2589                                    AffineExpr rhs);
2590   AffineExpr parseAffineOperandExpr(AffineExpr lhs);
2591   AffineExpr parseAffineLowPrecOpExpr(AffineExpr llhs, AffineLowPrecOp llhsOp);
2592   AffineExpr parseAffineHighPrecOpExpr(AffineExpr llhs, AffineHighPrecOp llhsOp,
2593                                        SMLoc llhsOpLoc);
2594   AffineExpr parseAffineConstraint(bool *isEq);
2595 
2596 private:
2597   bool allowParsingSSAIds;
2598   function_ref<ParseResult(bool)> parseElement;
2599   unsigned numDimOperands;
2600   unsigned numSymbolOperands;
2601   SmallVector<std::pair<StringRef, AffineExpr>, 4> dimsAndSymbols;
2602 };
2603 } // end anonymous namespace
2604 
2605 /// Create an affine binary high precedence op expression (mul's, div's, mod).
2606 /// opLoc is the location of the op token to be used to report errors
2607 /// for non-conforming expressions.
2608 AffineExpr AffineParser::getAffineBinaryOpExpr(AffineHighPrecOp op,
2609                                                AffineExpr lhs, AffineExpr rhs,
2610                                                SMLoc opLoc) {
2611   // TODO: make the error location info accurate.
2612   switch (op) {
2613   case Mul:
2614     if (!lhs.isSymbolicOrConstant() && !rhs.isSymbolicOrConstant()) {
2615       emitError(opLoc, "non-affine expression: at least one of the multiply "
2616                        "operands has to be either a constant or symbolic");
2617       return nullptr;
2618     }
2619     return lhs * rhs;
2620   case FloorDiv:
2621     if (!rhs.isSymbolicOrConstant()) {
2622       emitError(opLoc, "non-affine expression: right operand of floordiv "
2623                        "has to be either a constant or symbolic");
2624       return nullptr;
2625     }
2626     return lhs.floorDiv(rhs);
2627   case CeilDiv:
2628     if (!rhs.isSymbolicOrConstant()) {
2629       emitError(opLoc, "non-affine expression: right operand of ceildiv "
2630                        "has to be either a constant or symbolic");
2631       return nullptr;
2632     }
2633     return lhs.ceilDiv(rhs);
2634   case Mod:
2635     if (!rhs.isSymbolicOrConstant()) {
2636       emitError(opLoc, "non-affine expression: right operand of mod "
2637                        "has to be either a constant or symbolic");
2638       return nullptr;
2639     }
2640     return lhs % rhs;
2641   case HNoOp:
2642     llvm_unreachable("can't create affine expression for null high prec op");
2643     return nullptr;
2644   }
2645   llvm_unreachable("Unknown AffineHighPrecOp");
2646 }
2647 
2648 /// Create an affine binary low precedence op expression (add, sub).
2649 AffineExpr AffineParser::getAffineBinaryOpExpr(AffineLowPrecOp op,
2650                                                AffineExpr lhs, AffineExpr rhs) {
2651   switch (op) {
2652   case AffineLowPrecOp::Add:
2653     return lhs + rhs;
2654   case AffineLowPrecOp::Sub:
2655     return lhs - rhs;
2656   case AffineLowPrecOp::LNoOp:
2657     llvm_unreachable("can't create affine expression for null low prec op");
2658     return nullptr;
2659   }
2660   llvm_unreachable("Unknown AffineLowPrecOp");
2661 }
2662 
2663 /// Consume this token if it is a lower precedence affine op (there are only
2664 /// two precedence levels).
2665 AffineLowPrecOp AffineParser::consumeIfLowPrecOp() {
2666   switch (getToken().getKind()) {
2667   case Token::plus:
2668     consumeToken(Token::plus);
2669     return AffineLowPrecOp::Add;
2670   case Token::minus:
2671     consumeToken(Token::minus);
2672     return AffineLowPrecOp::Sub;
2673   default:
2674     return AffineLowPrecOp::LNoOp;
2675   }
2676 }
2677 
2678 /// Consume this token if it is a higher precedence affine op (there are only
2679 /// two precedence levels)
2680 AffineHighPrecOp AffineParser::consumeIfHighPrecOp() {
2681   switch (getToken().getKind()) {
2682   case Token::star:
2683     consumeToken(Token::star);
2684     return Mul;
2685   case Token::kw_floordiv:
2686     consumeToken(Token::kw_floordiv);
2687     return FloorDiv;
2688   case Token::kw_ceildiv:
2689     consumeToken(Token::kw_ceildiv);
2690     return CeilDiv;
2691   case Token::kw_mod:
2692     consumeToken(Token::kw_mod);
2693     return Mod;
2694   default:
2695     return HNoOp;
2696   }
2697 }
2698 
2699 /// Parse a high precedence op expression list: mul, div, and mod are high
2700 /// precedence binary ops, i.e., parse a
2701 ///   expr_1 op_1 expr_2 op_2 ... expr_n
2702 /// where op_1, op_2 are all a AffineHighPrecOp (mul, div, mod).
2703 /// All affine binary ops are left associative.
2704 /// Given llhs, returns (llhs llhsOp lhs) op rhs, or (lhs op rhs) if llhs is
2705 /// null. If no rhs can be found, returns (llhs llhsOp lhs) or lhs if llhs is
2706 /// null. llhsOpLoc is the location of the llhsOp token that will be used to
2707 /// report an error for non-conforming expressions.
2708 AffineExpr AffineParser::parseAffineHighPrecOpExpr(AffineExpr llhs,
2709                                                    AffineHighPrecOp llhsOp,
2710                                                    SMLoc llhsOpLoc) {
2711   AffineExpr lhs = parseAffineOperandExpr(llhs);
2712   if (!lhs)
2713     return nullptr;
2714 
2715   // Found an LHS. Parse the remaining expression.
2716   auto opLoc = getToken().getLoc();
2717   if (AffineHighPrecOp op = consumeIfHighPrecOp()) {
2718     if (llhs) {
2719       AffineExpr expr = getAffineBinaryOpExpr(llhsOp, llhs, lhs, opLoc);
2720       if (!expr)
2721         return nullptr;
2722       return parseAffineHighPrecOpExpr(expr, op, opLoc);
2723     }
2724     // No LLHS, get RHS
2725     return parseAffineHighPrecOpExpr(lhs, op, opLoc);
2726   }
2727 
2728   // This is the last operand in this expression.
2729   if (llhs)
2730     return getAffineBinaryOpExpr(llhsOp, llhs, lhs, llhsOpLoc);
2731 
2732   // No llhs, 'lhs' itself is the expression.
2733   return lhs;
2734 }
2735 
2736 /// Parse an affine expression inside parentheses.
2737 ///
2738 ///   affine-expr ::= `(` affine-expr `)`
2739 AffineExpr AffineParser::parseParentheticalExpr() {
2740   if (parseToken(Token::l_paren, "expected '('"))
2741     return nullptr;
2742   if (getToken().is(Token::r_paren))
2743     return (emitError("no expression inside parentheses"), nullptr);
2744 
2745   auto expr = parseAffineExpr();
2746   if (!expr)
2747     return nullptr;
2748   if (parseToken(Token::r_paren, "expected ')'"))
2749     return nullptr;
2750 
2751   return expr;
2752 }
2753 
2754 /// Parse the negation expression.
2755 ///
2756 ///   affine-expr ::= `-` affine-expr
2757 AffineExpr AffineParser::parseNegateExpression(AffineExpr lhs) {
2758   if (parseToken(Token::minus, "expected '-'"))
2759     return nullptr;
2760 
2761   AffineExpr operand = parseAffineOperandExpr(lhs);
2762   // Since negation has the highest precedence of all ops (including high
2763   // precedence ops) but lower than parentheses, we are only going to use
2764   // parseAffineOperandExpr instead of parseAffineExpr here.
2765   if (!operand)
2766     // Extra error message although parseAffineOperandExpr would have
2767     // complained. Leads to a better diagnostic.
2768     return (emitError("missing operand of negation"), nullptr);
2769   return (-1) * operand;
2770 }
2771 
2772 /// Parse a bare id that may appear in an affine expression.
2773 ///
2774 ///   affine-expr ::= bare-id
2775 AffineExpr AffineParser::parseBareIdExpr() {
2776   if (getToken().isNot(Token::bare_identifier))
2777     return (emitError("expected bare identifier"), nullptr);
2778 
2779   StringRef sRef = getTokenSpelling();
2780   for (auto entry : dimsAndSymbols) {
2781     if (entry.first == sRef) {
2782       consumeToken(Token::bare_identifier);
2783       return entry.second;
2784     }
2785   }
2786 
2787   return (emitError("use of undeclared identifier"), nullptr);
2788 }
2789 
2790 /// Parse an SSA id which may appear in an affine expression.
2791 AffineExpr AffineParser::parseSSAIdExpr(bool isSymbol) {
2792   if (!allowParsingSSAIds)
2793     return (emitError("unexpected ssa identifier"), nullptr);
2794   if (getToken().isNot(Token::percent_identifier))
2795     return (emitError("expected ssa identifier"), nullptr);
2796   auto name = getTokenSpelling();
2797   // Check if we already parsed this SSA id.
2798   for (auto entry : dimsAndSymbols) {
2799     if (entry.first == name) {
2800       consumeToken(Token::percent_identifier);
2801       return entry.second;
2802     }
2803   }
2804   // Parse the SSA id and add an AffineDim/SymbolExpr to represent it.
2805   if (parseElement(isSymbol))
2806     return (emitError("failed to parse ssa identifier"), nullptr);
2807   auto idExpr = isSymbol
2808                     ? getAffineSymbolExpr(numSymbolOperands++, getContext())
2809                     : getAffineDimExpr(numDimOperands++, getContext());
2810   dimsAndSymbols.push_back({name, idExpr});
2811   return idExpr;
2812 }
2813 
2814 AffineExpr AffineParser::parseSymbolSSAIdExpr() {
2815   if (parseToken(Token::kw_symbol, "expected symbol keyword") ||
2816       parseToken(Token::l_paren, "expected '(' at start of SSA symbol"))
2817     return nullptr;
2818   AffineExpr symbolExpr = parseSSAIdExpr(/*isSymbol=*/true);
2819   if (!symbolExpr)
2820     return nullptr;
2821   if (parseToken(Token::r_paren, "expected ')' at end of SSA symbol"))
2822     return nullptr;
2823   return symbolExpr;
2824 }
2825 
2826 /// Parse a positive integral constant appearing in an affine expression.
2827 ///
2828 ///   affine-expr ::= integer-literal
2829 AffineExpr AffineParser::parseIntegerExpr() {
2830   auto val = getToken().getUInt64IntegerValue();
2831   if (!val.hasValue() || (int64_t)val.getValue() < 0)
2832     return (emitError("constant too large for index"), nullptr);
2833 
2834   consumeToken(Token::integer);
2835   return builder.getAffineConstantExpr((int64_t)val.getValue());
2836 }
2837 
2838 /// Parses an expression that can be a valid operand of an affine expression.
2839 /// lhs: if non-null, lhs is an affine expression that is the lhs of a binary
2840 /// operator, the rhs of which is being parsed. This is used to determine
2841 /// whether an error should be emitted for a missing right operand.
2842 //  Eg: for an expression without parentheses (like i + j + k + l), each
2843 //  of the four identifiers is an operand. For i + j*k + l, j*k is not an
2844 //  operand expression, it's an op expression and will be parsed via
2845 //  parseAffineHighPrecOpExpression(). However, for i + (j*k) + -l, (j*k) and
2846 //  -l are valid operands that will be parsed by this function.
2847 AffineExpr AffineParser::parseAffineOperandExpr(AffineExpr lhs) {
2848   switch (getToken().getKind()) {
2849   case Token::bare_identifier:
2850     return parseBareIdExpr();
2851   case Token::kw_symbol:
2852     return parseSymbolSSAIdExpr();
2853   case Token::percent_identifier:
2854     return parseSSAIdExpr(/*isSymbol=*/false);
2855   case Token::integer:
2856     return parseIntegerExpr();
2857   case Token::l_paren:
2858     return parseParentheticalExpr();
2859   case Token::minus:
2860     return parseNegateExpression(lhs);
2861   case Token::kw_ceildiv:
2862   case Token::kw_floordiv:
2863   case Token::kw_mod:
2864   case Token::plus:
2865   case Token::star:
2866     if (lhs)
2867       emitError("missing right operand of binary operator");
2868     else
2869       emitError("missing left operand of binary operator");
2870     return nullptr;
2871   default:
2872     if (lhs)
2873       emitError("missing right operand of binary operator");
2874     else
2875       emitError("expected affine expression");
2876     return nullptr;
2877   }
2878 }
2879 
2880 /// Parse affine expressions that are bare-id's, integer constants,
2881 /// parenthetical affine expressions, and affine op expressions that are a
2882 /// composition of those.
2883 ///
2884 /// All binary op's associate from left to right.
2885 ///
2886 /// {add, sub} have lower precedence than {mul, div, and mod}.
2887 ///
2888 /// Add, sub'are themselves at the same precedence level. Mul, floordiv,
2889 /// ceildiv, and mod are at the same higher precedence level. Negation has
2890 /// higher precedence than any binary op.
2891 ///
2892 /// llhs: the affine expression appearing on the left of the one being parsed.
2893 /// This function will return ((llhs llhsOp lhs) op rhs) if llhs is non null,
2894 /// and lhs op rhs otherwise; if there is no rhs, llhs llhsOp lhs is returned
2895 /// if llhs is non-null; otherwise lhs is returned. This is to deal with left
2896 /// associativity.
2897 ///
2898 /// Eg: when the expression is e1 + e2*e3 + e4, with e1 as llhs, this function
2899 /// will return the affine expr equivalent of (e1 + (e2*e3)) + e4, where
2900 /// (e2*e3) will be parsed using parseAffineHighPrecOpExpr().
2901 AffineExpr AffineParser::parseAffineLowPrecOpExpr(AffineExpr llhs,
2902                                                   AffineLowPrecOp llhsOp) {
2903   AffineExpr lhs;
2904   if (!(lhs = parseAffineOperandExpr(llhs)))
2905     return nullptr;
2906 
2907   // Found an LHS. Deal with the ops.
2908   if (AffineLowPrecOp lOp = consumeIfLowPrecOp()) {
2909     if (llhs) {
2910       AffineExpr sum = getAffineBinaryOpExpr(llhsOp, llhs, lhs);
2911       return parseAffineLowPrecOpExpr(sum, lOp);
2912     }
2913     // No LLHS, get RHS and form the expression.
2914     return parseAffineLowPrecOpExpr(lhs, lOp);
2915   }
2916   auto opLoc = getToken().getLoc();
2917   if (AffineHighPrecOp hOp = consumeIfHighPrecOp()) {
2918     // We have a higher precedence op here. Get the rhs operand for the llhs
2919     // through parseAffineHighPrecOpExpr.
2920     AffineExpr highRes = parseAffineHighPrecOpExpr(lhs, hOp, opLoc);
2921     if (!highRes)
2922       return nullptr;
2923 
2924     // If llhs is null, the product forms the first operand of the yet to be
2925     // found expression. If non-null, the op to associate with llhs is llhsOp.
2926     AffineExpr expr =
2927         llhs ? getAffineBinaryOpExpr(llhsOp, llhs, highRes) : highRes;
2928 
2929     // Recurse for subsequent low prec op's after the affine high prec op
2930     // expression.
2931     if (AffineLowPrecOp nextOp = consumeIfLowPrecOp())
2932       return parseAffineLowPrecOpExpr(expr, nextOp);
2933     return expr;
2934   }
2935   // Last operand in the expression list.
2936   if (llhs)
2937     return getAffineBinaryOpExpr(llhsOp, llhs, lhs);
2938   // No llhs, 'lhs' itself is the expression.
2939   return lhs;
2940 }
2941 
2942 /// Parse an affine expression.
2943 ///  affine-expr ::= `(` affine-expr `)`
2944 ///                | `-` affine-expr
2945 ///                | affine-expr `+` affine-expr
2946 ///                | affine-expr `-` affine-expr
2947 ///                | affine-expr `*` affine-expr
2948 ///                | affine-expr `floordiv` affine-expr
2949 ///                | affine-expr `ceildiv` affine-expr
2950 ///                | affine-expr `mod` affine-expr
2951 ///                | bare-id
2952 ///                | integer-literal
2953 ///
2954 /// Additional conditions are checked depending on the production. For eg.,
2955 /// one of the operands for `*` has to be either constant/symbolic; the second
2956 /// operand for floordiv, ceildiv, and mod has to be a positive integer.
2957 AffineExpr AffineParser::parseAffineExpr() {
2958   return parseAffineLowPrecOpExpr(nullptr, AffineLowPrecOp::LNoOp);
2959 }
2960 
2961 /// Parse a dim or symbol from the lists appearing before the actual
2962 /// expressions of the affine map. Update our state to store the
2963 /// dimensional/symbolic identifier.
2964 ParseResult AffineParser::parseIdentifierDefinition(AffineExpr idExpr) {
2965   if (getToken().isNot(Token::bare_identifier))
2966     return emitError("expected bare identifier");
2967 
2968   auto name = getTokenSpelling();
2969   for (auto entry : dimsAndSymbols) {
2970     if (entry.first == name)
2971       return emitError("redefinition of identifier '" + name + "'");
2972   }
2973   consumeToken(Token::bare_identifier);
2974 
2975   dimsAndSymbols.push_back({name, idExpr});
2976   return success();
2977 }
2978 
2979 /// Parse the list of dimensional identifiers to an affine map.
2980 ParseResult AffineParser::parseDimIdList(unsigned &numDims) {
2981   if (parseToken(Token::l_paren,
2982                  "expected '(' at start of dimensional identifiers list")) {
2983     return failure();
2984   }
2985 
2986   auto parseElt = [&]() -> ParseResult {
2987     auto dimension = getAffineDimExpr(numDims++, getContext());
2988     return parseIdentifierDefinition(dimension);
2989   };
2990   return parseCommaSeparatedListUntil(Token::r_paren, parseElt);
2991 }
2992 
2993 /// Parse the list of symbolic identifiers to an affine map.
2994 ParseResult AffineParser::parseSymbolIdList(unsigned &numSymbols) {
2995   consumeToken(Token::l_square);
2996   auto parseElt = [&]() -> ParseResult {
2997     auto symbol = getAffineSymbolExpr(numSymbols++, getContext());
2998     return parseIdentifierDefinition(symbol);
2999   };
3000   return parseCommaSeparatedListUntil(Token::r_square, parseElt);
3001 }
3002 
3003 /// Parse the list of symbolic identifiers to an affine map.
3004 ParseResult
3005 AffineParser::parseDimAndOptionalSymbolIdList(unsigned &numDims,
3006                                               unsigned &numSymbols) {
3007   if (parseDimIdList(numDims)) {
3008     return failure();
3009   }
3010   if (!getToken().is(Token::l_square)) {
3011     numSymbols = 0;
3012     return success();
3013   }
3014   return parseSymbolIdList(numSymbols);
3015 }
3016 
3017 /// Parses an ambiguous affine map or integer set definition inline.
3018 ParseResult AffineParser::parseAffineMapOrIntegerSetInline(AffineMap &map,
3019                                                            IntegerSet &set) {
3020   unsigned numDims = 0, numSymbols = 0;
3021 
3022   // List of dimensional and optional symbol identifiers.
3023   if (parseDimAndOptionalSymbolIdList(numDims, numSymbols)) {
3024     return failure();
3025   }
3026 
3027   // This is needed for parsing attributes as we wouldn't know whether we would
3028   // be parsing an integer set attribute or an affine map attribute.
3029   bool isArrow = getToken().is(Token::arrow);
3030   bool isColon = getToken().is(Token::colon);
3031   if (!isArrow && !isColon) {
3032     return emitError("expected '->' or ':'");
3033   } else if (isArrow) {
3034     parseToken(Token::arrow, "expected '->' or '['");
3035     map = parseAffineMapRange(numDims, numSymbols);
3036     return map ? success() : failure();
3037   } else if (parseToken(Token::colon, "expected ':' or '['")) {
3038     return failure();
3039   }
3040 
3041   if ((set = parseIntegerSetConstraints(numDims, numSymbols)))
3042     return success();
3043 
3044   return failure();
3045 }
3046 
3047 /// Parse an AffineMap where the dim and symbol identifiers are SSA ids.
3048 ParseResult
3049 AffineParser::parseAffineMapOfSSAIds(AffineMap &map,
3050                                      OpAsmParser::Delimiter delimiter) {
3051   Token::Kind rightToken;
3052   switch (delimiter) {
3053   case OpAsmParser::Delimiter::Square:
3054     if (parseToken(Token::l_square, "expected '['"))
3055       return failure();
3056     rightToken = Token::r_square;
3057     break;
3058   case OpAsmParser::Delimiter::Paren:
3059     if (parseToken(Token::l_paren, "expected '('"))
3060       return failure();
3061     rightToken = Token::r_paren;
3062     break;
3063   default:
3064     return emitError("unexpected delimiter");
3065   }
3066 
3067   SmallVector<AffineExpr, 4> exprs;
3068   auto parseElt = [&]() -> ParseResult {
3069     auto elt = parseAffineExpr();
3070     exprs.push_back(elt);
3071     return elt ? success() : failure();
3072   };
3073 
3074   // Parse a multi-dimensional affine expression (a comma-separated list of
3075   // 1-d affine expressions); the list can be empty. Grammar:
3076   // multi-dim-affine-expr ::= `(` `)`
3077   //                         | `(` affine-expr (`,` affine-expr)* `)`
3078   if (parseCommaSeparatedListUntil(rightToken, parseElt,
3079                                    /*allowEmptyList=*/true))
3080     return failure();
3081   // Parsed a valid affine map.
3082   if (exprs.empty())
3083     map = AffineMap::get(numDimOperands, dimsAndSymbols.size() - numDimOperands,
3084                          getContext());
3085   else
3086     map = AffineMap::get(numDimOperands, dimsAndSymbols.size() - numDimOperands,
3087                          exprs);
3088   return success();
3089 }
3090 
3091 /// Parse the range and sizes affine map definition inline.
3092 ///
3093 ///  affine-map ::= dim-and-symbol-id-lists `->` multi-dim-affine-expr
3094 ///
3095 ///  multi-dim-affine-expr ::= `(` `)`
3096 ///  multi-dim-affine-expr ::= `(` affine-expr (`,` affine-expr)* `)`
3097 AffineMap AffineParser::parseAffineMapRange(unsigned numDims,
3098                                             unsigned numSymbols) {
3099   parseToken(Token::l_paren, "expected '(' at start of affine map range");
3100 
3101   SmallVector<AffineExpr, 4> exprs;
3102   auto parseElt = [&]() -> ParseResult {
3103     auto elt = parseAffineExpr();
3104     ParseResult res = elt ? success() : failure();
3105     exprs.push_back(elt);
3106     return res;
3107   };
3108 
3109   // Parse a multi-dimensional affine expression (a comma-separated list of
3110   // 1-d affine expressions). Grammar:
3111   // multi-dim-affine-expr ::= `(` `)`
3112   //                         | `(` affine-expr (`,` affine-expr)* `)`
3113   if (parseCommaSeparatedListUntil(Token::r_paren, parseElt, true))
3114     return AffineMap();
3115 
3116   if (exprs.empty())
3117     return AffineMap::get(numDims, numSymbols, getContext());
3118 
3119   // Parsed a valid affine map.
3120   return AffineMap::get(numDims, numSymbols, exprs);
3121 }
3122 
3123 /// Parse an affine constraint.
3124 ///  affine-constraint ::= affine-expr `>=` `0`
3125 ///                      | affine-expr `==` `0`
3126 ///
3127 /// isEq is set to true if the parsed constraint is an equality, false if it
3128 /// is an inequality (greater than or equal).
3129 ///
3130 AffineExpr AffineParser::parseAffineConstraint(bool *isEq) {
3131   AffineExpr expr = parseAffineExpr();
3132   if (!expr)
3133     return nullptr;
3134 
3135   if (consumeIf(Token::greater) && consumeIf(Token::equal) &&
3136       getToken().is(Token::integer)) {
3137     auto dim = getToken().getUnsignedIntegerValue();
3138     if (dim.hasValue() && dim.getValue() == 0) {
3139       consumeToken(Token::integer);
3140       *isEq = false;
3141       return expr;
3142     }
3143     return (emitError("expected '0' after '>='"), nullptr);
3144   }
3145 
3146   if (consumeIf(Token::equal) && consumeIf(Token::equal) &&
3147       getToken().is(Token::integer)) {
3148     auto dim = getToken().getUnsignedIntegerValue();
3149     if (dim.hasValue() && dim.getValue() == 0) {
3150       consumeToken(Token::integer);
3151       *isEq = true;
3152       return expr;
3153     }
3154     return (emitError("expected '0' after '=='"), nullptr);
3155   }
3156 
3157   return (emitError("expected '== 0' or '>= 0' at end of affine constraint"),
3158           nullptr);
3159 }
3160 
3161 /// Parse the constraints that are part of an integer set definition.
3162 ///  integer-set-inline
3163 ///                ::= dim-and-symbol-id-lists `:`
3164 ///                '(' affine-constraint-conjunction? ')'
3165 ///  affine-constraint-conjunction ::= affine-constraint (`,`
3166 ///                                       affine-constraint)*
3167 ///
3168 IntegerSet AffineParser::parseIntegerSetConstraints(unsigned numDims,
3169                                                     unsigned numSymbols) {
3170   if (parseToken(Token::l_paren,
3171                  "expected '(' at start of integer set constraint list"))
3172     return IntegerSet();
3173 
3174   SmallVector<AffineExpr, 4> constraints;
3175   SmallVector<bool, 4> isEqs;
3176   auto parseElt = [&]() -> ParseResult {
3177     bool isEq;
3178     auto elt = parseAffineConstraint(&isEq);
3179     ParseResult res = elt ? success() : failure();
3180     if (elt) {
3181       constraints.push_back(elt);
3182       isEqs.push_back(isEq);
3183     }
3184     return res;
3185   };
3186 
3187   // Parse a list of affine constraints (comma-separated).
3188   if (parseCommaSeparatedListUntil(Token::r_paren, parseElt, true))
3189     return IntegerSet();
3190 
3191   // If no constraints were parsed, then treat this as a degenerate 'true' case.
3192   if (constraints.empty()) {
3193     /* 0 == 0 */
3194     auto zero = getAffineConstantExpr(0, getContext());
3195     return IntegerSet::get(numDims, numSymbols, zero, true);
3196   }
3197 
3198   // Parsed a valid integer set.
3199   return IntegerSet::get(numDims, numSymbols, constraints, isEqs);
3200 }
3201 
3202 /// Parse an ambiguous reference to either and affine map or an integer set.
3203 ParseResult Parser::parseAffineMapOrIntegerSetReference(AffineMap &map,
3204                                                         IntegerSet &set) {
3205   return AffineParser(state).parseAffineMapOrIntegerSetInline(map, set);
3206 }
3207 ParseResult Parser::parseAffineMapReference(AffineMap &map) {
3208   llvm::SMLoc curLoc = getToken().getLoc();
3209   IntegerSet set;
3210   if (parseAffineMapOrIntegerSetReference(map, set))
3211     return failure();
3212   if (set)
3213     return emitError(curLoc, "expected AffineMap, but got IntegerSet");
3214   return success();
3215 }
3216 ParseResult Parser::parseIntegerSetReference(IntegerSet &set) {
3217   llvm::SMLoc curLoc = getToken().getLoc();
3218   AffineMap map;
3219   if (parseAffineMapOrIntegerSetReference(map, set))
3220     return failure();
3221   if (map)
3222     return emitError(curLoc, "expected IntegerSet, but got AffineMap");
3223   return success();
3224 }
3225 
3226 /// Parse an AffineMap of SSA ids. The callback 'parseElement' is used to
3227 /// parse SSA value uses encountered while parsing affine expressions.
3228 ParseResult
3229 Parser::parseAffineMapOfSSAIds(AffineMap &map,
3230                                function_ref<ParseResult(bool)> parseElement,
3231                                OpAsmParser::Delimiter delimiter) {
3232   return AffineParser(state, /*allowParsingSSAIds=*/true, parseElement)
3233       .parseAffineMapOfSSAIds(map, delimiter);
3234 }
3235 
3236 //===----------------------------------------------------------------------===//
3237 // OperationParser
3238 //===----------------------------------------------------------------------===//
3239 
3240 namespace {
3241 /// This class provides support for parsing operations and regions of
3242 /// operations.
3243 class OperationParser : public Parser {
3244 public:
3245   OperationParser(ParserState &state, ModuleOp moduleOp)
3246       : Parser(state), opBuilder(moduleOp.getBodyRegion()), moduleOp(moduleOp) {
3247   }
3248 
3249   ~OperationParser();
3250 
3251   /// After parsing is finished, this function must be called to see if there
3252   /// are any remaining issues.
3253   ParseResult finalize();
3254 
3255   //===--------------------------------------------------------------------===//
3256   // SSA Value Handling
3257   //===--------------------------------------------------------------------===//
3258 
3259   /// This represents a use of an SSA value in the program.  The first two
3260   /// entries in the tuple are the name and result number of a reference.  The
3261   /// third is the location of the reference, which is used in case this ends
3262   /// up being a use of an undefined value.
3263   struct SSAUseInfo {
3264     StringRef name;  // Value name, e.g. %42 or %abc
3265     unsigned number; // Number, specified with #12
3266     SMLoc loc;       // Location of first definition or use.
3267   };
3268 
3269   /// Push a new SSA name scope to the parser.
3270   void pushSSANameScope(bool isIsolated);
3271 
3272   /// Pop the last SSA name scope from the parser.
3273   ParseResult popSSANameScope();
3274 
3275   /// Register a definition of a value with the symbol table.
3276   ParseResult addDefinition(SSAUseInfo useInfo, Value value);
3277 
3278   /// Parse an optional list of SSA uses into 'results'.
3279   ParseResult parseOptionalSSAUseList(SmallVectorImpl<SSAUseInfo> &results);
3280 
3281   /// Parse a single SSA use into 'result'.
3282   ParseResult parseSSAUse(SSAUseInfo &result);
3283 
3284   /// Given a reference to an SSA value and its type, return a reference. This
3285   /// returns null on failure.
3286   Value resolveSSAUse(SSAUseInfo useInfo, Type type);
3287 
3288   ParseResult parseSSADefOrUseAndType(
3289       const std::function<ParseResult(SSAUseInfo, Type)> &action);
3290 
3291   ParseResult parseOptionalSSAUseAndTypeList(SmallVectorImpl<Value> &results);
3292 
3293   /// Return the location of the value identified by its name and number if it
3294   /// has been already reference.
3295   Optional<SMLoc> getReferenceLoc(StringRef name, unsigned number) {
3296     auto &values = isolatedNameScopes.back().values;
3297     if (!values.count(name) || number >= values[name].size())
3298       return {};
3299     if (values[name][number].first)
3300       return values[name][number].second;
3301     return {};
3302   }
3303 
3304   //===--------------------------------------------------------------------===//
3305   // Operation Parsing
3306   //===--------------------------------------------------------------------===//
3307 
3308   /// Parse an operation instance.
3309   ParseResult parseOperation();
3310 
3311   /// Parse a single operation successor.
3312   ParseResult parseSuccessor(Block *&dest);
3313 
3314   /// Parse a comma-separated list of operation successors in brackets.
3315   ParseResult parseSuccessors(SmallVectorImpl<Block *> &destinations);
3316 
3317   /// Parse an operation instance that is in the generic form.
3318   Operation *parseGenericOperation();
3319 
3320   /// Parse an operation instance that is in the generic form and insert it at
3321   /// the provided insertion point.
3322   Operation *parseGenericOperation(Block *insertBlock,
3323                                    Block::iterator insertPt);
3324 
3325   /// Parse an operation instance that is in the op-defined custom form.
3326   Operation *parseCustomOperation();
3327 
3328   //===--------------------------------------------------------------------===//
3329   // Region Parsing
3330   //===--------------------------------------------------------------------===//
3331 
3332   /// Parse a region into 'region' with the provided entry block arguments.
3333   /// 'isIsolatedNameScope' indicates if the naming scope of this region is
3334   /// isolated from those above.
3335   ParseResult parseRegion(Region &region,
3336                           ArrayRef<std::pair<SSAUseInfo, Type>> entryArguments,
3337                           bool isIsolatedNameScope = false);
3338 
3339   /// Parse a region body into 'region'.
3340   ParseResult parseRegionBody(Region &region);
3341 
3342   //===--------------------------------------------------------------------===//
3343   // Block Parsing
3344   //===--------------------------------------------------------------------===//
3345 
3346   /// Parse a new block into 'block'.
3347   ParseResult parseBlock(Block *&block);
3348 
3349   /// Parse a list of operations into 'block'.
3350   ParseResult parseBlockBody(Block *block);
3351 
3352   /// Parse a (possibly empty) list of block arguments.
3353   ParseResult parseOptionalBlockArgList(SmallVectorImpl<BlockArgument> &results,
3354                                         Block *owner);
3355 
3356   /// Get the block with the specified name, creating it if it doesn't
3357   /// already exist.  The location specified is the point of use, which allows
3358   /// us to diagnose references to blocks that are not defined precisely.
3359   Block *getBlockNamed(StringRef name, SMLoc loc);
3360 
3361   /// Define the block with the specified name. Returns the Block* or nullptr in
3362   /// the case of redefinition.
3363   Block *defineBlockNamed(StringRef name, SMLoc loc, Block *existing);
3364 
3365 private:
3366   /// Returns the info for a block at the current scope for the given name.
3367   std::pair<Block *, SMLoc> &getBlockInfoByName(StringRef name) {
3368     return blocksByName.back()[name];
3369   }
3370 
3371   /// Insert a new forward reference to the given block.
3372   void insertForwardRef(Block *block, SMLoc loc) {
3373     forwardRef.back().try_emplace(block, loc);
3374   }
3375 
3376   /// Erase any forward reference to the given block.
3377   bool eraseForwardRef(Block *block) { return forwardRef.back().erase(block); }
3378 
3379   /// Record that a definition was added at the current scope.
3380   void recordDefinition(StringRef def);
3381 
3382   /// Get the value entry for the given SSA name.
3383   SmallVectorImpl<std::pair<Value, SMLoc>> &getSSAValueEntry(StringRef name);
3384 
3385   /// Create a forward reference placeholder value with the given location and
3386   /// result type.
3387   Value createForwardRefPlaceholder(SMLoc loc, Type type);
3388 
3389   /// Return true if this is a forward reference.
3390   bool isForwardRefPlaceholder(Value value) {
3391     return forwardRefPlaceholders.count(value);
3392   }
3393 
3394   /// This struct represents an isolated SSA name scope. This scope may contain
3395   /// other nested non-isolated scopes. These scopes are used for operations
3396   /// that are known to be isolated to allow for reusing names within their
3397   /// regions, even if those names are used above.
3398   struct IsolatedSSANameScope {
3399     /// Record that a definition was added at the current scope.
3400     void recordDefinition(StringRef def) {
3401       definitionsPerScope.back().insert(def);
3402     }
3403 
3404     /// Push a nested name scope.
3405     void pushSSANameScope() { definitionsPerScope.push_back({}); }
3406 
3407     /// Pop a nested name scope.
3408     void popSSANameScope() {
3409       for (auto &def : definitionsPerScope.pop_back_val())
3410         values.erase(def.getKey());
3411     }
3412 
3413     /// This keeps track of all of the SSA values we are tracking for each name
3414     /// scope, indexed by their name. This has one entry per result number.
3415     llvm::StringMap<SmallVector<std::pair<Value, SMLoc>, 1>> values;
3416 
3417     /// This keeps track of all of the values defined by a specific name scope.
3418     SmallVector<llvm::StringSet<>, 2> definitionsPerScope;
3419   };
3420 
3421   /// A list of isolated name scopes.
3422   SmallVector<IsolatedSSANameScope, 2> isolatedNameScopes;
3423 
3424   /// This keeps track of the block names as well as the location of the first
3425   /// reference for each nested name scope. This is used to diagnose invalid
3426   /// block references and memorize them.
3427   SmallVector<DenseMap<StringRef, std::pair<Block *, SMLoc>>, 2> blocksByName;
3428   SmallVector<DenseMap<Block *, SMLoc>, 2> forwardRef;
3429 
3430   /// These are all of the placeholders we've made along with the location of
3431   /// their first reference, to allow checking for use of undefined values.
3432   DenseMap<Value, SMLoc> forwardRefPlaceholders;
3433 
3434   /// The builder used when creating parsed operation instances.
3435   OpBuilder opBuilder;
3436 
3437   /// The top level module operation.
3438   ModuleOp moduleOp;
3439 };
3440 } // end anonymous namespace
3441 
3442 OperationParser::~OperationParser() {
3443   for (auto &fwd : forwardRefPlaceholders) {
3444     // Drop all uses of undefined forward declared reference and destroy
3445     // defining operation.
3446     fwd.first.dropAllUses();
3447     fwd.first.getDefiningOp()->destroy();
3448   }
3449 }
3450 
3451 /// After parsing is finished, this function must be called to see if there are
3452 /// any remaining issues.
3453 ParseResult OperationParser::finalize() {
3454   // Check for any forward references that are left.  If we find any, error
3455   // out.
3456   if (!forwardRefPlaceholders.empty()) {
3457     SmallVector<std::pair<const char *, Value>, 4> errors;
3458     // Iteration over the map isn't deterministic, so sort by source location.
3459     for (auto entry : forwardRefPlaceholders)
3460       errors.push_back({entry.second.getPointer(), entry.first});
3461     llvm::array_pod_sort(errors.begin(), errors.end());
3462 
3463     for (auto entry : errors) {
3464       auto loc = SMLoc::getFromPointer(entry.first);
3465       emitError(loc, "use of undeclared SSA value name");
3466     }
3467     return failure();
3468   }
3469 
3470   return success();
3471 }
3472 
3473 //===----------------------------------------------------------------------===//
3474 // SSA Value Handling
3475 //===----------------------------------------------------------------------===//
3476 
3477 void OperationParser::pushSSANameScope(bool isIsolated) {
3478   blocksByName.push_back(DenseMap<StringRef, std::pair<Block *, SMLoc>>());
3479   forwardRef.push_back(DenseMap<Block *, SMLoc>());
3480 
3481   // Push back a new name definition scope.
3482   if (isIsolated)
3483     isolatedNameScopes.push_back({});
3484   isolatedNameScopes.back().pushSSANameScope();
3485 }
3486 
3487 ParseResult OperationParser::popSSANameScope() {
3488   auto forwardRefInCurrentScope = forwardRef.pop_back_val();
3489 
3490   // Verify that all referenced blocks were defined.
3491   if (!forwardRefInCurrentScope.empty()) {
3492     SmallVector<std::pair<const char *, Block *>, 4> errors;
3493     // Iteration over the map isn't deterministic, so sort by source location.
3494     for (auto entry : forwardRefInCurrentScope) {
3495       errors.push_back({entry.second.getPointer(), entry.first});
3496       // Add this block to the top-level region to allow for automatic cleanup.
3497       moduleOp.getOperation()->getRegion(0).push_back(entry.first);
3498     }
3499     llvm::array_pod_sort(errors.begin(), errors.end());
3500 
3501     for (auto entry : errors) {
3502       auto loc = SMLoc::getFromPointer(entry.first);
3503       emitError(loc, "reference to an undefined block");
3504     }
3505     return failure();
3506   }
3507 
3508   // Pop the next nested namescope. If there is only one internal namescope,
3509   // just pop the isolated scope.
3510   auto &currentNameScope = isolatedNameScopes.back();
3511   if (currentNameScope.definitionsPerScope.size() == 1)
3512     isolatedNameScopes.pop_back();
3513   else
3514     currentNameScope.popSSANameScope();
3515 
3516   blocksByName.pop_back();
3517   return success();
3518 }
3519 
3520 /// Register a definition of a value with the symbol table.
3521 ParseResult OperationParser::addDefinition(SSAUseInfo useInfo, Value value) {
3522   auto &entries = getSSAValueEntry(useInfo.name);
3523 
3524   // Make sure there is a slot for this value.
3525   if (entries.size() <= useInfo.number)
3526     entries.resize(useInfo.number + 1);
3527 
3528   // If we already have an entry for this, check to see if it was a definition
3529   // or a forward reference.
3530   if (auto existing = entries[useInfo.number].first) {
3531     if (!isForwardRefPlaceholder(existing)) {
3532       return emitError(useInfo.loc)
3533           .append("redefinition of SSA value '", useInfo.name, "'")
3534           .attachNote(getEncodedSourceLocation(entries[useInfo.number].second))
3535           .append("previously defined here");
3536     }
3537 
3538     // If it was a forward reference, update everything that used it to use
3539     // the actual definition instead, delete the forward ref, and remove it
3540     // from our set of forward references we track.
3541     existing.replaceAllUsesWith(value);
3542     existing.getDefiningOp()->destroy();
3543     forwardRefPlaceholders.erase(existing);
3544   }
3545 
3546   /// Record this definition for the current scope.
3547   entries[useInfo.number] = {value, useInfo.loc};
3548   recordDefinition(useInfo.name);
3549   return success();
3550 }
3551 
3552 /// Parse a (possibly empty) list of SSA operands.
3553 ///
3554 ///   ssa-use-list ::= ssa-use (`,` ssa-use)*
3555 ///   ssa-use-list-opt ::= ssa-use-list?
3556 ///
3557 ParseResult
3558 OperationParser::parseOptionalSSAUseList(SmallVectorImpl<SSAUseInfo> &results) {
3559   if (getToken().isNot(Token::percent_identifier))
3560     return success();
3561   return parseCommaSeparatedList([&]() -> ParseResult {
3562     SSAUseInfo result;
3563     if (parseSSAUse(result))
3564       return failure();
3565     results.push_back(result);
3566     return success();
3567   });
3568 }
3569 
3570 /// Parse a SSA operand for an operation.
3571 ///
3572 ///   ssa-use ::= ssa-id
3573 ///
3574 ParseResult OperationParser::parseSSAUse(SSAUseInfo &result) {
3575   result.name = getTokenSpelling();
3576   result.number = 0;
3577   result.loc = getToken().getLoc();
3578   if (parseToken(Token::percent_identifier, "expected SSA operand"))
3579     return failure();
3580 
3581   // If we have an attribute ID, it is a result number.
3582   if (getToken().is(Token::hash_identifier)) {
3583     if (auto value = getToken().getHashIdentifierNumber())
3584       result.number = value.getValue();
3585     else
3586       return emitError("invalid SSA value result number");
3587     consumeToken(Token::hash_identifier);
3588   }
3589 
3590   return success();
3591 }
3592 
3593 /// Given an unbound reference to an SSA value and its type, return the value
3594 /// it specifies.  This returns null on failure.
3595 Value OperationParser::resolveSSAUse(SSAUseInfo useInfo, Type type) {
3596   auto &entries = getSSAValueEntry(useInfo.name);
3597 
3598   // If we have already seen a value of this name, return it.
3599   if (useInfo.number < entries.size() && entries[useInfo.number].first) {
3600     auto result = entries[useInfo.number].first;
3601     // Check that the type matches the other uses.
3602     if (result.getType() == type)
3603       return result;
3604 
3605     emitError(useInfo.loc, "use of value '")
3606         .append(useInfo.name,
3607                 "' expects different type than prior uses: ", type, " vs ",
3608                 result.getType())
3609         .attachNote(getEncodedSourceLocation(entries[useInfo.number].second))
3610         .append("prior use here");
3611     return nullptr;
3612   }
3613 
3614   // Make sure we have enough slots for this.
3615   if (entries.size() <= useInfo.number)
3616     entries.resize(useInfo.number + 1);
3617 
3618   // If the value has already been defined and this is an overly large result
3619   // number, diagnose that.
3620   if (entries[0].first && !isForwardRefPlaceholder(entries[0].first))
3621     return (emitError(useInfo.loc, "reference to invalid result number"),
3622             nullptr);
3623 
3624   // Otherwise, this is a forward reference.  Create a placeholder and remember
3625   // that we did so.
3626   auto result = createForwardRefPlaceholder(useInfo.loc, type);
3627   entries[useInfo.number].first = result;
3628   entries[useInfo.number].second = useInfo.loc;
3629   return result;
3630 }
3631 
3632 /// Parse an SSA use with an associated type.
3633 ///
3634 ///   ssa-use-and-type ::= ssa-use `:` type
3635 ParseResult OperationParser::parseSSADefOrUseAndType(
3636     const std::function<ParseResult(SSAUseInfo, Type)> &action) {
3637   SSAUseInfo useInfo;
3638   if (parseSSAUse(useInfo) ||
3639       parseToken(Token::colon, "expected ':' and type for SSA operand"))
3640     return failure();
3641 
3642   auto type = parseType();
3643   if (!type)
3644     return failure();
3645 
3646   return action(useInfo, type);
3647 }
3648 
3649 /// Parse a (possibly empty) list of SSA operands, followed by a colon, then
3650 /// followed by a type list.
3651 ///
3652 ///   ssa-use-and-type-list
3653 ///     ::= ssa-use-list ':' type-list-no-parens
3654 ///
3655 ParseResult OperationParser::parseOptionalSSAUseAndTypeList(
3656     SmallVectorImpl<Value> &results) {
3657   SmallVector<SSAUseInfo, 4> valueIDs;
3658   if (parseOptionalSSAUseList(valueIDs))
3659     return failure();
3660 
3661   // If there were no operands, then there is no colon or type lists.
3662   if (valueIDs.empty())
3663     return success();
3664 
3665   SmallVector<Type, 4> types;
3666   if (parseToken(Token::colon, "expected ':' in operand list") ||
3667       parseTypeListNoParens(types))
3668     return failure();
3669 
3670   if (valueIDs.size() != types.size())
3671     return emitError("expected ")
3672            << valueIDs.size() << " types to match operand list";
3673 
3674   results.reserve(valueIDs.size());
3675   for (unsigned i = 0, e = valueIDs.size(); i != e; ++i) {
3676     if (auto value = resolveSSAUse(valueIDs[i], types[i]))
3677       results.push_back(value);
3678     else
3679       return failure();
3680   }
3681 
3682   return success();
3683 }
3684 
3685 /// Record that a definition was added at the current scope.
3686 void OperationParser::recordDefinition(StringRef def) {
3687   isolatedNameScopes.back().recordDefinition(def);
3688 }
3689 
3690 /// Get the value entry for the given SSA name.
3691 SmallVectorImpl<std::pair<Value, SMLoc>> &
3692 OperationParser::getSSAValueEntry(StringRef name) {
3693   return isolatedNameScopes.back().values[name];
3694 }
3695 
3696 /// Create and remember a new placeholder for a forward reference.
3697 Value OperationParser::createForwardRefPlaceholder(SMLoc loc, Type type) {
3698   // Forward references are always created as operations, because we just need
3699   // something with a def/use chain.
3700   //
3701   // We create these placeholders as having an empty name, which we know
3702   // cannot be created through normal user input, allowing us to distinguish
3703   // them.
3704   auto name = OperationName("placeholder", getContext());
3705   auto *op = Operation::create(
3706       getEncodedSourceLocation(loc), name, type, /*operands=*/{},
3707       /*attributes=*/llvm::None, /*successors=*/{}, /*numRegions=*/0,
3708       /*resizableOperandList=*/false);
3709   forwardRefPlaceholders[op->getResult(0)] = loc;
3710   return op->getResult(0);
3711 }
3712 
3713 //===----------------------------------------------------------------------===//
3714 // Operation Parsing
3715 //===----------------------------------------------------------------------===//
3716 
3717 /// Parse an operation.
3718 ///
3719 ///  operation         ::= op-result-list?
3720 ///                        (generic-operation | custom-operation)
3721 ///                        trailing-location?
3722 ///  generic-operation ::= string-literal `(` ssa-use-list? `)`
3723 ///                        successor-list? (`(` region-list `)`)?
3724 ///                        attribute-dict? `:` function-type
3725 ///  custom-operation  ::= bare-id custom-operation-format
3726 ///  op-result-list    ::= op-result (`,` op-result)* `=`
3727 ///  op-result         ::= ssa-id (`:` integer-literal)
3728 ///
3729 ParseResult OperationParser::parseOperation() {
3730   auto loc = getToken().getLoc();
3731   SmallVector<std::tuple<StringRef, unsigned, SMLoc>, 1> resultIDs;
3732   size_t numExpectedResults = 0;
3733   if (getToken().is(Token::percent_identifier)) {
3734     // Parse the group of result ids.
3735     auto parseNextResult = [&]() -> ParseResult {
3736       // Parse the next result id.
3737       if (!getToken().is(Token::percent_identifier))
3738         return emitError("expected valid ssa identifier");
3739 
3740       Token nameTok = getToken();
3741       consumeToken(Token::percent_identifier);
3742 
3743       // If the next token is a ':', we parse the expected result count.
3744       size_t expectedSubResults = 1;
3745       if (consumeIf(Token::colon)) {
3746         // Check that the next token is an integer.
3747         if (!getToken().is(Token::integer))
3748           return emitError("expected integer number of results");
3749 
3750         // Check that number of results is > 0.
3751         auto val = getToken().getUInt64IntegerValue();
3752         if (!val.hasValue() || val.getValue() < 1)
3753           return emitError("expected named operation to have atleast 1 result");
3754         consumeToken(Token::integer);
3755         expectedSubResults = *val;
3756       }
3757 
3758       resultIDs.emplace_back(nameTok.getSpelling(), expectedSubResults,
3759                              nameTok.getLoc());
3760       numExpectedResults += expectedSubResults;
3761       return success();
3762     };
3763     if (parseCommaSeparatedList(parseNextResult))
3764       return failure();
3765 
3766     if (parseToken(Token::equal, "expected '=' after SSA name"))
3767       return failure();
3768   }
3769 
3770   Operation *op;
3771   if (getToken().is(Token::bare_identifier) || getToken().isKeyword())
3772     op = parseCustomOperation();
3773   else if (getToken().is(Token::string))
3774     op = parseGenericOperation();
3775   else
3776     return emitError("expected operation name in quotes");
3777 
3778   // If parsing of the basic operation failed, then this whole thing fails.
3779   if (!op)
3780     return failure();
3781 
3782   // If the operation had a name, register it.
3783   if (!resultIDs.empty()) {
3784     if (op->getNumResults() == 0)
3785       return emitError(loc, "cannot name an operation with no results");
3786     if (numExpectedResults != op->getNumResults())
3787       return emitError(loc, "operation defines ")
3788              << op->getNumResults() << " results but was provided "
3789              << numExpectedResults << " to bind";
3790 
3791     // Add definitions for each of the result groups.
3792     unsigned opResI = 0;
3793     for (std::tuple<StringRef, unsigned, SMLoc> &resIt : resultIDs) {
3794       for (unsigned subRes : llvm::seq<unsigned>(0, std::get<1>(resIt))) {
3795         if (addDefinition({std::get<0>(resIt), subRes, std::get<2>(resIt)},
3796                           op->getResult(opResI++)))
3797           return failure();
3798       }
3799     }
3800   }
3801 
3802   return success();
3803 }
3804 
3805 /// Parse a single operation successor.
3806 ///
3807 ///   successor ::= block-id
3808 ///
3809 ParseResult OperationParser::parseSuccessor(Block *&dest) {
3810   // Verify branch is identifier and get the matching block.
3811   if (!getToken().is(Token::caret_identifier))
3812     return emitError("expected block name");
3813   dest = getBlockNamed(getTokenSpelling(), getToken().getLoc());
3814   consumeToken();
3815   return success();
3816 }
3817 
3818 /// Parse a comma-separated list of operation successors in brackets.
3819 ///
3820 ///   successor-list ::= `[` successor (`,` successor )* `]`
3821 ///
3822 ParseResult
3823 OperationParser::parseSuccessors(SmallVectorImpl<Block *> &destinations) {
3824   if (parseToken(Token::l_square, "expected '['"))
3825     return failure();
3826 
3827   auto parseElt = [this, &destinations] {
3828     Block *dest;
3829     ParseResult res = parseSuccessor(dest);
3830     destinations.push_back(dest);
3831     return res;
3832   };
3833   return parseCommaSeparatedListUntil(Token::r_square, parseElt,
3834                                       /*allowEmptyList=*/false);
3835 }
3836 
3837 namespace {
3838 // RAII-style guard for cleaning up the regions in the operation state before
3839 // deleting them.  Within the parser, regions may get deleted if parsing failed,
3840 // and other errors may be present, in particular undominated uses.  This makes
3841 // sure such uses are deleted.
3842 struct CleanupOpStateRegions {
3843   ~CleanupOpStateRegions() {
3844     SmallVector<Region *, 4> regionsToClean;
3845     regionsToClean.reserve(state.regions.size());
3846     for (auto &region : state.regions)
3847       if (region)
3848         for (auto &block : *region)
3849           block.dropAllDefinedValueUses();
3850   }
3851   OperationState &state;
3852 };
3853 } // namespace
3854 
3855 Operation *OperationParser::parseGenericOperation() {
3856   // Get location information for the operation.
3857   auto srcLocation = getEncodedSourceLocation(getToken().getLoc());
3858 
3859   auto name = getToken().getStringValue();
3860   if (name.empty())
3861     return (emitError("empty operation name is invalid"), nullptr);
3862   if (name.find('\0') != StringRef::npos)
3863     return (emitError("null character not allowed in operation name"), nullptr);
3864 
3865   consumeToken(Token::string);
3866 
3867   OperationState result(srcLocation, name);
3868 
3869   // Generic operations have a resizable operation list.
3870   result.setOperandListToResizable();
3871 
3872   // Parse the operand list.
3873   SmallVector<SSAUseInfo, 8> operandInfos;
3874   if (parseToken(Token::l_paren, "expected '(' to start operand list") ||
3875       parseOptionalSSAUseList(operandInfos) ||
3876       parseToken(Token::r_paren, "expected ')' to end operand list")) {
3877     return nullptr;
3878   }
3879 
3880   // Parse the successor list.
3881   if (getToken().is(Token::l_square)) {
3882     // Check if the operation is a known terminator.
3883     const AbstractOperation *abstractOp = result.name.getAbstractOperation();
3884     if (abstractOp && !abstractOp->hasProperty(OperationProperty::Terminator))
3885       return emitError("successors in non-terminator"), nullptr;
3886 
3887     SmallVector<Block *, 2> successors;
3888     if (parseSuccessors(successors))
3889       return nullptr;
3890     result.addSuccessors(successors);
3891   }
3892 
3893   // Parse the region list.
3894   CleanupOpStateRegions guard{result};
3895   if (consumeIf(Token::l_paren)) {
3896     do {
3897       // Create temporary regions with the top level region as parent.
3898       result.regions.emplace_back(new Region(moduleOp));
3899       if (parseRegion(*result.regions.back(), /*entryArguments=*/{}))
3900         return nullptr;
3901     } while (consumeIf(Token::comma));
3902     if (parseToken(Token::r_paren, "expected ')' to end region list"))
3903       return nullptr;
3904   }
3905 
3906   if (getToken().is(Token::l_brace)) {
3907     if (parseAttributeDict(result.attributes))
3908       return nullptr;
3909   }
3910 
3911   if (parseToken(Token::colon, "expected ':' followed by operation type"))
3912     return nullptr;
3913 
3914   auto typeLoc = getToken().getLoc();
3915   auto type = parseType();
3916   if (!type)
3917     return nullptr;
3918   auto fnType = type.dyn_cast<FunctionType>();
3919   if (!fnType)
3920     return (emitError(typeLoc, "expected function type"), nullptr);
3921 
3922   result.addTypes(fnType.getResults());
3923 
3924   // Check that we have the right number of types for the operands.
3925   auto operandTypes = fnType.getInputs();
3926   if (operandTypes.size() != operandInfos.size()) {
3927     auto plural = "s"[operandInfos.size() == 1];
3928     return (emitError(typeLoc, "expected ")
3929                 << operandInfos.size() << " operand type" << plural
3930                 << " but had " << operandTypes.size(),
3931             nullptr);
3932   }
3933 
3934   // Resolve all of the operands.
3935   for (unsigned i = 0, e = operandInfos.size(); i != e; ++i) {
3936     result.operands.push_back(resolveSSAUse(operandInfos[i], operandTypes[i]));
3937     if (!result.operands.back())
3938       return nullptr;
3939   }
3940 
3941   // Parse a location if one is present.
3942   if (parseOptionalTrailingLocation(result.location))
3943     return nullptr;
3944 
3945   return opBuilder.createOperation(result);
3946 }
3947 
3948 Operation *OperationParser::parseGenericOperation(Block *insertBlock,
3949                                                   Block::iterator insertPt) {
3950   OpBuilder::InsertionGuard restoreInsertionPoint(opBuilder);
3951   opBuilder.setInsertionPoint(insertBlock, insertPt);
3952   return parseGenericOperation();
3953 }
3954 
3955 namespace {
3956 class CustomOpAsmParser : public OpAsmParser {
3957 public:
3958   CustomOpAsmParser(SMLoc nameLoc, const AbstractOperation *opDefinition,
3959                     OperationParser &parser)
3960       : nameLoc(nameLoc), opDefinition(opDefinition), parser(parser) {}
3961 
3962   /// Parse an instance of the operation described by 'opDefinition' into the
3963   /// provided operation state.
3964   ParseResult parseOperation(OperationState &opState) {
3965     if (opDefinition->parseAssembly(*this, opState))
3966       return failure();
3967     return success();
3968   }
3969 
3970   Operation *parseGenericOperation(Block *insertBlock,
3971                                    Block::iterator insertPt) final {
3972     return parser.parseGenericOperation(insertBlock, insertPt);
3973   }
3974 
3975   //===--------------------------------------------------------------------===//
3976   // Utilities
3977   //===--------------------------------------------------------------------===//
3978 
3979   /// Return if any errors were emitted during parsing.
3980   bool didEmitError() const { return emittedError; }
3981 
3982   /// Emit a diagnostic at the specified location and return failure.
3983   InFlightDiagnostic emitError(llvm::SMLoc loc, const Twine &message) override {
3984     emittedError = true;
3985     return parser.emitError(loc, "custom op '" + opDefinition->name + "' " +
3986                                      message);
3987   }
3988 
3989   llvm::SMLoc getCurrentLocation() override {
3990     return parser.getToken().getLoc();
3991   }
3992 
3993   Builder &getBuilder() const override { return parser.builder; }
3994 
3995   llvm::SMLoc getNameLoc() const override { return nameLoc; }
3996 
3997   //===--------------------------------------------------------------------===//
3998   // Token Parsing
3999   //===--------------------------------------------------------------------===//
4000 
4001   /// Parse a `->` token.
4002   ParseResult parseArrow() override {
4003     return parser.parseToken(Token::arrow, "expected '->'");
4004   }
4005 
4006   /// Parses a `->` if present.
4007   ParseResult parseOptionalArrow() override {
4008     return success(parser.consumeIf(Token::arrow));
4009   }
4010 
4011   /// Parse a `:` token.
4012   ParseResult parseColon() override {
4013     return parser.parseToken(Token::colon, "expected ':'");
4014   }
4015 
4016   /// Parse a `:` token if present.
4017   ParseResult parseOptionalColon() override {
4018     return success(parser.consumeIf(Token::colon));
4019   }
4020 
4021   /// Parse a `,` token.
4022   ParseResult parseComma() override {
4023     return parser.parseToken(Token::comma, "expected ','");
4024   }
4025 
4026   /// Parse a `,` token if present.
4027   ParseResult parseOptionalComma() override {
4028     return success(parser.consumeIf(Token::comma));
4029   }
4030 
4031   /// Parses a `...` if present.
4032   ParseResult parseOptionalEllipsis() override {
4033     return success(parser.consumeIf(Token::ellipsis));
4034   }
4035 
4036   /// Parse a `=` token.
4037   ParseResult parseEqual() override {
4038     return parser.parseToken(Token::equal, "expected '='");
4039   }
4040 
4041   /// Parse a '<' token.
4042   ParseResult parseLess() override {
4043     return parser.parseToken(Token::less, "expected '<'");
4044   }
4045 
4046   /// Parse a '>' token.
4047   ParseResult parseGreater() override {
4048     return parser.parseToken(Token::greater, "expected '>'");
4049   }
4050 
4051   /// Parse a `(` token.
4052   ParseResult parseLParen() override {
4053     return parser.parseToken(Token::l_paren, "expected '('");
4054   }
4055 
4056   /// Parses a '(' if present.
4057   ParseResult parseOptionalLParen() override {
4058     return success(parser.consumeIf(Token::l_paren));
4059   }
4060 
4061   /// Parse a `)` token.
4062   ParseResult parseRParen() override {
4063     return parser.parseToken(Token::r_paren, "expected ')'");
4064   }
4065 
4066   /// Parses a ')' if present.
4067   ParseResult parseOptionalRParen() override {
4068     return success(parser.consumeIf(Token::r_paren));
4069   }
4070 
4071   /// Parse a `[` token.
4072   ParseResult parseLSquare() override {
4073     return parser.parseToken(Token::l_square, "expected '['");
4074   }
4075 
4076   /// Parses a '[' if present.
4077   ParseResult parseOptionalLSquare() override {
4078     return success(parser.consumeIf(Token::l_square));
4079   }
4080 
4081   /// Parse a `]` token.
4082   ParseResult parseRSquare() override {
4083     return parser.parseToken(Token::r_square, "expected ']'");
4084   }
4085 
4086   /// Parses a ']' if present.
4087   ParseResult parseOptionalRSquare() override {
4088     return success(parser.consumeIf(Token::r_square));
4089   }
4090 
4091   //===--------------------------------------------------------------------===//
4092   // Attribute Parsing
4093   //===--------------------------------------------------------------------===//
4094 
4095   /// Parse an arbitrary attribute of a given type and return it in result. This
4096   /// also adds the attribute to the specified attribute list with the specified
4097   /// name.
4098   ParseResult parseAttribute(Attribute &result, Type type, StringRef attrName,
4099                              SmallVectorImpl<NamedAttribute> &attrs) override {
4100     result = parser.parseAttribute(type);
4101     if (!result)
4102       return failure();
4103 
4104     attrs.push_back(parser.builder.getNamedAttr(attrName, result));
4105     return success();
4106   }
4107 
4108   /// Parse a named dictionary into 'result' if it is present.
4109   ParseResult
4110   parseOptionalAttrDict(SmallVectorImpl<NamedAttribute> &result) override {
4111     if (parser.getToken().isNot(Token::l_brace))
4112       return success();
4113     return parser.parseAttributeDict(result);
4114   }
4115 
4116   /// Parse a named dictionary into 'result' if the `attributes` keyword is
4117   /// present.
4118   ParseResult parseOptionalAttrDictWithKeyword(
4119       SmallVectorImpl<NamedAttribute> &result) override {
4120     if (failed(parseOptionalKeyword("attributes")))
4121       return success();
4122     return parser.parseAttributeDict(result);
4123   }
4124 
4125   /// Parse an affine map instance into 'map'.
4126   ParseResult parseAffineMap(AffineMap &map) override {
4127     return parser.parseAffineMapReference(map);
4128   }
4129 
4130   /// Parse an integer set instance into 'set'.
4131   ParseResult printIntegerSet(IntegerSet &set) override {
4132     return parser.parseIntegerSetReference(set);
4133   }
4134 
4135   //===--------------------------------------------------------------------===//
4136   // Identifier Parsing
4137   //===--------------------------------------------------------------------===//
4138 
4139   /// Returns if the current token corresponds to a keyword.
4140   bool isCurrentTokenAKeyword() const {
4141     return parser.getToken().is(Token::bare_identifier) ||
4142            parser.getToken().isKeyword();
4143   }
4144 
4145   /// Parse the given keyword if present.
4146   ParseResult parseOptionalKeyword(StringRef keyword) override {
4147     // Check that the current token has the same spelling.
4148     if (!isCurrentTokenAKeyword() || parser.getTokenSpelling() != keyword)
4149       return failure();
4150     parser.consumeToken();
4151     return success();
4152   }
4153 
4154   /// Parse a keyword, if present, into 'keyword'.
4155   ParseResult parseOptionalKeyword(StringRef *keyword) override {
4156     // Check that the current token is a keyword.
4157     if (!isCurrentTokenAKeyword())
4158       return failure();
4159 
4160     *keyword = parser.getTokenSpelling();
4161     parser.consumeToken();
4162     return success();
4163   }
4164 
4165   /// Parse an optional @-identifier and store it (without the '@' symbol) in a
4166   /// string attribute named 'attrName'.
4167   ParseResult
4168   parseOptionalSymbolName(StringAttr &result, StringRef attrName,
4169                           SmallVectorImpl<NamedAttribute> &attrs) override {
4170     Token atToken = parser.getToken();
4171     if (atToken.isNot(Token::at_identifier))
4172       return failure();
4173 
4174     result = getBuilder().getStringAttr(extractSymbolReference(atToken));
4175     attrs.push_back(getBuilder().getNamedAttr(attrName, result));
4176     parser.consumeToken();
4177     return success();
4178   }
4179 
4180   //===--------------------------------------------------------------------===//
4181   // Operand Parsing
4182   //===--------------------------------------------------------------------===//
4183 
4184   /// Parse a single operand.
4185   ParseResult parseOperand(OperandType &result) override {
4186     OperationParser::SSAUseInfo useInfo;
4187     if (parser.parseSSAUse(useInfo))
4188       return failure();
4189 
4190     result = {useInfo.loc, useInfo.name, useInfo.number};
4191     return success();
4192   }
4193 
4194   /// Parse zero or more SSA comma-separated operand references with a specified
4195   /// surrounding delimiter, and an optional required operand count.
4196   ParseResult parseOperandList(SmallVectorImpl<OperandType> &result,
4197                                int requiredOperandCount = -1,
4198                                Delimiter delimiter = Delimiter::None) override {
4199     return parseOperandOrRegionArgList(result, /*isOperandList=*/true,
4200                                        requiredOperandCount, delimiter);
4201   }
4202 
4203   /// Parse zero or more SSA comma-separated operand or region arguments with
4204   ///  optional surrounding delimiter and required operand count.
4205   ParseResult
4206   parseOperandOrRegionArgList(SmallVectorImpl<OperandType> &result,
4207                               bool isOperandList, int requiredOperandCount = -1,
4208                               Delimiter delimiter = Delimiter::None) {
4209     auto startLoc = parser.getToken().getLoc();
4210 
4211     // Handle delimiters.
4212     switch (delimiter) {
4213     case Delimiter::None:
4214       // Don't check for the absence of a delimiter if the number of operands
4215       // is unknown (and hence the operand list could be empty).
4216       if (requiredOperandCount == -1)
4217         break;
4218       // Token already matches an identifier and so can't be a delimiter.
4219       if (parser.getToken().is(Token::percent_identifier))
4220         break;
4221       // Test against known delimiters.
4222       if (parser.getToken().is(Token::l_paren) ||
4223           parser.getToken().is(Token::l_square))
4224         return emitError(startLoc, "unexpected delimiter");
4225       return emitError(startLoc, "invalid operand");
4226     case Delimiter::OptionalParen:
4227       if (parser.getToken().isNot(Token::l_paren))
4228         return success();
4229       LLVM_FALLTHROUGH;
4230     case Delimiter::Paren:
4231       if (parser.parseToken(Token::l_paren, "expected '(' in operand list"))
4232         return failure();
4233       break;
4234     case Delimiter::OptionalSquare:
4235       if (parser.getToken().isNot(Token::l_square))
4236         return success();
4237       LLVM_FALLTHROUGH;
4238     case Delimiter::Square:
4239       if (parser.parseToken(Token::l_square, "expected '[' in operand list"))
4240         return failure();
4241       break;
4242     }
4243 
4244     // Check for zero operands.
4245     if (parser.getToken().is(Token::percent_identifier)) {
4246       do {
4247         OperandType operandOrArg;
4248         if (isOperandList ? parseOperand(operandOrArg)
4249                           : parseRegionArgument(operandOrArg))
4250           return failure();
4251         result.push_back(operandOrArg);
4252       } while (parser.consumeIf(Token::comma));
4253     }
4254 
4255     // Handle delimiters.   If we reach here, the optional delimiters were
4256     // present, so we need to parse their closing one.
4257     switch (delimiter) {
4258     case Delimiter::None:
4259       break;
4260     case Delimiter::OptionalParen:
4261     case Delimiter::Paren:
4262       if (parser.parseToken(Token::r_paren, "expected ')' in operand list"))
4263         return failure();
4264       break;
4265     case Delimiter::OptionalSquare:
4266     case Delimiter::Square:
4267       if (parser.parseToken(Token::r_square, "expected ']' in operand list"))
4268         return failure();
4269       break;
4270     }
4271 
4272     if (requiredOperandCount != -1 &&
4273         result.size() != static_cast<size_t>(requiredOperandCount))
4274       return emitError(startLoc, "expected ")
4275              << requiredOperandCount << " operands";
4276     return success();
4277   }
4278 
4279   /// Parse zero or more trailing SSA comma-separated trailing operand
4280   /// references with a specified surrounding delimiter, and an optional
4281   /// required operand count. A leading comma is expected before the operands.
4282   ParseResult parseTrailingOperandList(SmallVectorImpl<OperandType> &result,
4283                                        int requiredOperandCount,
4284                                        Delimiter delimiter) override {
4285     if (parser.getToken().is(Token::comma)) {
4286       parseComma();
4287       return parseOperandList(result, requiredOperandCount, delimiter);
4288     }
4289     if (requiredOperandCount != -1)
4290       return emitError(parser.getToken().getLoc(), "expected ")
4291              << requiredOperandCount << " operands";
4292     return success();
4293   }
4294 
4295   /// Resolve an operand to an SSA value, emitting an error on failure.
4296   ParseResult resolveOperand(const OperandType &operand, Type type,
4297                              SmallVectorImpl<Value> &result) override {
4298     OperationParser::SSAUseInfo operandInfo = {operand.name, operand.number,
4299                                                operand.location};
4300     if (auto value = parser.resolveSSAUse(operandInfo, type)) {
4301       result.push_back(value);
4302       return success();
4303     }
4304     return failure();
4305   }
4306 
4307   /// Parse an AffineMap of SSA ids.
4308   ParseResult parseAffineMapOfSSAIds(SmallVectorImpl<OperandType> &operands,
4309                                      Attribute &mapAttr, StringRef attrName,
4310                                      SmallVectorImpl<NamedAttribute> &attrs,
4311                                      Delimiter delimiter) override {
4312     SmallVector<OperandType, 2> dimOperands;
4313     SmallVector<OperandType, 1> symOperands;
4314 
4315     auto parseElement = [&](bool isSymbol) -> ParseResult {
4316       OperandType operand;
4317       if (parseOperand(operand))
4318         return failure();
4319       if (isSymbol)
4320         symOperands.push_back(operand);
4321       else
4322         dimOperands.push_back(operand);
4323       return success();
4324     };
4325 
4326     AffineMap map;
4327     if (parser.parseAffineMapOfSSAIds(map, parseElement, delimiter))
4328       return failure();
4329     // Add AffineMap attribute.
4330     if (map) {
4331       mapAttr = AffineMapAttr::get(map);
4332       attrs.push_back(parser.builder.getNamedAttr(attrName, mapAttr));
4333     }
4334 
4335     // Add dim operands before symbol operands in 'operands'.
4336     operands.assign(dimOperands.begin(), dimOperands.end());
4337     operands.append(symOperands.begin(), symOperands.end());
4338     return success();
4339   }
4340 
4341   //===--------------------------------------------------------------------===//
4342   // Region Parsing
4343   //===--------------------------------------------------------------------===//
4344 
4345   /// Parse a region that takes `arguments` of `argTypes` types.  This
4346   /// effectively defines the SSA values of `arguments` and assigns their type.
4347   ParseResult parseRegion(Region &region, ArrayRef<OperandType> arguments,
4348                           ArrayRef<Type> argTypes,
4349                           bool enableNameShadowing) override {
4350     assert(arguments.size() == argTypes.size() &&
4351            "mismatching number of arguments and types");
4352 
4353     SmallVector<std::pair<OperationParser::SSAUseInfo, Type>, 2>
4354         regionArguments;
4355     for (auto pair : llvm::zip(arguments, argTypes)) {
4356       const OperandType &operand = std::get<0>(pair);
4357       Type type = std::get<1>(pair);
4358       OperationParser::SSAUseInfo operandInfo = {operand.name, operand.number,
4359                                                  operand.location};
4360       regionArguments.emplace_back(operandInfo, type);
4361     }
4362 
4363     // Try to parse the region.
4364     assert((!enableNameShadowing ||
4365             opDefinition->hasProperty(OperationProperty::IsolatedFromAbove)) &&
4366            "name shadowing is only allowed on isolated regions");
4367     if (parser.parseRegion(region, regionArguments, enableNameShadowing))
4368       return failure();
4369     return success();
4370   }
4371 
4372   /// Parses a region if present.
4373   ParseResult parseOptionalRegion(Region &region,
4374                                   ArrayRef<OperandType> arguments,
4375                                   ArrayRef<Type> argTypes,
4376                                   bool enableNameShadowing) override {
4377     if (parser.getToken().isNot(Token::l_brace))
4378       return success();
4379     return parseRegion(region, arguments, argTypes, enableNameShadowing);
4380   }
4381 
4382   /// Parse a region argument. The type of the argument will be resolved later
4383   /// by a call to `parseRegion`.
4384   ParseResult parseRegionArgument(OperandType &argument) override {
4385     return parseOperand(argument);
4386   }
4387 
4388   /// Parse a region argument if present.
4389   ParseResult parseOptionalRegionArgument(OperandType &argument) override {
4390     if (parser.getToken().isNot(Token::percent_identifier))
4391       return success();
4392     return parseRegionArgument(argument);
4393   }
4394 
4395   ParseResult
4396   parseRegionArgumentList(SmallVectorImpl<OperandType> &result,
4397                           int requiredOperandCount = -1,
4398                           Delimiter delimiter = Delimiter::None) override {
4399     return parseOperandOrRegionArgList(result, /*isOperandList=*/false,
4400                                        requiredOperandCount, delimiter);
4401   }
4402 
4403   //===--------------------------------------------------------------------===//
4404   // Successor Parsing
4405   //===--------------------------------------------------------------------===//
4406 
4407   /// Parse a single operation successor.
4408   ParseResult parseSuccessor(Block *&dest) override {
4409     return parser.parseSuccessor(dest);
4410   }
4411 
4412   /// Parse an optional operation successor and its operand list.
4413   OptionalParseResult parseOptionalSuccessor(Block *&dest) override {
4414     if (parser.getToken().isNot(Token::caret_identifier))
4415       return llvm::None;
4416     return parseSuccessor(dest);
4417   }
4418 
4419   /// Parse a single operation successor and its operand list.
4420   ParseResult
4421   parseSuccessorAndUseList(Block *&dest,
4422                            SmallVectorImpl<Value> &operands) override {
4423     if (parseSuccessor(dest))
4424       return failure();
4425 
4426     // Handle optional arguments.
4427     if (succeeded(parseOptionalLParen()) &&
4428         (parser.parseOptionalSSAUseAndTypeList(operands) || parseRParen())) {
4429       return failure();
4430     }
4431     return success();
4432   }
4433 
4434   //===--------------------------------------------------------------------===//
4435   // Type Parsing
4436   //===--------------------------------------------------------------------===//
4437 
4438   /// Parse a type.
4439   ParseResult parseType(Type &result) override {
4440     return failure(!(result = parser.parseType()));
4441   }
4442 
4443   /// Parse an arrow followed by a type list.
4444   ParseResult parseArrowTypeList(SmallVectorImpl<Type> &result) override {
4445     if (parseArrow() || parser.parseFunctionResultTypes(result))
4446       return failure();
4447     return success();
4448   }
4449 
4450   /// Parse an optional arrow followed by a type list.
4451   ParseResult
4452   parseOptionalArrowTypeList(SmallVectorImpl<Type> &result) override {
4453     if (!parser.consumeIf(Token::arrow))
4454       return success();
4455     return parser.parseFunctionResultTypes(result);
4456   }
4457 
4458   /// Parse a colon followed by a type.
4459   ParseResult parseColonType(Type &result) override {
4460     return failure(parser.parseToken(Token::colon, "expected ':'") ||
4461                    !(result = parser.parseType()));
4462   }
4463 
4464   /// Parse a colon followed by a type list, which must have at least one type.
4465   ParseResult parseColonTypeList(SmallVectorImpl<Type> &result) override {
4466     if (parser.parseToken(Token::colon, "expected ':'"))
4467       return failure();
4468     return parser.parseTypeListNoParens(result);
4469   }
4470 
4471   /// Parse an optional colon followed by a type list, which if present must
4472   /// have at least one type.
4473   ParseResult
4474   parseOptionalColonTypeList(SmallVectorImpl<Type> &result) override {
4475     if (!parser.consumeIf(Token::colon))
4476       return success();
4477     return parser.parseTypeListNoParens(result);
4478   }
4479 
4480   /// Parse a list of assignments of the form
4481   /// (%x1 = %y1 : type1, %x2 = %y2 : type2, ...).
4482   /// The list must contain at least one entry
4483   ParseResult parseAssignmentList(SmallVectorImpl<OperandType> &lhs,
4484                                   SmallVectorImpl<OperandType> &rhs) override {
4485     auto parseElt = [&]() -> ParseResult {
4486       OperandType regionArg, operand;
4487       if (parseRegionArgument(regionArg) || parseEqual() ||
4488           parseOperand(operand))
4489         return failure();
4490       lhs.push_back(regionArg);
4491       rhs.push_back(operand);
4492       return success();
4493     };
4494     if (parseLParen())
4495       return failure();
4496     return parser.parseCommaSeparatedListUntil(Token::r_paren, parseElt);
4497   }
4498 
4499 private:
4500   /// The source location of the operation name.
4501   SMLoc nameLoc;
4502 
4503   /// The abstract information of the operation.
4504   const AbstractOperation *opDefinition;
4505 
4506   /// The main operation parser.
4507   OperationParser &parser;
4508 
4509   /// A flag that indicates if any errors were emitted during parsing.
4510   bool emittedError = false;
4511 };
4512 } // end anonymous namespace.
4513 
4514 Operation *OperationParser::parseCustomOperation() {
4515   auto opLoc = getToken().getLoc();
4516   auto opName = getTokenSpelling();
4517 
4518   auto *opDefinition = AbstractOperation::lookup(opName, getContext());
4519   if (!opDefinition && !opName.contains('.')) {
4520     // If the operation name has no namespace prefix we treat it as a standard
4521     // operation and prefix it with "std".
4522     // TODO: Would it be better to just build a mapping of the registered
4523     // operations in the standard dialect?
4524     opDefinition =
4525         AbstractOperation::lookup(Twine("std." + opName).str(), getContext());
4526   }
4527 
4528   if (!opDefinition) {
4529     emitError(opLoc) << "custom op '" << opName << "' is unknown";
4530     return nullptr;
4531   }
4532 
4533   consumeToken();
4534 
4535   // If the custom op parser crashes, produce some indication to help
4536   // debugging.
4537   std::string opNameStr = opName.str();
4538   llvm::PrettyStackTraceFormat fmt("MLIR Parser: custom op parser '%s'",
4539                                    opNameStr.c_str());
4540 
4541   // Get location information for the operation.
4542   auto srcLocation = getEncodedSourceLocation(opLoc);
4543 
4544   // Have the op implementation take a crack and parsing this.
4545   OperationState opState(srcLocation, opDefinition->name);
4546   CleanupOpStateRegions guard{opState};
4547   CustomOpAsmParser opAsmParser(opLoc, opDefinition, *this);
4548   if (opAsmParser.parseOperation(opState))
4549     return nullptr;
4550 
4551   // If it emitted an error, we failed.
4552   if (opAsmParser.didEmitError())
4553     return nullptr;
4554 
4555   // Parse a location if one is present.
4556   if (parseOptionalTrailingLocation(opState.location))
4557     return nullptr;
4558 
4559   // Otherwise, we succeeded.  Use the state it parsed as our op information.
4560   return opBuilder.createOperation(opState);
4561 }
4562 
4563 //===----------------------------------------------------------------------===//
4564 // Region Parsing
4565 //===----------------------------------------------------------------------===//
4566 
4567 /// Region.
4568 ///
4569 ///   region ::= '{' region-body
4570 ///
4571 ParseResult OperationParser::parseRegion(
4572     Region &region,
4573     ArrayRef<std::pair<OperationParser::SSAUseInfo, Type>> entryArguments,
4574     bool isIsolatedNameScope) {
4575   // Parse the '{'.
4576   if (parseToken(Token::l_brace, "expected '{' to begin a region"))
4577     return failure();
4578 
4579   // Check for an empty region.
4580   if (entryArguments.empty() && consumeIf(Token::r_brace))
4581     return success();
4582   auto currentPt = opBuilder.saveInsertionPoint();
4583 
4584   // Push a new named value scope.
4585   pushSSANameScope(isIsolatedNameScope);
4586 
4587   // Parse the first block directly to allow for it to be unnamed.
4588   Block *block = new Block();
4589 
4590   // Add arguments to the entry block.
4591   if (!entryArguments.empty()) {
4592     for (auto &placeholderArgPair : entryArguments) {
4593       auto &argInfo = placeholderArgPair.first;
4594       // Ensure that the argument was not already defined.
4595       if (auto defLoc = getReferenceLoc(argInfo.name, argInfo.number)) {
4596         return emitError(argInfo.loc, "region entry argument '" + argInfo.name +
4597                                           "' is already in use")
4598                    .attachNote(getEncodedSourceLocation(*defLoc))
4599                << "previously referenced here";
4600       }
4601       if (addDefinition(placeholderArgPair.first,
4602                         block->addArgument(placeholderArgPair.second))) {
4603         delete block;
4604         return failure();
4605       }
4606     }
4607 
4608     // If we had named arguments, then don't allow a block name.
4609     if (getToken().is(Token::caret_identifier))
4610       return emitError("invalid block name in region with named arguments");
4611   }
4612 
4613   if (parseBlock(block)) {
4614     delete block;
4615     return failure();
4616   }
4617 
4618   // Verify that no other arguments were parsed.
4619   if (!entryArguments.empty() &&
4620       block->getNumArguments() > entryArguments.size()) {
4621     delete block;
4622     return emitError("entry block arguments were already defined");
4623   }
4624 
4625   // Parse the rest of the region.
4626   region.push_back(block);
4627   if (parseRegionBody(region))
4628     return failure();
4629 
4630   // Pop the SSA value scope for this region.
4631   if (popSSANameScope())
4632     return failure();
4633 
4634   // Reset the original insertion point.
4635   opBuilder.restoreInsertionPoint(currentPt);
4636   return success();
4637 }
4638 
4639 /// Region.
4640 ///
4641 ///   region-body ::= block* '}'
4642 ///
4643 ParseResult OperationParser::parseRegionBody(Region &region) {
4644   // Parse the list of blocks.
4645   while (!consumeIf(Token::r_brace)) {
4646     Block *newBlock = nullptr;
4647     if (parseBlock(newBlock))
4648       return failure();
4649     region.push_back(newBlock);
4650   }
4651   return success();
4652 }
4653 
4654 //===----------------------------------------------------------------------===//
4655 // Block Parsing
4656 //===----------------------------------------------------------------------===//
4657 
4658 /// Block declaration.
4659 ///
4660 ///   block ::= block-label? operation*
4661 ///   block-label    ::= block-id block-arg-list? `:`
4662 ///   block-id       ::= caret-id
4663 ///   block-arg-list ::= `(` ssa-id-and-type-list? `)`
4664 ///
4665 ParseResult OperationParser::parseBlock(Block *&block) {
4666   // The first block of a region may already exist, if it does the caret
4667   // identifier is optional.
4668   if (block && getToken().isNot(Token::caret_identifier))
4669     return parseBlockBody(block);
4670 
4671   SMLoc nameLoc = getToken().getLoc();
4672   auto name = getTokenSpelling();
4673   if (parseToken(Token::caret_identifier, "expected block name"))
4674     return failure();
4675 
4676   block = defineBlockNamed(name, nameLoc, block);
4677 
4678   // Fail if the block was already defined.
4679   if (!block)
4680     return emitError(nameLoc, "redefinition of block '") << name << "'";
4681 
4682   // If an argument list is present, parse it.
4683   if (consumeIf(Token::l_paren)) {
4684     SmallVector<BlockArgument, 8> bbArgs;
4685     if (parseOptionalBlockArgList(bbArgs, block) ||
4686         parseToken(Token::r_paren, "expected ')' to end argument list"))
4687       return failure();
4688   }
4689 
4690   if (parseToken(Token::colon, "expected ':' after block name"))
4691     return failure();
4692 
4693   return parseBlockBody(block);
4694 }
4695 
4696 ParseResult OperationParser::parseBlockBody(Block *block) {
4697   // Set the insertion point to the end of the block to parse.
4698   opBuilder.setInsertionPointToEnd(block);
4699 
4700   // Parse the list of operations that make up the body of the block.
4701   while (getToken().isNot(Token::caret_identifier, Token::r_brace))
4702     if (parseOperation())
4703       return failure();
4704 
4705   return success();
4706 }
4707 
4708 /// Get the block with the specified name, creating it if it doesn't already
4709 /// exist.  The location specified is the point of use, which allows
4710 /// us to diagnose references to blocks that are not defined precisely.
4711 Block *OperationParser::getBlockNamed(StringRef name, SMLoc loc) {
4712   auto &blockAndLoc = getBlockInfoByName(name);
4713   if (!blockAndLoc.first) {
4714     blockAndLoc = {new Block(), loc};
4715     insertForwardRef(blockAndLoc.first, loc);
4716   }
4717 
4718   return blockAndLoc.first;
4719 }
4720 
4721 /// Define the block with the specified name. Returns the Block* or nullptr in
4722 /// the case of redefinition.
4723 Block *OperationParser::defineBlockNamed(StringRef name, SMLoc loc,
4724                                          Block *existing) {
4725   auto &blockAndLoc = getBlockInfoByName(name);
4726   if (!blockAndLoc.first) {
4727     // If the caller provided a block, use it.  Otherwise create a new one.
4728     if (!existing)
4729       existing = new Block();
4730     blockAndLoc.first = existing;
4731     blockAndLoc.second = loc;
4732     return blockAndLoc.first;
4733   }
4734 
4735   // Forward declarations are removed once defined, so if we are defining a
4736   // existing block and it is not a forward declaration, then it is a
4737   // redeclaration.
4738   if (!eraseForwardRef(blockAndLoc.first))
4739     return nullptr;
4740   return blockAndLoc.first;
4741 }
4742 
4743 /// Parse a (possibly empty) list of SSA operands with types as block arguments.
4744 ///
4745 ///   ssa-id-and-type-list ::= ssa-id-and-type (`,` ssa-id-and-type)*
4746 ///
4747 ParseResult OperationParser::parseOptionalBlockArgList(
4748     SmallVectorImpl<BlockArgument> &results, Block *owner) {
4749   if (getToken().is(Token::r_brace))
4750     return success();
4751 
4752   // If the block already has arguments, then we're handling the entry block.
4753   // Parse and register the names for the arguments, but do not add them.
4754   bool definingExistingArgs = owner->getNumArguments() != 0;
4755   unsigned nextArgument = 0;
4756 
4757   return parseCommaSeparatedList([&]() -> ParseResult {
4758     return parseSSADefOrUseAndType(
4759         [&](SSAUseInfo useInfo, Type type) -> ParseResult {
4760           // If this block did not have existing arguments, define a new one.
4761           if (!definingExistingArgs)
4762             return addDefinition(useInfo, owner->addArgument(type));
4763 
4764           // Otherwise, ensure that this argument has already been created.
4765           if (nextArgument >= owner->getNumArguments())
4766             return emitError("too many arguments specified in argument list");
4767 
4768           // Finally, make sure the existing argument has the correct type.
4769           auto arg = owner->getArgument(nextArgument++);
4770           if (arg.getType() != type)
4771             return emitError("argument and block argument type mismatch");
4772           return addDefinition(useInfo, arg);
4773         });
4774   });
4775 }
4776 
4777 //===----------------------------------------------------------------------===//
4778 // Top-level entity parsing.
4779 //===----------------------------------------------------------------------===//
4780 
4781 namespace {
4782 /// This parser handles entities that are only valid at the top level of the
4783 /// file.
4784 class ModuleParser : public Parser {
4785 public:
4786   explicit ModuleParser(ParserState &state) : Parser(state) {}
4787 
4788   ParseResult parseModule(ModuleOp module);
4789 
4790 private:
4791   /// Parse an attribute alias declaration.
4792   ParseResult parseAttributeAliasDef();
4793 
4794   /// Parse an attribute alias declaration.
4795   ParseResult parseTypeAliasDef();
4796 };
4797 } // end anonymous namespace
4798 
4799 /// Parses an attribute alias declaration.
4800 ///
4801 ///   attribute-alias-def ::= '#' alias-name `=` attribute-value
4802 ///
4803 ParseResult ModuleParser::parseAttributeAliasDef() {
4804   assert(getToken().is(Token::hash_identifier));
4805   StringRef aliasName = getTokenSpelling().drop_front();
4806 
4807   // Check for redefinitions.
4808   if (getState().symbols.attributeAliasDefinitions.count(aliasName) > 0)
4809     return emitError("redefinition of attribute alias id '" + aliasName + "'");
4810 
4811   // Make sure this isn't invading the dialect attribute namespace.
4812   if (aliasName.contains('.'))
4813     return emitError("attribute names with a '.' are reserved for "
4814                      "dialect-defined names");
4815 
4816   consumeToken(Token::hash_identifier);
4817 
4818   // Parse the '='.
4819   if (parseToken(Token::equal, "expected '=' in attribute alias definition"))
4820     return failure();
4821 
4822   // Parse the attribute value.
4823   Attribute attr = parseAttribute();
4824   if (!attr)
4825     return failure();
4826 
4827   getState().symbols.attributeAliasDefinitions[aliasName] = attr;
4828   return success();
4829 }
4830 
4831 /// Parse a type alias declaration.
4832 ///
4833 ///   type-alias-def ::= '!' alias-name `=` 'type' type
4834 ///
4835 ParseResult ModuleParser::parseTypeAliasDef() {
4836   assert(getToken().is(Token::exclamation_identifier));
4837   StringRef aliasName = getTokenSpelling().drop_front();
4838 
4839   // Check for redefinitions.
4840   if (getState().symbols.typeAliasDefinitions.count(aliasName) > 0)
4841     return emitError("redefinition of type alias id '" + aliasName + "'");
4842 
4843   // Make sure this isn't invading the dialect type namespace.
4844   if (aliasName.contains('.'))
4845     return emitError("type names with a '.' are reserved for "
4846                      "dialect-defined names");
4847 
4848   consumeToken(Token::exclamation_identifier);
4849 
4850   // Parse the '=' and 'type'.
4851   if (parseToken(Token::equal, "expected '=' in type alias definition") ||
4852       parseToken(Token::kw_type, "expected 'type' in type alias definition"))
4853     return failure();
4854 
4855   // Parse the type.
4856   Type aliasedType = parseType();
4857   if (!aliasedType)
4858     return failure();
4859 
4860   // Register this alias with the parser state.
4861   getState().symbols.typeAliasDefinitions.try_emplace(aliasName, aliasedType);
4862   return success();
4863 }
4864 
4865 /// This is the top-level module parser.
4866 ParseResult ModuleParser::parseModule(ModuleOp module) {
4867   OperationParser opParser(getState(), module);
4868 
4869   // Module itself is a name scope.
4870   opParser.pushSSANameScope(/*isIsolated=*/true);
4871 
4872   while (true) {
4873     switch (getToken().getKind()) {
4874     default:
4875       // Parse a top-level operation.
4876       if (opParser.parseOperation())
4877         return failure();
4878       break;
4879 
4880     // If we got to the end of the file, then we're done.
4881     case Token::eof: {
4882       if (opParser.finalize())
4883         return failure();
4884 
4885       // Handle the case where the top level module was explicitly defined.
4886       auto &bodyBlocks = module.getBodyRegion().getBlocks();
4887       auto &operations = bodyBlocks.front().getOperations();
4888       assert(!operations.empty() && "expected a valid module terminator");
4889 
4890       // Check that the first operation is a module, and it is the only
4891       // non-terminator operation.
4892       ModuleOp nested = dyn_cast<ModuleOp>(operations.front());
4893       if (nested && std::next(operations.begin(), 2) == operations.end()) {
4894         // Merge the data of the nested module operation into 'module'.
4895         module.setLoc(nested.getLoc());
4896         module.setAttrs(nested.getOperation()->getAttrList());
4897         bodyBlocks.splice(bodyBlocks.end(), nested.getBodyRegion().getBlocks());
4898 
4899         // Erase the original module body.
4900         bodyBlocks.pop_front();
4901       }
4902 
4903       return opParser.popSSANameScope();
4904     }
4905 
4906     // If we got an error token, then the lexer already emitted an error, just
4907     // stop.  Someday we could introduce error recovery if there was demand
4908     // for it.
4909     case Token::error:
4910       return failure();
4911 
4912     // Parse an attribute alias.
4913     case Token::hash_identifier:
4914       if (parseAttributeAliasDef())
4915         return failure();
4916       break;
4917 
4918     // Parse a type alias.
4919     case Token::exclamation_identifier:
4920       if (parseTypeAliasDef())
4921         return failure();
4922       break;
4923     }
4924   }
4925 }
4926 
4927 //===----------------------------------------------------------------------===//
4928 
4929 /// This parses the file specified by the indicated SourceMgr and returns an
4930 /// MLIR module if it was valid.  If not, it emits diagnostics and returns
4931 /// null.
4932 OwningModuleRef mlir::parseSourceFile(const llvm::SourceMgr &sourceMgr,
4933                                       MLIRContext *context) {
4934   auto sourceBuf = sourceMgr.getMemoryBuffer(sourceMgr.getMainFileID());
4935 
4936   // This is the result module we are parsing into.
4937   OwningModuleRef module(ModuleOp::create(FileLineColLoc::get(
4938       sourceBuf->getBufferIdentifier(), /*line=*/0, /*column=*/0, context)));
4939 
4940   SymbolState aliasState;
4941   ParserState state(sourceMgr, context, aliasState);
4942   if (ModuleParser(state).parseModule(*module))
4943     return nullptr;
4944 
4945   // Make sure the parse module has no other structural problems detected by
4946   // the verifier.
4947   if (failed(verify(*module)))
4948     return nullptr;
4949 
4950   return module;
4951 }
4952 
4953 /// This parses the file specified by the indicated filename and returns an
4954 /// MLIR module if it was valid.  If not, the error message is emitted through
4955 /// the error handler registered in the context, and a null pointer is returned.
4956 OwningModuleRef mlir::parseSourceFile(StringRef filename,
4957                                       MLIRContext *context) {
4958   llvm::SourceMgr sourceMgr;
4959   return parseSourceFile(filename, sourceMgr, context);
4960 }
4961 
4962 /// This parses the file specified by the indicated filename using the provided
4963 /// SourceMgr and returns an MLIR module if it was valid.  If not, the error
4964 /// message is emitted through the error handler registered in the context, and
4965 /// a null pointer is returned.
4966 OwningModuleRef mlir::parseSourceFile(StringRef filename,
4967                                       llvm::SourceMgr &sourceMgr,
4968                                       MLIRContext *context) {
4969   if (sourceMgr.getNumBuffers() != 0) {
4970     // TODO(b/136086478): Extend to support multiple buffers.
4971     emitError(mlir::UnknownLoc::get(context),
4972               "only main buffer parsed at the moment");
4973     return nullptr;
4974   }
4975   auto file_or_err = llvm::MemoryBuffer::getFileOrSTDIN(filename);
4976   if (std::error_code error = file_or_err.getError()) {
4977     emitError(mlir::UnknownLoc::get(context),
4978               "could not open input file " + filename);
4979     return nullptr;
4980   }
4981 
4982   // Load the MLIR module.
4983   sourceMgr.AddNewSourceBuffer(std::move(*file_or_err), llvm::SMLoc());
4984   return parseSourceFile(sourceMgr, context);
4985 }
4986 
4987 /// This parses the program string to a MLIR module if it was valid. If not,
4988 /// it emits diagnostics and returns null.
4989 OwningModuleRef mlir::parseSourceString(StringRef moduleStr,
4990                                         MLIRContext *context) {
4991   auto memBuffer = MemoryBuffer::getMemBuffer(moduleStr);
4992   if (!memBuffer)
4993     return nullptr;
4994 
4995   SourceMgr sourceMgr;
4996   sourceMgr.AddNewSourceBuffer(std::move(memBuffer), SMLoc());
4997   return parseSourceFile(sourceMgr, context);
4998 }
4999 
5000 /// Parses a symbol, of type 'T', and returns it if parsing was successful. If
5001 /// parsing failed, nullptr is returned. The number of bytes read from the input
5002 /// string is returned in 'numRead'.
5003 template <typename T, typename ParserFn>
5004 static T parseSymbol(StringRef inputStr, MLIRContext *context, size_t &numRead,
5005                      ParserFn &&parserFn) {
5006   SymbolState aliasState;
5007   return parseSymbol<T>(
5008       inputStr, context, aliasState,
5009       [&](Parser &parser) {
5010         SourceMgrDiagnosticHandler handler(
5011             const_cast<llvm::SourceMgr &>(parser.getSourceMgr()),
5012             parser.getContext());
5013         return parserFn(parser);
5014       },
5015       &numRead);
5016 }
5017 
5018 Attribute mlir::parseAttribute(StringRef attrStr, MLIRContext *context) {
5019   size_t numRead = 0;
5020   return parseAttribute(attrStr, context, numRead);
5021 }
5022 Attribute mlir::parseAttribute(StringRef attrStr, Type type) {
5023   size_t numRead = 0;
5024   return parseAttribute(attrStr, type, numRead);
5025 }
5026 
5027 Attribute mlir::parseAttribute(StringRef attrStr, MLIRContext *context,
5028                                size_t &numRead) {
5029   return parseSymbol<Attribute>(attrStr, context, numRead, [](Parser &parser) {
5030     return parser.parseAttribute();
5031   });
5032 }
5033 Attribute mlir::parseAttribute(StringRef attrStr, Type type, size_t &numRead) {
5034   return parseSymbol<Attribute>(
5035       attrStr, type.getContext(), numRead,
5036       [type](Parser &parser) { return parser.parseAttribute(type); });
5037 }
5038 
5039 Type mlir::parseType(StringRef typeStr, MLIRContext *context) {
5040   size_t numRead = 0;
5041   return parseType(typeStr, context, numRead);
5042 }
5043 
5044 Type mlir::parseType(StringRef typeStr, MLIRContext *context, size_t &numRead) {
5045   return parseSymbol<Type>(typeStr, context, numRead,
5046                            [](Parser &parser) { return parser.parseType(); });
5047 }
5048