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