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