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