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