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 "Parser.h"
14 #include "mlir/IR/AffineMap.h"
15 #include "mlir/IR/BuiltinOps.h"
16 #include "mlir/IR/Dialect.h"
17 #include "mlir/IR/Verifier.h"
18 #include "mlir/Parser.h"
19 #include "mlir/Parser/AsmParserState.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/ScopeExit.h"
22 #include "llvm/ADT/StringSet.h"
23 #include "llvm/ADT/bit.h"
24 #include "llvm/Support/PrettyStackTrace.h"
25 #include "llvm/Support/SourceMgr.h"
26 #include <algorithm>
27 
28 using namespace mlir;
29 using namespace mlir::detail;
30 using llvm::MemoryBuffer;
31 using llvm::SMLoc;
32 using llvm::SourceMgr;
33 
34 //===----------------------------------------------------------------------===//
35 // Parser
36 //===----------------------------------------------------------------------===//
37 
38 /// Parse a list of comma-separated items with an optional delimiter.  If a
39 /// delimiter is provided, then an empty list is allowed.  If not, then at
40 /// least one element will be parsed.
41 ParseResult
42 Parser::parseCommaSeparatedList(Delimiter delimiter,
43                                 function_ref<ParseResult()> parseElementFn,
44                                 StringRef contextMessage) {
45   switch (delimiter) {
46   case Delimiter::None:
47     break;
48   case Delimiter::OptionalParen:
49     if (getToken().isNot(Token::l_paren))
50       return success();
51     LLVM_FALLTHROUGH;
52   case Delimiter::Paren:
53     if (parseToken(Token::l_paren, "expected '('" + contextMessage))
54       return failure();
55     // Check for empty list.
56     if (consumeIf(Token::r_paren))
57       return success();
58     break;
59   case Delimiter::OptionalLessGreater:
60     // Check for absent list.
61     if (getToken().isNot(Token::less))
62       return success();
63     LLVM_FALLTHROUGH;
64   case Delimiter::LessGreater:
65     if (parseToken(Token::less, "expected '<'" + contextMessage))
66       return success();
67     // Check for empty list.
68     if (consumeIf(Token::greater))
69       return success();
70     break;
71   case Delimiter::OptionalSquare:
72     if (getToken().isNot(Token::l_square))
73       return success();
74     LLVM_FALLTHROUGH;
75   case Delimiter::Square:
76     if (parseToken(Token::l_square, "expected '['" + contextMessage))
77       return failure();
78     // Check for empty list.
79     if (consumeIf(Token::r_square))
80       return success();
81     break;
82   case Delimiter::OptionalBraces:
83     if (getToken().isNot(Token::l_brace))
84       return success();
85     LLVM_FALLTHROUGH;
86   case Delimiter::Braces:
87     if (parseToken(Token::l_brace, "expected '{'" + contextMessage))
88       return failure();
89     // Check for empty list.
90     if (consumeIf(Token::r_brace))
91       return success();
92     break;
93   }
94 
95   // Non-empty case starts with an element.
96   if (parseElementFn())
97     return failure();
98 
99   // Otherwise we have a list of comma separated elements.
100   while (consumeIf(Token::comma)) {
101     if (parseElementFn())
102       return failure();
103   }
104 
105   switch (delimiter) {
106   case Delimiter::None:
107     return success();
108   case Delimiter::OptionalParen:
109   case Delimiter::Paren:
110     return parseToken(Token::r_paren, "expected ')'" + contextMessage);
111   case Delimiter::OptionalLessGreater:
112   case Delimiter::LessGreater:
113     return parseToken(Token::greater, "expected '>'" + contextMessage);
114   case Delimiter::OptionalSquare:
115   case Delimiter::Square:
116     return parseToken(Token::r_square, "expected ']'" + contextMessage);
117   case Delimiter::OptionalBraces:
118   case Delimiter::Braces:
119     return parseToken(Token::r_brace, "expected '}'" + contextMessage);
120   }
121   llvm_unreachable("Unknown delimiter");
122 }
123 
124 /// Parse a comma-separated list of elements, terminated with an arbitrary
125 /// token.  This allows empty lists if allowEmptyList is true.
126 ///
127 ///   abstract-list ::= rightToken                  // if allowEmptyList == true
128 ///   abstract-list ::= element (',' element)* rightToken
129 ///
130 ParseResult
131 Parser::parseCommaSeparatedListUntil(Token::Kind rightToken,
132                                      function_ref<ParseResult()> parseElement,
133                                      bool allowEmptyList) {
134   // Handle the empty case.
135   if (getToken().is(rightToken)) {
136     if (!allowEmptyList)
137       return emitError("expected list element");
138     consumeToken(rightToken);
139     return success();
140   }
141 
142   if (parseCommaSeparatedList(parseElement) ||
143       parseToken(rightToken, "expected ',' or '" +
144                                  Token::getTokenSpelling(rightToken) + "'"))
145     return failure();
146 
147   return success();
148 }
149 
150 InFlightDiagnostic Parser::emitError(SMLoc loc, const Twine &message) {
151   auto diag = mlir::emitError(getEncodedSourceLocation(loc), message);
152 
153   // If we hit a parse error in response to a lexer error, then the lexer
154   // already reported the error.
155   if (getToken().is(Token::error))
156     diag.abandon();
157   return diag;
158 }
159 
160 /// Consume the specified token if present and return success.  On failure,
161 /// output a diagnostic and return failure.
162 ParseResult Parser::parseToken(Token::Kind expectedToken,
163                                const Twine &message) {
164   if (consumeIf(expectedToken))
165     return success();
166   return emitError(message);
167 }
168 
169 /// Parse an optional integer value from the stream.
170 OptionalParseResult Parser::parseOptionalInteger(APInt &result) {
171   Token curToken = getToken();
172   if (curToken.isNot(Token::integer, Token::minus))
173     return llvm::None;
174 
175   bool negative = consumeIf(Token::minus);
176   Token curTok = getToken();
177   if (parseToken(Token::integer, "expected integer value"))
178     return failure();
179 
180   StringRef spelling = curTok.getSpelling();
181   bool isHex = spelling.size() > 1 && spelling[1] == 'x';
182   if (spelling.getAsInteger(isHex ? 0 : 10, result))
183     return emitError(curTok.getLoc(), "integer value too large");
184 
185   // Make sure we have a zero at the top so we return the right signedness.
186   if (result.isNegative())
187     result = result.zext(result.getBitWidth() + 1);
188 
189   // Process the negative sign if present.
190   if (negative)
191     result.negate();
192 
193   return success();
194 }
195 
196 /// Parse a floating point value from an integer literal token.
197 ParseResult Parser::parseFloatFromIntegerLiteral(
198     Optional<APFloat> &result, const Token &tok, bool isNegative,
199     const llvm::fltSemantics &semantics, size_t typeSizeInBits) {
200   llvm::SMLoc loc = tok.getLoc();
201   StringRef spelling = tok.getSpelling();
202   bool isHex = spelling.size() > 1 && spelling[1] == 'x';
203   if (!isHex) {
204     return emitError(loc, "unexpected decimal integer literal for a "
205                           "floating point value")
206                .attachNote()
207            << "add a trailing dot to make the literal a float";
208   }
209   if (isNegative) {
210     return emitError(loc, "hexadecimal float literal should not have a "
211                           "leading minus");
212   }
213 
214   Optional<uint64_t> value = tok.getUInt64IntegerValue();
215   if (!value.hasValue())
216     return emitError(loc, "hexadecimal float constant out of range for type");
217 
218   if (&semantics == &APFloat::IEEEdouble()) {
219     result = APFloat(semantics, APInt(typeSizeInBits, *value));
220     return success();
221   }
222 
223   APInt apInt(typeSizeInBits, *value);
224   if (apInt != *value)
225     return emitError(loc, "hexadecimal float constant out of range for type");
226   result = APFloat(semantics, apInt);
227 
228   return success();
229 }
230 
231 //===----------------------------------------------------------------------===//
232 // OperationParser
233 //===----------------------------------------------------------------------===//
234 
235 namespace {
236 /// This class provides support for parsing operations and regions of
237 /// operations.
238 class OperationParser : public Parser {
239 public:
240   OperationParser(ParserState &state, ModuleOp topLevelOp);
241   ~OperationParser();
242 
243   /// After parsing is finished, this function must be called to see if there
244   /// are any remaining issues.
245   ParseResult finalize();
246 
247   //===--------------------------------------------------------------------===//
248   // SSA Value Handling
249   //===--------------------------------------------------------------------===//
250 
251   /// This represents a use of an SSA value in the program.  The first two
252   /// entries in the tuple are the name and result number of a reference.  The
253   /// third is the location of the reference, which is used in case this ends
254   /// up being a use of an undefined value.
255   struct SSAUseInfo {
256     StringRef name;  // Value name, e.g. %42 or %abc
257     unsigned number; // Number, specified with #12
258     SMLoc loc;       // Location of first definition or use.
259   };
260 
261   /// Push a new SSA name scope to the parser.
262   void pushSSANameScope(bool isIsolated);
263 
264   /// Pop the last SSA name scope from the parser.
265   ParseResult popSSANameScope();
266 
267   /// Register a definition of a value with the symbol table.
268   ParseResult addDefinition(SSAUseInfo useInfo, Value value);
269 
270   /// Parse an optional list of SSA uses into 'results'.
271   ParseResult parseOptionalSSAUseList(SmallVectorImpl<SSAUseInfo> &results);
272 
273   /// Parse a single SSA use into 'result'.
274   ParseResult parseSSAUse(SSAUseInfo &result);
275 
276   /// Given a reference to an SSA value and its type, return a reference. This
277   /// returns null on failure.
278   Value resolveSSAUse(SSAUseInfo useInfo, Type type);
279 
280   ParseResult
281   parseSSADefOrUseAndType(function_ref<ParseResult(SSAUseInfo, Type)> action);
282 
283   ParseResult parseOptionalSSAUseAndTypeList(SmallVectorImpl<Value> &results);
284 
285   /// Return the location of the value identified by its name and number if it
286   /// has been already reference.
287   Optional<SMLoc> getReferenceLoc(StringRef name, unsigned number) {
288     auto &values = isolatedNameScopes.back().values;
289     if (!values.count(name) || number >= values[name].size())
290       return {};
291     if (values[name][number].value)
292       return values[name][number].loc;
293     return {};
294   }
295 
296   //===--------------------------------------------------------------------===//
297   // Operation Parsing
298   //===--------------------------------------------------------------------===//
299 
300   /// Parse an operation instance.
301   ParseResult parseOperation();
302 
303   /// Parse a single operation successor.
304   ParseResult parseSuccessor(Block *&dest);
305 
306   /// Parse a comma-separated list of operation successors in brackets.
307   ParseResult parseSuccessors(SmallVectorImpl<Block *> &destinations);
308 
309   /// Parse an operation instance that is in the generic form.
310   Operation *parseGenericOperation();
311 
312   /// Parse an operation instance that is in the generic form and insert it at
313   /// the provided insertion point.
314   Operation *parseGenericOperation(Block *insertBlock,
315                                    Block::iterator insertPt);
316 
317   /// This type is used to keep track of things that are either an Operation or
318   /// a BlockArgument.  We cannot use Value for this, because not all Operations
319   /// have results.
320   using OpOrArgument = llvm::PointerUnion<Operation *, BlockArgument>;
321 
322   /// Parse an optional trailing location and add it to the specifier Operation
323   /// or `OperandType` if present.
324   ///
325   ///   trailing-location ::= (`loc` (`(` location `)` | attribute-alias))?
326   ///
327   ParseResult parseTrailingLocationSpecifier(OpOrArgument opOrArgument);
328 
329   /// This is the structure of a result specifier in the assembly syntax,
330   /// including the name, number of results, and location.
331   using ResultRecord = std::tuple<StringRef, unsigned, SMLoc>;
332 
333   /// Parse an operation instance that is in the op-defined custom form.
334   /// resultInfo specifies information about the "%name =" specifiers.
335   Operation *parseCustomOperation(ArrayRef<ResultRecord> resultIDs);
336 
337   //===--------------------------------------------------------------------===//
338   // Region Parsing
339   //===--------------------------------------------------------------------===//
340 
341   /// Parse a region into 'region' with the provided entry block arguments.
342   /// 'isIsolatedNameScope' indicates if the naming scope of this region is
343   /// isolated from those above.
344   ParseResult parseRegion(Region &region,
345                           ArrayRef<std::pair<SSAUseInfo, Type>> entryArguments,
346                           bool isIsolatedNameScope = false);
347 
348   /// Parse a region body into 'region'.
349   ParseResult
350   parseRegionBody(Region &region, llvm::SMLoc startLoc,
351                   ArrayRef<std::pair<SSAUseInfo, Type>> entryArguments,
352                   bool isIsolatedNameScope);
353 
354   //===--------------------------------------------------------------------===//
355   // Block Parsing
356   //===--------------------------------------------------------------------===//
357 
358   /// Parse a new block into 'block'.
359   ParseResult parseBlock(Block *&block);
360 
361   /// Parse a list of operations into 'block'.
362   ParseResult parseBlockBody(Block *block);
363 
364   /// Parse a (possibly empty) list of block arguments.
365   ParseResult parseOptionalBlockArgList(Block *owner);
366 
367   /// Get the block with the specified name, creating it if it doesn't
368   /// already exist.  The location specified is the point of use, which allows
369   /// us to diagnose references to blocks that are not defined precisely.
370   Block *getBlockNamed(StringRef name, SMLoc loc);
371 
372   /// Define the block with the specified name. Returns the Block* or nullptr in
373   /// the case of redefinition.
374   Block *defineBlockNamed(StringRef name, SMLoc loc, Block *existing);
375 
376 private:
377   /// This class represents a definition of a Block.
378   struct BlockDefinition {
379     /// A pointer to the defined Block.
380     Block *block;
381     /// The location that the Block was defined at.
382     SMLoc loc;
383   };
384   /// This class represents a definition of a Value.
385   struct ValueDefinition {
386     /// A pointer to the defined Value.
387     Value value;
388     /// The location that the Value was defined at.
389     SMLoc loc;
390   };
391 
392   /// Returns the info for a block at the current scope for the given name.
393   BlockDefinition &getBlockInfoByName(StringRef name) {
394     return blocksByName.back()[name];
395   }
396 
397   /// Insert a new forward reference to the given block.
398   void insertForwardRef(Block *block, SMLoc loc) {
399     forwardRef.back().try_emplace(block, loc);
400   }
401 
402   /// Erase any forward reference to the given block.
403   bool eraseForwardRef(Block *block) { return forwardRef.back().erase(block); }
404 
405   /// Record that a definition was added at the current scope.
406   void recordDefinition(StringRef def);
407 
408   /// Get the value entry for the given SSA name.
409   SmallVectorImpl<ValueDefinition> &getSSAValueEntry(StringRef name);
410 
411   /// Create a forward reference placeholder value with the given location and
412   /// result type.
413   Value createForwardRefPlaceholder(SMLoc loc, Type type);
414 
415   /// Return true if this is a forward reference.
416   bool isForwardRefPlaceholder(Value value) {
417     return forwardRefPlaceholders.count(value);
418   }
419 
420   /// This struct represents an isolated SSA name scope. This scope may contain
421   /// other nested non-isolated scopes. These scopes are used for operations
422   /// that are known to be isolated to allow for reusing names within their
423   /// regions, even if those names are used above.
424   struct IsolatedSSANameScope {
425     /// Record that a definition was added at the current scope.
426     void recordDefinition(StringRef def) {
427       definitionsPerScope.back().insert(def);
428     }
429 
430     /// Push a nested name scope.
431     void pushSSANameScope() { definitionsPerScope.push_back({}); }
432 
433     /// Pop a nested name scope.
434     void popSSANameScope() {
435       for (auto &def : definitionsPerScope.pop_back_val())
436         values.erase(def.getKey());
437     }
438 
439     /// This keeps track of all of the SSA values we are tracking for each name
440     /// scope, indexed by their name. This has one entry per result number.
441     llvm::StringMap<SmallVector<ValueDefinition, 1>> values;
442 
443     /// This keeps track of all of the values defined by a specific name scope.
444     SmallVector<llvm::StringSet<>, 2> definitionsPerScope;
445   };
446 
447   /// A list of isolated name scopes.
448   SmallVector<IsolatedSSANameScope, 2> isolatedNameScopes;
449 
450   /// This keeps track of the block names as well as the location of the first
451   /// reference for each nested name scope. This is used to diagnose invalid
452   /// block references and memorize them.
453   SmallVector<DenseMap<StringRef, BlockDefinition>, 2> blocksByName;
454   SmallVector<DenseMap<Block *, SMLoc>, 2> forwardRef;
455 
456   /// These are all of the placeholders we've made along with the location of
457   /// their first reference, to allow checking for use of undefined values.
458   DenseMap<Value, SMLoc> forwardRefPlaceholders;
459 
460   /// A set of operations whose locations reference aliases that have yet to
461   /// be resolved.
462   SmallVector<std::pair<OpOrArgument, Token>, 8>
463       opsAndArgumentsWithDeferredLocs;
464 
465   /// The builder used when creating parsed operation instances.
466   OpBuilder opBuilder;
467 
468   /// The top level operation that holds all of the parsed operations.
469   Operation *topLevelOp;
470 };
471 } // end anonymous namespace
472 
473 OperationParser::OperationParser(ParserState &state, ModuleOp topLevelOp)
474     : Parser(state), opBuilder(topLevelOp.getRegion()), topLevelOp(topLevelOp) {
475   // The top level operation starts a new name scope.
476   pushSSANameScope(/*isIsolated=*/true);
477 
478   // If we are populating the parser state, prepare it for parsing.
479   if (state.asmState)
480     state.asmState->initialize(topLevelOp);
481 }
482 
483 OperationParser::~OperationParser() {
484   for (auto &fwd : forwardRefPlaceholders) {
485     // Drop all uses of undefined forward declared reference and destroy
486     // defining operation.
487     fwd.first.dropAllUses();
488     fwd.first.getDefiningOp()->destroy();
489   }
490   for (const auto &scope : forwardRef) {
491     for (const auto &fwd : scope) {
492       // Delete all blocks that were created as forward references but never
493       // included into a region.
494       fwd.first->dropAllUses();
495       delete fwd.first;
496     }
497   }
498 }
499 
500 /// After parsing is finished, this function must be called to see if there are
501 /// any remaining issues.
502 ParseResult OperationParser::finalize() {
503   // Check for any forward references that are left.  If we find any, error
504   // out.
505   if (!forwardRefPlaceholders.empty()) {
506     SmallVector<const char *, 4> errors;
507     // Iteration over the map isn't deterministic, so sort by source location.
508     for (auto entry : forwardRefPlaceholders)
509       errors.push_back(entry.second.getPointer());
510     llvm::array_pod_sort(errors.begin(), errors.end());
511 
512     for (auto entry : errors) {
513       auto loc = SMLoc::getFromPointer(entry);
514       emitError(loc, "use of undeclared SSA value name");
515     }
516     return failure();
517   }
518 
519   // Resolve the locations of any deferred operations.
520   auto &attributeAliases = state.symbols.attributeAliasDefinitions;
521   for (std::pair<OpOrArgument, Token> &it : opsAndArgumentsWithDeferredLocs) {
522     llvm::SMLoc tokLoc = it.second.getLoc();
523     StringRef identifier = it.second.getSpelling().drop_front();
524     Attribute attr = attributeAliases.lookup(identifier);
525     if (!attr)
526       return emitError(tokLoc) << "operation location alias was never defined";
527 
528     LocationAttr locAttr = attr.dyn_cast<LocationAttr>();
529     if (!locAttr)
530       return emitError(tokLoc)
531              << "expected location, but found '" << attr << "'";
532     auto opOrArgument = it.first;
533     if (auto *op = opOrArgument.dyn_cast<Operation *>())
534       op->setLoc(locAttr);
535     else
536       opOrArgument.get<BlockArgument>().setLoc(locAttr);
537   }
538 
539   // Pop the top level name scope.
540   if (failed(popSSANameScope()))
541     return failure();
542 
543   // Verify that the parsed operations are valid.
544   if (failed(verify(topLevelOp)))
545     return failure();
546 
547   // If we are populating the parser state, finalize the top-level operation.
548   if (state.asmState)
549     state.asmState->finalize(topLevelOp);
550   return success();
551 }
552 
553 //===----------------------------------------------------------------------===//
554 // SSA Value Handling
555 //===----------------------------------------------------------------------===//
556 
557 void OperationParser::pushSSANameScope(bool isIsolated) {
558   blocksByName.push_back(DenseMap<StringRef, BlockDefinition>());
559   forwardRef.push_back(DenseMap<Block *, SMLoc>());
560 
561   // Push back a new name definition scope.
562   if (isIsolated)
563     isolatedNameScopes.push_back({});
564   isolatedNameScopes.back().pushSSANameScope();
565 }
566 
567 ParseResult OperationParser::popSSANameScope() {
568   auto forwardRefInCurrentScope = forwardRef.pop_back_val();
569 
570   // Verify that all referenced blocks were defined.
571   if (!forwardRefInCurrentScope.empty()) {
572     SmallVector<std::pair<const char *, Block *>, 4> errors;
573     // Iteration over the map isn't deterministic, so sort by source location.
574     for (auto entry : forwardRefInCurrentScope) {
575       errors.push_back({entry.second.getPointer(), entry.first});
576       // Add this block to the top-level region to allow for automatic cleanup.
577       topLevelOp->getRegion(0).push_back(entry.first);
578     }
579     llvm::array_pod_sort(errors.begin(), errors.end());
580 
581     for (auto entry : errors) {
582       auto loc = SMLoc::getFromPointer(entry.first);
583       emitError(loc, "reference to an undefined block");
584     }
585     return failure();
586   }
587 
588   // Pop the next nested namescope. If there is only one internal namescope,
589   // just pop the isolated scope.
590   auto &currentNameScope = isolatedNameScopes.back();
591   if (currentNameScope.definitionsPerScope.size() == 1)
592     isolatedNameScopes.pop_back();
593   else
594     currentNameScope.popSSANameScope();
595 
596   blocksByName.pop_back();
597   return success();
598 }
599 
600 /// Register a definition of a value with the symbol table.
601 ParseResult OperationParser::addDefinition(SSAUseInfo useInfo, Value value) {
602   auto &entries = getSSAValueEntry(useInfo.name);
603 
604   // Make sure there is a slot for this value.
605   if (entries.size() <= useInfo.number)
606     entries.resize(useInfo.number + 1);
607 
608   // If we already have an entry for this, check to see if it was a definition
609   // or a forward reference.
610   if (auto existing = entries[useInfo.number].value) {
611     if (!isForwardRefPlaceholder(existing)) {
612       return emitError(useInfo.loc)
613           .append("redefinition of SSA value '", useInfo.name, "'")
614           .attachNote(getEncodedSourceLocation(entries[useInfo.number].loc))
615           .append("previously defined here");
616     }
617 
618     if (existing.getType() != value.getType()) {
619       return emitError(useInfo.loc)
620           .append("definition of SSA value '", useInfo.name, "#",
621                   useInfo.number, "' has type ", value.getType())
622           .attachNote(getEncodedSourceLocation(entries[useInfo.number].loc))
623           .append("previously used here with type ", existing.getType());
624     }
625 
626     // If it was a forward reference, update everything that used it to use
627     // the actual definition instead, delete the forward ref, and remove it
628     // from our set of forward references we track.
629     existing.replaceAllUsesWith(value);
630     existing.getDefiningOp()->destroy();
631     forwardRefPlaceholders.erase(existing);
632 
633     // If a definition of the value already exists, replace it in the assembly
634     // state.
635     if (state.asmState)
636       state.asmState->refineDefinition(existing, value);
637   }
638 
639   /// Record this definition for the current scope.
640   entries[useInfo.number] = {value, useInfo.loc};
641   recordDefinition(useInfo.name);
642   return success();
643 }
644 
645 /// Parse a (possibly empty) list of SSA operands.
646 ///
647 ///   ssa-use-list ::= ssa-use (`,` ssa-use)*
648 ///   ssa-use-list-opt ::= ssa-use-list?
649 ///
650 ParseResult
651 OperationParser::parseOptionalSSAUseList(SmallVectorImpl<SSAUseInfo> &results) {
652   if (getToken().isNot(Token::percent_identifier))
653     return success();
654   return parseCommaSeparatedList([&]() -> ParseResult {
655     SSAUseInfo result;
656     if (parseSSAUse(result))
657       return failure();
658     results.push_back(result);
659     return success();
660   });
661 }
662 
663 /// Parse a SSA operand for an operation.
664 ///
665 ///   ssa-use ::= ssa-id
666 ///
667 ParseResult OperationParser::parseSSAUse(SSAUseInfo &result) {
668   result.name = getTokenSpelling();
669   result.number = 0;
670   result.loc = getToken().getLoc();
671   if (parseToken(Token::percent_identifier, "expected SSA operand"))
672     return failure();
673 
674   // If we have an attribute ID, it is a result number.
675   if (getToken().is(Token::hash_identifier)) {
676     if (auto value = getToken().getHashIdentifierNumber())
677       result.number = value.getValue();
678     else
679       return emitError("invalid SSA value result number");
680     consumeToken(Token::hash_identifier);
681   }
682 
683   return success();
684 }
685 
686 /// Given an unbound reference to an SSA value and its type, return the value
687 /// it specifies.  This returns null on failure.
688 Value OperationParser::resolveSSAUse(SSAUseInfo useInfo, Type type) {
689   auto &entries = getSSAValueEntry(useInfo.name);
690 
691   // Functor used to record the use of the given value if the assembly state
692   // field is populated.
693   auto maybeRecordUse = [&](Value value) {
694     if (state.asmState)
695       state.asmState->addUses(value, useInfo.loc);
696     return value;
697   };
698 
699   // If we have already seen a value of this name, return it.
700   if (useInfo.number < entries.size() && entries[useInfo.number].value) {
701     Value result = entries[useInfo.number].value;
702     // Check that the type matches the other uses.
703     if (result.getType() == type)
704       return maybeRecordUse(result);
705 
706     emitError(useInfo.loc, "use of value '")
707         .append(useInfo.name,
708                 "' expects different type than prior uses: ", type, " vs ",
709                 result.getType())
710         .attachNote(getEncodedSourceLocation(entries[useInfo.number].loc))
711         .append("prior use here");
712     return nullptr;
713   }
714 
715   // Make sure we have enough slots for this.
716   if (entries.size() <= useInfo.number)
717     entries.resize(useInfo.number + 1);
718 
719   // If the value has already been defined and this is an overly large result
720   // number, diagnose that.
721   if (entries[0].value && !isForwardRefPlaceholder(entries[0].value))
722     return (emitError(useInfo.loc, "reference to invalid result number"),
723             nullptr);
724 
725   // Otherwise, this is a forward reference.  Create a placeholder and remember
726   // that we did so.
727   Value result = createForwardRefPlaceholder(useInfo.loc, type);
728   entries[useInfo.number] = {result, useInfo.loc};
729   return maybeRecordUse(result);
730 }
731 
732 /// Parse an SSA use with an associated type.
733 ///
734 ///   ssa-use-and-type ::= ssa-use `:` type
735 ParseResult OperationParser::parseSSADefOrUseAndType(
736     function_ref<ParseResult(SSAUseInfo, Type)> action) {
737   SSAUseInfo useInfo;
738   if (parseSSAUse(useInfo) ||
739       parseToken(Token::colon, "expected ':' and type for SSA operand"))
740     return failure();
741 
742   auto type = parseType();
743   if (!type)
744     return failure();
745 
746   return action(useInfo, type);
747 }
748 
749 /// Parse a (possibly empty) list of SSA operands, followed by a colon, then
750 /// followed by a type list.
751 ///
752 ///   ssa-use-and-type-list
753 ///     ::= ssa-use-list ':' type-list-no-parens
754 ///
755 ParseResult OperationParser::parseOptionalSSAUseAndTypeList(
756     SmallVectorImpl<Value> &results) {
757   SmallVector<SSAUseInfo, 4> valueIDs;
758   if (parseOptionalSSAUseList(valueIDs))
759     return failure();
760 
761   // If there were no operands, then there is no colon or type lists.
762   if (valueIDs.empty())
763     return success();
764 
765   SmallVector<Type, 4> types;
766   if (parseToken(Token::colon, "expected ':' in operand list") ||
767       parseTypeListNoParens(types))
768     return failure();
769 
770   if (valueIDs.size() != types.size())
771     return emitError("expected ")
772            << valueIDs.size() << " types to match operand list";
773 
774   results.reserve(valueIDs.size());
775   for (unsigned i = 0, e = valueIDs.size(); i != e; ++i) {
776     if (auto value = resolveSSAUse(valueIDs[i], types[i]))
777       results.push_back(value);
778     else
779       return failure();
780   }
781 
782   return success();
783 }
784 
785 /// Record that a definition was added at the current scope.
786 void OperationParser::recordDefinition(StringRef def) {
787   isolatedNameScopes.back().recordDefinition(def);
788 }
789 
790 /// Get the value entry for the given SSA name.
791 auto OperationParser::getSSAValueEntry(StringRef name)
792     -> SmallVectorImpl<ValueDefinition> & {
793   return isolatedNameScopes.back().values[name];
794 }
795 
796 /// Create and remember a new placeholder for a forward reference.
797 Value OperationParser::createForwardRefPlaceholder(SMLoc loc, Type type) {
798   // Forward references are always created as operations, because we just need
799   // something with a def/use chain.
800   //
801   // We create these placeholders as having an empty name, which we know
802   // cannot be created through normal user input, allowing us to distinguish
803   // them.
804   auto name = OperationName("builtin.unrealized_conversion_cast", getContext());
805   auto *op = Operation::create(
806       getEncodedSourceLocation(loc), name, type, /*operands=*/{},
807       /*attributes=*/llvm::None, /*successors=*/{}, /*numRegions=*/0);
808   forwardRefPlaceholders[op->getResult(0)] = loc;
809   return op->getResult(0);
810 }
811 
812 //===----------------------------------------------------------------------===//
813 // Operation Parsing
814 //===----------------------------------------------------------------------===//
815 
816 /// Parse an operation.
817 ///
818 ///  operation         ::= op-result-list?
819 ///                        (generic-operation | custom-operation)
820 ///                        trailing-location?
821 ///  generic-operation ::= string-literal `(` ssa-use-list? `)`
822 ///                        successor-list? (`(` region-list `)`)?
823 ///                        attribute-dict? `:` function-type
824 ///  custom-operation  ::= bare-id custom-operation-format
825 ///  op-result-list    ::= op-result (`,` op-result)* `=`
826 ///  op-result         ::= ssa-id (`:` integer-literal)
827 ///
828 ParseResult OperationParser::parseOperation() {
829   auto loc = getToken().getLoc();
830   SmallVector<ResultRecord, 1> resultIDs;
831   size_t numExpectedResults = 0;
832   if (getToken().is(Token::percent_identifier)) {
833     // Parse the group of result ids.
834     auto parseNextResult = [&]() -> ParseResult {
835       // Parse the next result id.
836       if (!getToken().is(Token::percent_identifier))
837         return emitError("expected valid ssa identifier");
838 
839       Token nameTok = getToken();
840       consumeToken(Token::percent_identifier);
841 
842       // If the next token is a ':', we parse the expected result count.
843       size_t expectedSubResults = 1;
844       if (consumeIf(Token::colon)) {
845         // Check that the next token is an integer.
846         if (!getToken().is(Token::integer))
847           return emitError("expected integer number of results");
848 
849         // Check that number of results is > 0.
850         auto val = getToken().getUInt64IntegerValue();
851         if (!val.hasValue() || val.getValue() < 1)
852           return emitError("expected named operation to have atleast 1 result");
853         consumeToken(Token::integer);
854         expectedSubResults = *val;
855       }
856 
857       resultIDs.emplace_back(nameTok.getSpelling(), expectedSubResults,
858                              nameTok.getLoc());
859       numExpectedResults += expectedSubResults;
860       return success();
861     };
862     if (parseCommaSeparatedList(parseNextResult))
863       return failure();
864 
865     if (parseToken(Token::equal, "expected '=' after SSA name"))
866       return failure();
867   }
868 
869   Operation *op;
870   Token nameTok = getToken();
871   if (nameTok.is(Token::bare_identifier) || nameTok.isKeyword())
872     op = parseCustomOperation(resultIDs);
873   else if (nameTok.is(Token::string))
874     op = parseGenericOperation();
875   else
876     return emitError("expected operation name in quotes");
877 
878   // If parsing of the basic operation failed, then this whole thing fails.
879   if (!op)
880     return failure();
881 
882   // If the operation had a name, register it.
883   if (!resultIDs.empty()) {
884     if (op->getNumResults() == 0)
885       return emitError(loc, "cannot name an operation with no results");
886     if (numExpectedResults != op->getNumResults())
887       return emitError(loc, "operation defines ")
888              << op->getNumResults() << " results but was provided "
889              << numExpectedResults << " to bind";
890 
891     // Add this operation to the assembly state if it was provided to populate.
892     if (state.asmState) {
893       unsigned resultIt = 0;
894       SmallVector<std::pair<unsigned, llvm::SMLoc>> asmResultGroups;
895       asmResultGroups.reserve(resultIDs.size());
896       for (ResultRecord &record : resultIDs) {
897         asmResultGroups.emplace_back(resultIt, std::get<2>(record));
898         resultIt += std::get<1>(record);
899       }
900       state.asmState->finalizeOperationDefinition(
901           op, nameTok.getLocRange(), /*endLoc=*/getToken().getLoc(),
902           asmResultGroups);
903     }
904 
905     // Add definitions for each of the result groups.
906     unsigned opResI = 0;
907     for (ResultRecord &resIt : resultIDs) {
908       for (unsigned subRes : llvm::seq<unsigned>(0, std::get<1>(resIt))) {
909         if (addDefinition({std::get<0>(resIt), subRes, std::get<2>(resIt)},
910                           op->getResult(opResI++)))
911           return failure();
912       }
913     }
914 
915     // Add this operation to the assembly state if it was provided to populate.
916   } else if (state.asmState) {
917     state.asmState->finalizeOperationDefinition(op, nameTok.getLocRange(),
918                                                 /*endLoc=*/getToken().getLoc());
919   }
920 
921   return success();
922 }
923 
924 /// Parse a single operation successor.
925 ///
926 ///   successor ::= block-id
927 ///
928 ParseResult OperationParser::parseSuccessor(Block *&dest) {
929   // Verify branch is identifier and get the matching block.
930   if (!getToken().is(Token::caret_identifier))
931     return emitError("expected block name");
932   dest = getBlockNamed(getTokenSpelling(), getToken().getLoc());
933   consumeToken();
934   return success();
935 }
936 
937 /// Parse a comma-separated list of operation successors in brackets.
938 ///
939 ///   successor-list ::= `[` successor (`,` successor )* `]`
940 ///
941 ParseResult
942 OperationParser::parseSuccessors(SmallVectorImpl<Block *> &destinations) {
943   if (parseToken(Token::l_square, "expected '['"))
944     return failure();
945 
946   auto parseElt = [this, &destinations] {
947     Block *dest;
948     ParseResult res = parseSuccessor(dest);
949     destinations.push_back(dest);
950     return res;
951   };
952   return parseCommaSeparatedListUntil(Token::r_square, parseElt,
953                                       /*allowEmptyList=*/false);
954 }
955 
956 namespace {
957 // RAII-style guard for cleaning up the regions in the operation state before
958 // deleting them.  Within the parser, regions may get deleted if parsing failed,
959 // and other errors may be present, in particular undominated uses.  This makes
960 // sure such uses are deleted.
961 struct CleanupOpStateRegions {
962   ~CleanupOpStateRegions() {
963     SmallVector<Region *, 4> regionsToClean;
964     regionsToClean.reserve(state.regions.size());
965     for (auto &region : state.regions)
966       if (region)
967         for (auto &block : *region)
968           block.dropAllDefinedValueUses();
969   }
970   OperationState &state;
971 };
972 } // namespace
973 
974 Operation *OperationParser::parseGenericOperation() {
975   // Get location information for the operation.
976   auto srcLocation = getEncodedSourceLocation(getToken().getLoc());
977 
978   std::string name = getToken().getStringValue();
979   if (name.empty())
980     return (emitError("empty operation name is invalid"), nullptr);
981   if (name.find('\0') != StringRef::npos)
982     return (emitError("null character not allowed in operation name"), nullptr);
983 
984   consumeToken(Token::string);
985 
986   OperationState result(srcLocation, name);
987 
988   // Lazy load dialects in the context as needed.
989   if (!result.name.getAbstractOperation()) {
990     StringRef dialectName = StringRef(name).split('.').first;
991     if (!getContext()->getLoadedDialect(dialectName) &&
992         getContext()->getOrLoadDialect(dialectName)) {
993       result.name = OperationName(name, getContext());
994     }
995   }
996 
997   // If we are populating the parser state, start a new operation definition.
998   if (state.asmState)
999     state.asmState->startOperationDefinition(result.name);
1000 
1001   // Parse the operand list.
1002   SmallVector<SSAUseInfo, 8> operandInfos;
1003   if (parseToken(Token::l_paren, "expected '(' to start operand list") ||
1004       parseOptionalSSAUseList(operandInfos) ||
1005       parseToken(Token::r_paren, "expected ')' to end operand list")) {
1006     return nullptr;
1007   }
1008 
1009   // Parse the successor list.
1010   if (getToken().is(Token::l_square)) {
1011     // Check if the operation is a known terminator.
1012     const AbstractOperation *abstractOp = result.name.getAbstractOperation();
1013     if (abstractOp && !abstractOp->hasTrait<OpTrait::IsTerminator>())
1014       return emitError("successors in non-terminator"), nullptr;
1015 
1016     SmallVector<Block *, 2> successors;
1017     if (parseSuccessors(successors))
1018       return nullptr;
1019     result.addSuccessors(successors);
1020   }
1021 
1022   // Parse the region list.
1023   CleanupOpStateRegions guard{result};
1024   if (consumeIf(Token::l_paren)) {
1025     do {
1026       // Create temporary regions with the top level region as parent.
1027       result.regions.emplace_back(new Region(topLevelOp));
1028       if (parseRegion(*result.regions.back(), /*entryArguments=*/{}))
1029         return nullptr;
1030     } while (consumeIf(Token::comma));
1031     if (parseToken(Token::r_paren, "expected ')' to end region list"))
1032       return nullptr;
1033   }
1034 
1035   if (getToken().is(Token::l_brace)) {
1036     if (parseAttributeDict(result.attributes))
1037       return nullptr;
1038   }
1039 
1040   if (parseToken(Token::colon, "expected ':' followed by operation type"))
1041     return nullptr;
1042 
1043   auto typeLoc = getToken().getLoc();
1044   auto type = parseType();
1045   if (!type)
1046     return nullptr;
1047   auto fnType = type.dyn_cast<FunctionType>();
1048   if (!fnType)
1049     return (emitError(typeLoc, "expected function type"), nullptr);
1050 
1051   result.addTypes(fnType.getResults());
1052 
1053   // Check that we have the right number of types for the operands.
1054   auto operandTypes = fnType.getInputs();
1055   if (operandTypes.size() != operandInfos.size()) {
1056     auto plural = "s"[operandInfos.size() == 1];
1057     return (emitError(typeLoc, "expected ")
1058                 << operandInfos.size() << " operand type" << plural
1059                 << " but had " << operandTypes.size(),
1060             nullptr);
1061   }
1062 
1063   // Resolve all of the operands.
1064   for (unsigned i = 0, e = operandInfos.size(); i != e; ++i) {
1065     result.operands.push_back(resolveSSAUse(operandInfos[i], operandTypes[i]));
1066     if (!result.operands.back())
1067       return nullptr;
1068   }
1069 
1070   // Create the operation and try to parse a location for it.
1071   Operation *op = opBuilder.createOperation(result);
1072   if (parseTrailingLocationSpecifier(op))
1073     return nullptr;
1074   return op;
1075 }
1076 
1077 Operation *OperationParser::parseGenericOperation(Block *insertBlock,
1078                                                   Block::iterator insertPt) {
1079   Token nameToken = getToken();
1080 
1081   OpBuilder::InsertionGuard restoreInsertionPoint(opBuilder);
1082   opBuilder.setInsertionPoint(insertBlock, insertPt);
1083   Operation *op = parseGenericOperation();
1084   if (!op)
1085     return nullptr;
1086 
1087   // If we are populating the parser asm state, finalize this operation
1088   // definition.
1089   if (state.asmState)
1090     state.asmState->finalizeOperationDefinition(op, nameToken.getLocRange(),
1091                                                 /*endLoc=*/getToken().getLoc());
1092   return op;
1093 }
1094 
1095 namespace {
1096 class CustomOpAsmParser : public OpAsmParser {
1097 public:
1098   CustomOpAsmParser(
1099       SMLoc nameLoc, ArrayRef<OperationParser::ResultRecord> resultIDs,
1100       function_ref<ParseResult(OpAsmParser &, OperationState &)> parseAssembly,
1101       bool isIsolatedFromAbove, StringRef opName, OperationParser &parser)
1102       : nameLoc(nameLoc), resultIDs(resultIDs), parseAssembly(parseAssembly),
1103         isIsolatedFromAbove(isIsolatedFromAbove), opName(opName),
1104         parser(parser) {
1105     (void)isIsolatedFromAbove; // Only used in assert, silence unused warning.
1106   }
1107 
1108   /// Parse an instance of the operation described by 'opDefinition' into the
1109   /// provided operation state.
1110   ParseResult parseOperation(OperationState &opState) {
1111     if (parseAssembly(*this, opState))
1112       return failure();
1113     // Verify that the parsed attributes does not have duplicate attributes.
1114     // This can happen if an attribute set during parsing is also specified in
1115     // the attribute dictionary in the assembly, or the attribute is set
1116     // multiple during parsing.
1117     Optional<NamedAttribute> duplicate = opState.attributes.findDuplicate();
1118     if (duplicate)
1119       return emitError(getNameLoc(), "attribute '")
1120              << duplicate->first
1121              << "' occurs more than once in the attribute list";
1122     return success();
1123   }
1124 
1125   Operation *parseGenericOperation(Block *insertBlock,
1126                                    Block::iterator insertPt) final {
1127     return parser.parseGenericOperation(insertBlock, insertPt);
1128   }
1129 
1130   //===--------------------------------------------------------------------===//
1131   // Utilities
1132   //===--------------------------------------------------------------------===//
1133 
1134   /// Return if any errors were emitted during parsing.
1135   bool didEmitError() const { return emittedError; }
1136 
1137   /// Emit a diagnostic at the specified location and return failure.
1138   InFlightDiagnostic emitError(llvm::SMLoc loc, const Twine &message) override {
1139     emittedError = true;
1140     return parser.emitError(loc, "custom op '" + opName + "' " + message);
1141   }
1142 
1143   llvm::SMLoc getCurrentLocation() override {
1144     return parser.getToken().getLoc();
1145   }
1146 
1147   Builder &getBuilder() const override { return parser.builder; }
1148 
1149   /// Return the name of the specified result in the specified syntax, as well
1150   /// as the subelement in the name.  For example, in this operation:
1151   ///
1152   ///  %x, %y:2, %z = foo.op
1153   ///
1154   ///    getResultName(0) == {"x", 0 }
1155   ///    getResultName(1) == {"y", 0 }
1156   ///    getResultName(2) == {"y", 1 }
1157   ///    getResultName(3) == {"z", 0 }
1158   std::pair<StringRef, unsigned>
1159   getResultName(unsigned resultNo) const override {
1160     // Scan for the resultID that contains this result number.
1161     for (unsigned nameID = 0, e = resultIDs.size(); nameID != e; ++nameID) {
1162       const auto &entry = resultIDs[nameID];
1163       if (resultNo < std::get<1>(entry)) {
1164         // Don't pass on the leading %.
1165         StringRef name = std::get<0>(entry).drop_front();
1166         return {name, resultNo};
1167       }
1168       resultNo -= std::get<1>(entry);
1169     }
1170 
1171     // Invalid result number.
1172     return {"", ~0U};
1173   }
1174 
1175   /// Return the number of declared SSA results.  This returns 4 for the foo.op
1176   /// example in the comment for getResultName.
1177   size_t getNumResults() const override {
1178     size_t count = 0;
1179     for (auto &entry : resultIDs)
1180       count += std::get<1>(entry);
1181     return count;
1182   }
1183 
1184   llvm::SMLoc getNameLoc() const override { return nameLoc; }
1185 
1186   /// Re-encode the given source location as an MLIR location and return it.
1187   Location getEncodedSourceLoc(llvm::SMLoc loc) override {
1188     return parser.getEncodedSourceLocation(loc);
1189   }
1190 
1191   //===--------------------------------------------------------------------===//
1192   // Token Parsing
1193   //===--------------------------------------------------------------------===//
1194 
1195   /// Parse a `->` token.
1196   ParseResult parseArrow() override {
1197     return parser.parseToken(Token::arrow, "expected '->'");
1198   }
1199 
1200   /// Parses a `->` if present.
1201   ParseResult parseOptionalArrow() override {
1202     return success(parser.consumeIf(Token::arrow));
1203   }
1204 
1205   /// Parse a '{' token.
1206   ParseResult parseLBrace() override {
1207     return parser.parseToken(Token::l_brace, "expected '{'");
1208   }
1209 
1210   /// Parse a '{' token if present
1211   ParseResult parseOptionalLBrace() override {
1212     return success(parser.consumeIf(Token::l_brace));
1213   }
1214 
1215   /// Parse a `}` token.
1216   ParseResult parseRBrace() override {
1217     return parser.parseToken(Token::r_brace, "expected '}'");
1218   }
1219 
1220   /// Parse a `}` token if present
1221   ParseResult parseOptionalRBrace() override {
1222     return success(parser.consumeIf(Token::r_brace));
1223   }
1224 
1225   /// Parse a `:` token.
1226   ParseResult parseColon() override {
1227     return parser.parseToken(Token::colon, "expected ':'");
1228   }
1229 
1230   /// Parse a `:` token if present.
1231   ParseResult parseOptionalColon() override {
1232     return success(parser.consumeIf(Token::colon));
1233   }
1234 
1235   /// Parse a `,` token.
1236   ParseResult parseComma() override {
1237     return parser.parseToken(Token::comma, "expected ','");
1238   }
1239 
1240   /// Parse a `,` token if present.
1241   ParseResult parseOptionalComma() override {
1242     return success(parser.consumeIf(Token::comma));
1243   }
1244 
1245   /// Parses a `...` if present.
1246   ParseResult parseOptionalEllipsis() override {
1247     return success(parser.consumeIf(Token::ellipsis));
1248   }
1249 
1250   /// Parse a `=` token.
1251   ParseResult parseEqual() override {
1252     return parser.parseToken(Token::equal, "expected '='");
1253   }
1254 
1255   /// Parse a `=` token if present.
1256   ParseResult parseOptionalEqual() override {
1257     return success(parser.consumeIf(Token::equal));
1258   }
1259 
1260   /// Parse a '<' token.
1261   ParseResult parseLess() override {
1262     return parser.parseToken(Token::less, "expected '<'");
1263   }
1264 
1265   /// Parse a '<' token if present.
1266   ParseResult parseOptionalLess() override {
1267     return success(parser.consumeIf(Token::less));
1268   }
1269 
1270   /// Parse a '>' token.
1271   ParseResult parseGreater() override {
1272     return parser.parseToken(Token::greater, "expected '>'");
1273   }
1274 
1275   /// Parse a '>' token if present.
1276   ParseResult parseOptionalGreater() override {
1277     return success(parser.consumeIf(Token::greater));
1278   }
1279 
1280   /// Parse a `(` token.
1281   ParseResult parseLParen() override {
1282     return parser.parseToken(Token::l_paren, "expected '('");
1283   }
1284 
1285   /// Parses a '(' if present.
1286   ParseResult parseOptionalLParen() override {
1287     return success(parser.consumeIf(Token::l_paren));
1288   }
1289 
1290   /// Parse a `)` token.
1291   ParseResult parseRParen() override {
1292     return parser.parseToken(Token::r_paren, "expected ')'");
1293   }
1294 
1295   /// Parses a ')' if present.
1296   ParseResult parseOptionalRParen() override {
1297     return success(parser.consumeIf(Token::r_paren));
1298   }
1299 
1300   /// Parse a `[` token.
1301   ParseResult parseLSquare() override {
1302     return parser.parseToken(Token::l_square, "expected '['");
1303   }
1304 
1305   /// Parses a '[' if present.
1306   ParseResult parseOptionalLSquare() override {
1307     return success(parser.consumeIf(Token::l_square));
1308   }
1309 
1310   /// Parse a `]` token.
1311   ParseResult parseRSquare() override {
1312     return parser.parseToken(Token::r_square, "expected ']'");
1313   }
1314 
1315   /// Parses a ']' if present.
1316   ParseResult parseOptionalRSquare() override {
1317     return success(parser.consumeIf(Token::r_square));
1318   }
1319 
1320   /// Parses a '?' token.
1321   ParseResult parseQuestion() override {
1322     return parser.parseToken(Token::question, "expected '?'");
1323   }
1324 
1325   /// Parses a '?' token if present.
1326   ParseResult parseOptionalQuestion() override {
1327     return success(parser.consumeIf(Token::question));
1328   }
1329 
1330   /// Parses a '+' token.
1331   ParseResult parsePlus() override {
1332     return parser.parseToken(Token::plus, "expected '+'");
1333   }
1334 
1335   /// Parses a '+' token if present.
1336   ParseResult parseOptionalPlus() override {
1337     return success(parser.consumeIf(Token::plus));
1338   }
1339 
1340   /// Parses a '*' token.
1341   ParseResult parseStar() override {
1342     return parser.parseToken(Token::star, "expected '*'");
1343   }
1344 
1345   /// Parses a '*' token if present.
1346   ParseResult parseOptionalStar() override {
1347     return success(parser.consumeIf(Token::star));
1348   }
1349 
1350   /// Parse an optional integer value from the stream.
1351   OptionalParseResult parseOptionalInteger(APInt &result) override {
1352     return parser.parseOptionalInteger(result);
1353   }
1354 
1355   /// Parse a list of comma-separated items with an optional delimiter.  If a
1356   /// delimiter is provided, then an empty list is allowed.  If not, then at
1357   /// least one element will be parsed.
1358   ParseResult parseCommaSeparatedList(Delimiter delimiter,
1359                                       function_ref<ParseResult()> parseElt,
1360                                       StringRef contextMessage) override {
1361     return parser.parseCommaSeparatedList(delimiter, parseElt, contextMessage);
1362   }
1363 
1364   //===--------------------------------------------------------------------===//
1365   // Attribute Parsing
1366   //===--------------------------------------------------------------------===//
1367 
1368   /// Parse an arbitrary attribute of a given type and return it in result.
1369   ParseResult parseAttribute(Attribute &result, Type type) override {
1370     result = parser.parseAttribute(type);
1371     return success(static_cast<bool>(result));
1372   }
1373 
1374   /// Parse an optional attribute.
1375   template <typename AttrT>
1376   OptionalParseResult
1377   parseOptionalAttributeAndAddToList(AttrT &result, Type type,
1378                                      StringRef attrName, NamedAttrList &attrs) {
1379     OptionalParseResult parseResult =
1380         parser.parseOptionalAttribute(result, type);
1381     if (parseResult.hasValue() && succeeded(*parseResult))
1382       attrs.push_back(parser.builder.getNamedAttr(attrName, result));
1383     return parseResult;
1384   }
1385   OptionalParseResult parseOptionalAttribute(Attribute &result, Type type,
1386                                              StringRef attrName,
1387                                              NamedAttrList &attrs) override {
1388     return parseOptionalAttributeAndAddToList(result, type, attrName, attrs);
1389   }
1390   OptionalParseResult parseOptionalAttribute(ArrayAttr &result, Type type,
1391                                              StringRef attrName,
1392                                              NamedAttrList &attrs) override {
1393     return parseOptionalAttributeAndAddToList(result, type, attrName, attrs);
1394   }
1395   OptionalParseResult parseOptionalAttribute(StringAttr &result, Type type,
1396                                              StringRef attrName,
1397                                              NamedAttrList &attrs) override {
1398     return parseOptionalAttributeAndAddToList(result, type, attrName, attrs);
1399   }
1400 
1401   /// Parse a named dictionary into 'result' if it is present.
1402   ParseResult parseOptionalAttrDict(NamedAttrList &result) override {
1403     if (parser.getToken().isNot(Token::l_brace))
1404       return success();
1405     return parser.parseAttributeDict(result);
1406   }
1407 
1408   /// Parse a named dictionary into 'result' if the `attributes` keyword is
1409   /// present.
1410   ParseResult parseOptionalAttrDictWithKeyword(NamedAttrList &result) override {
1411     if (failed(parseOptionalKeyword("attributes")))
1412       return success();
1413     return parser.parseAttributeDict(result);
1414   }
1415 
1416   /// Parse an affine map instance into 'map'.
1417   ParseResult parseAffineMap(AffineMap &map) override {
1418     return parser.parseAffineMapReference(map);
1419   }
1420 
1421   /// Parse an integer set instance into 'set'.
1422   ParseResult printIntegerSet(IntegerSet &set) override {
1423     return parser.parseIntegerSetReference(set);
1424   }
1425 
1426   //===--------------------------------------------------------------------===//
1427   // Identifier Parsing
1428   //===--------------------------------------------------------------------===//
1429 
1430   /// Returns true if the current token corresponds to a keyword.
1431   bool isCurrentTokenAKeyword() const {
1432     return parser.getToken().is(Token::bare_identifier) ||
1433            parser.getToken().isKeyword();
1434   }
1435 
1436   /// Parse the given keyword if present.
1437   ParseResult parseOptionalKeyword(StringRef keyword) override {
1438     // Check that the current token has the same spelling.
1439     if (!isCurrentTokenAKeyword() || parser.getTokenSpelling() != keyword)
1440       return failure();
1441     parser.consumeToken();
1442     return success();
1443   }
1444 
1445   /// Parse a keyword, if present, into 'keyword'.
1446   ParseResult parseOptionalKeyword(StringRef *keyword) override {
1447     // Check that the current token is a keyword.
1448     if (!isCurrentTokenAKeyword())
1449       return failure();
1450 
1451     *keyword = parser.getTokenSpelling();
1452     parser.consumeToken();
1453     return success();
1454   }
1455 
1456   /// Parse a keyword if it is one of the 'allowedKeywords'.
1457   ParseResult
1458   parseOptionalKeyword(StringRef *keyword,
1459                        ArrayRef<StringRef> allowedKeywords) override {
1460     // Check that the current token is a keyword.
1461     if (!isCurrentTokenAKeyword())
1462       return failure();
1463 
1464     StringRef currentKeyword = parser.getTokenSpelling();
1465     if (llvm::is_contained(allowedKeywords, currentKeyword)) {
1466       *keyword = currentKeyword;
1467       parser.consumeToken();
1468       return success();
1469     }
1470 
1471     return failure();
1472   }
1473 
1474   /// Parse an optional @-identifier and store it (without the '@' symbol) in a
1475   /// string attribute named 'attrName'.
1476   ParseResult parseOptionalSymbolName(StringAttr &result, StringRef attrName,
1477                                       NamedAttrList &attrs) override {
1478     Token atToken = parser.getToken();
1479     if (atToken.isNot(Token::at_identifier))
1480       return failure();
1481 
1482     result = getBuilder().getStringAttr(atToken.getSymbolReference());
1483     attrs.push_back(getBuilder().getNamedAttr(attrName, result));
1484     parser.consumeToken();
1485 
1486     // If we are populating the assembly parser state, record this as a symbol
1487     // reference.
1488     if (parser.getState().asmState) {
1489       parser.getState().asmState->addUses(SymbolRefAttr::get(result),
1490                                           atToken.getLocRange());
1491     }
1492     return success();
1493   }
1494 
1495   /// Parse a loc(...) specifier if present, filling in result if so.
1496   ParseResult
1497   parseOptionalLocationSpecifier(Optional<Location> &result) override {
1498     // If there is a 'loc' we parse a trailing location.
1499     if (!parser.consumeIf(Token::kw_loc))
1500       return success();
1501     LocationAttr directLoc;
1502     if (parser.parseToken(Token::l_paren, "expected '(' in location") ||
1503         parser.parseLocationInstance(directLoc) ||
1504         parser.parseToken(Token::r_paren, "expected ')' in location"))
1505       return failure();
1506 
1507     result = directLoc;
1508     return success();
1509   }
1510 
1511   //===--------------------------------------------------------------------===//
1512   // Operand Parsing
1513   //===--------------------------------------------------------------------===//
1514 
1515   /// Parse a single operand.
1516   ParseResult parseOperand(OperandType &result) override {
1517     OperationParser::SSAUseInfo useInfo;
1518     if (parser.parseSSAUse(useInfo))
1519       return failure();
1520 
1521     result = {useInfo.loc, useInfo.name, useInfo.number};
1522     return success();
1523   }
1524 
1525   /// Parse a single operand if present.
1526   OptionalParseResult parseOptionalOperand(OperandType &result) override {
1527     if (parser.getToken().is(Token::percent_identifier))
1528       return parseOperand(result);
1529     return llvm::None;
1530   }
1531 
1532   /// Parse zero or more SSA comma-separated operand references with a specified
1533   /// surrounding delimiter, and an optional required operand count.
1534   ParseResult parseOperandList(SmallVectorImpl<OperandType> &result,
1535                                int requiredOperandCount = -1,
1536                                Delimiter delimiter = Delimiter::None) override {
1537     return parseOperandOrRegionArgList(result, /*isOperandList=*/true,
1538                                        requiredOperandCount, delimiter);
1539   }
1540 
1541   /// Parse zero or more SSA comma-separated operand or region arguments with
1542   ///  optional surrounding delimiter and required operand count.
1543   ParseResult
1544   parseOperandOrRegionArgList(SmallVectorImpl<OperandType> &result,
1545                               bool isOperandList, int requiredOperandCount = -1,
1546                               Delimiter delimiter = Delimiter::None) {
1547     auto startLoc = parser.getToken().getLoc();
1548 
1549     // The no-delimiter case has some special handling for better diagnostics.
1550     if (delimiter == Delimiter::None) {
1551       // parseCommaSeparatedList doesn't handle the missing case for "none",
1552       // so we handle it custom here.
1553       if (parser.getToken().isNot(Token::percent_identifier)) {
1554         // If we didn't require any operands or required exactly zero (weird)
1555         // then this is success.
1556         if (requiredOperandCount == -1 || requiredOperandCount == 0)
1557           return success();
1558 
1559         // Otherwise, try to produce a nice error message.
1560         if (parser.getToken().is(Token::l_paren) ||
1561             parser.getToken().is(Token::l_square))
1562           return emitError(startLoc, "unexpected delimiter");
1563         return emitError(startLoc, "invalid operand");
1564       }
1565     }
1566 
1567     auto parseOneOperand = [&]() -> ParseResult {
1568       OperandType operandOrArg;
1569       if (isOperandList ? parseOperand(operandOrArg)
1570                         : parseRegionArgument(operandOrArg))
1571         return failure();
1572       result.push_back(operandOrArg);
1573       return success();
1574     };
1575 
1576     if (parseCommaSeparatedList(delimiter, parseOneOperand, " in operand list"))
1577       return failure();
1578 
1579     // Check that we got the expected # of elements.
1580     if (requiredOperandCount != -1 &&
1581         result.size() != static_cast<size_t>(requiredOperandCount))
1582       return emitError(startLoc, "expected ")
1583              << requiredOperandCount << " operands";
1584     return success();
1585   }
1586 
1587   /// Parse zero or more trailing SSA comma-separated trailing operand
1588   /// references with a specified surrounding delimiter, and an optional
1589   /// required operand count. A leading comma is expected before the operands.
1590   ParseResult parseTrailingOperandList(SmallVectorImpl<OperandType> &result,
1591                                        int requiredOperandCount,
1592                                        Delimiter delimiter) override {
1593     if (parser.getToken().is(Token::comma)) {
1594       parseComma();
1595       return parseOperandList(result, requiredOperandCount, delimiter);
1596     }
1597     if (requiredOperandCount != -1)
1598       return emitError(parser.getToken().getLoc(), "expected ")
1599              << requiredOperandCount << " operands";
1600     return success();
1601   }
1602 
1603   /// Resolve an operand to an SSA value, emitting an error on failure.
1604   ParseResult resolveOperand(const OperandType &operand, Type type,
1605                              SmallVectorImpl<Value> &result) override {
1606     OperationParser::SSAUseInfo operandInfo = {operand.name, operand.number,
1607                                                operand.location};
1608     if (auto value = parser.resolveSSAUse(operandInfo, type)) {
1609       result.push_back(value);
1610       return success();
1611     }
1612     return failure();
1613   }
1614 
1615   /// Parse an AffineMap of SSA ids.
1616   ParseResult parseAffineMapOfSSAIds(SmallVectorImpl<OperandType> &operands,
1617                                      Attribute &mapAttr, StringRef attrName,
1618                                      NamedAttrList &attrs,
1619                                      Delimiter delimiter) override {
1620     SmallVector<OperandType, 2> dimOperands;
1621     SmallVector<OperandType, 1> symOperands;
1622 
1623     auto parseElement = [&](bool isSymbol) -> ParseResult {
1624       OperandType operand;
1625       if (parseOperand(operand))
1626         return failure();
1627       if (isSymbol)
1628         symOperands.push_back(operand);
1629       else
1630         dimOperands.push_back(operand);
1631       return success();
1632     };
1633 
1634     AffineMap map;
1635     if (parser.parseAffineMapOfSSAIds(map, parseElement, delimiter))
1636       return failure();
1637     // Add AffineMap attribute.
1638     if (map) {
1639       mapAttr = AffineMapAttr::get(map);
1640       attrs.push_back(parser.builder.getNamedAttr(attrName, mapAttr));
1641     }
1642 
1643     // Add dim operands before symbol operands in 'operands'.
1644     operands.assign(dimOperands.begin(), dimOperands.end());
1645     operands.append(symOperands.begin(), symOperands.end());
1646     return success();
1647   }
1648 
1649   /// Parse an AffineExpr of SSA ids.
1650   ParseResult
1651   parseAffineExprOfSSAIds(SmallVectorImpl<OperandType> &dimOperands,
1652                           SmallVectorImpl<OperandType> &symbOperands,
1653                           AffineExpr &expr) override {
1654     auto parseElement = [&](bool isSymbol) -> ParseResult {
1655       OperandType operand;
1656       if (parseOperand(operand))
1657         return failure();
1658       if (isSymbol)
1659         symbOperands.push_back(operand);
1660       else
1661         dimOperands.push_back(operand);
1662       return success();
1663     };
1664 
1665     return parser.parseAffineExprOfSSAIds(expr, parseElement);
1666   }
1667 
1668   //===--------------------------------------------------------------------===//
1669   // Region Parsing
1670   //===--------------------------------------------------------------------===//
1671 
1672   /// Parse a region that takes `arguments` of `argTypes` types.  This
1673   /// effectively defines the SSA values of `arguments` and assigns their type.
1674   ParseResult parseRegion(Region &region, ArrayRef<OperandType> arguments,
1675                           ArrayRef<Type> argTypes,
1676                           bool enableNameShadowing) override {
1677     assert(arguments.size() == argTypes.size() &&
1678            "mismatching number of arguments and types");
1679 
1680     SmallVector<std::pair<OperationParser::SSAUseInfo, Type>, 2>
1681         regionArguments;
1682     for (auto pair : llvm::zip(arguments, argTypes)) {
1683       const OperandType &operand = std::get<0>(pair);
1684       Type type = std::get<1>(pair);
1685       OperationParser::SSAUseInfo operandInfo = {operand.name, operand.number,
1686                                                  operand.location};
1687       regionArguments.emplace_back(operandInfo, type);
1688     }
1689 
1690     // Try to parse the region.
1691     (void)isIsolatedFromAbove;
1692     assert((!enableNameShadowing || isIsolatedFromAbove) &&
1693            "name shadowing is only allowed on isolated regions");
1694     if (parser.parseRegion(region, regionArguments, enableNameShadowing))
1695       return failure();
1696     return success();
1697   }
1698 
1699   /// Parses a region if present.
1700   OptionalParseResult parseOptionalRegion(Region &region,
1701                                           ArrayRef<OperandType> arguments,
1702                                           ArrayRef<Type> argTypes,
1703                                           bool enableNameShadowing) override {
1704     if (parser.getToken().isNot(Token::l_brace))
1705       return llvm::None;
1706     return parseRegion(region, arguments, argTypes, enableNameShadowing);
1707   }
1708 
1709   /// Parses a region if present. If the region is present, a new region is
1710   /// allocated and placed in `region`. If no region is present, `region`
1711   /// remains untouched.
1712   OptionalParseResult
1713   parseOptionalRegion(std::unique_ptr<Region> &region,
1714                       ArrayRef<OperandType> arguments, ArrayRef<Type> argTypes,
1715                       bool enableNameShadowing = false) override {
1716     if (parser.getToken().isNot(Token::l_brace))
1717       return llvm::None;
1718     std::unique_ptr<Region> newRegion = std::make_unique<Region>();
1719     if (parseRegion(*newRegion, arguments, argTypes, enableNameShadowing))
1720       return failure();
1721 
1722     region = std::move(newRegion);
1723     return success();
1724   }
1725 
1726   /// Parse a region argument. The type of the argument will be resolved later
1727   /// by a call to `parseRegion`.
1728   ParseResult parseRegionArgument(OperandType &argument) override {
1729     return parseOperand(argument);
1730   }
1731 
1732   /// Parse a region argument if present.
1733   ParseResult parseOptionalRegionArgument(OperandType &argument) override {
1734     if (parser.getToken().isNot(Token::percent_identifier))
1735       return success();
1736     return parseRegionArgument(argument);
1737   }
1738 
1739   ParseResult
1740   parseRegionArgumentList(SmallVectorImpl<OperandType> &result,
1741                           int requiredOperandCount = -1,
1742                           Delimiter delimiter = Delimiter::None) override {
1743     return parseOperandOrRegionArgList(result, /*isOperandList=*/false,
1744                                        requiredOperandCount, delimiter);
1745   }
1746 
1747   //===--------------------------------------------------------------------===//
1748   // Successor Parsing
1749   //===--------------------------------------------------------------------===//
1750 
1751   /// Parse a single operation successor.
1752   ParseResult parseSuccessor(Block *&dest) override {
1753     return parser.parseSuccessor(dest);
1754   }
1755 
1756   /// Parse an optional operation successor and its operand list.
1757   OptionalParseResult parseOptionalSuccessor(Block *&dest) override {
1758     if (parser.getToken().isNot(Token::caret_identifier))
1759       return llvm::None;
1760     return parseSuccessor(dest);
1761   }
1762 
1763   /// Parse a single operation successor and its operand list.
1764   ParseResult
1765   parseSuccessorAndUseList(Block *&dest,
1766                            SmallVectorImpl<Value> &operands) override {
1767     if (parseSuccessor(dest))
1768       return failure();
1769 
1770     // Handle optional arguments.
1771     if (succeeded(parseOptionalLParen()) &&
1772         (parser.parseOptionalSSAUseAndTypeList(operands) || parseRParen())) {
1773       return failure();
1774     }
1775     return success();
1776   }
1777 
1778   //===--------------------------------------------------------------------===//
1779   // Type Parsing
1780   //===--------------------------------------------------------------------===//
1781 
1782   /// Parse a type.
1783   ParseResult parseType(Type &result) override {
1784     return failure(!(result = parser.parseType()));
1785   }
1786 
1787   /// Parse an optional type.
1788   OptionalParseResult parseOptionalType(Type &result) override {
1789     return parser.parseOptionalType(result);
1790   }
1791 
1792   /// Parse an arrow followed by a type list.
1793   ParseResult parseArrowTypeList(SmallVectorImpl<Type> &result) override {
1794     if (parseArrow() || parser.parseFunctionResultTypes(result))
1795       return failure();
1796     return success();
1797   }
1798 
1799   /// Parse an optional arrow followed by a type list.
1800   ParseResult
1801   parseOptionalArrowTypeList(SmallVectorImpl<Type> &result) override {
1802     if (!parser.consumeIf(Token::arrow))
1803       return success();
1804     return parser.parseFunctionResultTypes(result);
1805   }
1806 
1807   /// Parse a colon followed by a type.
1808   ParseResult parseColonType(Type &result) override {
1809     return failure(parser.parseToken(Token::colon, "expected ':'") ||
1810                    !(result = parser.parseType()));
1811   }
1812 
1813   /// Parse a colon followed by a type list, which must have at least one type.
1814   ParseResult parseColonTypeList(SmallVectorImpl<Type> &result) override {
1815     if (parser.parseToken(Token::colon, "expected ':'"))
1816       return failure();
1817     return parser.parseTypeListNoParens(result);
1818   }
1819 
1820   /// Parse an optional colon followed by a type list, which if present must
1821   /// have at least one type.
1822   ParseResult
1823   parseOptionalColonTypeList(SmallVectorImpl<Type> &result) override {
1824     if (!parser.consumeIf(Token::colon))
1825       return success();
1826     return parser.parseTypeListNoParens(result);
1827   }
1828 
1829   /// Parse a list of assignments of the form
1830   ///   (%x1 = %y1, %x2 = %y2, ...).
1831   OptionalParseResult
1832   parseOptionalAssignmentList(SmallVectorImpl<OperandType> &lhs,
1833                               SmallVectorImpl<OperandType> &rhs) override {
1834     if (failed(parseOptionalLParen()))
1835       return llvm::None;
1836 
1837     auto parseElt = [&]() -> ParseResult {
1838       OperandType regionArg, operand;
1839       if (parseRegionArgument(regionArg) || parseEqual() ||
1840           parseOperand(operand))
1841         return failure();
1842       lhs.push_back(regionArg);
1843       rhs.push_back(operand);
1844       return success();
1845     };
1846     return parser.parseCommaSeparatedListUntil(Token::r_paren, parseElt);
1847   }
1848 
1849   /// Parse a list of assignments of the form
1850   ///   (%x1 = %y1 : type1, %x2 = %y2 : type2, ...).
1851   OptionalParseResult
1852   parseOptionalAssignmentListWithTypes(SmallVectorImpl<OperandType> &lhs,
1853                                        SmallVectorImpl<OperandType> &rhs,
1854                                        SmallVectorImpl<Type> &types) override {
1855     if (failed(parseOptionalLParen()))
1856       return llvm::None;
1857 
1858     auto parseElt = [&]() -> ParseResult {
1859       OperandType regionArg, operand;
1860       Type type;
1861       if (parseRegionArgument(regionArg) || parseEqual() ||
1862           parseOperand(operand) || parseColon() || parseType(type))
1863         return failure();
1864       lhs.push_back(regionArg);
1865       rhs.push_back(operand);
1866       types.push_back(type);
1867       return success();
1868     };
1869     return parser.parseCommaSeparatedListUntil(Token::r_paren, parseElt);
1870   }
1871 
1872 private:
1873   /// The source location of the operation name.
1874   SMLoc nameLoc;
1875 
1876   /// Information about the result name specifiers.
1877   ArrayRef<OperationParser::ResultRecord> resultIDs;
1878 
1879   /// The abstract information of the operation.
1880   function_ref<ParseResult(OpAsmParser &, OperationState &)> parseAssembly;
1881   bool isIsolatedFromAbove;
1882   StringRef opName;
1883 
1884   /// The main operation parser.
1885   OperationParser &parser;
1886 
1887   /// A flag that indicates if any errors were emitted during parsing.
1888   bool emittedError = false;
1889 };
1890 } // end anonymous namespace.
1891 
1892 Operation *
1893 OperationParser::parseCustomOperation(ArrayRef<ResultRecord> resultIDs) {
1894   llvm::SMLoc opLoc = getToken().getLoc();
1895   std::string opName = getTokenSpelling().str();
1896   auto *opDefinition = AbstractOperation::lookup(opName, getContext());
1897   StringRef defaultDialect = getState().defaultDialectStack.back();
1898   Dialect *dialect = nullptr;
1899   if (opDefinition) {
1900     dialect = &opDefinition->dialect;
1901   } else {
1902     if (StringRef(opName).contains('.')) {
1903       // This op has a dialect, we try to check if we can register it in the
1904       // context on the fly.
1905       StringRef dialectName = StringRef(opName).split('.').first;
1906       dialect = getContext()->getLoadedDialect(dialectName);
1907       if (!dialect && (dialect = getContext()->getOrLoadDialect(dialectName)))
1908         opDefinition = AbstractOperation::lookup(opName, getContext());
1909     } else {
1910       // If the operation name has no namespace prefix we lookup the current
1911       // default dialect (set through OpAsmOpInterface).
1912       opDefinition = AbstractOperation::lookup(
1913           Twine(defaultDialect + "." + opName).str(), getContext());
1914       if (!opDefinition && getContext()->getOrLoadDialect("std")) {
1915         opDefinition = AbstractOperation::lookup(Twine("std." + opName).str(),
1916                                                  getContext());
1917       }
1918       if (opDefinition) {
1919         dialect = &opDefinition->dialect;
1920         opName = opDefinition->name.str();
1921       } else if (!defaultDialect.empty()) {
1922         dialect = getContext()->getOrLoadDialect(defaultDialect);
1923         opName = (defaultDialect + "." + opName).str();
1924       }
1925     }
1926   }
1927 
1928   // This is the actual hook for the custom op parsing, usually implemented by
1929   // the op itself (`Op::parse()`). We retrieve it either from the
1930   // AbstractOperation or from the Dialect.
1931   function_ref<ParseResult(OpAsmParser &, OperationState &)> parseAssemblyFn;
1932   bool isIsolatedFromAbove = false;
1933 
1934   defaultDialect = "";
1935   if (opDefinition) {
1936     parseAssemblyFn = opDefinition->getParseAssemblyFn();
1937     isIsolatedFromAbove =
1938         opDefinition->hasTrait<OpTrait::IsIsolatedFromAbove>();
1939     auto *iface = opDefinition->getInterface<OpAsmOpInterface>();
1940     if (iface && !iface->getDefaultDialect().empty())
1941       defaultDialect = iface->getDefaultDialect();
1942   } else {
1943     Optional<Dialect::ParseOpHook> dialectHook;
1944     if (dialect)
1945       dialectHook = dialect->getParseOperationHook(opName);
1946     if (!dialectHook.hasValue()) {
1947       emitError(opLoc) << "custom op '" << opName << "' is unknown";
1948       return nullptr;
1949     }
1950     parseAssemblyFn = *dialectHook;
1951   }
1952   getState().defaultDialectStack.push_back(defaultDialect);
1953   auto restoreDefaultDialect = llvm::make_scope_exit(
1954       [&]() { getState().defaultDialectStack.pop_back(); });
1955 
1956   consumeToken();
1957 
1958   // If the custom op parser crashes, produce some indication to help
1959   // debugging.
1960   llvm::PrettyStackTraceFormat fmt("MLIR Parser: custom op parser '%s'",
1961                                    opName.c_str());
1962 
1963   // Get location information for the operation.
1964   auto srcLocation = getEncodedSourceLocation(opLoc);
1965   OperationState opState(srcLocation, opName);
1966 
1967   // If we are populating the parser state, start a new operation definition.
1968   if (state.asmState)
1969     state.asmState->startOperationDefinition(opState.name);
1970 
1971   // Have the op implementation take a crack and parsing this.
1972   CleanupOpStateRegions guard{opState};
1973   CustomOpAsmParser opAsmParser(opLoc, resultIDs, parseAssemblyFn,
1974                                 isIsolatedFromAbove, opName, *this);
1975   if (opAsmParser.parseOperation(opState))
1976     return nullptr;
1977 
1978   // If it emitted an error, we failed.
1979   if (opAsmParser.didEmitError())
1980     return nullptr;
1981 
1982   // Otherwise, create the operation and try to parse a location for it.
1983   Operation *op = opBuilder.createOperation(opState);
1984   if (parseTrailingLocationSpecifier(op))
1985     return nullptr;
1986   return op;
1987 }
1988 
1989 ParseResult
1990 OperationParser::parseTrailingLocationSpecifier(OpOrArgument opOrArgument) {
1991   // If there is a 'loc' we parse a trailing location.
1992   if (!consumeIf(Token::kw_loc))
1993     return success();
1994   if (parseToken(Token::l_paren, "expected '(' in location"))
1995     return failure();
1996   Token tok = getToken();
1997 
1998   // Check to see if we are parsing a location alias.
1999   LocationAttr directLoc;
2000   if (tok.is(Token::hash_identifier)) {
2001     consumeToken();
2002 
2003     StringRef identifier = tok.getSpelling().drop_front();
2004     if (identifier.contains('.')) {
2005       return emitError(tok.getLoc())
2006              << "expected location, but found dialect attribute: '#"
2007              << identifier << "'";
2008     }
2009 
2010     // If this alias can be resolved, do it now.
2011     Attribute attr = state.symbols.attributeAliasDefinitions.lookup(identifier);
2012     if (attr) {
2013       if (!(directLoc = attr.dyn_cast<LocationAttr>()))
2014         return emitError(tok.getLoc())
2015                << "expected location, but found '" << attr << "'";
2016     } else {
2017       // Otherwise, remember this operation and resolve its location later.
2018       opsAndArgumentsWithDeferredLocs.emplace_back(opOrArgument, tok);
2019     }
2020 
2021     // Otherwise, we parse the location directly.
2022   } else if (parseLocationInstance(directLoc)) {
2023     return failure();
2024   }
2025 
2026   if (parseToken(Token::r_paren, "expected ')' in location"))
2027     return failure();
2028 
2029   if (directLoc) {
2030     if (auto *op = opOrArgument.dyn_cast<Operation *>())
2031       op->setLoc(directLoc);
2032     else
2033       opOrArgument.get<BlockArgument>().setLoc(directLoc);
2034   }
2035   return success();
2036 }
2037 
2038 //===----------------------------------------------------------------------===//
2039 // Region Parsing
2040 //===----------------------------------------------------------------------===//
2041 
2042 ParseResult OperationParser::parseRegion(
2043     Region &region,
2044     ArrayRef<std::pair<OperationParser::SSAUseInfo, Type>> entryArguments,
2045     bool isIsolatedNameScope) {
2046   // Parse the '{'.
2047   Token lBraceTok = getToken();
2048   if (parseToken(Token::l_brace, "expected '{' to begin a region"))
2049     return failure();
2050 
2051   // If we are populating the parser state, start a new region definition.
2052   if (state.asmState)
2053     state.asmState->startRegionDefinition();
2054 
2055   // Parse the region body.
2056   if ((!entryArguments.empty() || getToken().isNot(Token::r_brace)) &&
2057       parseRegionBody(region, lBraceTok.getLoc(), entryArguments,
2058                       isIsolatedNameScope)) {
2059     return failure();
2060   }
2061   consumeToken(Token::r_brace);
2062 
2063   // If we are populating the parser state, finalize this region.
2064   if (state.asmState)
2065     state.asmState->finalizeRegionDefinition();
2066 
2067   return success();
2068 }
2069 
2070 ParseResult OperationParser::parseRegionBody(
2071     Region &region, llvm::SMLoc startLoc,
2072     ArrayRef<std::pair<OperationParser::SSAUseInfo, Type>> entryArguments,
2073     bool isIsolatedNameScope) {
2074   auto currentPt = opBuilder.saveInsertionPoint();
2075 
2076   // Push a new named value scope.
2077   pushSSANameScope(isIsolatedNameScope);
2078 
2079   // Parse the first block directly to allow for it to be unnamed.
2080   auto owning_block = std::make_unique<Block>();
2081   Block *block = owning_block.get();
2082 
2083   // If this block is not defined in the source file, add a definition for it
2084   // now in the assembly state. Blocks with a name will be defined when the name
2085   // is parsed.
2086   if (state.asmState && getToken().isNot(Token::caret_identifier))
2087     state.asmState->addDefinition(block, startLoc);
2088 
2089   // Add arguments to the entry block.
2090   if (!entryArguments.empty()) {
2091     // If we had named arguments, then don't allow a block name.
2092     if (getToken().is(Token::caret_identifier))
2093       return emitError("invalid block name in region with named arguments");
2094 
2095     for (auto &placeholderArgPair : entryArguments) {
2096       auto &argInfo = placeholderArgPair.first;
2097 
2098       // Ensure that the argument was not already defined.
2099       if (auto defLoc = getReferenceLoc(argInfo.name, argInfo.number)) {
2100         return emitError(argInfo.loc, "region entry argument '" + argInfo.name +
2101                                           "' is already in use")
2102                    .attachNote(getEncodedSourceLocation(*defLoc))
2103                << "previously referenced here";
2104       }
2105       auto loc = getEncodedSourceLocation(placeholderArgPair.first.loc);
2106       BlockArgument arg = block->addArgument(placeholderArgPair.second, loc);
2107 
2108       // Add a definition of this arg to the assembly state if provided.
2109       if (state.asmState)
2110         state.asmState->addDefinition(arg, argInfo.loc);
2111 
2112       // Record the definition for this argument.
2113       if (addDefinition(argInfo, arg))
2114         return failure();
2115     }
2116   }
2117 
2118   if (parseBlock(block))
2119     return failure();
2120 
2121   // Verify that no other arguments were parsed.
2122   if (!entryArguments.empty() &&
2123       block->getNumArguments() > entryArguments.size()) {
2124     return emitError("entry block arguments were already defined");
2125   }
2126 
2127   // Parse the rest of the region.
2128   region.push_back(owning_block.release());
2129   while (getToken().isNot(Token::r_brace)) {
2130     Block *newBlock = nullptr;
2131     if (parseBlock(newBlock))
2132       return failure();
2133     region.push_back(newBlock);
2134   }
2135 
2136   // Pop the SSA value scope for this region.
2137   if (popSSANameScope())
2138     return failure();
2139 
2140   // Reset the original insertion point.
2141   opBuilder.restoreInsertionPoint(currentPt);
2142   return success();
2143 }
2144 
2145 //===----------------------------------------------------------------------===//
2146 // Block Parsing
2147 //===----------------------------------------------------------------------===//
2148 
2149 /// Block declaration.
2150 ///
2151 ///   block ::= block-label? operation*
2152 ///   block-label    ::= block-id block-arg-list? `:`
2153 ///   block-id       ::= caret-id
2154 ///   block-arg-list ::= `(` ssa-id-and-type-list? `)`
2155 ///
2156 ParseResult OperationParser::parseBlock(Block *&block) {
2157   // The first block of a region may already exist, if it does the caret
2158   // identifier is optional.
2159   if (block && getToken().isNot(Token::caret_identifier))
2160     return parseBlockBody(block);
2161 
2162   SMLoc nameLoc = getToken().getLoc();
2163   auto name = getTokenSpelling();
2164   if (parseToken(Token::caret_identifier, "expected block name"))
2165     return failure();
2166 
2167   block = defineBlockNamed(name, nameLoc, block);
2168 
2169   // Fail if the block was already defined.
2170   if (!block)
2171     return emitError(nameLoc, "redefinition of block '") << name << "'";
2172 
2173   // If an argument list is present, parse it.
2174   if (consumeIf(Token::l_paren)) {
2175     if (parseOptionalBlockArgList(block) ||
2176         parseToken(Token::r_paren, "expected ')' to end argument list"))
2177       return failure();
2178   }
2179 
2180   if (parseToken(Token::colon, "expected ':' after block name"))
2181     return failure();
2182 
2183   return parseBlockBody(block);
2184 }
2185 
2186 ParseResult OperationParser::parseBlockBody(Block *block) {
2187   // Set the insertion point to the end of the block to parse.
2188   opBuilder.setInsertionPointToEnd(block);
2189 
2190   // Parse the list of operations that make up the body of the block.
2191   while (getToken().isNot(Token::caret_identifier, Token::r_brace))
2192     if (parseOperation())
2193       return failure();
2194 
2195   return success();
2196 }
2197 
2198 /// Get the block with the specified name, creating it if it doesn't already
2199 /// exist.  The location specified is the point of use, which allows
2200 /// us to diagnose references to blocks that are not defined precisely.
2201 Block *OperationParser::getBlockNamed(StringRef name, SMLoc loc) {
2202   BlockDefinition &blockDef = getBlockInfoByName(name);
2203   if (!blockDef.block) {
2204     blockDef = {new Block(), loc};
2205     insertForwardRef(blockDef.block, blockDef.loc);
2206   }
2207 
2208   // Populate the high level assembly state if necessary.
2209   if (state.asmState)
2210     state.asmState->addUses(blockDef.block, loc);
2211 
2212   return blockDef.block;
2213 }
2214 
2215 /// Define the block with the specified name. Returns the Block* or nullptr in
2216 /// the case of redefinition.
2217 Block *OperationParser::defineBlockNamed(StringRef name, SMLoc loc,
2218                                          Block *existing) {
2219   auto &blockAndLoc = getBlockInfoByName(name);
2220   blockAndLoc.loc = loc;
2221 
2222   // If a block has yet to be set, this is a new definition. If the caller
2223   // provided a block, use it. Otherwise create a new one.
2224   if (!blockAndLoc.block) {
2225     blockAndLoc.block = existing ? existing : new Block();
2226 
2227     // Otherwise, the block has a forward declaration. Forward declarations are
2228     // removed once defined, so if we are defining a existing block and it is
2229     // not a forward declaration, then it is a redeclaration.
2230   } else if (!eraseForwardRef(blockAndLoc.block)) {
2231     return nullptr;
2232   }
2233 
2234   // Populate the high level assembly state if necessary.
2235   if (state.asmState)
2236     state.asmState->addDefinition(blockAndLoc.block, loc);
2237 
2238   return blockAndLoc.block;
2239 }
2240 
2241 /// Parse a (possibly empty) list of SSA operands with types as block arguments.
2242 ///
2243 ///   ssa-id-and-type-list ::= ssa-id-and-type (`,` ssa-id-and-type)*
2244 ///
2245 ParseResult OperationParser::parseOptionalBlockArgList(Block *owner) {
2246   if (getToken().is(Token::r_brace))
2247     return success();
2248 
2249   // If the block already has arguments, then we're handling the entry block.
2250   // Parse and register the names for the arguments, but do not add them.
2251   bool definingExistingArgs = owner->getNumArguments() != 0;
2252   unsigned nextArgument = 0;
2253 
2254   return parseCommaSeparatedList([&]() -> ParseResult {
2255     return parseSSADefOrUseAndType(
2256         [&](SSAUseInfo useInfo, Type type) -> ParseResult {
2257           BlockArgument arg;
2258 
2259           // If we are defining existing arguments, ensure that the argument
2260           // has already been created with the right type.
2261           if (definingExistingArgs) {
2262             // Otherwise, ensure that this argument has already been created.
2263             if (nextArgument >= owner->getNumArguments())
2264               return emitError("too many arguments specified in argument list");
2265 
2266             // Finally, make sure the existing argument has the correct type.
2267             arg = owner->getArgument(nextArgument++);
2268             if (arg.getType() != type)
2269               return emitError("argument and block argument type mismatch");
2270           } else {
2271             auto loc = getEncodedSourceLocation(useInfo.loc);
2272             arg = owner->addArgument(type, loc);
2273           }
2274 
2275           // If the argument has an explicit loc(...) specifier, parse and apply
2276           // it.
2277           if (parseTrailingLocationSpecifier(arg))
2278             return failure();
2279 
2280           // Mark this block argument definition in the parser state if it was
2281           // provided.
2282           if (state.asmState)
2283             state.asmState->addDefinition(arg, useInfo.loc);
2284 
2285           return addDefinition(useInfo, arg);
2286         });
2287   });
2288 }
2289 
2290 //===----------------------------------------------------------------------===//
2291 // Top-level entity parsing.
2292 //===----------------------------------------------------------------------===//
2293 
2294 namespace {
2295 /// This parser handles entities that are only valid at the top level of the
2296 /// file.
2297 class TopLevelOperationParser : public Parser {
2298 public:
2299   explicit TopLevelOperationParser(ParserState &state) : Parser(state) {}
2300 
2301   /// Parse a set of operations into the end of the given Block.
2302   ParseResult parse(Block *topLevelBlock, Location parserLoc);
2303 
2304 private:
2305   /// Parse an attribute alias declaration.
2306   ParseResult parseAttributeAliasDef();
2307 
2308   /// Parse an attribute alias declaration.
2309   ParseResult parseTypeAliasDef();
2310 };
2311 } // end anonymous namespace
2312 
2313 /// Parses an attribute alias declaration.
2314 ///
2315 ///   attribute-alias-def ::= '#' alias-name `=` attribute-value
2316 ///
2317 ParseResult TopLevelOperationParser::parseAttributeAliasDef() {
2318   assert(getToken().is(Token::hash_identifier));
2319   StringRef aliasName = getTokenSpelling().drop_front();
2320 
2321   // Check for redefinitions.
2322   if (state.symbols.attributeAliasDefinitions.count(aliasName) > 0)
2323     return emitError("redefinition of attribute alias id '" + aliasName + "'");
2324 
2325   // Make sure this isn't invading the dialect attribute namespace.
2326   if (aliasName.contains('.'))
2327     return emitError("attribute names with a '.' are reserved for "
2328                      "dialect-defined names");
2329 
2330   consumeToken(Token::hash_identifier);
2331 
2332   // Parse the '='.
2333   if (parseToken(Token::equal, "expected '=' in attribute alias definition"))
2334     return failure();
2335 
2336   // Parse the attribute value.
2337   Attribute attr = parseAttribute();
2338   if (!attr)
2339     return failure();
2340 
2341   state.symbols.attributeAliasDefinitions[aliasName] = attr;
2342   return success();
2343 }
2344 
2345 /// Parse a type alias declaration.
2346 ///
2347 ///   type-alias-def ::= '!' alias-name `=` 'type' type
2348 ///
2349 ParseResult TopLevelOperationParser::parseTypeAliasDef() {
2350   assert(getToken().is(Token::exclamation_identifier));
2351   StringRef aliasName = getTokenSpelling().drop_front();
2352 
2353   // Check for redefinitions.
2354   if (state.symbols.typeAliasDefinitions.count(aliasName) > 0)
2355     return emitError("redefinition of type alias id '" + aliasName + "'");
2356 
2357   // Make sure this isn't invading the dialect type namespace.
2358   if (aliasName.contains('.'))
2359     return emitError("type names with a '.' are reserved for "
2360                      "dialect-defined names");
2361 
2362   consumeToken(Token::exclamation_identifier);
2363 
2364   // Parse the '=' and 'type'.
2365   if (parseToken(Token::equal, "expected '=' in type alias definition") ||
2366       parseToken(Token::kw_type, "expected 'type' in type alias definition"))
2367     return failure();
2368 
2369   // Parse the type.
2370   Type aliasedType = parseType();
2371   if (!aliasedType)
2372     return failure();
2373 
2374   // Register this alias with the parser state.
2375   state.symbols.typeAliasDefinitions.try_emplace(aliasName, aliasedType);
2376   return success();
2377 }
2378 
2379 ParseResult TopLevelOperationParser::parse(Block *topLevelBlock,
2380                                            Location parserLoc) {
2381   // Create a top-level operation to contain the parsed state.
2382   OwningOpRef<ModuleOp> topLevelOp(ModuleOp::create(parserLoc));
2383   OperationParser opParser(state, topLevelOp.get());
2384   while (true) {
2385     switch (getToken().getKind()) {
2386     default:
2387       // Parse a top-level operation.
2388       if (opParser.parseOperation())
2389         return failure();
2390       break;
2391 
2392     // If we got to the end of the file, then we're done.
2393     case Token::eof: {
2394       if (opParser.finalize())
2395         return failure();
2396 
2397       // Splice the blocks of the parsed operation over to the provided
2398       // top-level block.
2399       auto &parsedOps = topLevelOp->getBody()->getOperations();
2400       auto &destOps = topLevelBlock->getOperations();
2401       destOps.splice(destOps.empty() ? destOps.end() : std::prev(destOps.end()),
2402                      parsedOps, parsedOps.begin(), parsedOps.end());
2403       return success();
2404     }
2405 
2406     // If we got an error token, then the lexer already emitted an error, just
2407     // stop.  Someday we could introduce error recovery if there was demand
2408     // for it.
2409     case Token::error:
2410       return failure();
2411 
2412     // Parse an attribute alias.
2413     case Token::hash_identifier:
2414       if (parseAttributeAliasDef())
2415         return failure();
2416       break;
2417 
2418     // Parse a type alias.
2419     case Token::exclamation_identifier:
2420       if (parseTypeAliasDef())
2421         return failure();
2422       break;
2423     }
2424   }
2425 }
2426 
2427 //===----------------------------------------------------------------------===//
2428 
2429 LogicalResult mlir::parseSourceFile(const llvm::SourceMgr &sourceMgr,
2430                                     Block *block, MLIRContext *context,
2431                                     LocationAttr *sourceFileLoc,
2432                                     AsmParserState *asmState) {
2433   const auto *sourceBuf = sourceMgr.getMemoryBuffer(sourceMgr.getMainFileID());
2434 
2435   Location parserLoc = FileLineColLoc::get(
2436       context, sourceBuf->getBufferIdentifier(), /*line=*/0, /*column=*/0);
2437   if (sourceFileLoc)
2438     *sourceFileLoc = parserLoc;
2439 
2440   SymbolState aliasState;
2441   ParserState state(sourceMgr, context, aliasState, asmState);
2442   return TopLevelOperationParser(state).parse(block, parserLoc);
2443 }
2444 
2445 LogicalResult mlir::parseSourceFile(llvm::StringRef filename, Block *block,
2446                                     MLIRContext *context,
2447                                     LocationAttr *sourceFileLoc) {
2448   llvm::SourceMgr sourceMgr;
2449   return parseSourceFile(filename, sourceMgr, block, context, sourceFileLoc);
2450 }
2451 
2452 LogicalResult mlir::parseSourceFile(llvm::StringRef filename,
2453                                     llvm::SourceMgr &sourceMgr, Block *block,
2454                                     MLIRContext *context,
2455                                     LocationAttr *sourceFileLoc,
2456                                     AsmParserState *asmState) {
2457   if (sourceMgr.getNumBuffers() != 0) {
2458     // TODO: Extend to support multiple buffers.
2459     return emitError(mlir::UnknownLoc::get(context),
2460                      "only main buffer parsed at the moment");
2461   }
2462   auto file_or_err = llvm::MemoryBuffer::getFileOrSTDIN(filename);
2463   if (std::error_code error = file_or_err.getError())
2464     return emitError(mlir::UnknownLoc::get(context),
2465                      "could not open input file " + filename);
2466 
2467   // Load the MLIR source file.
2468   sourceMgr.AddNewSourceBuffer(std::move(*file_or_err), llvm::SMLoc());
2469   return parseSourceFile(sourceMgr, block, context, sourceFileLoc, asmState);
2470 }
2471 
2472 LogicalResult mlir::parseSourceString(llvm::StringRef sourceStr, Block *block,
2473                                       MLIRContext *context,
2474                                       LocationAttr *sourceFileLoc) {
2475   auto memBuffer = MemoryBuffer::getMemBuffer(sourceStr);
2476   if (!memBuffer)
2477     return failure();
2478 
2479   SourceMgr sourceMgr;
2480   sourceMgr.AddNewSourceBuffer(std::move(memBuffer), SMLoc());
2481   return parseSourceFile(sourceMgr, block, context, sourceFileLoc);
2482 }
2483