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