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