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