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