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