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