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