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