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