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   // FIXME: bfloat is currently stored as a double internally because it doesn't
1713   // have valid APFloat semantics.
1714   if (type.isF64() || type.isBF16()) {
1715     APFloat apFloat(type.getFloatSemantics(), APInt(/*numBits=*/64, value));
1716     return p->builder.getFloatAttr(type, apFloat);
1717   }
1718 
1719   APInt apInt(type.getWidth(), value);
1720   if (apInt != value) {
1721     p->emitError("hexadecimal float constant out of range for type");
1722     return nullptr;
1723   }
1724   APFloat apFloat(type.getFloatSemantics(), apInt);
1725   return p->builder.getFloatAttr(type, apFloat);
1726 }
1727 
1728 /// Parse a decimal or a hexadecimal literal, which can be either an integer
1729 /// or a float attribute.
1730 Attribute Parser::parseDecOrHexAttr(Type type, bool isNegative) {
1731   auto val = getToken().getUInt64IntegerValue();
1732   if (!val.hasValue())
1733     return (emitError("integer constant out of range for attribute"), nullptr);
1734 
1735   // Remember if the literal is hexadecimal.
1736   StringRef spelling = getToken().getSpelling();
1737   auto loc = state.curToken.getLoc();
1738   bool isHex = spelling.size() > 1 && spelling[1] == 'x';
1739 
1740   consumeToken(Token::integer);
1741   if (!type) {
1742     // Default to i64 if not type is specified.
1743     if (!consumeIf(Token::colon))
1744       type = builder.getIntegerType(64);
1745     else if (!(type = parseType()))
1746       return nullptr;
1747   }
1748 
1749   if (auto floatType = type.dyn_cast<FloatType>()) {
1750     if (isNegative)
1751       return emitError(
1752                  loc,
1753                  "hexadecimal float literal should not have a leading minus"),
1754              nullptr;
1755     if (!isHex) {
1756       emitError(loc, "unexpected decimal integer literal for a float attribute")
1757               .attachNote()
1758           << "add a trailing dot to make the literal a float";
1759       return nullptr;
1760     }
1761 
1762     // Construct a float attribute bitwise equivalent to the integer literal.
1763     return buildHexadecimalFloatLiteral(this, floatType, *val);
1764   }
1765 
1766   if (!type.isIntOrIndex())
1767     return emitError(loc, "integer literal not valid for specified type"),
1768            nullptr;
1769 
1770   // Parse the integer literal.
1771   int width = type.isIndex() ? 64 : type.getIntOrFloatBitWidth();
1772   APInt apInt(width, *val, isNegative);
1773   if (apInt != *val)
1774     return emitError(loc, "integer constant out of range for attribute"),
1775            nullptr;
1776 
1777   // Otherwise construct an integer attribute.
1778   if (isNegative ? (int64_t)-val.getValue() >= 0 : (int64_t)val.getValue() < 0)
1779     return emitError(loc, "integer constant out of range for attribute"),
1780            nullptr;
1781 
1782   return builder.getIntegerAttr(type, isNegative ? -apInt : apInt);
1783 }
1784 
1785 /// Parse an opaque elements attribute.
1786 Attribute Parser::parseOpaqueElementsAttr() {
1787   consumeToken(Token::kw_opaque);
1788   if (parseToken(Token::less, "expected '<' after 'opaque'"))
1789     return nullptr;
1790 
1791   if (getToken().isNot(Token::string))
1792     return (emitError("expected dialect namespace"), nullptr);
1793 
1794   auto name = getToken().getStringValue();
1795   auto *dialect = builder.getContext()->getRegisteredDialect(name);
1796   // TODO(shpeisman): Allow for having an unknown dialect on an opaque
1797   // attribute. Otherwise, it can't be roundtripped without having the dialect
1798   // registered.
1799   if (!dialect)
1800     return (emitError("no registered dialect with namespace '" + name + "'"),
1801             nullptr);
1802 
1803   consumeToken(Token::string);
1804   if (parseToken(Token::comma, "expected ','"))
1805     return nullptr;
1806 
1807   if (getToken().getKind() != Token::string)
1808     return (emitError("opaque string should start with '0x'"), nullptr);
1809 
1810   auto val = getToken().getStringValue();
1811   if (val.size() < 2 || val[0] != '0' || val[1] != 'x')
1812     return (emitError("opaque string should start with '0x'"), nullptr);
1813 
1814   val = val.substr(2);
1815   if (!llvm::all_of(val, llvm::isHexDigit))
1816     return (emitError("opaque string only contains hex digits"), nullptr);
1817 
1818   consumeToken(Token::string);
1819   if (parseToken(Token::greater, "expected '>'") ||
1820       parseToken(Token::colon, "expected ':'"))
1821     return nullptr;
1822 
1823   auto type = parseElementsLiteralType();
1824   if (!type)
1825     return nullptr;
1826 
1827   return OpaqueElementsAttr::get(dialect, type, llvm::fromHex(val));
1828 }
1829 
1830 namespace {
1831 class TensorLiteralParser {
1832 public:
1833   TensorLiteralParser(Parser &p) : p(p) {}
1834 
1835   ParseResult parse() {
1836     if (p.getToken().is(Token::l_square))
1837       return parseList(shape);
1838     return parseElement();
1839   }
1840 
1841   /// Build a dense attribute instance with the parsed elements and the given
1842   /// shaped type.
1843   DenseElementsAttr getAttr(llvm::SMLoc loc, ShapedType type);
1844 
1845   ArrayRef<int64_t> getShape() const { return shape; }
1846 
1847 private:
1848   enum class ElementKind { Boolean, Integer, Float };
1849 
1850   /// Return a string to represent the given element kind.
1851   const char *getElementKindStr(ElementKind kind) {
1852     switch (kind) {
1853     case ElementKind::Boolean:
1854       return "'boolean'";
1855     case ElementKind::Integer:
1856       return "'integer'";
1857     case ElementKind::Float:
1858       return "'float'";
1859     }
1860     llvm_unreachable("unknown element kind");
1861   }
1862 
1863   /// Build a Dense Integer attribute for the given type.
1864   DenseElementsAttr getIntAttr(llvm::SMLoc loc, ShapedType type,
1865                                IntegerType eltTy);
1866 
1867   /// Build a Dense Float attribute for the given type.
1868   DenseElementsAttr getFloatAttr(llvm::SMLoc loc, ShapedType type,
1869                                  FloatType eltTy);
1870 
1871   /// Parse a single element, returning failure if it isn't a valid element
1872   /// literal. For example:
1873   /// parseElement(1) -> Success, 1
1874   /// parseElement([1]) -> Failure
1875   ParseResult parseElement();
1876 
1877   /// Parse a list of either lists or elements, returning the dimensions of the
1878   /// parsed sub-tensors in dims. For example:
1879   ///   parseList([1, 2, 3]) -> Success, [3]
1880   ///   parseList([[1, 2], [3, 4]]) -> Success, [2, 2]
1881   ///   parseList([[1, 2], 3]) -> Failure
1882   ///   parseList([[1, [2, 3]], [4, [5]]]) -> Failure
1883   ParseResult parseList(SmallVectorImpl<int64_t> &dims);
1884 
1885   Parser &p;
1886 
1887   /// The shape inferred from the parsed elements.
1888   SmallVector<int64_t, 4> shape;
1889 
1890   /// Storage used when parsing elements, this is a pair of <is_negated, token>.
1891   std::vector<std::pair<bool, Token>> storage;
1892 
1893   /// A flag that indicates the type of elements that have been parsed.
1894   Optional<ElementKind> knownEltKind;
1895 };
1896 } // namespace
1897 
1898 /// Build a dense attribute instance with the parsed elements and the given
1899 /// shaped type.
1900 DenseElementsAttr TensorLiteralParser::getAttr(llvm::SMLoc loc,
1901                                                ShapedType type) {
1902   // Check that the parsed storage size has the same number of elements to the
1903   // type, or is a known splat.
1904   if (!shape.empty() && getShape() != type.getShape()) {
1905     p.emitError(loc) << "inferred shape of elements literal ([" << getShape()
1906                      << "]) does not match type ([" << type.getShape() << "])";
1907     return nullptr;
1908   }
1909 
1910   // If the type is an integer, build a set of APInt values from the storage
1911   // with the correct bitwidth.
1912   if (auto intTy = type.getElementType().dyn_cast<IntegerType>())
1913     return getIntAttr(loc, type, intTy);
1914 
1915   // Otherwise, this must be a floating point type.
1916   auto floatTy = type.getElementType().dyn_cast<FloatType>();
1917   if (!floatTy) {
1918     p.emitError(loc) << "expected floating-point or integer element type, got "
1919                      << type.getElementType();
1920     return nullptr;
1921   }
1922   return getFloatAttr(loc, type, floatTy);
1923 }
1924 
1925 /// Build a Dense Integer attribute for the given type.
1926 DenseElementsAttr TensorLiteralParser::getIntAttr(llvm::SMLoc loc,
1927                                                   ShapedType type,
1928                                                   IntegerType eltTy) {
1929   std::vector<APInt> intElements;
1930   intElements.reserve(storage.size());
1931   for (const auto &signAndToken : storage) {
1932     bool isNegative = signAndToken.first;
1933     const Token &token = signAndToken.second;
1934 
1935     // Check to see if floating point values were parsed.
1936     if (token.is(Token::floatliteral)) {
1937       p.emitError() << "expected integer elements, but parsed floating-point";
1938       return nullptr;
1939     }
1940 
1941     assert(token.isAny(Token::integer, Token::kw_true, Token::kw_false) &&
1942            "unexpected token type");
1943     if (token.isAny(Token::kw_true, Token::kw_false)) {
1944       if (!eltTy.isInteger(1))
1945         p.emitError() << "expected i1 type for 'true' or 'false' values";
1946       APInt apInt(eltTy.getWidth(), token.is(Token::kw_true),
1947                   /*isSigned=*/false);
1948       intElements.push_back(apInt);
1949       continue;
1950     }
1951 
1952     // Create APInt values for each element with the correct bitwidth.
1953     auto val = token.getUInt64IntegerValue();
1954     if (!val.hasValue() || (isNegative ? (int64_t)-val.getValue() >= 0
1955                                        : (int64_t)val.getValue() < 0)) {
1956       p.emitError(token.getLoc(),
1957                   "integer constant out of range for attribute");
1958       return nullptr;
1959     }
1960     APInt apInt(eltTy.getWidth(), val.getValue(), isNegative);
1961     if (apInt != val.getValue())
1962       return (p.emitError("integer constant out of range for type"), nullptr);
1963     intElements.push_back(isNegative ? -apInt : apInt);
1964   }
1965 
1966   return DenseElementsAttr::get(type, intElements);
1967 }
1968 
1969 /// Build a Dense Float attribute for the given type.
1970 DenseElementsAttr TensorLiteralParser::getFloatAttr(llvm::SMLoc loc,
1971                                                     ShapedType type,
1972                                                     FloatType eltTy) {
1973   std::vector<Attribute> floatValues;
1974   floatValues.reserve(storage.size());
1975   for (const auto &signAndToken : storage) {
1976     bool isNegative = signAndToken.first;
1977     const Token &token = signAndToken.second;
1978 
1979     // Handle hexadecimal float literals.
1980     if (token.is(Token::integer) && token.getSpelling().startswith("0x")) {
1981       if (isNegative) {
1982         p.emitError(token.getLoc())
1983             << "hexadecimal float literal should not have a leading minus";
1984         return nullptr;
1985       }
1986       auto val = token.getUInt64IntegerValue();
1987       if (!val.hasValue()) {
1988         p.emitError("hexadecimal float constant out of range for attribute");
1989         return nullptr;
1990       }
1991       FloatAttr attr = buildHexadecimalFloatLiteral(&p, eltTy, *val);
1992       if (!attr)
1993         return nullptr;
1994       floatValues.push_back(attr);
1995       continue;
1996     }
1997 
1998     // Check to see if any decimal integers or booleans were parsed.
1999     if (!token.is(Token::floatliteral)) {
2000       p.emitError() << "expected floating-point elements, but parsed integer";
2001       return nullptr;
2002     }
2003 
2004     // Build the float values from tokens.
2005     auto val = token.getFloatingPointValue();
2006     if (!val.hasValue()) {
2007       p.emitError("floating point value too large for attribute");
2008       return nullptr;
2009     }
2010     floatValues.push_back(FloatAttr::get(eltTy, isNegative ? -*val : *val));
2011   }
2012 
2013   return DenseElementsAttr::get(type, floatValues);
2014 }
2015 
2016 ParseResult TensorLiteralParser::parseElement() {
2017   switch (p.getToken().getKind()) {
2018   // Parse a boolean element.
2019   case Token::kw_true:
2020   case Token::kw_false:
2021   case Token::floatliteral:
2022   case Token::integer:
2023     storage.emplace_back(/*isNegative=*/false, p.getToken());
2024     p.consumeToken();
2025     break;
2026 
2027   // Parse a signed integer or a negative floating-point element.
2028   case Token::minus:
2029     p.consumeToken(Token::minus);
2030     if (!p.getToken().isAny(Token::floatliteral, Token::integer))
2031       return p.emitError("expected integer or floating point literal");
2032     storage.emplace_back(/*isNegative=*/true, p.getToken());
2033     p.consumeToken();
2034     break;
2035 
2036   default:
2037     return p.emitError("expected element literal of primitive type");
2038   }
2039 
2040   return success();
2041 }
2042 
2043 /// Parse a list of either lists or elements, returning the dimensions of the
2044 /// parsed sub-tensors in dims. For example:
2045 ///   parseList([1, 2, 3]) -> Success, [3]
2046 ///   parseList([[1, 2], [3, 4]]) -> Success, [2, 2]
2047 ///   parseList([[1, 2], 3]) -> Failure
2048 ///   parseList([[1, [2, 3]], [4, [5]]]) -> Failure
2049 ParseResult TensorLiteralParser::parseList(SmallVectorImpl<int64_t> &dims) {
2050   p.consumeToken(Token::l_square);
2051 
2052   auto checkDims = [&](const SmallVectorImpl<int64_t> &prevDims,
2053                        const SmallVectorImpl<int64_t> &newDims) -> ParseResult {
2054     if (prevDims == newDims)
2055       return success();
2056     return p.emitError("tensor literal is invalid; ranks are not consistent "
2057                        "between elements");
2058   };
2059 
2060   bool first = true;
2061   SmallVector<int64_t, 4> newDims;
2062   unsigned size = 0;
2063   auto parseCommaSeparatedList = [&]() -> ParseResult {
2064     SmallVector<int64_t, 4> thisDims;
2065     if (p.getToken().getKind() == Token::l_square) {
2066       if (parseList(thisDims))
2067         return failure();
2068     } else if (parseElement()) {
2069       return failure();
2070     }
2071     ++size;
2072     if (!first)
2073       return checkDims(newDims, thisDims);
2074     newDims = thisDims;
2075     first = false;
2076     return success();
2077   };
2078   if (p.parseCommaSeparatedListUntil(Token::r_square, parseCommaSeparatedList))
2079     return failure();
2080 
2081   // Return the sublists' dimensions with 'size' prepended.
2082   dims.clear();
2083   dims.push_back(size);
2084   dims.append(newDims.begin(), newDims.end());
2085   return success();
2086 }
2087 
2088 /// Parse a dense elements attribute.
2089 Attribute Parser::parseDenseElementsAttr() {
2090   consumeToken(Token::kw_dense);
2091   if (parseToken(Token::less, "expected '<' after 'dense'"))
2092     return nullptr;
2093 
2094   // Parse the literal data.
2095   TensorLiteralParser literalParser(*this);
2096   if (literalParser.parse())
2097     return nullptr;
2098 
2099   if (parseToken(Token::greater, "expected '>'") ||
2100       parseToken(Token::colon, "expected ':'"))
2101     return nullptr;
2102 
2103   auto typeLoc = getToken().getLoc();
2104   auto type = parseElementsLiteralType();
2105   if (!type)
2106     return nullptr;
2107   return literalParser.getAttr(typeLoc, type);
2108 }
2109 
2110 /// Shaped type for elements attribute.
2111 ///
2112 ///   elements-literal-type ::= vector-type | ranked-tensor-type
2113 ///
2114 /// This method also checks the type has static shape.
2115 ShapedType Parser::parseElementsLiteralType() {
2116   auto type = parseType();
2117   if (!type)
2118     return nullptr;
2119 
2120   if (!type.isa<RankedTensorType>() && !type.isa<VectorType>()) {
2121     emitError("elements literal must be a ranked tensor or vector type");
2122     return nullptr;
2123   }
2124 
2125   auto sType = type.cast<ShapedType>();
2126   if (!sType.hasStaticShape())
2127     return (emitError("elements literal type must have static shape"), nullptr);
2128 
2129   return sType;
2130 }
2131 
2132 /// Parse a sparse elements attribute.
2133 Attribute Parser::parseSparseElementsAttr() {
2134   consumeToken(Token::kw_sparse);
2135   if (parseToken(Token::less, "Expected '<' after 'sparse'"))
2136     return nullptr;
2137 
2138   /// Parse indices
2139   auto indicesLoc = getToken().getLoc();
2140   TensorLiteralParser indiceParser(*this);
2141   if (indiceParser.parse())
2142     return nullptr;
2143 
2144   if (parseToken(Token::comma, "expected ','"))
2145     return nullptr;
2146 
2147   /// Parse values.
2148   auto valuesLoc = getToken().getLoc();
2149   TensorLiteralParser valuesParser(*this);
2150   if (valuesParser.parse())
2151     return nullptr;
2152 
2153   if (parseToken(Token::greater, "expected '>'") ||
2154       parseToken(Token::colon, "expected ':'"))
2155     return nullptr;
2156 
2157   auto type = parseElementsLiteralType();
2158   if (!type)
2159     return nullptr;
2160 
2161   // If the indices are a splat, i.e. the literal parser parsed an element and
2162   // not a list, we set the shape explicitly. The indices are represented by a
2163   // 2-dimensional shape where the second dimension is the rank of the type.
2164   // Given that the parsed indices is a splat, we know that we only have one
2165   // indice and thus one for the first dimension.
2166   auto indiceEltType = builder.getIntegerType(64);
2167   ShapedType indicesType;
2168   if (indiceParser.getShape().empty()) {
2169     indicesType = RankedTensorType::get({1, type.getRank()}, indiceEltType);
2170   } else {
2171     // Otherwise, set the shape to the one parsed by the literal parser.
2172     indicesType = RankedTensorType::get(indiceParser.getShape(), indiceEltType);
2173   }
2174   auto indices = indiceParser.getAttr(indicesLoc, indicesType);
2175 
2176   // If the values are a splat, set the shape explicitly based on the number of
2177   // indices. The number of indices is encoded in the first dimension of the
2178   // indice shape type.
2179   auto valuesEltType = type.getElementType();
2180   ShapedType valuesType =
2181       valuesParser.getShape().empty()
2182           ? RankedTensorType::get({indicesType.getDimSize(0)}, valuesEltType)
2183           : RankedTensorType::get(valuesParser.getShape(), valuesEltType);
2184   auto values = valuesParser.getAttr(valuesLoc, valuesType);
2185 
2186   /// Sanity check.
2187   if (valuesType.getRank() != 1)
2188     return (emitError("expected 1-d tensor for values"), nullptr);
2189 
2190   auto sameShape = (indicesType.getRank() == 1) ||
2191                    (type.getRank() == indicesType.getDimSize(1));
2192   auto sameElementNum = indicesType.getDimSize(0) == valuesType.getDimSize(0);
2193   if (!sameShape || !sameElementNum) {
2194     emitError() << "expected shape ([" << type.getShape()
2195                 << "]); inferred shape of indices literal (["
2196                 << indicesType.getShape()
2197                 << "]); inferred shape of values literal (["
2198                 << valuesType.getShape() << "])";
2199     return nullptr;
2200   }
2201 
2202   // Build the sparse elements attribute by the indices and values.
2203   return SparseElementsAttr::get(type, indices, values);
2204 }
2205 
2206 //===----------------------------------------------------------------------===//
2207 // Location parsing.
2208 //===----------------------------------------------------------------------===//
2209 
2210 /// Parse a location.
2211 ///
2212 ///   location           ::= `loc` inline-location
2213 ///   inline-location    ::= '(' location-inst ')'
2214 ///
2215 ParseResult Parser::parseLocation(LocationAttr &loc) {
2216   // Check for 'loc' identifier.
2217   if (parseToken(Token::kw_loc, "expected 'loc' keyword"))
2218     return emitError();
2219 
2220   // Parse the inline-location.
2221   if (parseToken(Token::l_paren, "expected '(' in inline location") ||
2222       parseLocationInstance(loc) ||
2223       parseToken(Token::r_paren, "expected ')' in inline location"))
2224     return failure();
2225   return success();
2226 }
2227 
2228 /// Specific location instances.
2229 ///
2230 /// location-inst ::= filelinecol-location |
2231 ///                   name-location |
2232 ///                   callsite-location |
2233 ///                   fused-location |
2234 ///                   unknown-location
2235 /// filelinecol-location ::= string-literal ':' integer-literal
2236 ///                                         ':' integer-literal
2237 /// name-location ::= string-literal
2238 /// callsite-location ::= 'callsite' '(' location-inst 'at' location-inst ')'
2239 /// fused-location ::= fused ('<' attribute-value '>')?
2240 ///                    '[' location-inst (location-inst ',')* ']'
2241 /// unknown-location ::= 'unknown'
2242 ///
2243 ParseResult Parser::parseCallSiteLocation(LocationAttr &loc) {
2244   consumeToken(Token::bare_identifier);
2245 
2246   // Parse the '('.
2247   if (parseToken(Token::l_paren, "expected '(' in callsite location"))
2248     return failure();
2249 
2250   // Parse the callee location.
2251   LocationAttr calleeLoc;
2252   if (parseLocationInstance(calleeLoc))
2253     return failure();
2254 
2255   // Parse the 'at'.
2256   if (getToken().isNot(Token::bare_identifier) ||
2257       getToken().getSpelling() != "at")
2258     return emitError("expected 'at' in callsite location");
2259   consumeToken(Token::bare_identifier);
2260 
2261   // Parse the caller location.
2262   LocationAttr callerLoc;
2263   if (parseLocationInstance(callerLoc))
2264     return failure();
2265 
2266   // Parse the ')'.
2267   if (parseToken(Token::r_paren, "expected ')' in callsite location"))
2268     return failure();
2269 
2270   // Return the callsite location.
2271   loc = CallSiteLoc::get(calleeLoc, callerLoc);
2272   return success();
2273 }
2274 
2275 ParseResult Parser::parseFusedLocation(LocationAttr &loc) {
2276   consumeToken(Token::bare_identifier);
2277 
2278   // Try to parse the optional metadata.
2279   Attribute metadata;
2280   if (consumeIf(Token::less)) {
2281     metadata = parseAttribute();
2282     if (!metadata)
2283       return emitError("expected valid attribute metadata");
2284     // Parse the '>' token.
2285     if (parseToken(Token::greater,
2286                    "expected '>' after fused location metadata"))
2287       return failure();
2288   }
2289 
2290   SmallVector<Location, 4> locations;
2291   auto parseElt = [&] {
2292     LocationAttr newLoc;
2293     if (parseLocationInstance(newLoc))
2294       return failure();
2295     locations.push_back(newLoc);
2296     return success();
2297   };
2298 
2299   if (parseToken(Token::l_square, "expected '[' in fused location") ||
2300       parseCommaSeparatedList(parseElt) ||
2301       parseToken(Token::r_square, "expected ']' in fused location"))
2302     return failure();
2303 
2304   // Return the fused location.
2305   loc = FusedLoc::get(locations, metadata, getContext());
2306   return success();
2307 }
2308 
2309 ParseResult Parser::parseNameOrFileLineColLocation(LocationAttr &loc) {
2310   auto *ctx = getContext();
2311   auto str = getToken().getStringValue();
2312   consumeToken(Token::string);
2313 
2314   // If the next token is ':' this is a filelinecol location.
2315   if (consumeIf(Token::colon)) {
2316     // Parse the line number.
2317     if (getToken().isNot(Token::integer))
2318       return emitError("expected integer line number in FileLineColLoc");
2319     auto line = getToken().getUnsignedIntegerValue();
2320     if (!line.hasValue())
2321       return emitError("expected integer line number in FileLineColLoc");
2322     consumeToken(Token::integer);
2323 
2324     // Parse the ':'.
2325     if (parseToken(Token::colon, "expected ':' in FileLineColLoc"))
2326       return failure();
2327 
2328     // Parse the column number.
2329     if (getToken().isNot(Token::integer))
2330       return emitError("expected integer column number in FileLineColLoc");
2331     auto column = getToken().getUnsignedIntegerValue();
2332     if (!column.hasValue())
2333       return emitError("expected integer column number in FileLineColLoc");
2334     consumeToken(Token::integer);
2335 
2336     loc = FileLineColLoc::get(str, line.getValue(), column.getValue(), ctx);
2337     return success();
2338   }
2339 
2340   // Otherwise, this is a NameLoc.
2341 
2342   // Check for a child location.
2343   if (consumeIf(Token::l_paren)) {
2344     auto childSourceLoc = getToken().getLoc();
2345 
2346     // Parse the child location.
2347     LocationAttr childLoc;
2348     if (parseLocationInstance(childLoc))
2349       return failure();
2350 
2351     // The child must not be another NameLoc.
2352     if (childLoc.isa<NameLoc>())
2353       return emitError(childSourceLoc,
2354                        "child of NameLoc cannot be another NameLoc");
2355     loc = NameLoc::get(Identifier::get(str, ctx), childLoc);
2356 
2357     // Parse the closing ')'.
2358     if (parseToken(Token::r_paren,
2359                    "expected ')' after child location of NameLoc"))
2360       return failure();
2361   } else {
2362     loc = NameLoc::get(Identifier::get(str, ctx), ctx);
2363   }
2364 
2365   return success();
2366 }
2367 
2368 ParseResult Parser::parseLocationInstance(LocationAttr &loc) {
2369   // Handle either name or filelinecol locations.
2370   if (getToken().is(Token::string))
2371     return parseNameOrFileLineColLocation(loc);
2372 
2373   // Bare tokens required for other cases.
2374   if (!getToken().is(Token::bare_identifier))
2375     return emitError("expected location instance");
2376 
2377   // Check for the 'callsite' signifying a callsite location.
2378   if (getToken().getSpelling() == "callsite")
2379     return parseCallSiteLocation(loc);
2380 
2381   // If the token is 'fused', then this is a fused location.
2382   if (getToken().getSpelling() == "fused")
2383     return parseFusedLocation(loc);
2384 
2385   // Check for a 'unknown' for an unknown location.
2386   if (getToken().getSpelling() == "unknown") {
2387     consumeToken(Token::bare_identifier);
2388     loc = UnknownLoc::get(getContext());
2389     return success();
2390   }
2391 
2392   return emitError("expected location instance");
2393 }
2394 
2395 //===----------------------------------------------------------------------===//
2396 // Affine parsing.
2397 //===----------------------------------------------------------------------===//
2398 
2399 /// Lower precedence ops (all at the same precedence level). LNoOp is false in
2400 /// the boolean sense.
2401 enum AffineLowPrecOp {
2402   /// Null value.
2403   LNoOp,
2404   Add,
2405   Sub
2406 };
2407 
2408 /// Higher precedence ops - all at the same precedence level. HNoOp is false
2409 /// in the boolean sense.
2410 enum AffineHighPrecOp {
2411   /// Null value.
2412   HNoOp,
2413   Mul,
2414   FloorDiv,
2415   CeilDiv,
2416   Mod
2417 };
2418 
2419 namespace {
2420 /// This is a specialized parser for affine structures (affine maps, affine
2421 /// expressions, and integer sets), maintaining the state transient to their
2422 /// bodies.
2423 class AffineParser : public Parser {
2424 public:
2425   AffineParser(ParserState &state, bool allowParsingSSAIds = false,
2426                function_ref<ParseResult(bool)> parseElement = nullptr)
2427       : Parser(state), allowParsingSSAIds(allowParsingSSAIds),
2428         parseElement(parseElement), numDimOperands(0), numSymbolOperands(0) {}
2429 
2430   AffineMap parseAffineMapRange(unsigned numDims, unsigned numSymbols);
2431   ParseResult parseAffineMapOrIntegerSetInline(AffineMap &map, IntegerSet &set);
2432   IntegerSet parseIntegerSetConstraints(unsigned numDims, unsigned numSymbols);
2433   ParseResult parseAffineMapOfSSAIds(AffineMap &map);
2434   void getDimsAndSymbolSSAIds(SmallVectorImpl<StringRef> &dimAndSymbolSSAIds,
2435                               unsigned &numDims);
2436 
2437 private:
2438   // Binary affine op parsing.
2439   AffineLowPrecOp consumeIfLowPrecOp();
2440   AffineHighPrecOp consumeIfHighPrecOp();
2441 
2442   // Identifier lists for polyhedral structures.
2443   ParseResult parseDimIdList(unsigned &numDims);
2444   ParseResult parseSymbolIdList(unsigned &numSymbols);
2445   ParseResult parseDimAndOptionalSymbolIdList(unsigned &numDims,
2446                                               unsigned &numSymbols);
2447   ParseResult parseIdentifierDefinition(AffineExpr idExpr);
2448 
2449   AffineExpr parseAffineExpr();
2450   AffineExpr parseParentheticalExpr();
2451   AffineExpr parseNegateExpression(AffineExpr lhs);
2452   AffineExpr parseIntegerExpr();
2453   AffineExpr parseBareIdExpr();
2454   AffineExpr parseSSAIdExpr(bool isSymbol);
2455   AffineExpr parseSymbolSSAIdExpr();
2456 
2457   AffineExpr getAffineBinaryOpExpr(AffineHighPrecOp op, AffineExpr lhs,
2458                                    AffineExpr rhs, SMLoc opLoc);
2459   AffineExpr getAffineBinaryOpExpr(AffineLowPrecOp op, AffineExpr lhs,
2460                                    AffineExpr rhs);
2461   AffineExpr parseAffineOperandExpr(AffineExpr lhs);
2462   AffineExpr parseAffineLowPrecOpExpr(AffineExpr llhs, AffineLowPrecOp llhsOp);
2463   AffineExpr parseAffineHighPrecOpExpr(AffineExpr llhs, AffineHighPrecOp llhsOp,
2464                                        SMLoc llhsOpLoc);
2465   AffineExpr parseAffineConstraint(bool *isEq);
2466 
2467 private:
2468   bool allowParsingSSAIds;
2469   function_ref<ParseResult(bool)> parseElement;
2470   unsigned numDimOperands;
2471   unsigned numSymbolOperands;
2472   SmallVector<std::pair<StringRef, AffineExpr>, 4> dimsAndSymbols;
2473 };
2474 } // end anonymous namespace
2475 
2476 /// Create an affine binary high precedence op expression (mul's, div's, mod).
2477 /// opLoc is the location of the op token to be used to report errors
2478 /// for non-conforming expressions.
2479 AffineExpr AffineParser::getAffineBinaryOpExpr(AffineHighPrecOp op,
2480                                                AffineExpr lhs, AffineExpr rhs,
2481                                                SMLoc opLoc) {
2482   // TODO: make the error location info accurate.
2483   switch (op) {
2484   case Mul:
2485     if (!lhs.isSymbolicOrConstant() && !rhs.isSymbolicOrConstant()) {
2486       emitError(opLoc, "non-affine expression: at least one of the multiply "
2487                        "operands has to be either a constant or symbolic");
2488       return nullptr;
2489     }
2490     return lhs * rhs;
2491   case FloorDiv:
2492     if (!rhs.isSymbolicOrConstant()) {
2493       emitError(opLoc, "non-affine expression: right operand of floordiv "
2494                        "has to be either a constant or symbolic");
2495       return nullptr;
2496     }
2497     return lhs.floorDiv(rhs);
2498   case CeilDiv:
2499     if (!rhs.isSymbolicOrConstant()) {
2500       emitError(opLoc, "non-affine expression: right operand of ceildiv "
2501                        "has to be either a constant or symbolic");
2502       return nullptr;
2503     }
2504     return lhs.ceilDiv(rhs);
2505   case Mod:
2506     if (!rhs.isSymbolicOrConstant()) {
2507       emitError(opLoc, "non-affine expression: right operand of mod "
2508                        "has to be either a constant or symbolic");
2509       return nullptr;
2510     }
2511     return lhs % rhs;
2512   case HNoOp:
2513     llvm_unreachable("can't create affine expression for null high prec op");
2514     return nullptr;
2515   }
2516   llvm_unreachable("Unknown AffineHighPrecOp");
2517 }
2518 
2519 /// Create an affine binary low precedence op expression (add, sub).
2520 AffineExpr AffineParser::getAffineBinaryOpExpr(AffineLowPrecOp op,
2521                                                AffineExpr lhs, AffineExpr rhs) {
2522   switch (op) {
2523   case AffineLowPrecOp::Add:
2524     return lhs + rhs;
2525   case AffineLowPrecOp::Sub:
2526     return lhs - rhs;
2527   case AffineLowPrecOp::LNoOp:
2528     llvm_unreachable("can't create affine expression for null low prec op");
2529     return nullptr;
2530   }
2531   llvm_unreachable("Unknown AffineLowPrecOp");
2532 }
2533 
2534 /// Consume this token if it is a lower precedence affine op (there are only
2535 /// two precedence levels).
2536 AffineLowPrecOp AffineParser::consumeIfLowPrecOp() {
2537   switch (getToken().getKind()) {
2538   case Token::plus:
2539     consumeToken(Token::plus);
2540     return AffineLowPrecOp::Add;
2541   case Token::minus:
2542     consumeToken(Token::minus);
2543     return AffineLowPrecOp::Sub;
2544   default:
2545     return AffineLowPrecOp::LNoOp;
2546   }
2547 }
2548 
2549 /// Consume this token if it is a higher precedence affine op (there are only
2550 /// two precedence levels)
2551 AffineHighPrecOp AffineParser::consumeIfHighPrecOp() {
2552   switch (getToken().getKind()) {
2553   case Token::star:
2554     consumeToken(Token::star);
2555     return Mul;
2556   case Token::kw_floordiv:
2557     consumeToken(Token::kw_floordiv);
2558     return FloorDiv;
2559   case Token::kw_ceildiv:
2560     consumeToken(Token::kw_ceildiv);
2561     return CeilDiv;
2562   case Token::kw_mod:
2563     consumeToken(Token::kw_mod);
2564     return Mod;
2565   default:
2566     return HNoOp;
2567   }
2568 }
2569 
2570 /// Parse a high precedence op expression list: mul, div, and mod are high
2571 /// precedence binary ops, i.e., parse a
2572 ///   expr_1 op_1 expr_2 op_2 ... expr_n
2573 /// where op_1, op_2 are all a AffineHighPrecOp (mul, div, mod).
2574 /// All affine binary ops are left associative.
2575 /// Given llhs, returns (llhs llhsOp lhs) op rhs, or (lhs op rhs) if llhs is
2576 /// null. If no rhs can be found, returns (llhs llhsOp lhs) or lhs if llhs is
2577 /// null. llhsOpLoc is the location of the llhsOp token that will be used to
2578 /// report an error for non-conforming expressions.
2579 AffineExpr AffineParser::parseAffineHighPrecOpExpr(AffineExpr llhs,
2580                                                    AffineHighPrecOp llhsOp,
2581                                                    SMLoc llhsOpLoc) {
2582   AffineExpr lhs = parseAffineOperandExpr(llhs);
2583   if (!lhs)
2584     return nullptr;
2585 
2586   // Found an LHS. Parse the remaining expression.
2587   auto opLoc = getToken().getLoc();
2588   if (AffineHighPrecOp op = consumeIfHighPrecOp()) {
2589     if (llhs) {
2590       AffineExpr expr = getAffineBinaryOpExpr(llhsOp, llhs, lhs, opLoc);
2591       if (!expr)
2592         return nullptr;
2593       return parseAffineHighPrecOpExpr(expr, op, opLoc);
2594     }
2595     // No LLHS, get RHS
2596     return parseAffineHighPrecOpExpr(lhs, op, opLoc);
2597   }
2598 
2599   // This is the last operand in this expression.
2600   if (llhs)
2601     return getAffineBinaryOpExpr(llhsOp, llhs, lhs, llhsOpLoc);
2602 
2603   // No llhs, 'lhs' itself is the expression.
2604   return lhs;
2605 }
2606 
2607 /// Parse an affine expression inside parentheses.
2608 ///
2609 ///   affine-expr ::= `(` affine-expr `)`
2610 AffineExpr AffineParser::parseParentheticalExpr() {
2611   if (parseToken(Token::l_paren, "expected '('"))
2612     return nullptr;
2613   if (getToken().is(Token::r_paren))
2614     return (emitError("no expression inside parentheses"), nullptr);
2615 
2616   auto expr = parseAffineExpr();
2617   if (!expr)
2618     return nullptr;
2619   if (parseToken(Token::r_paren, "expected ')'"))
2620     return nullptr;
2621 
2622   return expr;
2623 }
2624 
2625 /// Parse the negation expression.
2626 ///
2627 ///   affine-expr ::= `-` affine-expr
2628 AffineExpr AffineParser::parseNegateExpression(AffineExpr lhs) {
2629   if (parseToken(Token::minus, "expected '-'"))
2630     return nullptr;
2631 
2632   AffineExpr operand = parseAffineOperandExpr(lhs);
2633   // Since negation has the highest precedence of all ops (including high
2634   // precedence ops) but lower than parentheses, we are only going to use
2635   // parseAffineOperandExpr instead of parseAffineExpr here.
2636   if (!operand)
2637     // Extra error message although parseAffineOperandExpr would have
2638     // complained. Leads to a better diagnostic.
2639     return (emitError("missing operand of negation"), nullptr);
2640   return (-1) * operand;
2641 }
2642 
2643 /// Parse a bare id that may appear in an affine expression.
2644 ///
2645 ///   affine-expr ::= bare-id
2646 AffineExpr AffineParser::parseBareIdExpr() {
2647   if (getToken().isNot(Token::bare_identifier))
2648     return (emitError("expected bare identifier"), nullptr);
2649 
2650   StringRef sRef = getTokenSpelling();
2651   for (auto entry : dimsAndSymbols) {
2652     if (entry.first == sRef) {
2653       consumeToken(Token::bare_identifier);
2654       return entry.second;
2655     }
2656   }
2657 
2658   return (emitError("use of undeclared identifier"), nullptr);
2659 }
2660 
2661 /// Parse an SSA id which may appear in an affine expression.
2662 AffineExpr AffineParser::parseSSAIdExpr(bool isSymbol) {
2663   if (!allowParsingSSAIds)
2664     return (emitError("unexpected ssa identifier"), nullptr);
2665   if (getToken().isNot(Token::percent_identifier))
2666     return (emitError("expected ssa identifier"), nullptr);
2667   auto name = getTokenSpelling();
2668   // Check if we already parsed this SSA id.
2669   for (auto entry : dimsAndSymbols) {
2670     if (entry.first == name) {
2671       consumeToken(Token::percent_identifier);
2672       return entry.second;
2673     }
2674   }
2675   // Parse the SSA id and add an AffineDim/SymbolExpr to represent it.
2676   if (parseElement(isSymbol))
2677     return (emitError("failed to parse ssa identifier"), nullptr);
2678   auto idExpr = isSymbol
2679                     ? getAffineSymbolExpr(numSymbolOperands++, getContext())
2680                     : getAffineDimExpr(numDimOperands++, getContext());
2681   dimsAndSymbols.push_back({name, idExpr});
2682   return idExpr;
2683 }
2684 
2685 AffineExpr AffineParser::parseSymbolSSAIdExpr() {
2686   if (parseToken(Token::kw_symbol, "expected symbol keyword") ||
2687       parseToken(Token::l_paren, "expected '(' at start of SSA symbol"))
2688     return nullptr;
2689   AffineExpr symbolExpr = parseSSAIdExpr(/*isSymbol=*/true);
2690   if (!symbolExpr)
2691     return nullptr;
2692   if (parseToken(Token::r_paren, "expected ')' at end of SSA symbol"))
2693     return nullptr;
2694   return symbolExpr;
2695 }
2696 
2697 /// Parse a positive integral constant appearing in an affine expression.
2698 ///
2699 ///   affine-expr ::= integer-literal
2700 AffineExpr AffineParser::parseIntegerExpr() {
2701   auto val = getToken().getUInt64IntegerValue();
2702   if (!val.hasValue() || (int64_t)val.getValue() < 0)
2703     return (emitError("constant too large for index"), nullptr);
2704 
2705   consumeToken(Token::integer);
2706   return builder.getAffineConstantExpr((int64_t)val.getValue());
2707 }
2708 
2709 /// Parses an expression that can be a valid operand of an affine expression.
2710 /// lhs: if non-null, lhs is an affine expression that is the lhs of a binary
2711 /// operator, the rhs of which is being parsed. This is used to determine
2712 /// whether an error should be emitted for a missing right operand.
2713 //  Eg: for an expression without parentheses (like i + j + k + l), each
2714 //  of the four identifiers is an operand. For i + j*k + l, j*k is not an
2715 //  operand expression, it's an op expression and will be parsed via
2716 //  parseAffineHighPrecOpExpression(). However, for i + (j*k) + -l, (j*k) and
2717 //  -l are valid operands that will be parsed by this function.
2718 AffineExpr AffineParser::parseAffineOperandExpr(AffineExpr lhs) {
2719   switch (getToken().getKind()) {
2720   case Token::bare_identifier:
2721     return parseBareIdExpr();
2722   case Token::kw_symbol:
2723     return parseSymbolSSAIdExpr();
2724   case Token::percent_identifier:
2725     return parseSSAIdExpr(/*isSymbol=*/false);
2726   case Token::integer:
2727     return parseIntegerExpr();
2728   case Token::l_paren:
2729     return parseParentheticalExpr();
2730   case Token::minus:
2731     return parseNegateExpression(lhs);
2732   case Token::kw_ceildiv:
2733   case Token::kw_floordiv:
2734   case Token::kw_mod:
2735   case Token::plus:
2736   case Token::star:
2737     if (lhs)
2738       emitError("missing right operand of binary operator");
2739     else
2740       emitError("missing left operand of binary operator");
2741     return nullptr;
2742   default:
2743     if (lhs)
2744       emitError("missing right operand of binary operator");
2745     else
2746       emitError("expected affine expression");
2747     return nullptr;
2748   }
2749 }
2750 
2751 /// Parse affine expressions that are bare-id's, integer constants,
2752 /// parenthetical affine expressions, and affine op expressions that are a
2753 /// composition of those.
2754 ///
2755 /// All binary op's associate from left to right.
2756 ///
2757 /// {add, sub} have lower precedence than {mul, div, and mod}.
2758 ///
2759 /// Add, sub'are themselves at the same precedence level. Mul, floordiv,
2760 /// ceildiv, and mod are at the same higher precedence level. Negation has
2761 /// higher precedence than any binary op.
2762 ///
2763 /// llhs: the affine expression appearing on the left of the one being parsed.
2764 /// This function will return ((llhs llhsOp lhs) op rhs) if llhs is non null,
2765 /// and lhs op rhs otherwise; if there is no rhs, llhs llhsOp lhs is returned
2766 /// if llhs is non-null; otherwise lhs is returned. This is to deal with left
2767 /// associativity.
2768 ///
2769 /// Eg: when the expression is e1 + e2*e3 + e4, with e1 as llhs, this function
2770 /// will return the affine expr equivalent of (e1 + (e2*e3)) + e4, where
2771 /// (e2*e3) will be parsed using parseAffineHighPrecOpExpr().
2772 AffineExpr AffineParser::parseAffineLowPrecOpExpr(AffineExpr llhs,
2773                                                   AffineLowPrecOp llhsOp) {
2774   AffineExpr lhs;
2775   if (!(lhs = parseAffineOperandExpr(llhs)))
2776     return nullptr;
2777 
2778   // Found an LHS. Deal with the ops.
2779   if (AffineLowPrecOp lOp = consumeIfLowPrecOp()) {
2780     if (llhs) {
2781       AffineExpr sum = getAffineBinaryOpExpr(llhsOp, llhs, lhs);
2782       return parseAffineLowPrecOpExpr(sum, lOp);
2783     }
2784     // No LLHS, get RHS and form the expression.
2785     return parseAffineLowPrecOpExpr(lhs, lOp);
2786   }
2787   auto opLoc = getToken().getLoc();
2788   if (AffineHighPrecOp hOp = consumeIfHighPrecOp()) {
2789     // We have a higher precedence op here. Get the rhs operand for the llhs
2790     // through parseAffineHighPrecOpExpr.
2791     AffineExpr highRes = parseAffineHighPrecOpExpr(lhs, hOp, opLoc);
2792     if (!highRes)
2793       return nullptr;
2794 
2795     // If llhs is null, the product forms the first operand of the yet to be
2796     // found expression. If non-null, the op to associate with llhs is llhsOp.
2797     AffineExpr expr =
2798         llhs ? getAffineBinaryOpExpr(llhsOp, llhs, highRes) : highRes;
2799 
2800     // Recurse for subsequent low prec op's after the affine high prec op
2801     // expression.
2802     if (AffineLowPrecOp nextOp = consumeIfLowPrecOp())
2803       return parseAffineLowPrecOpExpr(expr, nextOp);
2804     return expr;
2805   }
2806   // Last operand in the expression list.
2807   if (llhs)
2808     return getAffineBinaryOpExpr(llhsOp, llhs, lhs);
2809   // No llhs, 'lhs' itself is the expression.
2810   return lhs;
2811 }
2812 
2813 /// Parse an affine expression.
2814 ///  affine-expr ::= `(` affine-expr `)`
2815 ///                | `-` affine-expr
2816 ///                | affine-expr `+` affine-expr
2817 ///                | affine-expr `-` affine-expr
2818 ///                | affine-expr `*` affine-expr
2819 ///                | affine-expr `floordiv` affine-expr
2820 ///                | affine-expr `ceildiv` affine-expr
2821 ///                | affine-expr `mod` affine-expr
2822 ///                | bare-id
2823 ///                | integer-literal
2824 ///
2825 /// Additional conditions are checked depending on the production. For eg.,
2826 /// one of the operands for `*` has to be either constant/symbolic; the second
2827 /// operand for floordiv, ceildiv, and mod has to be a positive integer.
2828 AffineExpr AffineParser::parseAffineExpr() {
2829   return parseAffineLowPrecOpExpr(nullptr, AffineLowPrecOp::LNoOp);
2830 }
2831 
2832 /// Parse a dim or symbol from the lists appearing before the actual
2833 /// expressions of the affine map. Update our state to store the
2834 /// dimensional/symbolic identifier.
2835 ParseResult AffineParser::parseIdentifierDefinition(AffineExpr idExpr) {
2836   if (getToken().isNot(Token::bare_identifier))
2837     return emitError("expected bare identifier");
2838 
2839   auto name = getTokenSpelling();
2840   for (auto entry : dimsAndSymbols) {
2841     if (entry.first == name)
2842       return emitError("redefinition of identifier '" + name + "'");
2843   }
2844   consumeToken(Token::bare_identifier);
2845 
2846   dimsAndSymbols.push_back({name, idExpr});
2847   return success();
2848 }
2849 
2850 /// Parse the list of dimensional identifiers to an affine map.
2851 ParseResult AffineParser::parseDimIdList(unsigned &numDims) {
2852   if (parseToken(Token::l_paren,
2853                  "expected '(' at start of dimensional identifiers list")) {
2854     return failure();
2855   }
2856 
2857   auto parseElt = [&]() -> ParseResult {
2858     auto dimension = getAffineDimExpr(numDims++, getContext());
2859     return parseIdentifierDefinition(dimension);
2860   };
2861   return parseCommaSeparatedListUntil(Token::r_paren, parseElt);
2862 }
2863 
2864 /// Parse the list of symbolic identifiers to an affine map.
2865 ParseResult AffineParser::parseSymbolIdList(unsigned &numSymbols) {
2866   consumeToken(Token::l_square);
2867   auto parseElt = [&]() -> ParseResult {
2868     auto symbol = getAffineSymbolExpr(numSymbols++, getContext());
2869     return parseIdentifierDefinition(symbol);
2870   };
2871   return parseCommaSeparatedListUntil(Token::r_square, parseElt);
2872 }
2873 
2874 /// Parse the list of symbolic identifiers to an affine map.
2875 ParseResult
2876 AffineParser::parseDimAndOptionalSymbolIdList(unsigned &numDims,
2877                                               unsigned &numSymbols) {
2878   if (parseDimIdList(numDims)) {
2879     return failure();
2880   }
2881   if (!getToken().is(Token::l_square)) {
2882     numSymbols = 0;
2883     return success();
2884   }
2885   return parseSymbolIdList(numSymbols);
2886 }
2887 
2888 /// Parses an ambiguous affine map or integer set definition inline.
2889 ParseResult AffineParser::parseAffineMapOrIntegerSetInline(AffineMap &map,
2890                                                            IntegerSet &set) {
2891   unsigned numDims = 0, numSymbols = 0;
2892 
2893   // List of dimensional and optional symbol identifiers.
2894   if (parseDimAndOptionalSymbolIdList(numDims, numSymbols)) {
2895     return failure();
2896   }
2897 
2898   // This is needed for parsing attributes as we wouldn't know whether we would
2899   // be parsing an integer set attribute or an affine map attribute.
2900   bool isArrow = getToken().is(Token::arrow);
2901   bool isColon = getToken().is(Token::colon);
2902   if (!isArrow && !isColon) {
2903     return emitError("expected '->' or ':'");
2904   } else if (isArrow) {
2905     parseToken(Token::arrow, "expected '->' or '['");
2906     map = parseAffineMapRange(numDims, numSymbols);
2907     return map ? success() : failure();
2908   } else if (parseToken(Token::colon, "expected ':' or '['")) {
2909     return failure();
2910   }
2911 
2912   if ((set = parseIntegerSetConstraints(numDims, numSymbols)))
2913     return success();
2914 
2915   return failure();
2916 }
2917 
2918 /// Parse an AffineMap where the dim and symbol identifiers are SSA ids.
2919 ParseResult AffineParser::parseAffineMapOfSSAIds(AffineMap &map) {
2920   if (parseToken(Token::l_square, "expected '['"))
2921     return failure();
2922 
2923   SmallVector<AffineExpr, 4> exprs;
2924   auto parseElt = [&]() -> ParseResult {
2925     auto elt = parseAffineExpr();
2926     exprs.push_back(elt);
2927     return elt ? success() : failure();
2928   };
2929 
2930   // Parse a multi-dimensional affine expression (a comma-separated list of
2931   // 1-d affine expressions); the list cannot be empty. Grammar:
2932   // multi-dim-affine-expr ::= `(` affine-expr (`,` affine-expr)* `)
2933   if (parseCommaSeparatedListUntil(Token::r_square, parseElt,
2934                                    /*allowEmptyList=*/true))
2935     return failure();
2936   // Parsed a valid affine map.
2937   if (exprs.empty())
2938     map = AffineMap::get(getContext());
2939   else
2940     map = AffineMap::get(numDimOperands, dimsAndSymbols.size() - numDimOperands,
2941                          exprs);
2942   return success();
2943 }
2944 
2945 /// Parse the range and sizes affine map definition inline.
2946 ///
2947 ///  affine-map ::= dim-and-symbol-id-lists `->` multi-dim-affine-expr
2948 ///
2949 ///  multi-dim-affine-expr ::= `(` `)`
2950 ///  multi-dim-affine-expr ::= `(` affine-expr (`,` affine-expr)* `)`
2951 AffineMap AffineParser::parseAffineMapRange(unsigned numDims,
2952                                             unsigned numSymbols) {
2953   parseToken(Token::l_paren, "expected '(' at start of affine map range");
2954 
2955   SmallVector<AffineExpr, 4> exprs;
2956   auto parseElt = [&]() -> ParseResult {
2957     auto elt = parseAffineExpr();
2958     ParseResult res = elt ? success() : failure();
2959     exprs.push_back(elt);
2960     return res;
2961   };
2962 
2963   // Parse a multi-dimensional affine expression (a comma-separated list of
2964   // 1-d affine expressions); the list cannot be empty. Grammar:
2965   // multi-dim-affine-expr ::= `(` affine-expr (`,` affine-expr)* `)
2966   if (parseCommaSeparatedListUntil(Token::r_paren, parseElt, true))
2967     return AffineMap();
2968 
2969   if (exprs.empty())
2970     return AffineMap::get(getContext());
2971 
2972   // Parsed a valid affine map.
2973   return AffineMap::get(numDims, numSymbols, exprs);
2974 }
2975 
2976 /// Parse an affine constraint.
2977 ///  affine-constraint ::= affine-expr `>=` `0`
2978 ///                      | affine-expr `==` `0`
2979 ///
2980 /// isEq is set to true if the parsed constraint is an equality, false if it
2981 /// is an inequality (greater than or equal).
2982 ///
2983 AffineExpr AffineParser::parseAffineConstraint(bool *isEq) {
2984   AffineExpr expr = parseAffineExpr();
2985   if (!expr)
2986     return nullptr;
2987 
2988   if (consumeIf(Token::greater) && consumeIf(Token::equal) &&
2989       getToken().is(Token::integer)) {
2990     auto dim = getToken().getUnsignedIntegerValue();
2991     if (dim.hasValue() && dim.getValue() == 0) {
2992       consumeToken(Token::integer);
2993       *isEq = false;
2994       return expr;
2995     }
2996     return (emitError("expected '0' after '>='"), nullptr);
2997   }
2998 
2999   if (consumeIf(Token::equal) && consumeIf(Token::equal) &&
3000       getToken().is(Token::integer)) {
3001     auto dim = getToken().getUnsignedIntegerValue();
3002     if (dim.hasValue() && dim.getValue() == 0) {
3003       consumeToken(Token::integer);
3004       *isEq = true;
3005       return expr;
3006     }
3007     return (emitError("expected '0' after '=='"), nullptr);
3008   }
3009 
3010   return (emitError("expected '== 0' or '>= 0' at end of affine constraint"),
3011           nullptr);
3012 }
3013 
3014 /// Parse the constraints that are part of an integer set definition.
3015 ///  integer-set-inline
3016 ///                ::= dim-and-symbol-id-lists `:`
3017 ///                '(' affine-constraint-conjunction? ')'
3018 ///  affine-constraint-conjunction ::= affine-constraint (`,`
3019 ///                                       affine-constraint)*
3020 ///
3021 IntegerSet AffineParser::parseIntegerSetConstraints(unsigned numDims,
3022                                                     unsigned numSymbols) {
3023   if (parseToken(Token::l_paren,
3024                  "expected '(' at start of integer set constraint list"))
3025     return IntegerSet();
3026 
3027   SmallVector<AffineExpr, 4> constraints;
3028   SmallVector<bool, 4> isEqs;
3029   auto parseElt = [&]() -> ParseResult {
3030     bool isEq;
3031     auto elt = parseAffineConstraint(&isEq);
3032     ParseResult res = elt ? success() : failure();
3033     if (elt) {
3034       constraints.push_back(elt);
3035       isEqs.push_back(isEq);
3036     }
3037     return res;
3038   };
3039 
3040   // Parse a list of affine constraints (comma-separated).
3041   if (parseCommaSeparatedListUntil(Token::r_paren, parseElt, true))
3042     return IntegerSet();
3043 
3044   // If no constraints were parsed, then treat this as a degenerate 'true' case.
3045   if (constraints.empty()) {
3046     /* 0 == 0 */
3047     auto zero = getAffineConstantExpr(0, getContext());
3048     return IntegerSet::get(numDims, numSymbols, zero, true);
3049   }
3050 
3051   // Parsed a valid integer set.
3052   return IntegerSet::get(numDims, numSymbols, constraints, isEqs);
3053 }
3054 
3055 /// Parse an ambiguous reference to either and affine map or an integer set.
3056 ParseResult Parser::parseAffineMapOrIntegerSetReference(AffineMap &map,
3057                                                         IntegerSet &set) {
3058   return AffineParser(state).parseAffineMapOrIntegerSetInline(map, set);
3059 }
3060 ParseResult Parser::parseAffineMapReference(AffineMap &map) {
3061   llvm::SMLoc curLoc = getToken().getLoc();
3062   IntegerSet set;
3063   if (parseAffineMapOrIntegerSetReference(map, set))
3064     return failure();
3065   if (set)
3066     return emitError(curLoc, "expected AffineMap, but got IntegerSet");
3067   return success();
3068 }
3069 ParseResult Parser::parseIntegerSetReference(IntegerSet &set) {
3070   llvm::SMLoc curLoc = getToken().getLoc();
3071   AffineMap map;
3072   if (parseAffineMapOrIntegerSetReference(map, set))
3073     return failure();
3074   if (map)
3075     return emitError(curLoc, "expected IntegerSet, but got AffineMap");
3076   return success();
3077 }
3078 
3079 /// Parse an AffineMap of SSA ids. The callback 'parseElement' is used to
3080 /// parse SSA value uses encountered while parsing affine expressions.
3081 ParseResult
3082 Parser::parseAffineMapOfSSAIds(AffineMap &map,
3083                                function_ref<ParseResult(bool)> parseElement) {
3084   return AffineParser(state, /*allowParsingSSAIds=*/true, parseElement)
3085       .parseAffineMapOfSSAIds(map);
3086 }
3087 
3088 //===----------------------------------------------------------------------===//
3089 // OperationParser
3090 //===----------------------------------------------------------------------===//
3091 
3092 namespace {
3093 /// This class provides support for parsing operations and regions of
3094 /// operations.
3095 class OperationParser : public Parser {
3096 public:
3097   OperationParser(ParserState &state, ModuleOp moduleOp)
3098       : Parser(state), opBuilder(moduleOp.getBodyRegion()), moduleOp(moduleOp) {
3099   }
3100 
3101   ~OperationParser();
3102 
3103   /// After parsing is finished, this function must be called to see if there
3104   /// are any remaining issues.
3105   ParseResult finalize();
3106 
3107   //===--------------------------------------------------------------------===//
3108   // SSA Value Handling
3109   //===--------------------------------------------------------------------===//
3110 
3111   /// This represents a use of an SSA value in the program.  The first two
3112   /// entries in the tuple are the name and result number of a reference.  The
3113   /// third is the location of the reference, which is used in case this ends
3114   /// up being a use of an undefined value.
3115   struct SSAUseInfo {
3116     StringRef name;  // Value name, e.g. %42 or %abc
3117     unsigned number; // Number, specified with #12
3118     SMLoc loc;       // Location of first definition or use.
3119   };
3120 
3121   /// Push a new SSA name scope to the parser.
3122   void pushSSANameScope(bool isIsolated);
3123 
3124   /// Pop the last SSA name scope from the parser.
3125   ParseResult popSSANameScope();
3126 
3127   /// Register a definition of a value with the symbol table.
3128   ParseResult addDefinition(SSAUseInfo useInfo, Value value);
3129 
3130   /// Parse an optional list of SSA uses into 'results'.
3131   ParseResult parseOptionalSSAUseList(SmallVectorImpl<SSAUseInfo> &results);
3132 
3133   /// Parse a single SSA use into 'result'.
3134   ParseResult parseSSAUse(SSAUseInfo &result);
3135 
3136   /// Given a reference to an SSA value and its type, return a reference. This
3137   /// returns null on failure.
3138   Value resolveSSAUse(SSAUseInfo useInfo, Type type);
3139 
3140   ParseResult parseSSADefOrUseAndType(
3141       const std::function<ParseResult(SSAUseInfo, Type)> &action);
3142 
3143   ParseResult parseOptionalSSAUseAndTypeList(SmallVectorImpl<Value> &results);
3144 
3145   /// Return the location of the value identified by its name and number if it
3146   /// has been already reference.
3147   Optional<SMLoc> getReferenceLoc(StringRef name, unsigned number) {
3148     auto &values = isolatedNameScopes.back().values;
3149     if (!values.count(name) || number >= values[name].size())
3150       return {};
3151     if (values[name][number].first)
3152       return values[name][number].second;
3153     return {};
3154   }
3155 
3156   //===--------------------------------------------------------------------===//
3157   // Operation Parsing
3158   //===--------------------------------------------------------------------===//
3159 
3160   /// Parse an operation instance.
3161   ParseResult parseOperation();
3162 
3163   /// Parse a single operation successor and its operand list.
3164   ParseResult parseSuccessorAndUseList(Block *&dest,
3165                                        SmallVectorImpl<Value> &operands);
3166 
3167   /// Parse a comma-separated list of operation successors in brackets.
3168   ParseResult parseSuccessors(SmallVectorImpl<Block *> &destinations,
3169                               SmallVectorImpl<SmallVector<Value, 4>> &operands);
3170 
3171   /// Parse an operation instance that is in the generic form.
3172   Operation *parseGenericOperation();
3173 
3174   /// Parse an operation instance that is in the generic form and insert it at
3175   /// the provided insertion point.
3176   Operation *parseGenericOperation(Block *insertBlock,
3177                                    Block::iterator insertPt);
3178 
3179   /// Parse an operation instance that is in the op-defined custom form.
3180   Operation *parseCustomOperation();
3181 
3182   //===--------------------------------------------------------------------===//
3183   // Region Parsing
3184   //===--------------------------------------------------------------------===//
3185 
3186   /// Parse a region into 'region' with the provided entry block arguments.
3187   /// 'isIsolatedNameScope' indicates if the naming scope of this region is
3188   /// isolated from those above.
3189   ParseResult parseRegion(Region &region,
3190                           ArrayRef<std::pair<SSAUseInfo, Type>> entryArguments,
3191                           bool isIsolatedNameScope = false);
3192 
3193   /// Parse a region body into 'region'.
3194   ParseResult parseRegionBody(Region &region);
3195 
3196   //===--------------------------------------------------------------------===//
3197   // Block Parsing
3198   //===--------------------------------------------------------------------===//
3199 
3200   /// Parse a new block into 'block'.
3201   ParseResult parseBlock(Block *&block);
3202 
3203   /// Parse a list of operations into 'block'.
3204   ParseResult parseBlockBody(Block *block);
3205 
3206   /// Parse a (possibly empty) list of block arguments.
3207   ParseResult parseOptionalBlockArgList(SmallVectorImpl<BlockArgument> &results,
3208                                         Block *owner);
3209 
3210   /// Get the block with the specified name, creating it if it doesn't
3211   /// already exist.  The location specified is the point of use, which allows
3212   /// us to diagnose references to blocks that are not defined precisely.
3213   Block *getBlockNamed(StringRef name, SMLoc loc);
3214 
3215   /// Define the block with the specified name. Returns the Block* or nullptr in
3216   /// the case of redefinition.
3217   Block *defineBlockNamed(StringRef name, SMLoc loc, Block *existing);
3218 
3219 private:
3220   /// Returns the info for a block at the current scope for the given name.
3221   std::pair<Block *, SMLoc> &getBlockInfoByName(StringRef name) {
3222     return blocksByName.back()[name];
3223   }
3224 
3225   /// Insert a new forward reference to the given block.
3226   void insertForwardRef(Block *block, SMLoc loc) {
3227     forwardRef.back().try_emplace(block, loc);
3228   }
3229 
3230   /// Erase any forward reference to the given block.
3231   bool eraseForwardRef(Block *block) { return forwardRef.back().erase(block); }
3232 
3233   /// Record that a definition was added at the current scope.
3234   void recordDefinition(StringRef def);
3235 
3236   /// Get the value entry for the given SSA name.
3237   SmallVectorImpl<std::pair<Value, SMLoc>> &getSSAValueEntry(StringRef name);
3238 
3239   /// Create a forward reference placeholder value with the given location and
3240   /// result type.
3241   Value createForwardRefPlaceholder(SMLoc loc, Type type);
3242 
3243   /// Return true if this is a forward reference.
3244   bool isForwardRefPlaceholder(Value value) {
3245     return forwardRefPlaceholders.count(value);
3246   }
3247 
3248   /// This struct represents an isolated SSA name scope. This scope may contain
3249   /// other nested non-isolated scopes. These scopes are used for operations
3250   /// that are known to be isolated to allow for reusing names within their
3251   /// regions, even if those names are used above.
3252   struct IsolatedSSANameScope {
3253     /// Record that a definition was added at the current scope.
3254     void recordDefinition(StringRef def) {
3255       definitionsPerScope.back().insert(def);
3256     }
3257 
3258     /// Push a nested name scope.
3259     void pushSSANameScope() { definitionsPerScope.push_back({}); }
3260 
3261     /// Pop a nested name scope.
3262     void popSSANameScope() {
3263       for (auto &def : definitionsPerScope.pop_back_val())
3264         values.erase(def.getKey());
3265     }
3266 
3267     /// This keeps track of all of the SSA values we are tracking for each name
3268     /// scope, indexed by their name. This has one entry per result number.
3269     llvm::StringMap<SmallVector<std::pair<Value, SMLoc>, 1>> values;
3270 
3271     /// This keeps track of all of the values defined by a specific name scope.
3272     SmallVector<llvm::StringSet<>, 2> definitionsPerScope;
3273   };
3274 
3275   /// A list of isolated name scopes.
3276   SmallVector<IsolatedSSANameScope, 2> isolatedNameScopes;
3277 
3278   /// This keeps track of the block names as well as the location of the first
3279   /// reference for each nested name scope. This is used to diagnose invalid
3280   /// block references and memorize them.
3281   SmallVector<DenseMap<StringRef, std::pair<Block *, SMLoc>>, 2> blocksByName;
3282   SmallVector<DenseMap<Block *, SMLoc>, 2> forwardRef;
3283 
3284   /// These are all of the placeholders we've made along with the location of
3285   /// their first reference, to allow checking for use of undefined values.
3286   DenseMap<Value, SMLoc> forwardRefPlaceholders;
3287 
3288   /// The builder used when creating parsed operation instances.
3289   OpBuilder opBuilder;
3290 
3291   /// The top level module operation.
3292   ModuleOp moduleOp;
3293 };
3294 } // end anonymous namespace
3295 
3296 OperationParser::~OperationParser() {
3297   for (auto &fwd : forwardRefPlaceholders) {
3298     // Drop all uses of undefined forward declared reference and destroy
3299     // defining operation.
3300     fwd.first.dropAllUses();
3301     fwd.first.getDefiningOp()->destroy();
3302   }
3303 }
3304 
3305 /// After parsing is finished, this function must be called to see if there are
3306 /// any remaining issues.
3307 ParseResult OperationParser::finalize() {
3308   // Check for any forward references that are left.  If we find any, error
3309   // out.
3310   if (!forwardRefPlaceholders.empty()) {
3311     SmallVector<std::pair<const char *, Value>, 4> errors;
3312     // Iteration over the map isn't deterministic, so sort by source location.
3313     for (auto entry : forwardRefPlaceholders)
3314       errors.push_back({entry.second.getPointer(), entry.first});
3315     llvm::array_pod_sort(errors.begin(), errors.end());
3316 
3317     for (auto entry : errors) {
3318       auto loc = SMLoc::getFromPointer(entry.first);
3319       emitError(loc, "use of undeclared SSA value name");
3320     }
3321     return failure();
3322   }
3323 
3324   return success();
3325 }
3326 
3327 //===----------------------------------------------------------------------===//
3328 // SSA Value Handling
3329 //===----------------------------------------------------------------------===//
3330 
3331 void OperationParser::pushSSANameScope(bool isIsolated) {
3332   blocksByName.push_back(DenseMap<StringRef, std::pair<Block *, SMLoc>>());
3333   forwardRef.push_back(DenseMap<Block *, SMLoc>());
3334 
3335   // Push back a new name definition scope.
3336   if (isIsolated)
3337     isolatedNameScopes.push_back({});
3338   isolatedNameScopes.back().pushSSANameScope();
3339 }
3340 
3341 ParseResult OperationParser::popSSANameScope() {
3342   auto forwardRefInCurrentScope = forwardRef.pop_back_val();
3343 
3344   // Verify that all referenced blocks were defined.
3345   if (!forwardRefInCurrentScope.empty()) {
3346     SmallVector<std::pair<const char *, Block *>, 4> errors;
3347     // Iteration over the map isn't deterministic, so sort by source location.
3348     for (auto entry : forwardRefInCurrentScope) {
3349       errors.push_back({entry.second.getPointer(), entry.first});
3350       // Add this block to the top-level region to allow for automatic cleanup.
3351       moduleOp.getOperation()->getRegion(0).push_back(entry.first);
3352     }
3353     llvm::array_pod_sort(errors.begin(), errors.end());
3354 
3355     for (auto entry : errors) {
3356       auto loc = SMLoc::getFromPointer(entry.first);
3357       emitError(loc, "reference to an undefined block");
3358     }
3359     return failure();
3360   }
3361 
3362   // Pop the next nested namescope. If there is only one internal namescope,
3363   // just pop the isolated scope.
3364   auto &currentNameScope = isolatedNameScopes.back();
3365   if (currentNameScope.definitionsPerScope.size() == 1)
3366     isolatedNameScopes.pop_back();
3367   else
3368     currentNameScope.popSSANameScope();
3369 
3370   blocksByName.pop_back();
3371   return success();
3372 }
3373 
3374 /// Register a definition of a value with the symbol table.
3375 ParseResult OperationParser::addDefinition(SSAUseInfo useInfo, Value value) {
3376   auto &entries = getSSAValueEntry(useInfo.name);
3377 
3378   // Make sure there is a slot for this value.
3379   if (entries.size() <= useInfo.number)
3380     entries.resize(useInfo.number + 1);
3381 
3382   // If we already have an entry for this, check to see if it was a definition
3383   // or a forward reference.
3384   if (auto existing = entries[useInfo.number].first) {
3385     if (!isForwardRefPlaceholder(existing)) {
3386       return emitError(useInfo.loc)
3387           .append("redefinition of SSA value '", useInfo.name, "'")
3388           .attachNote(getEncodedSourceLocation(entries[useInfo.number].second))
3389           .append("previously defined here");
3390     }
3391 
3392     // If it was a forward reference, update everything that used it to use
3393     // the actual definition instead, delete the forward ref, and remove it
3394     // from our set of forward references we track.
3395     existing.replaceAllUsesWith(value);
3396     existing.getDefiningOp()->destroy();
3397     forwardRefPlaceholders.erase(existing);
3398   }
3399 
3400   /// Record this definition for the current scope.
3401   entries[useInfo.number] = {value, useInfo.loc};
3402   recordDefinition(useInfo.name);
3403   return success();
3404 }
3405 
3406 /// Parse a (possibly empty) list of SSA operands.
3407 ///
3408 ///   ssa-use-list ::= ssa-use (`,` ssa-use)*
3409 ///   ssa-use-list-opt ::= ssa-use-list?
3410 ///
3411 ParseResult
3412 OperationParser::parseOptionalSSAUseList(SmallVectorImpl<SSAUseInfo> &results) {
3413   if (getToken().isNot(Token::percent_identifier))
3414     return success();
3415   return parseCommaSeparatedList([&]() -> ParseResult {
3416     SSAUseInfo result;
3417     if (parseSSAUse(result))
3418       return failure();
3419     results.push_back(result);
3420     return success();
3421   });
3422 }
3423 
3424 /// Parse a SSA operand for an operation.
3425 ///
3426 ///   ssa-use ::= ssa-id
3427 ///
3428 ParseResult OperationParser::parseSSAUse(SSAUseInfo &result) {
3429   result.name = getTokenSpelling();
3430   result.number = 0;
3431   result.loc = getToken().getLoc();
3432   if (parseToken(Token::percent_identifier, "expected SSA operand"))
3433     return failure();
3434 
3435   // If we have an attribute ID, it is a result number.
3436   if (getToken().is(Token::hash_identifier)) {
3437     if (auto value = getToken().getHashIdentifierNumber())
3438       result.number = value.getValue();
3439     else
3440       return emitError("invalid SSA value result number");
3441     consumeToken(Token::hash_identifier);
3442   }
3443 
3444   return success();
3445 }
3446 
3447 /// Given an unbound reference to an SSA value and its type, return the value
3448 /// it specifies.  This returns null on failure.
3449 Value OperationParser::resolveSSAUse(SSAUseInfo useInfo, Type type) {
3450   auto &entries = getSSAValueEntry(useInfo.name);
3451 
3452   // If we have already seen a value of this name, return it.
3453   if (useInfo.number < entries.size() && entries[useInfo.number].first) {
3454     auto result = entries[useInfo.number].first;
3455     // Check that the type matches the other uses.
3456     if (result.getType() == type)
3457       return result;
3458 
3459     emitError(useInfo.loc, "use of value '")
3460         .append(useInfo.name,
3461                 "' expects different type than prior uses: ", type, " vs ",
3462                 result.getType())
3463         .attachNote(getEncodedSourceLocation(entries[useInfo.number].second))
3464         .append("prior use here");
3465     return nullptr;
3466   }
3467 
3468   // Make sure we have enough slots for this.
3469   if (entries.size() <= useInfo.number)
3470     entries.resize(useInfo.number + 1);
3471 
3472   // If the value has already been defined and this is an overly large result
3473   // number, diagnose that.
3474   if (entries[0].first && !isForwardRefPlaceholder(entries[0].first))
3475     return (emitError(useInfo.loc, "reference to invalid result number"),
3476             nullptr);
3477 
3478   // Otherwise, this is a forward reference.  Create a placeholder and remember
3479   // that we did so.
3480   auto result = createForwardRefPlaceholder(useInfo.loc, type);
3481   entries[useInfo.number].first = result;
3482   entries[useInfo.number].second = useInfo.loc;
3483   return result;
3484 }
3485 
3486 /// Parse an SSA use with an associated type.
3487 ///
3488 ///   ssa-use-and-type ::= ssa-use `:` type
3489 ParseResult OperationParser::parseSSADefOrUseAndType(
3490     const std::function<ParseResult(SSAUseInfo, Type)> &action) {
3491   SSAUseInfo useInfo;
3492   if (parseSSAUse(useInfo) ||
3493       parseToken(Token::colon, "expected ':' and type for SSA operand"))
3494     return failure();
3495 
3496   auto type = parseType();
3497   if (!type)
3498     return failure();
3499 
3500   return action(useInfo, type);
3501 }
3502 
3503 /// Parse a (possibly empty) list of SSA operands, followed by a colon, then
3504 /// followed by a type list.
3505 ///
3506 ///   ssa-use-and-type-list
3507 ///     ::= ssa-use-list ':' type-list-no-parens
3508 ///
3509 ParseResult OperationParser::parseOptionalSSAUseAndTypeList(
3510     SmallVectorImpl<Value> &results) {
3511   SmallVector<SSAUseInfo, 4> valueIDs;
3512   if (parseOptionalSSAUseList(valueIDs))
3513     return failure();
3514 
3515   // If there were no operands, then there is no colon or type lists.
3516   if (valueIDs.empty())
3517     return success();
3518 
3519   SmallVector<Type, 4> types;
3520   if (parseToken(Token::colon, "expected ':' in operand list") ||
3521       parseTypeListNoParens(types))
3522     return failure();
3523 
3524   if (valueIDs.size() != types.size())
3525     return emitError("expected ")
3526            << valueIDs.size() << " types to match operand list";
3527 
3528   results.reserve(valueIDs.size());
3529   for (unsigned i = 0, e = valueIDs.size(); i != e; ++i) {
3530     if (auto value = resolveSSAUse(valueIDs[i], types[i]))
3531       results.push_back(value);
3532     else
3533       return failure();
3534   }
3535 
3536   return success();
3537 }
3538 
3539 /// Record that a definition was added at the current scope.
3540 void OperationParser::recordDefinition(StringRef def) {
3541   isolatedNameScopes.back().recordDefinition(def);
3542 }
3543 
3544 /// Get the value entry for the given SSA name.
3545 SmallVectorImpl<std::pair<Value, SMLoc>> &
3546 OperationParser::getSSAValueEntry(StringRef name) {
3547   return isolatedNameScopes.back().values[name];
3548 }
3549 
3550 /// Create and remember a new placeholder for a forward reference.
3551 Value OperationParser::createForwardRefPlaceholder(SMLoc loc, Type type) {
3552   // Forward references are always created as operations, because we just need
3553   // something with a def/use chain.
3554   //
3555   // We create these placeholders as having an empty name, which we know
3556   // cannot be created through normal user input, allowing us to distinguish
3557   // them.
3558   auto name = OperationName("placeholder", getContext());
3559   auto *op = Operation::create(
3560       getEncodedSourceLocation(loc), name, type, /*operands=*/{},
3561       /*attributes=*/llvm::None, /*successors=*/{}, /*numRegions=*/0,
3562       /*resizableOperandList=*/false);
3563   forwardRefPlaceholders[op->getResult(0)] = loc;
3564   return op->getResult(0);
3565 }
3566 
3567 //===----------------------------------------------------------------------===//
3568 // Operation Parsing
3569 //===----------------------------------------------------------------------===//
3570 
3571 /// Parse an operation.
3572 ///
3573 ///  operation         ::= op-result-list?
3574 ///                        (generic-operation | custom-operation)
3575 ///                        trailing-location?
3576 ///  generic-operation ::= string-literal '(' ssa-use-list? ')' attribute-dict?
3577 ///                        `:` function-type
3578 ///  custom-operation  ::= bare-id custom-operation-format
3579 ///  op-result-list    ::= op-result (`,` op-result)* `=`
3580 ///  op-result         ::= ssa-id (`:` integer-literal)
3581 ///
3582 ParseResult OperationParser::parseOperation() {
3583   auto loc = getToken().getLoc();
3584   SmallVector<std::tuple<StringRef, unsigned, SMLoc>, 1> resultIDs;
3585   size_t numExpectedResults = 0;
3586   if (getToken().is(Token::percent_identifier)) {
3587     // Parse the group of result ids.
3588     auto parseNextResult = [&]() -> ParseResult {
3589       // Parse the next result id.
3590       if (!getToken().is(Token::percent_identifier))
3591         return emitError("expected valid ssa identifier");
3592 
3593       Token nameTok = getToken();
3594       consumeToken(Token::percent_identifier);
3595 
3596       // If the next token is a ':', we parse the expected result count.
3597       size_t expectedSubResults = 1;
3598       if (consumeIf(Token::colon)) {
3599         // Check that the next token is an integer.
3600         if (!getToken().is(Token::integer))
3601           return emitError("expected integer number of results");
3602 
3603         // Check that number of results is > 0.
3604         auto val = getToken().getUInt64IntegerValue();
3605         if (!val.hasValue() || val.getValue() < 1)
3606           return emitError("expected named operation to have atleast 1 result");
3607         consumeToken(Token::integer);
3608         expectedSubResults = *val;
3609       }
3610 
3611       resultIDs.emplace_back(nameTok.getSpelling(), expectedSubResults,
3612                              nameTok.getLoc());
3613       numExpectedResults += expectedSubResults;
3614       return success();
3615     };
3616     if (parseCommaSeparatedList(parseNextResult))
3617       return failure();
3618 
3619     if (parseToken(Token::equal, "expected '=' after SSA name"))
3620       return failure();
3621   }
3622 
3623   Operation *op;
3624   if (getToken().is(Token::bare_identifier) || getToken().isKeyword())
3625     op = parseCustomOperation();
3626   else if (getToken().is(Token::string))
3627     op = parseGenericOperation();
3628   else
3629     return emitError("expected operation name in quotes");
3630 
3631   // If parsing of the basic operation failed, then this whole thing fails.
3632   if (!op)
3633     return failure();
3634 
3635   // If the operation had a name, register it.
3636   if (!resultIDs.empty()) {
3637     if (op->getNumResults() == 0)
3638       return emitError(loc, "cannot name an operation with no results");
3639     if (numExpectedResults != op->getNumResults())
3640       return emitError(loc, "operation defines ")
3641              << op->getNumResults() << " results but was provided "
3642              << numExpectedResults << " to bind";
3643 
3644     // Add definitions for each of the result groups.
3645     unsigned opResI = 0;
3646     for (std::tuple<StringRef, unsigned, SMLoc> &resIt : resultIDs) {
3647       for (unsigned subRes : llvm::seq<unsigned>(0, std::get<1>(resIt))) {
3648         if (addDefinition({std::get<0>(resIt), subRes, std::get<2>(resIt)},
3649                           op->getResult(opResI++)))
3650           return failure();
3651       }
3652     }
3653   }
3654 
3655   return success();
3656 }
3657 
3658 /// Parse a single operation successor and its operand list.
3659 ///
3660 ///   successor ::= block-id branch-use-list?
3661 ///   branch-use-list ::= `(` ssa-use-list ':' type-list-no-parens `)`
3662 ///
3663 ParseResult
3664 OperationParser::parseSuccessorAndUseList(Block *&dest,
3665                                           SmallVectorImpl<Value> &operands) {
3666   // Verify branch is identifier and get the matching block.
3667   if (!getToken().is(Token::caret_identifier))
3668     return emitError("expected block name");
3669   dest = getBlockNamed(getTokenSpelling(), getToken().getLoc());
3670   consumeToken();
3671 
3672   // Handle optional arguments.
3673   if (consumeIf(Token::l_paren) &&
3674       (parseOptionalSSAUseAndTypeList(operands) ||
3675        parseToken(Token::r_paren, "expected ')' to close argument list"))) {
3676     return failure();
3677   }
3678 
3679   return success();
3680 }
3681 
3682 /// Parse a comma-separated list of operation successors in brackets.
3683 ///
3684 ///   successor-list ::= `[` successor (`,` successor )* `]`
3685 ///
3686 ParseResult OperationParser::parseSuccessors(
3687     SmallVectorImpl<Block *> &destinations,
3688     SmallVectorImpl<SmallVector<Value, 4>> &operands) {
3689   if (parseToken(Token::l_square, "expected '['"))
3690     return failure();
3691 
3692   auto parseElt = [this, &destinations, &operands]() {
3693     Block *dest;
3694     SmallVector<Value, 4> destOperands;
3695     auto res = parseSuccessorAndUseList(dest, destOperands);
3696     destinations.push_back(dest);
3697     operands.push_back(destOperands);
3698     return res;
3699   };
3700   return parseCommaSeparatedListUntil(Token::r_square, parseElt,
3701                                       /*allowEmptyList=*/false);
3702 }
3703 
3704 namespace {
3705 // RAII-style guard for cleaning up the regions in the operation state before
3706 // deleting them.  Within the parser, regions may get deleted if parsing failed,
3707 // and other errors may be present, in particular undominated uses.  This makes
3708 // sure such uses are deleted.
3709 struct CleanupOpStateRegions {
3710   ~CleanupOpStateRegions() {
3711     SmallVector<Region *, 4> regionsToClean;
3712     regionsToClean.reserve(state.regions.size());
3713     for (auto &region : state.regions)
3714       if (region)
3715         for (auto &block : *region)
3716           block.dropAllDefinedValueUses();
3717   }
3718   OperationState &state;
3719 };
3720 } // namespace
3721 
3722 Operation *OperationParser::parseGenericOperation() {
3723   // Get location information for the operation.
3724   auto srcLocation = getEncodedSourceLocation(getToken().getLoc());
3725 
3726   auto name = getToken().getStringValue();
3727   if (name.empty())
3728     return (emitError("empty operation name is invalid"), nullptr);
3729   if (name.find('\0') != StringRef::npos)
3730     return (emitError("null character not allowed in operation name"), nullptr);
3731 
3732   consumeToken(Token::string);
3733 
3734   OperationState result(srcLocation, name);
3735 
3736   // Generic operations have a resizable operation list.
3737   result.setOperandListToResizable();
3738 
3739   // Parse the operand list.
3740   SmallVector<SSAUseInfo, 8> operandInfos;
3741 
3742   if (parseToken(Token::l_paren, "expected '(' to start operand list") ||
3743       parseOptionalSSAUseList(operandInfos) ||
3744       parseToken(Token::r_paren, "expected ')' to end operand list")) {
3745     return nullptr;
3746   }
3747 
3748   // Parse the successor list but don't add successors to the result yet to
3749   // avoid messing up with the argument order.
3750   SmallVector<Block *, 2> successors;
3751   SmallVector<SmallVector<Value, 4>, 2> successorOperands;
3752   if (getToken().is(Token::l_square)) {
3753     // Check if the operation is a known terminator.
3754     const AbstractOperation *abstractOp = result.name.getAbstractOperation();
3755     if (abstractOp && !abstractOp->hasProperty(OperationProperty::Terminator))
3756       return emitError("successors in non-terminator"), nullptr;
3757     if (parseSuccessors(successors, successorOperands))
3758       return nullptr;
3759   }
3760 
3761   // Parse the region list.
3762   CleanupOpStateRegions guard{result};
3763   if (consumeIf(Token::l_paren)) {
3764     do {
3765       // Create temporary regions with the top level region as parent.
3766       result.regions.emplace_back(new Region(moduleOp));
3767       if (parseRegion(*result.regions.back(), /*entryArguments=*/{}))
3768         return nullptr;
3769     } while (consumeIf(Token::comma));
3770     if (parseToken(Token::r_paren, "expected ')' to end region list"))
3771       return nullptr;
3772   }
3773 
3774   if (getToken().is(Token::l_brace)) {
3775     if (parseAttributeDict(result.attributes))
3776       return nullptr;
3777   }
3778 
3779   if (parseToken(Token::colon, "expected ':' followed by operation type"))
3780     return nullptr;
3781 
3782   auto typeLoc = getToken().getLoc();
3783   auto type = parseType();
3784   if (!type)
3785     return nullptr;
3786   auto fnType = type.dyn_cast<FunctionType>();
3787   if (!fnType)
3788     return (emitError(typeLoc, "expected function type"), nullptr);
3789 
3790   result.addTypes(fnType.getResults());
3791 
3792   // Check that we have the right number of types for the operands.
3793   auto operandTypes = fnType.getInputs();
3794   if (operandTypes.size() != operandInfos.size()) {
3795     auto plural = "s"[operandInfos.size() == 1];
3796     return (emitError(typeLoc, "expected ")
3797                 << operandInfos.size() << " operand type" << plural
3798                 << " but had " << operandTypes.size(),
3799             nullptr);
3800   }
3801 
3802   // Resolve all of the operands.
3803   for (unsigned i = 0, e = operandInfos.size(); i != e; ++i) {
3804     result.operands.push_back(resolveSSAUse(operandInfos[i], operandTypes[i]));
3805     if (!result.operands.back())
3806       return nullptr;
3807   }
3808 
3809   // Add the successors, and their operands after the proper operands.
3810   for (auto succ : llvm::zip(successors, successorOperands)) {
3811     Block *successor = std::get<0>(succ);
3812     const SmallVector<Value, 4> &operands = std::get<1>(succ);
3813     result.addSuccessor(successor, operands);
3814   }
3815 
3816   // Parse a location if one is present.
3817   if (parseOptionalTrailingLocation(result.location))
3818     return nullptr;
3819 
3820   return opBuilder.createOperation(result);
3821 }
3822 
3823 Operation *OperationParser::parseGenericOperation(Block *insertBlock,
3824                                                   Block::iterator insertPt) {
3825   OpBuilder::InsertionGuard restoreInsertionPoint(opBuilder);
3826   opBuilder.setInsertionPoint(insertBlock, insertPt);
3827   return parseGenericOperation();
3828 }
3829 
3830 namespace {
3831 class CustomOpAsmParser : public OpAsmParser {
3832 public:
3833   CustomOpAsmParser(SMLoc nameLoc, const AbstractOperation *opDefinition,
3834                     OperationParser &parser)
3835       : nameLoc(nameLoc), opDefinition(opDefinition), parser(parser) {}
3836 
3837   /// Parse an instance of the operation described by 'opDefinition' into the
3838   /// provided operation state.
3839   ParseResult parseOperation(OperationState &opState) {
3840     if (opDefinition->parseAssembly(*this, opState))
3841       return failure();
3842     return success();
3843   }
3844 
3845   Operation *parseGenericOperation(Block *insertBlock,
3846                                    Block::iterator insertPt) final {
3847     return parser.parseGenericOperation(insertBlock, insertPt);
3848   }
3849 
3850   //===--------------------------------------------------------------------===//
3851   // Utilities
3852   //===--------------------------------------------------------------------===//
3853 
3854   /// Return if any errors were emitted during parsing.
3855   bool didEmitError() const { return emittedError; }
3856 
3857   /// Emit a diagnostic at the specified location and return failure.
3858   InFlightDiagnostic emitError(llvm::SMLoc loc, const Twine &message) override {
3859     emittedError = true;
3860     return parser.emitError(loc, "custom op '" + opDefinition->name + "' " +
3861                                      message);
3862   }
3863 
3864   llvm::SMLoc getCurrentLocation() override {
3865     return parser.getToken().getLoc();
3866   }
3867 
3868   Builder &getBuilder() const override { return parser.builder; }
3869 
3870   llvm::SMLoc getNameLoc() const override { return nameLoc; }
3871 
3872   //===--------------------------------------------------------------------===//
3873   // Token Parsing
3874   //===--------------------------------------------------------------------===//
3875 
3876   /// Parse a `->` token.
3877   ParseResult parseArrow() override {
3878     return parser.parseToken(Token::arrow, "expected '->'");
3879   }
3880 
3881   /// Parses a `->` if present.
3882   ParseResult parseOptionalArrow() override {
3883     return success(parser.consumeIf(Token::arrow));
3884   }
3885 
3886   /// Parse a `:` token.
3887   ParseResult parseColon() override {
3888     return parser.parseToken(Token::colon, "expected ':'");
3889   }
3890 
3891   /// Parse a `:` token if present.
3892   ParseResult parseOptionalColon() override {
3893     return success(parser.consumeIf(Token::colon));
3894   }
3895 
3896   /// Parse a `,` token.
3897   ParseResult parseComma() override {
3898     return parser.parseToken(Token::comma, "expected ','");
3899   }
3900 
3901   /// Parse a `,` token if present.
3902   ParseResult parseOptionalComma() override {
3903     return success(parser.consumeIf(Token::comma));
3904   }
3905 
3906   /// Parses a `...` if present.
3907   ParseResult parseOptionalEllipsis() override {
3908     return success(parser.consumeIf(Token::ellipsis));
3909   }
3910 
3911   /// Parse a `=` token.
3912   ParseResult parseEqual() override {
3913     return parser.parseToken(Token::equal, "expected '='");
3914   }
3915 
3916   /// Parse a '<' token.
3917   ParseResult parseLess() override {
3918     return parser.parseToken(Token::less, "expected '<'");
3919   }
3920 
3921   /// Parse a '>' token.
3922   ParseResult parseGreater() override {
3923     return parser.parseToken(Token::greater, "expected '>'");
3924   }
3925 
3926   /// Parse a `(` token.
3927   ParseResult parseLParen() override {
3928     return parser.parseToken(Token::l_paren, "expected '('");
3929   }
3930 
3931   /// Parses a '(' if present.
3932   ParseResult parseOptionalLParen() override {
3933     return success(parser.consumeIf(Token::l_paren));
3934   }
3935 
3936   /// Parse a `)` token.
3937   ParseResult parseRParen() override {
3938     return parser.parseToken(Token::r_paren, "expected ')'");
3939   }
3940 
3941   /// Parses a ')' if present.
3942   ParseResult parseOptionalRParen() override {
3943     return success(parser.consumeIf(Token::r_paren));
3944   }
3945 
3946   /// Parse a `[` token.
3947   ParseResult parseLSquare() override {
3948     return parser.parseToken(Token::l_square, "expected '['");
3949   }
3950 
3951   /// Parses a '[' if present.
3952   ParseResult parseOptionalLSquare() override {
3953     return success(parser.consumeIf(Token::l_square));
3954   }
3955 
3956   /// Parse a `]` token.
3957   ParseResult parseRSquare() override {
3958     return parser.parseToken(Token::r_square, "expected ']'");
3959   }
3960 
3961   /// Parses a ']' if present.
3962   ParseResult parseOptionalRSquare() override {
3963     return success(parser.consumeIf(Token::r_square));
3964   }
3965 
3966   //===--------------------------------------------------------------------===//
3967   // Attribute Parsing
3968   //===--------------------------------------------------------------------===//
3969 
3970   /// Parse an arbitrary attribute of a given type and return it in result. This
3971   /// also adds the attribute to the specified attribute list with the specified
3972   /// name.
3973   ParseResult parseAttribute(Attribute &result, Type type, StringRef attrName,
3974                              SmallVectorImpl<NamedAttribute> &attrs) override {
3975     result = parser.parseAttribute(type);
3976     if (!result)
3977       return failure();
3978 
3979     attrs.push_back(parser.builder.getNamedAttr(attrName, result));
3980     return success();
3981   }
3982 
3983   /// Parse a named dictionary into 'result' if it is present.
3984   ParseResult
3985   parseOptionalAttrDict(SmallVectorImpl<NamedAttribute> &result) override {
3986     if (parser.getToken().isNot(Token::l_brace))
3987       return success();
3988     return parser.parseAttributeDict(result);
3989   }
3990 
3991   /// Parse a named dictionary into 'result' if the `attributes` keyword is
3992   /// present.
3993   ParseResult parseOptionalAttrDictWithKeyword(
3994       SmallVectorImpl<NamedAttribute> &result) override {
3995     if (failed(parseOptionalKeyword("attributes")))
3996       return success();
3997     return parser.parseAttributeDict(result);
3998   }
3999 
4000   /// Parse an affine map instance into 'map'.
4001   ParseResult parseAffineMap(AffineMap &map) override {
4002     return parser.parseAffineMapReference(map);
4003   }
4004 
4005   /// Parse an integer set instance into 'set'.
4006   ParseResult printIntegerSet(IntegerSet &set) override {
4007     return parser.parseIntegerSetReference(set);
4008   }
4009 
4010   //===--------------------------------------------------------------------===//
4011   // Identifier Parsing
4012   //===--------------------------------------------------------------------===//
4013 
4014   /// Returns if the current token corresponds to a keyword.
4015   bool isCurrentTokenAKeyword() const {
4016     return parser.getToken().is(Token::bare_identifier) ||
4017            parser.getToken().isKeyword();
4018   }
4019 
4020   /// Parse the given keyword if present.
4021   ParseResult parseOptionalKeyword(StringRef keyword) override {
4022     // Check that the current token has the same spelling.
4023     if (!isCurrentTokenAKeyword() || parser.getTokenSpelling() != keyword)
4024       return failure();
4025     parser.consumeToken();
4026     return success();
4027   }
4028 
4029   /// Parse a keyword, if present, into 'keyword'.
4030   ParseResult parseOptionalKeyword(StringRef *keyword) override {
4031     // Check that the current token is a keyword.
4032     if (!isCurrentTokenAKeyword())
4033       return failure();
4034 
4035     *keyword = parser.getTokenSpelling();
4036     parser.consumeToken();
4037     return success();
4038   }
4039 
4040   /// Parse an optional @-identifier and store it (without the '@' symbol) in a
4041   /// string attribute named 'attrName'.
4042   ParseResult
4043   parseOptionalSymbolName(StringAttr &result, StringRef attrName,
4044                           SmallVectorImpl<NamedAttribute> &attrs) override {
4045     Token atToken = parser.getToken();
4046     if (atToken.isNot(Token::at_identifier))
4047       return failure();
4048 
4049     result = getBuilder().getStringAttr(extractSymbolReference(atToken));
4050     attrs.push_back(getBuilder().getNamedAttr(attrName, result));
4051     parser.consumeToken();
4052     return success();
4053   }
4054 
4055   //===--------------------------------------------------------------------===//
4056   // Operand Parsing
4057   //===--------------------------------------------------------------------===//
4058 
4059   /// Parse a single operand.
4060   ParseResult parseOperand(OperandType &result) override {
4061     OperationParser::SSAUseInfo useInfo;
4062     if (parser.parseSSAUse(useInfo))
4063       return failure();
4064 
4065     result = {useInfo.loc, useInfo.name, useInfo.number};
4066     return success();
4067   }
4068 
4069   /// Parse zero or more SSA comma-separated operand references with a specified
4070   /// surrounding delimiter, and an optional required operand count.
4071   ParseResult parseOperandList(SmallVectorImpl<OperandType> &result,
4072                                int requiredOperandCount = -1,
4073                                Delimiter delimiter = Delimiter::None) override {
4074     return parseOperandOrRegionArgList(result, /*isOperandList=*/true,
4075                                        requiredOperandCount, delimiter);
4076   }
4077 
4078   /// Parse zero or more SSA comma-separated operand or region arguments with
4079   ///  optional surrounding delimiter and required operand count.
4080   ParseResult
4081   parseOperandOrRegionArgList(SmallVectorImpl<OperandType> &result,
4082                               bool isOperandList, int requiredOperandCount = -1,
4083                               Delimiter delimiter = Delimiter::None) {
4084     auto startLoc = parser.getToken().getLoc();
4085 
4086     // Handle delimiters.
4087     switch (delimiter) {
4088     case Delimiter::None:
4089       // Don't check for the absence of a delimiter if the number of operands
4090       // is unknown (and hence the operand list could be empty).
4091       if (requiredOperandCount == -1)
4092         break;
4093       // Token already matches an identifier and so can't be a delimiter.
4094       if (parser.getToken().is(Token::percent_identifier))
4095         break;
4096       // Test against known delimiters.
4097       if (parser.getToken().is(Token::l_paren) ||
4098           parser.getToken().is(Token::l_square))
4099         return emitError(startLoc, "unexpected delimiter");
4100       return emitError(startLoc, "invalid operand");
4101     case Delimiter::OptionalParen:
4102       if (parser.getToken().isNot(Token::l_paren))
4103         return success();
4104       LLVM_FALLTHROUGH;
4105     case Delimiter::Paren:
4106       if (parser.parseToken(Token::l_paren, "expected '(' in operand list"))
4107         return failure();
4108       break;
4109     case Delimiter::OptionalSquare:
4110       if (parser.getToken().isNot(Token::l_square))
4111         return success();
4112       LLVM_FALLTHROUGH;
4113     case Delimiter::Square:
4114       if (parser.parseToken(Token::l_square, "expected '[' in operand list"))
4115         return failure();
4116       break;
4117     }
4118 
4119     // Check for zero operands.
4120     if (parser.getToken().is(Token::percent_identifier)) {
4121       do {
4122         OperandType operandOrArg;
4123         if (isOperandList ? parseOperand(operandOrArg)
4124                           : parseRegionArgument(operandOrArg))
4125           return failure();
4126         result.push_back(operandOrArg);
4127       } while (parser.consumeIf(Token::comma));
4128     }
4129 
4130     // Handle delimiters.   If we reach here, the optional delimiters were
4131     // present, so we need to parse their closing one.
4132     switch (delimiter) {
4133     case Delimiter::None:
4134       break;
4135     case Delimiter::OptionalParen:
4136     case Delimiter::Paren:
4137       if (parser.parseToken(Token::r_paren, "expected ')' in operand list"))
4138         return failure();
4139       break;
4140     case Delimiter::OptionalSquare:
4141     case Delimiter::Square:
4142       if (parser.parseToken(Token::r_square, "expected ']' in operand list"))
4143         return failure();
4144       break;
4145     }
4146 
4147     if (requiredOperandCount != -1 &&
4148         result.size() != static_cast<size_t>(requiredOperandCount))
4149       return emitError(startLoc, "expected ")
4150              << requiredOperandCount << " operands";
4151     return success();
4152   }
4153 
4154   /// Parse zero or more trailing SSA comma-separated trailing operand
4155   /// references with a specified surrounding delimiter, and an optional
4156   /// required operand count. A leading comma is expected before the operands.
4157   ParseResult parseTrailingOperandList(SmallVectorImpl<OperandType> &result,
4158                                        int requiredOperandCount,
4159                                        Delimiter delimiter) override {
4160     if (parser.getToken().is(Token::comma)) {
4161       parseComma();
4162       return parseOperandList(result, requiredOperandCount, delimiter);
4163     }
4164     if (requiredOperandCount != -1)
4165       return emitError(parser.getToken().getLoc(), "expected ")
4166              << requiredOperandCount << " operands";
4167     return success();
4168   }
4169 
4170   /// Resolve an operand to an SSA value, emitting an error on failure.
4171   ParseResult resolveOperand(const OperandType &operand, Type type,
4172                              SmallVectorImpl<Value> &result) override {
4173     OperationParser::SSAUseInfo operandInfo = {operand.name, operand.number,
4174                                                operand.location};
4175     if (auto value = parser.resolveSSAUse(operandInfo, type)) {
4176       result.push_back(value);
4177       return success();
4178     }
4179     return failure();
4180   }
4181 
4182   /// Parse an AffineMap of SSA ids.
4183   ParseResult
4184   parseAffineMapOfSSAIds(SmallVectorImpl<OperandType> &operands,
4185                          Attribute &mapAttr, StringRef attrName,
4186                          SmallVectorImpl<NamedAttribute> &attrs) override {
4187     SmallVector<OperandType, 2> dimOperands;
4188     SmallVector<OperandType, 1> symOperands;
4189 
4190     auto parseElement = [&](bool isSymbol) -> ParseResult {
4191       OperandType operand;
4192       if (parseOperand(operand))
4193         return failure();
4194       if (isSymbol)
4195         symOperands.push_back(operand);
4196       else
4197         dimOperands.push_back(operand);
4198       return success();
4199     };
4200 
4201     AffineMap map;
4202     if (parser.parseAffineMapOfSSAIds(map, parseElement))
4203       return failure();
4204     // Add AffineMap attribute.
4205     if (map) {
4206       mapAttr = AffineMapAttr::get(map);
4207       attrs.push_back(parser.builder.getNamedAttr(attrName, mapAttr));
4208     }
4209 
4210     // Add dim operands before symbol operands in 'operands'.
4211     operands.assign(dimOperands.begin(), dimOperands.end());
4212     operands.append(symOperands.begin(), symOperands.end());
4213     return success();
4214   }
4215 
4216   //===--------------------------------------------------------------------===//
4217   // Region Parsing
4218   //===--------------------------------------------------------------------===//
4219 
4220   /// Parse a region that takes `arguments` of `argTypes` types.  This
4221   /// effectively defines the SSA values of `arguments` and assigns their type.
4222   ParseResult parseRegion(Region &region, ArrayRef<OperandType> arguments,
4223                           ArrayRef<Type> argTypes,
4224                           bool enableNameShadowing) override {
4225     assert(arguments.size() == argTypes.size() &&
4226            "mismatching number of arguments and types");
4227 
4228     SmallVector<std::pair<OperationParser::SSAUseInfo, Type>, 2>
4229         regionArguments;
4230     for (auto pair : llvm::zip(arguments, argTypes)) {
4231       const OperandType &operand = std::get<0>(pair);
4232       Type type = std::get<1>(pair);
4233       OperationParser::SSAUseInfo operandInfo = {operand.name, operand.number,
4234                                                  operand.location};
4235       regionArguments.emplace_back(operandInfo, type);
4236     }
4237 
4238     // Try to parse the region.
4239     assert((!enableNameShadowing ||
4240             opDefinition->hasProperty(OperationProperty::IsolatedFromAbove)) &&
4241            "name shadowing is only allowed on isolated regions");
4242     if (parser.parseRegion(region, regionArguments, enableNameShadowing))
4243       return failure();
4244     return success();
4245   }
4246 
4247   /// Parses a region if present.
4248   ParseResult parseOptionalRegion(Region &region,
4249                                   ArrayRef<OperandType> arguments,
4250                                   ArrayRef<Type> argTypes,
4251                                   bool enableNameShadowing) override {
4252     if (parser.getToken().isNot(Token::l_brace))
4253       return success();
4254     return parseRegion(region, arguments, argTypes, enableNameShadowing);
4255   }
4256 
4257   /// Parse a region argument. The type of the argument will be resolved later
4258   /// by a call to `parseRegion`.
4259   ParseResult parseRegionArgument(OperandType &argument) override {
4260     return parseOperand(argument);
4261   }
4262 
4263   /// Parse a region argument if present.
4264   ParseResult parseOptionalRegionArgument(OperandType &argument) override {
4265     if (parser.getToken().isNot(Token::percent_identifier))
4266       return success();
4267     return parseRegionArgument(argument);
4268   }
4269 
4270   ParseResult
4271   parseRegionArgumentList(SmallVectorImpl<OperandType> &result,
4272                           int requiredOperandCount = -1,
4273                           Delimiter delimiter = Delimiter::None) override {
4274     return parseOperandOrRegionArgList(result, /*isOperandList=*/false,
4275                                        requiredOperandCount, delimiter);
4276   }
4277 
4278   //===--------------------------------------------------------------------===//
4279   // Successor Parsing
4280   //===--------------------------------------------------------------------===//
4281 
4282   /// Parse a single operation successor and its operand list.
4283   ParseResult
4284   parseSuccessorAndUseList(Block *&dest,
4285                            SmallVectorImpl<Value> &operands) override {
4286     return parser.parseSuccessorAndUseList(dest, operands);
4287   }
4288 
4289   //===--------------------------------------------------------------------===//
4290   // Type Parsing
4291   //===--------------------------------------------------------------------===//
4292 
4293   /// Parse a type.
4294   ParseResult parseType(Type &result) override {
4295     return failure(!(result = parser.parseType()));
4296   }
4297 
4298   /// Parse an optional arrow followed by a type list.
4299   ParseResult
4300   parseOptionalArrowTypeList(SmallVectorImpl<Type> &result) override {
4301     if (!parser.consumeIf(Token::arrow))
4302       return success();
4303     return parser.parseFunctionResultTypes(result);
4304   }
4305 
4306   /// Parse a colon followed by a type.
4307   ParseResult parseColonType(Type &result) override {
4308     return failure(parser.parseToken(Token::colon, "expected ':'") ||
4309                    !(result = parser.parseType()));
4310   }
4311 
4312   /// Parse a colon followed by a type list, which must have at least one type.
4313   ParseResult parseColonTypeList(SmallVectorImpl<Type> &result) override {
4314     if (parser.parseToken(Token::colon, "expected ':'"))
4315       return failure();
4316     return parser.parseTypeListNoParens(result);
4317   }
4318 
4319   /// Parse an optional colon followed by a type list, which if present must
4320   /// have at least one type.
4321   ParseResult
4322   parseOptionalColonTypeList(SmallVectorImpl<Type> &result) override {
4323     if (!parser.consumeIf(Token::colon))
4324       return success();
4325     return parser.parseTypeListNoParens(result);
4326   }
4327 
4328 private:
4329   /// The source location of the operation name.
4330   SMLoc nameLoc;
4331 
4332   /// The abstract information of the operation.
4333   const AbstractOperation *opDefinition;
4334 
4335   /// The main operation parser.
4336   OperationParser &parser;
4337 
4338   /// A flag that indicates if any errors were emitted during parsing.
4339   bool emittedError = false;
4340 };
4341 } // end anonymous namespace.
4342 
4343 Operation *OperationParser::parseCustomOperation() {
4344   auto opLoc = getToken().getLoc();
4345   auto opName = getTokenSpelling();
4346 
4347   auto *opDefinition = AbstractOperation::lookup(opName, getContext());
4348   if (!opDefinition && !opName.contains('.')) {
4349     // If the operation name has no namespace prefix we treat it as a standard
4350     // operation and prefix it with "std".
4351     // TODO: Would it be better to just build a mapping of the registered
4352     // operations in the standard dialect?
4353     opDefinition =
4354         AbstractOperation::lookup(Twine("std." + opName).str(), getContext());
4355   }
4356 
4357   if (!opDefinition) {
4358     emitError(opLoc) << "custom op '" << opName << "' is unknown";
4359     return nullptr;
4360   }
4361 
4362   consumeToken();
4363 
4364   // If the custom op parser crashes, produce some indication to help
4365   // debugging.
4366   std::string opNameStr = opName.str();
4367   llvm::PrettyStackTraceFormat fmt("MLIR Parser: custom op parser '%s'",
4368                                    opNameStr.c_str());
4369 
4370   // Get location information for the operation.
4371   auto srcLocation = getEncodedSourceLocation(opLoc);
4372 
4373   // Have the op implementation take a crack and parsing this.
4374   OperationState opState(srcLocation, opDefinition->name);
4375   CleanupOpStateRegions guard{opState};
4376   CustomOpAsmParser opAsmParser(opLoc, opDefinition, *this);
4377   if (opAsmParser.parseOperation(opState))
4378     return nullptr;
4379 
4380   // If it emitted an error, we failed.
4381   if (opAsmParser.didEmitError())
4382     return nullptr;
4383 
4384   // Parse a location if one is present.
4385   if (parseOptionalTrailingLocation(opState.location))
4386     return nullptr;
4387 
4388   // Otherwise, we succeeded.  Use the state it parsed as our op information.
4389   return opBuilder.createOperation(opState);
4390 }
4391 
4392 //===----------------------------------------------------------------------===//
4393 // Region Parsing
4394 //===----------------------------------------------------------------------===//
4395 
4396 /// Region.
4397 ///
4398 ///   region ::= '{' region-body
4399 ///
4400 ParseResult OperationParser::parseRegion(
4401     Region &region,
4402     ArrayRef<std::pair<OperationParser::SSAUseInfo, Type>> entryArguments,
4403     bool isIsolatedNameScope) {
4404   // Parse the '{'.
4405   if (parseToken(Token::l_brace, "expected '{' to begin a region"))
4406     return failure();
4407 
4408   // Check for an empty region.
4409   if (entryArguments.empty() && consumeIf(Token::r_brace))
4410     return success();
4411   auto currentPt = opBuilder.saveInsertionPoint();
4412 
4413   // Push a new named value scope.
4414   pushSSANameScope(isIsolatedNameScope);
4415 
4416   // Parse the first block directly to allow for it to be unnamed.
4417   Block *block = new Block();
4418 
4419   // Add arguments to the entry block.
4420   if (!entryArguments.empty()) {
4421     for (auto &placeholderArgPair : entryArguments) {
4422       auto &argInfo = placeholderArgPair.first;
4423       // Ensure that the argument was not already defined.
4424       if (auto defLoc = getReferenceLoc(argInfo.name, argInfo.number)) {
4425         return emitError(argInfo.loc, "region entry argument '" + argInfo.name +
4426                                           "' is already in use")
4427                    .attachNote(getEncodedSourceLocation(*defLoc))
4428                << "previously referenced here";
4429       }
4430       if (addDefinition(placeholderArgPair.first,
4431                         block->addArgument(placeholderArgPair.second))) {
4432         delete block;
4433         return failure();
4434       }
4435     }
4436 
4437     // If we had named arguments, then don't allow a block name.
4438     if (getToken().is(Token::caret_identifier))
4439       return emitError("invalid block name in region with named arguments");
4440   }
4441 
4442   if (parseBlock(block)) {
4443     delete block;
4444     return failure();
4445   }
4446 
4447   // Verify that no other arguments were parsed.
4448   if (!entryArguments.empty() &&
4449       block->getNumArguments() > entryArguments.size()) {
4450     delete block;
4451     return emitError("entry block arguments were already defined");
4452   }
4453 
4454   // Parse the rest of the region.
4455   region.push_back(block);
4456   if (parseRegionBody(region))
4457     return failure();
4458 
4459   // Pop the SSA value scope for this region.
4460   if (popSSANameScope())
4461     return failure();
4462 
4463   // Reset the original insertion point.
4464   opBuilder.restoreInsertionPoint(currentPt);
4465   return success();
4466 }
4467 
4468 /// Region.
4469 ///
4470 ///   region-body ::= block* '}'
4471 ///
4472 ParseResult OperationParser::parseRegionBody(Region &region) {
4473   // Parse the list of blocks.
4474   while (!consumeIf(Token::r_brace)) {
4475     Block *newBlock = nullptr;
4476     if (parseBlock(newBlock))
4477       return failure();
4478     region.push_back(newBlock);
4479   }
4480   return success();
4481 }
4482 
4483 //===----------------------------------------------------------------------===//
4484 // Block Parsing
4485 //===----------------------------------------------------------------------===//
4486 
4487 /// Block declaration.
4488 ///
4489 ///   block ::= block-label? operation*
4490 ///   block-label    ::= block-id block-arg-list? `:`
4491 ///   block-id       ::= caret-id
4492 ///   block-arg-list ::= `(` ssa-id-and-type-list? `)`
4493 ///
4494 ParseResult OperationParser::parseBlock(Block *&block) {
4495   // The first block of a region may already exist, if it does the caret
4496   // identifier is optional.
4497   if (block && getToken().isNot(Token::caret_identifier))
4498     return parseBlockBody(block);
4499 
4500   SMLoc nameLoc = getToken().getLoc();
4501   auto name = getTokenSpelling();
4502   if (parseToken(Token::caret_identifier, "expected block name"))
4503     return failure();
4504 
4505   block = defineBlockNamed(name, nameLoc, block);
4506 
4507   // Fail if the block was already defined.
4508   if (!block)
4509     return emitError(nameLoc, "redefinition of block '") << name << "'";
4510 
4511   // If an argument list is present, parse it.
4512   if (consumeIf(Token::l_paren)) {
4513     SmallVector<BlockArgument, 8> bbArgs;
4514     if (parseOptionalBlockArgList(bbArgs, block) ||
4515         parseToken(Token::r_paren, "expected ')' to end argument list"))
4516       return failure();
4517   }
4518 
4519   if (parseToken(Token::colon, "expected ':' after block name"))
4520     return failure();
4521 
4522   return parseBlockBody(block);
4523 }
4524 
4525 ParseResult OperationParser::parseBlockBody(Block *block) {
4526   // Set the insertion point to the end of the block to parse.
4527   opBuilder.setInsertionPointToEnd(block);
4528 
4529   // Parse the list of operations that make up the body of the block.
4530   while (getToken().isNot(Token::caret_identifier, Token::r_brace))
4531     if (parseOperation())
4532       return failure();
4533 
4534   return success();
4535 }
4536 
4537 /// Get the block with the specified name, creating it if it doesn't already
4538 /// exist.  The location specified is the point of use, which allows
4539 /// us to diagnose references to blocks that are not defined precisely.
4540 Block *OperationParser::getBlockNamed(StringRef name, SMLoc loc) {
4541   auto &blockAndLoc = getBlockInfoByName(name);
4542   if (!blockAndLoc.first) {
4543     blockAndLoc = {new Block(), loc};
4544     insertForwardRef(blockAndLoc.first, loc);
4545   }
4546 
4547   return blockAndLoc.first;
4548 }
4549 
4550 /// Define the block with the specified name. Returns the Block* or nullptr in
4551 /// the case of redefinition.
4552 Block *OperationParser::defineBlockNamed(StringRef name, SMLoc loc,
4553                                          Block *existing) {
4554   auto &blockAndLoc = getBlockInfoByName(name);
4555   if (!blockAndLoc.first) {
4556     // If the caller provided a block, use it.  Otherwise create a new one.
4557     if (!existing)
4558       existing = new Block();
4559     blockAndLoc.first = existing;
4560     blockAndLoc.second = loc;
4561     return blockAndLoc.first;
4562   }
4563 
4564   // Forward declarations are removed once defined, so if we are defining a
4565   // existing block and it is not a forward declaration, then it is a
4566   // redeclaration.
4567   if (!eraseForwardRef(blockAndLoc.first))
4568     return nullptr;
4569   return blockAndLoc.first;
4570 }
4571 
4572 /// Parse a (possibly empty) list of SSA operands with types as block arguments.
4573 ///
4574 ///   ssa-id-and-type-list ::= ssa-id-and-type (`,` ssa-id-and-type)*
4575 ///
4576 ParseResult OperationParser::parseOptionalBlockArgList(
4577     SmallVectorImpl<BlockArgument> &results, Block *owner) {
4578   if (getToken().is(Token::r_brace))
4579     return success();
4580 
4581   // If the block already has arguments, then we're handling the entry block.
4582   // Parse and register the names for the arguments, but do not add them.
4583   bool definingExistingArgs = owner->getNumArguments() != 0;
4584   unsigned nextArgument = 0;
4585 
4586   return parseCommaSeparatedList([&]() -> ParseResult {
4587     return parseSSADefOrUseAndType(
4588         [&](SSAUseInfo useInfo, Type type) -> ParseResult {
4589           // If this block did not have existing arguments, define a new one.
4590           if (!definingExistingArgs)
4591             return addDefinition(useInfo, owner->addArgument(type));
4592 
4593           // Otherwise, ensure that this argument has already been created.
4594           if (nextArgument >= owner->getNumArguments())
4595             return emitError("too many arguments specified in argument list");
4596 
4597           // Finally, make sure the existing argument has the correct type.
4598           auto arg = owner->getArgument(nextArgument++);
4599           if (arg.getType() != type)
4600             return emitError("argument and block argument type mismatch");
4601           return addDefinition(useInfo, arg);
4602         });
4603   });
4604 }
4605 
4606 //===----------------------------------------------------------------------===//
4607 // Top-level entity parsing.
4608 //===----------------------------------------------------------------------===//
4609 
4610 namespace {
4611 /// This parser handles entities that are only valid at the top level of the
4612 /// file.
4613 class ModuleParser : public Parser {
4614 public:
4615   explicit ModuleParser(ParserState &state) : Parser(state) {}
4616 
4617   ParseResult parseModule(ModuleOp module);
4618 
4619 private:
4620   /// Parse an attribute alias declaration.
4621   ParseResult parseAttributeAliasDef();
4622 
4623   /// Parse an attribute alias declaration.
4624   ParseResult parseTypeAliasDef();
4625 };
4626 } // end anonymous namespace
4627 
4628 /// Parses an attribute alias declaration.
4629 ///
4630 ///   attribute-alias-def ::= '#' alias-name `=` attribute-value
4631 ///
4632 ParseResult ModuleParser::parseAttributeAliasDef() {
4633   assert(getToken().is(Token::hash_identifier));
4634   StringRef aliasName = getTokenSpelling().drop_front();
4635 
4636   // Check for redefinitions.
4637   if (getState().symbols.attributeAliasDefinitions.count(aliasName) > 0)
4638     return emitError("redefinition of attribute alias id '" + aliasName + "'");
4639 
4640   // Make sure this isn't invading the dialect attribute namespace.
4641   if (aliasName.contains('.'))
4642     return emitError("attribute names with a '.' are reserved for "
4643                      "dialect-defined names");
4644 
4645   consumeToken(Token::hash_identifier);
4646 
4647   // Parse the '='.
4648   if (parseToken(Token::equal, "expected '=' in attribute alias definition"))
4649     return failure();
4650 
4651   // Parse the attribute value.
4652   Attribute attr = parseAttribute();
4653   if (!attr)
4654     return failure();
4655 
4656   getState().symbols.attributeAliasDefinitions[aliasName] = attr;
4657   return success();
4658 }
4659 
4660 /// Parse a type alias declaration.
4661 ///
4662 ///   type-alias-def ::= '!' alias-name `=` 'type' type
4663 ///
4664 ParseResult ModuleParser::parseTypeAliasDef() {
4665   assert(getToken().is(Token::exclamation_identifier));
4666   StringRef aliasName = getTokenSpelling().drop_front();
4667 
4668   // Check for redefinitions.
4669   if (getState().symbols.typeAliasDefinitions.count(aliasName) > 0)
4670     return emitError("redefinition of type alias id '" + aliasName + "'");
4671 
4672   // Make sure this isn't invading the dialect type namespace.
4673   if (aliasName.contains('.'))
4674     return emitError("type names with a '.' are reserved for "
4675                      "dialect-defined names");
4676 
4677   consumeToken(Token::exclamation_identifier);
4678 
4679   // Parse the '=' and 'type'.
4680   if (parseToken(Token::equal, "expected '=' in type alias definition") ||
4681       parseToken(Token::kw_type, "expected 'type' in type alias definition"))
4682     return failure();
4683 
4684   // Parse the type.
4685   Type aliasedType = parseType();
4686   if (!aliasedType)
4687     return failure();
4688 
4689   // Register this alias with the parser state.
4690   getState().symbols.typeAliasDefinitions.try_emplace(aliasName, aliasedType);
4691   return success();
4692 }
4693 
4694 /// This is the top-level module parser.
4695 ParseResult ModuleParser::parseModule(ModuleOp module) {
4696   OperationParser opParser(getState(), module);
4697 
4698   // Module itself is a name scope.
4699   opParser.pushSSANameScope(/*isIsolated=*/true);
4700 
4701   while (true) {
4702     switch (getToken().getKind()) {
4703     default:
4704       // Parse a top-level operation.
4705       if (opParser.parseOperation())
4706         return failure();
4707       break;
4708 
4709     // If we got to the end of the file, then we're done.
4710     case Token::eof: {
4711       if (opParser.finalize())
4712         return failure();
4713 
4714       // Handle the case where the top level module was explicitly defined.
4715       auto &bodyBlocks = module.getBodyRegion().getBlocks();
4716       auto &operations = bodyBlocks.front().getOperations();
4717       assert(!operations.empty() && "expected a valid module terminator");
4718 
4719       // Check that the first operation is a module, and it is the only
4720       // non-terminator operation.
4721       ModuleOp nested = dyn_cast<ModuleOp>(operations.front());
4722       if (nested && std::next(operations.begin(), 2) == operations.end()) {
4723         // Merge the data of the nested module operation into 'module'.
4724         module.setLoc(nested.getLoc());
4725         module.setAttrs(nested.getOperation()->getAttrList());
4726         bodyBlocks.splice(bodyBlocks.end(), nested.getBodyRegion().getBlocks());
4727 
4728         // Erase the original module body.
4729         bodyBlocks.pop_front();
4730       }
4731 
4732       return opParser.popSSANameScope();
4733     }
4734 
4735     // If we got an error token, then the lexer already emitted an error, just
4736     // stop.  Someday we could introduce error recovery if there was demand
4737     // for it.
4738     case Token::error:
4739       return failure();
4740 
4741     // Parse an attribute alias.
4742     case Token::hash_identifier:
4743       if (parseAttributeAliasDef())
4744         return failure();
4745       break;
4746 
4747     // Parse a type alias.
4748     case Token::exclamation_identifier:
4749       if (parseTypeAliasDef())
4750         return failure();
4751       break;
4752     }
4753   }
4754 }
4755 
4756 //===----------------------------------------------------------------------===//
4757 
4758 /// This parses the file specified by the indicated SourceMgr and returns an
4759 /// MLIR module if it was valid.  If not, it emits diagnostics and returns
4760 /// null.
4761 OwningModuleRef mlir::parseSourceFile(const llvm::SourceMgr &sourceMgr,
4762                                       MLIRContext *context) {
4763   auto sourceBuf = sourceMgr.getMemoryBuffer(sourceMgr.getMainFileID());
4764 
4765   // This is the result module we are parsing into.
4766   OwningModuleRef module(ModuleOp::create(FileLineColLoc::get(
4767       sourceBuf->getBufferIdentifier(), /*line=*/0, /*column=*/0, context)));
4768 
4769   SymbolState aliasState;
4770   ParserState state(sourceMgr, context, aliasState);
4771   if (ModuleParser(state).parseModule(*module))
4772     return nullptr;
4773 
4774   // Make sure the parse module has no other structural problems detected by
4775   // the verifier.
4776   if (failed(verify(*module)))
4777     return nullptr;
4778 
4779   return module;
4780 }
4781 
4782 /// This parses the file specified by the indicated filename and returns an
4783 /// MLIR module if it was valid.  If not, the error message is emitted through
4784 /// the error handler registered in the context, and a null pointer is returned.
4785 OwningModuleRef mlir::parseSourceFile(StringRef filename,
4786                                       MLIRContext *context) {
4787   llvm::SourceMgr sourceMgr;
4788   return parseSourceFile(filename, sourceMgr, context);
4789 }
4790 
4791 /// This parses the file specified by the indicated filename using the provided
4792 /// SourceMgr and returns an MLIR module if it was valid.  If not, the error
4793 /// message is emitted through the error handler registered in the context, and
4794 /// a null pointer is returned.
4795 OwningModuleRef mlir::parseSourceFile(StringRef filename,
4796                                       llvm::SourceMgr &sourceMgr,
4797                                       MLIRContext *context) {
4798   if (sourceMgr.getNumBuffers() != 0) {
4799     // TODO(b/136086478): Extend to support multiple buffers.
4800     emitError(mlir::UnknownLoc::get(context),
4801               "only main buffer parsed at the moment");
4802     return nullptr;
4803   }
4804   auto file_or_err = llvm::MemoryBuffer::getFileOrSTDIN(filename);
4805   if (std::error_code error = file_or_err.getError()) {
4806     emitError(mlir::UnknownLoc::get(context),
4807               "could not open input file " + filename);
4808     return nullptr;
4809   }
4810 
4811   // Load the MLIR module.
4812   sourceMgr.AddNewSourceBuffer(std::move(*file_or_err), llvm::SMLoc());
4813   return parseSourceFile(sourceMgr, context);
4814 }
4815 
4816 /// This parses the program string to a MLIR module if it was valid. If not,
4817 /// it emits diagnostics and returns null.
4818 OwningModuleRef mlir::parseSourceString(StringRef moduleStr,
4819                                         MLIRContext *context) {
4820   auto memBuffer = MemoryBuffer::getMemBuffer(moduleStr);
4821   if (!memBuffer)
4822     return nullptr;
4823 
4824   SourceMgr sourceMgr;
4825   sourceMgr.AddNewSourceBuffer(std::move(memBuffer), SMLoc());
4826   return parseSourceFile(sourceMgr, context);
4827 }
4828 
4829 /// Parses a symbol, of type 'T', and returns it if parsing was successful. If
4830 /// parsing failed, nullptr is returned. The number of bytes read from the input
4831 /// string is returned in 'numRead'.
4832 template <typename T, typename ParserFn>
4833 static T parseSymbol(StringRef inputStr, MLIRContext *context, size_t &numRead,
4834                      ParserFn &&parserFn) {
4835   SymbolState aliasState;
4836   return parseSymbol<T>(
4837       inputStr, context, aliasState,
4838       [&](Parser &parser) {
4839         SourceMgrDiagnosticHandler handler(
4840             const_cast<llvm::SourceMgr &>(parser.getSourceMgr()),
4841             parser.getContext());
4842         return parserFn(parser);
4843       },
4844       &numRead);
4845 }
4846 
4847 Attribute mlir::parseAttribute(StringRef attrStr, MLIRContext *context) {
4848   size_t numRead = 0;
4849   return parseAttribute(attrStr, context, numRead);
4850 }
4851 Attribute mlir::parseAttribute(StringRef attrStr, Type type) {
4852   size_t numRead = 0;
4853   return parseAttribute(attrStr, type, numRead);
4854 }
4855 
4856 Attribute mlir::parseAttribute(StringRef attrStr, MLIRContext *context,
4857                                size_t &numRead) {
4858   return parseSymbol<Attribute>(attrStr, context, numRead, [](Parser &parser) {
4859     return parser.parseAttribute();
4860   });
4861 }
4862 Attribute mlir::parseAttribute(StringRef attrStr, Type type, size_t &numRead) {
4863   return parseSymbol<Attribute>(
4864       attrStr, type.getContext(), numRead,
4865       [type](Parser &parser) { return parser.parseAttribute(type); });
4866 }
4867 
4868 Type mlir::parseType(StringRef typeStr, MLIRContext *context) {
4869   size_t numRead = 0;
4870   return parseType(typeStr, context, numRead);
4871 }
4872 
4873 Type mlir::parseType(StringRef typeStr, MLIRContext *context, size_t &numRead) {
4874   return parseSymbol<Type>(typeStr, context, numRead,
4875                            [](Parser &parser) { return parser.parseType(); });
4876 }
4877