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