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