MLIR  21.0.0git
OpImplementation.h
Go to the documentation of this file.
1 //===- OpImplementation.h - Classes for implementing Op types ---*- C++ -*-===//
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 classes used by the implementation details of Op types.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef MLIR_IR_OPIMPLEMENTATION_H
14 #define MLIR_IR_OPIMPLEMENTATION_H
15 
16 #include "mlir/IR/BuiltinTypes.h"
18 #include "mlir/IR/OpAsmSupport.h"
19 #include "mlir/IR/OpDefinition.h"
20 #include "llvm/ADT/Twine.h"
21 #include "llvm/Support/SMLoc.h"
22 #include <optional>
23 
24 namespace {
25 // reference https://stackoverflow.com/a/16000226
26 template <typename T, typename = void>
27 struct HasStaticName : std::false_type {};
28 
29 template <typename T>
30 struct HasStaticName<T,
31  typename std::enable_if<
32  std::is_same<::llvm::StringLiteral,
33  std::decay_t<decltype(T::name)>>::value,
34  void>::type> : std::true_type {};
35 } // namespace
36 
37 namespace mlir {
38 class AsmParsedResourceEntry;
39 class AsmResourceBuilder;
40 class Builder;
41 
42 //===----------------------------------------------------------------------===//
43 // AsmDialectResourceHandle
44 //===----------------------------------------------------------------------===//
45 
46 /// This class represents an opaque handle to a dialect resource entry.
48 public:
50  AsmDialectResourceHandle(void *resource, TypeID resourceID, Dialect *dialect)
51  : resource(resource), opaqueID(resourceID), dialect(dialect) {}
52  bool operator==(const AsmDialectResourceHandle &other) const {
53  return resource == other.resource;
54  }
55 
56  /// Return an opaque pointer to the referenced resource.
57  void *getResource() const { return resource; }
58 
59  /// Return the type ID of the resource.
60  TypeID getTypeID() const { return opaqueID; }
61 
62  /// Return the dialect that owns the resource.
63  Dialect *getDialect() const { return dialect; }
64 
65 private:
66  /// The opaque handle to the dialect resource.
67  void *resource = nullptr;
68  /// The type of the resource referenced.
69  TypeID opaqueID;
70  /// The dialect owning the given resource.
71  Dialect *dialect;
72 };
73 
74 /// This class represents a CRTP base class for dialect resource handles. It
75 /// abstracts away various utilities necessary for defined derived resource
76 /// handles.
77 template <typename DerivedT, typename ResourceT, typename DialectT>
79 public:
80  using Dialect = DialectT;
81 
82  /// Construct a handle from a pointer to the resource. The given pointer
83  /// should be guaranteed to live beyond the life of this handle.
84  AsmDialectResourceHandleBase(ResourceT *resource, DialectT *dialect)
85  : AsmDialectResourceHandle(resource, TypeID::get<DerivedT>(), dialect) {}
87  : AsmDialectResourceHandle(handle) {
88  assert(handle.getTypeID() == TypeID::get<DerivedT>());
89  }
90 
91  /// Return the resource referenced by this handle.
92  ResourceT *getResource() {
93  return static_cast<ResourceT *>(AsmDialectResourceHandle::getResource());
94  }
95  const ResourceT *getResource() const {
96  return const_cast<AsmDialectResourceHandleBase *>(this)->getResource();
97  }
98 
99  /// Return the dialect that owns the resource.
100  DialectT *getDialect() const {
101  return static_cast<DialectT *>(AsmDialectResourceHandle::getDialect());
102  }
103 
104  /// Support llvm style casting.
105  static bool classof(const AsmDialectResourceHandle *handle) {
106  return handle->getTypeID() == TypeID::get<DerivedT>();
107  }
108 };
109 
110 inline llvm::hash_code hash_value(const AsmDialectResourceHandle &param) {
111  return llvm::hash_value(param.getResource());
112 }
113 
114 //===----------------------------------------------------------------------===//
115 // AsmPrinter
116 //===----------------------------------------------------------------------===//
117 
118 /// This base class exposes generic asm printer hooks, usable across the various
119 /// derived printers.
120 class AsmPrinter {
121 public:
122  /// This class contains the internal default implementation of the base
123  /// printer methods.
124  class Impl;
125 
126  /// Initialize the printer with the given internal implementation.
128  virtual ~AsmPrinter();
129 
130  /// Return the raw output stream used by this printer.
131  virtual raw_ostream &getStream() const;
132 
133  /// Print the given floating point value in a stabilized form that can be
134  /// roundtripped through the IR. This is the companion to the 'parseFloat'
135  /// hook on the AsmParser.
136  virtual void printFloat(const APFloat &value);
137 
138  virtual void printType(Type type);
139  virtual void printAttribute(Attribute attr);
140 
141  /// Trait to check if `AttrType` provides a `print` method.
142  template <typename AttrOrType>
144  decltype(std::declval<AttrOrType>().print(std::declval<AsmPrinter &>()));
145  template <typename AttrOrType>
147  llvm::is_detected<has_print_method, AttrOrType>;
148 
149  /// Print the provided attribute in the context of an operation custom
150  /// printer/parser: this will invoke directly the print method on the
151  /// attribute class and skip the `#dialect.mnemonic` prefix in most cases.
152  template <typename AttrOrType,
153  std::enable_if_t<detect_has_print_method<AttrOrType>::value>
154  *sfinae = nullptr>
155  void printStrippedAttrOrType(AttrOrType attrOrType) {
156  if (succeeded(printAlias(attrOrType)))
157  return;
158 
159  raw_ostream &os = getStream();
160  uint64_t posPrior = os.tell();
161  attrOrType.print(*this);
162  if (posPrior != os.tell())
163  return;
164 
165  // Fallback to printing with prefix if the above failed to write anything
166  // to the output stream.
167  *this << attrOrType;
168  }
169 
170  /// Print the provided array of attributes or types in the context of an
171  /// operation custom printer/parser: this will invoke directly the print
172  /// method on the attribute class and skip the `#dialect.mnemonic` prefix in
173  /// most cases.
174  template <typename AttrOrType,
175  std::enable_if_t<detect_has_print_method<AttrOrType>::value>
176  *sfinae = nullptr>
178  llvm::interleaveComma(
179  attrOrTypes, getStream(),
180  [this](AttrOrType attrOrType) { printStrippedAttrOrType(attrOrType); });
181  }
182 
183  /// SFINAE for printing the provided attribute in the context of an operation
184  /// custom printer in the case where the attribute does not define a print
185  /// method.
186  template <typename AttrOrType,
187  std::enable_if_t<!detect_has_print_method<AttrOrType>::value>
188  *sfinae = nullptr>
189  void printStrippedAttrOrType(AttrOrType attrOrType) {
190  *this << attrOrType;
191  }
192 
193  /// Print the given attribute without its type. The corresponding parser must
194  /// provide a valid type for the attribute.
195  virtual void printAttributeWithoutType(Attribute attr);
196 
197  /// Print the alias for the given attribute, return failure if no alias could
198  /// be printed.
199  virtual LogicalResult printAlias(Attribute attr);
200 
201  /// Print the alias for the given type, return failure if no alias could
202  /// be printed.
203  virtual LogicalResult printAlias(Type type);
204 
205  /// Print the given string as a keyword, or a quoted and escaped string if it
206  /// has any special or non-printable characters in it.
207  virtual void printKeywordOrString(StringRef keyword);
208 
209  /// Print the given string as a quoted string, escaping any special or
210  /// non-printable characters in it.
211  virtual void printString(StringRef string);
212 
213  /// Print the given string as a symbol reference, i.e. a form representable by
214  /// a SymbolRefAttr. A symbol reference is represented as a string prefixed
215  /// with '@'. The reference is surrounded with ""'s and escaped if it has any
216  /// special or non-printable characters in it.
217  virtual void printSymbolName(StringRef symbolRef);
218 
219  /// Print a handle to the given dialect resource. The handle key is quoted and
220  /// escaped if it has any special or non-printable characters in it.
221  virtual void printResourceHandle(const AsmDialectResourceHandle &resource);
222 
223  /// Print an optional arrow followed by a type list.
224  template <typename TypeRange>
226  if (types.begin() != types.end())
227  printArrowTypeList(types);
228  }
229  template <typename TypeRange>
231  auto &os = getStream() << " -> ";
232 
233  bool wrapped = !llvm::hasSingleElement(types) ||
234  llvm::isa<FunctionType>((*types.begin()));
235  if (wrapped)
236  os << '(';
237  llvm::interleaveComma(types, *this);
238  if (wrapped)
239  os << ')';
240  }
241 
242  /// Print the two given type ranges in a functional form.
243  template <typename InputRangeT, typename ResultRangeT>
244  void printFunctionalType(InputRangeT &&inputs, ResultRangeT &&results) {
245  auto &os = getStream();
246  os << '(';
247  llvm::interleaveComma(inputs, *this);
248  os << ')';
249  printArrowTypeList(results);
250  }
251 
253 
254  /// Class used to automatically end a cyclic region on destruction.
256  public:
257  explicit CyclicPrintReset(AsmPrinter *printer) : printer(printer) {}
258 
260  if (printer)
261  printer->popCyclicPrinting();
262  }
263 
265 
267 
269  : printer(std::exchange(rhs.printer, nullptr)) {}
270 
272  printer = std::exchange(rhs.printer, nullptr);
273  return *this;
274  }
275 
276  private:
277  AsmPrinter *printer;
278  };
279 
280  /// Attempts to start a cyclic printing region for `attrOrType`.
281  /// A cyclic printing region starts with this call and ends with the
282  /// destruction of the returned `CyclicPrintReset`. During this time,
283  /// calling `tryStartCyclicPrint` with the same attribute in any printer
284  /// will lead to returning failure.
285  ///
286  /// This makes it possible to break infinite recursions when trying to print
287  /// cyclic attributes or types by printing only immutable parameters if nested
288  /// within itself.
289  template <class AttrOrTypeT>
290  FailureOr<CyclicPrintReset> tryStartCyclicPrint(AttrOrTypeT attrOrType) {
291  static_assert(
292  std::is_base_of_v<AttributeTrait::IsMutable<AttrOrTypeT>,
293  AttrOrTypeT> ||
294  std::is_base_of_v<TypeTrait::IsMutable<AttrOrTypeT>, AttrOrTypeT>,
295  "Only mutable attributes or types can be cyclic");
296  if (failed(pushCyclicPrinting(attrOrType.getAsOpaquePointer())))
297  return failure();
298  return CyclicPrintReset(this);
299  }
300 
301 protected:
302  /// Initialize the printer with no internal implementation. In this case, all
303  /// virtual methods of this class must be overriden.
304  AsmPrinter() = default;
305 
306  /// Pushes a new attribute or type in the form of a type erased pointer
307  /// into an internal set.
308  /// Returns success if the type or attribute was inserted in the set or
309  /// failure if it was already contained.
310  virtual LogicalResult pushCyclicPrinting(const void *opaquePointer);
311 
312  /// Removes the element that was last inserted with a successful call to
313  /// `pushCyclicPrinting`. There must be exactly one `popCyclicPrinting` call
314  /// in reverse order of all successful `pushCyclicPrinting`.
315  virtual void popCyclicPrinting();
316 
317 private:
318  AsmPrinter(const AsmPrinter &) = delete;
319  void operator=(const AsmPrinter &) = delete;
320 
321  /// The internal implementation of the printer.
322  Impl *impl{nullptr};
323 };
324 
325 template <typename AsmPrinterT>
326 inline std::enable_if_t<std::is_base_of<AsmPrinter, AsmPrinterT>::value,
327  AsmPrinterT &>
328 operator<<(AsmPrinterT &p, Type type) {
329  p.printType(type);
330  return p;
331 }
332 
333 template <typename AsmPrinterT>
334 inline std::enable_if_t<std::is_base_of<AsmPrinter, AsmPrinterT>::value,
335  AsmPrinterT &>
336 operator<<(AsmPrinterT &p, Attribute attr) {
337  p.printAttribute(attr);
338  return p;
339 }
340 
341 template <typename AsmPrinterT>
342 inline std::enable_if_t<std::is_base_of<AsmPrinter, AsmPrinterT>::value,
343  AsmPrinterT &>
344 operator<<(AsmPrinterT &p, const APFloat &value) {
345  p.printFloat(value);
346  return p;
347 }
348 template <typename AsmPrinterT>
349 inline std::enable_if_t<std::is_base_of<AsmPrinter, AsmPrinterT>::value,
350  AsmPrinterT &>
351 operator<<(AsmPrinterT &p, float value) {
352  return p << APFloat(value);
353 }
354 template <typename AsmPrinterT>
355 inline std::enable_if_t<std::is_base_of<AsmPrinter, AsmPrinterT>::value,
356  AsmPrinterT &>
357 operator<<(AsmPrinterT &p, double value) {
358  return p << APFloat(value);
359 }
360 
361 // Support printing anything that isn't convertible to one of the other
362 // streamable types, even if it isn't exactly one of them. For example, we want
363 // to print FunctionType with the Type version above, not have it match this.
364 template <typename AsmPrinterT, typename T,
365  std::enable_if_t<!std::is_convertible<T &, Value &>::value &&
366  !std::is_convertible<T &, Type &>::value &&
367  !std::is_convertible<T &, Attribute &>::value &&
368  !std::is_convertible<T &, ValueRange>::value &&
369  !std::is_convertible<T &, APFloat &>::value &&
370  !llvm::is_one_of<T, bool, float, double>::value,
371  T> * = nullptr>
372 inline std::enable_if_t<std::is_base_of<AsmPrinter, AsmPrinterT>::value,
373  AsmPrinterT &>
374 operator<<(AsmPrinterT &p, const T &other) {
375  p.getStream() << other;
376  return p;
377 }
378 
379 template <typename AsmPrinterT>
380 inline std::enable_if_t<std::is_base_of<AsmPrinter, AsmPrinterT>::value,
381  AsmPrinterT &>
382 operator<<(AsmPrinterT &p, bool value) {
383  return p << (value ? StringRef("true") : "false");
384 }
385 
386 template <typename AsmPrinterT, typename ValueRangeT>
387 inline std::enable_if_t<std::is_base_of<AsmPrinter, AsmPrinterT>::value,
388  AsmPrinterT &>
389 operator<<(AsmPrinterT &p, const ValueTypeRange<ValueRangeT> &types) {
390  llvm::interleaveComma(types, p);
391  return p;
392 }
393 
394 template <typename AsmPrinterT>
395 inline std::enable_if_t<std::is_base_of<AsmPrinter, AsmPrinterT>::value,
396  AsmPrinterT &>
397 operator<<(AsmPrinterT &p, const TypeRange &types) {
398  llvm::interleaveComma(types, p);
399  return p;
400 }
401 
402 // Prevent matching the TypeRange version above for ValueRange
403 // printing through base AsmPrinter. This is needed so that the
404 // ValueRange printing behaviour does not change from printing
405 // the SSA values to printing the types for the operands when
406 // using AsmPrinter instead of OpAsmPrinter.
407 template <typename AsmPrinterT, typename T>
408 inline std::enable_if_t<std::is_same<AsmPrinter, AsmPrinterT>::value &&
409  std::is_convertible<T &, ValueRange>::value,
410  AsmPrinterT &>
411 operator<<(AsmPrinterT &p, const T &other) = delete;
412 
413 template <typename AsmPrinterT, typename ElementT>
414 inline std::enable_if_t<std::is_base_of<AsmPrinter, AsmPrinterT>::value,
415  AsmPrinterT &>
416 operator<<(AsmPrinterT &p, ArrayRef<ElementT> types) {
417  llvm::interleaveComma(types, p);
418  return p;
419 }
420 
421 //===----------------------------------------------------------------------===//
422 // OpAsmPrinter
423 //===----------------------------------------------------------------------===//
424 
425 /// This is a pure-virtual base class that exposes the asmprinter hooks
426 /// necessary to implement a custom print() method.
427 class OpAsmPrinter : public AsmPrinter {
428 public:
430  ~OpAsmPrinter() override;
431 
432  /// Print a loc(...) specifier if printing debug info is enabled.
434 
435  /// Print a newline and indent the printer to the start of the current
436  /// operation.
437  virtual void printNewline() = 0;
438 
439  /// Increase indentation.
440  virtual void increaseIndent() = 0;
441 
442  /// Decrease indentation.
443  virtual void decreaseIndent() = 0;
444 
445  /// Print a block argument in the usual format of:
446  /// %ssaName : type {attr1=42} loc("here")
447  /// where location printing is controlled by the standard internal option.
448  /// You may pass omitType=true to not print a type, and pass an empty
449  /// attribute list if you don't care for attributes.
451  ArrayRef<NamedAttribute> argAttrs = {},
452  bool omitType = false) = 0;
453 
454  /// Print implementations for various things an operation contains.
455  virtual void printOperand(Value value) = 0;
456  virtual void printOperand(Value value, raw_ostream &os) = 0;
457 
458  /// Print a comma separated list of operands.
459  template <typename ContainerType>
460  void printOperands(const ContainerType &container) {
461  printOperands(container.begin(), container.end());
462  }
463 
464  /// Print a comma separated list of operands.
465  template <typename IteratorType>
466  void printOperands(IteratorType it, IteratorType end) {
467  llvm::interleaveComma(llvm::make_range(it, end), getStream(),
468  [this](Value value) { printOperand(value); });
469  }
470 
471  /// Print the given successor.
472  virtual void printSuccessor(Block *successor) = 0;
473 
474  /// Print the successor and its operands.
475  virtual void printSuccessorAndUseList(Block *successor,
476  ValueRange succOperands) = 0;
477 
478  /// If the specified operation has attributes, print out an attribute
479  /// dictionary with their values. elidedAttrs allows the client to ignore
480  /// specific well known attributes, commonly used if the attribute value is
481  /// printed some other way (like as a fixed operand).
483  ArrayRef<StringRef> elidedAttrs = {}) = 0;
484 
485  /// If the specified operation has attributes, print out an attribute
486  /// dictionary prefixed with 'attributes'.
487  virtual void
489  ArrayRef<StringRef> elidedAttrs = {}) = 0;
490 
491  /// Prints the entire operation with the custom assembly form, if available,
492  /// or the generic assembly form, otherwise.
493  virtual void printCustomOrGenericOp(Operation *op) = 0;
494 
495  /// Print the entire operation with the default generic assembly form.
496  /// If `printOpName` is true, then the operation name is printed (the default)
497  /// otherwise it is omitted and the print will start with the operand list.
498  virtual void printGenericOp(Operation *op, bool printOpName = true) = 0;
499 
500  /// Prints a region.
501  /// If 'printEntryBlockArgs' is false, the arguments of the
502  /// block are not printed. If 'printBlockTerminator' is false, the terminator
503  /// operation of the block is not printed. If printEmptyBlock is true, then
504  /// the block header is printed even if the block is empty.
505  virtual void printRegion(Region &blocks, bool printEntryBlockArgs = true,
506  bool printBlockTerminators = true,
507  bool printEmptyBlock = false) = 0;
508 
509  /// Renumber the arguments for the specified region to the same names as the
510  /// SSA values in namesToUse. This may only be used for IsolatedFromAbove
511  /// operations. If any entry in namesToUse is null, the corresponding
512  /// argument name is left alone.
513  virtual void shadowRegionArgs(Region &region, ValueRange namesToUse) = 0;
514 
515  /// Prints an affine map of SSA ids, where SSA id names are used in place
516  /// of dims/symbols.
517  /// Operand values must come from single-result sources, and be valid
518  /// dimensions/symbol identifiers according to mlir::isValidDim/Symbol.
519  virtual void printAffineMapOfSSAIds(AffineMapAttr mapAttr,
520  ValueRange operands) = 0;
521 
522  /// Prints an affine expression of SSA ids with SSA id names used instead of
523  /// dims and symbols.
524  /// Operand values must come from single-result sources, and be valid
525  /// dimensions/symbol identifiers according to mlir::isValidDim/Symbol.
526  virtual void printAffineExprOfSSAIds(AffineExpr expr, ValueRange dimOperands,
527  ValueRange symOperands) = 0;
528 
529  /// Print the complete type of an operation in functional form.
530  void printFunctionalType(Operation *op);
532 };
533 
534 // Make the implementations convenient to use.
536  p.printOperand(value);
537  return p;
538 }
539 
540 template <typename T,
541  std::enable_if_t<std::is_convertible<T &, ValueRange>::value &&
542  !std::is_convertible<T &, Value &>::value,
543  T> * = nullptr>
544 inline OpAsmPrinter &operator<<(OpAsmPrinter &p, const T &values) {
545  p.printOperands(values);
546  return p;
547 }
548 
550  p.printSuccessor(value);
551  return p;
552 }
553 
554 //===----------------------------------------------------------------------===//
555 // AsmParser
556 //===----------------------------------------------------------------------===//
557 
558 /// This base class exposes generic asm parser hooks, usable across the various
559 /// derived parsers.
560 class AsmParser {
561 public:
562  AsmParser() = default;
563  virtual ~AsmParser();
564 
565  MLIRContext *getContext() const;
566 
567  /// Return the location of the original name token.
568  virtual SMLoc getNameLoc() const = 0;
569 
570  //===--------------------------------------------------------------------===//
571  // Utilities
572  //===--------------------------------------------------------------------===//
573 
574  /// Emit a diagnostic at the specified location and return failure.
575  virtual InFlightDiagnostic emitError(SMLoc loc,
576  const Twine &message = {}) = 0;
577 
578  /// Return a builder which provides useful access to MLIRContext, global
579  /// objects like types and attributes.
580  virtual Builder &getBuilder() const = 0;
581 
582  /// Get the location of the next token and store it into the argument. This
583  /// always succeeds.
584  virtual SMLoc getCurrentLocation() = 0;
585  ParseResult getCurrentLocation(SMLoc *loc) {
586  *loc = getCurrentLocation();
587  return success();
588  }
589 
590  /// Re-encode the given source location as an MLIR location and return it.
591  /// Note: This method should only be used when a `Location` is necessary, as
592  /// the encoding process is not efficient.
593  virtual Location getEncodedSourceLoc(SMLoc loc) = 0;
594 
595  //===--------------------------------------------------------------------===//
596  // Token Parsing
597  //===--------------------------------------------------------------------===//
598 
599  /// Parse a '->' token.
600  virtual ParseResult parseArrow() = 0;
601 
602  /// Parse a '->' token if present
603  virtual ParseResult parseOptionalArrow() = 0;
604 
605  /// Parse a `{` token.
606  virtual ParseResult parseLBrace() = 0;
607 
608  /// Parse a `{` token if present.
609  virtual ParseResult parseOptionalLBrace() = 0;
610 
611  /// Parse a `}` token.
612  virtual ParseResult parseRBrace() = 0;
613 
614  /// Parse a `}` token if present.
615  virtual ParseResult parseOptionalRBrace() = 0;
616 
617  /// Parse a `:` token.
618  virtual ParseResult parseColon() = 0;
619 
620  /// Parse a `:` token if present.
621  virtual ParseResult parseOptionalColon() = 0;
622 
623  /// Parse a `,` token.
624  virtual ParseResult parseComma() = 0;
625 
626  /// Parse a `,` token if present.
627  virtual ParseResult parseOptionalComma() = 0;
628 
629  /// Parse a `=` token.
630  virtual ParseResult parseEqual() = 0;
631 
632  /// Parse a `=` token if present.
633  virtual ParseResult parseOptionalEqual() = 0;
634 
635  /// Parse a '<' token.
636  virtual ParseResult parseLess() = 0;
637 
638  /// Parse a '<' token if present.
639  virtual ParseResult parseOptionalLess() = 0;
640 
641  /// Parse a '>' token.
642  virtual ParseResult parseGreater() = 0;
643 
644  /// Parse a '>' token if present.
645  virtual ParseResult parseOptionalGreater() = 0;
646 
647  /// Parse a '?' token.
648  virtual ParseResult parseQuestion() = 0;
649 
650  /// Parse a '?' token if present.
651  virtual ParseResult parseOptionalQuestion() = 0;
652 
653  /// Parse a '+' token.
654  virtual ParseResult parsePlus() = 0;
655 
656  /// Parse a '+' token if present.
657  virtual ParseResult parseOptionalPlus() = 0;
658 
659  /// Parse a '-' token.
660  virtual ParseResult parseMinus() = 0;
661 
662  /// Parse a '-' token if present.
663  virtual ParseResult parseOptionalMinus() = 0;
664 
665  /// Parse a '*' token.
666  virtual ParseResult parseStar() = 0;
667 
668  /// Parse a '*' token if present.
669  virtual ParseResult parseOptionalStar() = 0;
670 
671  /// Parse a '|' token.
672  virtual ParseResult parseVerticalBar() = 0;
673 
674  /// Parse a '|' token if present.
675  virtual ParseResult parseOptionalVerticalBar() = 0;
676 
677  /// Parse a quoted string token.
678  ParseResult parseString(std::string *string) {
679  auto loc = getCurrentLocation();
680  if (parseOptionalString(string))
681  return emitError(loc, "expected string");
682  return success();
683  }
684 
685  /// Parse a quoted string token if present.
686  virtual ParseResult parseOptionalString(std::string *string) = 0;
687 
688  /// Parses a Base64 encoded string of bytes.
689  virtual ParseResult parseBase64Bytes(std::vector<char> *bytes) = 0;
690 
691  /// Parse a `(` token.
692  virtual ParseResult parseLParen() = 0;
693 
694  /// Parse a `(` token if present.
695  virtual ParseResult parseOptionalLParen() = 0;
696 
697  /// Parse a `)` token.
698  virtual ParseResult parseRParen() = 0;
699 
700  /// Parse a `)` token if present.
701  virtual ParseResult parseOptionalRParen() = 0;
702 
703  /// Parse a `[` token.
704  virtual ParseResult parseLSquare() = 0;
705 
706  /// Parse a `[` token if present.
707  virtual ParseResult parseOptionalLSquare() = 0;
708 
709  /// Parse a `]` token.
710  virtual ParseResult parseRSquare() = 0;
711 
712  /// Parse a `]` token if present.
713  virtual ParseResult parseOptionalRSquare() = 0;
714 
715  /// Parse a `...` token.
716  virtual ParseResult parseEllipsis() = 0;
717 
718  /// Parse a `...` token if present;
719  virtual ParseResult parseOptionalEllipsis() = 0;
720 
721  /// Parse a floating point value from the stream.
722  virtual ParseResult parseFloat(double &result) = 0;
723 
724  /// Parse a floating point value into APFloat from the stream.
725  virtual ParseResult parseFloat(const llvm::fltSemantics &semantics,
726  APFloat &result) = 0;
727 
728  /// Parse an integer value from the stream.
729  template <typename IntT>
730  ParseResult parseInteger(IntT &result) {
731  auto loc = getCurrentLocation();
732  OptionalParseResult parseResult = parseOptionalInteger(result);
733  if (!parseResult.has_value())
734  return emitError(loc, "expected integer value");
735  return *parseResult;
736  }
737 
738  /// Parse a decimal integer value from the stream.
739  template <typename IntT>
740  ParseResult parseDecimalInteger(IntT &result) {
741  auto loc = getCurrentLocation();
742  OptionalParseResult parseResult = parseOptionalDecimalInteger(result);
743  if (!parseResult.has_value())
744  return emitError(loc, "expected decimal integer value");
745  return *parseResult;
746  }
747 
748  /// Parse an optional integer value from the stream.
749  virtual OptionalParseResult parseOptionalInteger(APInt &result) = 0;
751 
752 private:
753  template <typename IntT, typename ParseFn>
754  OptionalParseResult parseOptionalIntegerAndCheck(IntT &result,
755  ParseFn &&parseFn) {
756  auto loc = getCurrentLocation();
757  APInt uintResult;
758  OptionalParseResult parseResult = parseFn(uintResult);
759  if (!parseResult.has_value() || failed(*parseResult))
760  return parseResult;
761 
762  // Try to convert to the provided integer type. sextOrTrunc is correct even
763  // for unsigned types because parseOptionalInteger ensures the sign bit is
764  // zero for non-negated integers.
765  result =
766  (IntT)uintResult.sextOrTrunc(sizeof(IntT) * CHAR_BIT).getLimitedValue();
767  if (APInt(uintResult.getBitWidth(), result,
768  /*isSigned=*/std::is_signed_v<IntT>,
769  /*implicitTrunc=*/true) != uintResult)
770  return emitError(loc, "integer value too large");
771  return success();
772  }
773 
774 public:
775  template <typename IntT>
777  return parseOptionalIntegerAndCheck(
778  result, [&](APInt &result) { return parseOptionalInteger(result); });
779  }
780 
781  template <typename IntT>
783  return parseOptionalIntegerAndCheck(result, [&](APInt &result) {
784  return parseOptionalDecimalInteger(result);
785  });
786  }
787 
788  /// These are the supported delimiters around operand lists and region
789  /// argument lists, used by parseOperandList.
790  enum class Delimiter {
791  /// Zero or more operands with no delimiters.
792  None,
793  /// Parens surrounding zero or more operands.
794  Paren,
795  /// Square brackets surrounding zero or more operands.
796  Square,
797  /// <> brackets surrounding zero or more operands.
798  LessGreater,
799  /// {} brackets surrounding zero or more operands.
800  Braces,
801  /// Parens supporting zero or more operands, or nothing.
803  /// Square brackets supporting zero or more ops, or nothing.
805  /// <> brackets supporting zero or more ops, or nothing.
807  /// {} brackets surrounding zero or more operands, or nothing.
809  };
810 
811  /// Parse a list of comma-separated items with an optional delimiter. If a
812  /// delimiter is provided, then an empty list is allowed. If not, then at
813  /// least one element will be parsed.
814  ///
815  /// contextMessage is an optional message appended to "expected '('" sorts of
816  /// diagnostics when parsing the delimeters.
817  virtual ParseResult
819  function_ref<ParseResult()> parseElementFn,
820  StringRef contextMessage = StringRef()) = 0;
821 
822  /// Parse a comma separated list of elements that must have at least one entry
823  /// in it.
824  ParseResult
825  parseCommaSeparatedList(function_ref<ParseResult()> parseElementFn) {
826  return parseCommaSeparatedList(Delimiter::None, parseElementFn);
827  }
828 
829  //===--------------------------------------------------------------------===//
830  // Keyword Parsing
831  //===--------------------------------------------------------------------===//
832 
833  /// This class represents a StringSwitch like class that is useful for parsing
834  /// expected keywords. On construction, unless a non-empty keyword is
835  /// provided, it invokes `parseKeyword` and processes each of the provided
836  /// cases statements until a match is hit. The provided `ResultT` must be
837  /// assignable from `failure()`.
838  template <typename ResultT = ParseResult>
840  public:
841  KeywordSwitch(AsmParser &parser, StringRef *keyword = nullptr)
842  : parser(parser), loc(parser.getCurrentLocation()) {
843  if (keyword && !keyword->empty())
844  this->keyword = *keyword;
845  else if (failed(parser.parseKeywordOrCompletion(&this->keyword)))
846  result = failure();
847  }
848  /// Case that uses the provided value when true.
849  KeywordSwitch &Case(StringLiteral str, ResultT value) {
850  return Case(str, [&](StringRef, SMLoc) { return std::move(value); });
851  }
852  KeywordSwitch &Default(ResultT value) {
853  return Default([&](StringRef, SMLoc) { return std::move(value); });
854  }
855  /// Case that invokes the provided functor when true. The parameters passed
856  /// to the functor are the keyword, and the location of the keyword (in case
857  /// any errors need to be emitted).
858  template <typename FnT>
859  std::enable_if_t<!std::is_convertible<FnT, ResultT>::value, KeywordSwitch &>
860  Case(StringLiteral str, FnT &&fn) {
861  if (result)
862  return *this;
863 
864  // If the word was empty, record this as a completion.
865  if (keyword.empty())
866  parser.codeCompleteExpectedTokens(str);
867  else if (keyword == str)
868  result.emplace(std::move(fn(keyword, loc)));
869  return *this;
870  }
871  template <typename FnT>
872  std::enable_if_t<!std::is_convertible<FnT, ResultT>::value, KeywordSwitch &>
873  Default(FnT &&fn) {
874  if (!result)
875  result.emplace(fn(keyword, loc));
876  return *this;
877  }
878 
879  /// Returns true if this switch has a value yet.
880  bool hasValue() const { return result.has_value(); }
881 
882  /// Return the result of the switch.
883  [[nodiscard]] operator ResultT() {
884  if (!result)
885  return parser.emitError(loc, "unexpected keyword: ") << keyword;
886  return std::move(*result);
887  }
888 
889  private:
890  /// The parser used to construct this switch.
891  AsmParser &parser;
892 
893  /// The location of the keyword, used to emit errors as necessary.
894  SMLoc loc;
895 
896  /// The parsed keyword itself.
897  StringRef keyword;
898 
899  /// The result of the switch statement or std::nullopt if currently unknown.
900  std::optional<ResultT> result;
901  };
902 
903  /// Parse a given keyword.
904  ParseResult parseKeyword(StringRef keyword) {
905  return parseKeyword(keyword, "");
906  }
907  virtual ParseResult parseKeyword(StringRef keyword, const Twine &msg) = 0;
908 
909  /// Parse a keyword into 'keyword'.
910  ParseResult parseKeyword(StringRef *keyword) {
911  auto loc = getCurrentLocation();
912  if (parseOptionalKeyword(keyword))
913  return emitError(loc, "expected valid keyword");
914  return success();
915  }
916 
917  /// Parse the given keyword if present.
918  virtual ParseResult parseOptionalKeyword(StringRef keyword) = 0;
919 
920  /// Parse a keyword, if present, into 'keyword'.
921  virtual ParseResult parseOptionalKeyword(StringRef *keyword) = 0;
922 
923  /// Parse a keyword, if present, and if one of the 'allowedValues',
924  /// into 'keyword'
925  virtual ParseResult
926  parseOptionalKeyword(StringRef *keyword,
927  ArrayRef<StringRef> allowedValues) = 0;
928 
929  /// Parse a keyword or a quoted string.
930  ParseResult parseKeywordOrString(std::string *result) {
931  if (failed(parseOptionalKeywordOrString(result)))
932  return emitError(getCurrentLocation())
933  << "expected valid keyword or string";
934  return success();
935  }
936 
937  /// Parse an optional keyword or string.
938  virtual ParseResult parseOptionalKeywordOrString(std::string *result) = 0;
939 
940  //===--------------------------------------------------------------------===//
941  // Attribute/Type Parsing
942  //===--------------------------------------------------------------------===//
943 
944  /// Invoke the `getChecked` method of the given Attribute or Type class, using
945  /// the provided location to emit errors in the case of failure. Note that
946  /// unlike `OpBuilder::getType`, this method does not implicitly insert a
947  /// context parameter.
948  template <typename T, typename... ParamsT>
949  auto getChecked(SMLoc loc, ParamsT &&...params) {
950  return T::getChecked([&] { return emitError(loc); },
951  std::forward<ParamsT>(params)...);
952  }
953  /// A variant of `getChecked` that uses the result of `getNameLoc` to emit
954  /// errors.
955  template <typename T, typename... ParamsT>
956  auto getChecked(ParamsT &&...params) {
957  return T::getChecked([&] { return emitError(getNameLoc()); },
958  std::forward<ParamsT>(params)...);
959  }
960 
961  //===--------------------------------------------------------------------===//
962  // Attribute Parsing
963  //===--------------------------------------------------------------------===//
964 
965  /// Parse an arbitrary attribute of a given type and return it in result.
966  virtual ParseResult parseAttribute(Attribute &result, Type type = {}) = 0;
967 
968  /// Parse a custom attribute with the provided callback, unless the next
969  /// token is `#`, in which case the generic parser is invoked.
970  virtual ParseResult parseCustomAttributeWithFallback(
971  Attribute &result, Type type,
972  function_ref<ParseResult(Attribute &result, Type type)>
973  parseAttribute) = 0;
974 
975  /// Parse an attribute of a specific kind and type.
976  template <typename AttrType>
977  ParseResult parseAttribute(AttrType &result, Type type = {}) {
978  SMLoc loc = getCurrentLocation();
979 
980  // Parse any kind of attribute.
981  Attribute attr;
982  if (parseAttribute(attr, type))
983  return failure();
984 
985  // Check for the right kind of attribute.
986  if (!(result = llvm::dyn_cast<AttrType>(attr)))
987  return emitError(loc, "invalid kind of attribute specified");
988 
989  return success();
990  }
991 
992  /// Parse an arbitrary attribute and return it in result. This also adds the
993  /// attribute to the specified attribute list with the specified name.
994  ParseResult parseAttribute(Attribute &result, StringRef attrName,
995  NamedAttrList &attrs) {
996  return parseAttribute(result, Type(), attrName, attrs);
997  }
998 
999  /// Parse an attribute of a specific kind and type.
1000  template <typename AttrType>
1001  ParseResult parseAttribute(AttrType &result, StringRef attrName,
1002  NamedAttrList &attrs) {
1003  return parseAttribute(result, Type(), attrName, attrs);
1004  }
1005 
1006  /// Parse an arbitrary attribute of a given type and populate it in `result`.
1007  /// This also adds the attribute to the specified attribute list with the
1008  /// specified name.
1009  template <typename AttrType>
1010  ParseResult parseAttribute(AttrType &result, Type type, StringRef attrName,
1011  NamedAttrList &attrs) {
1012  SMLoc loc = getCurrentLocation();
1013 
1014  // Parse any kind of attribute.
1015  Attribute attr;
1016  if (parseAttribute(attr, type))
1017  return failure();
1018 
1019  // Check for the right kind of attribute.
1020  result = llvm::dyn_cast<AttrType>(attr);
1021  if (!result)
1022  return emitError(loc, "invalid kind of attribute specified");
1023 
1024  attrs.append(attrName, result);
1025  return success();
1026  }
1027 
1028  /// Trait to check if `AttrType` provides a `parse` method.
1029  template <typename AttrType>
1030  using has_parse_method = decltype(AttrType::parse(std::declval<AsmParser &>(),
1031  std::declval<Type>()));
1032  template <typename AttrType>
1033  using detect_has_parse_method = llvm::is_detected<has_parse_method, AttrType>;
1034 
1035  /// Parse a custom attribute of a given type unless the next token is `#`, in
1036  /// which case the generic parser is invoked. The parsed attribute is
1037  /// populated in `result` and also added to the specified attribute list with
1038  /// the specified name.
1039  template <typename AttrType>
1040  std::enable_if_t<detect_has_parse_method<AttrType>::value, ParseResult>
1041  parseCustomAttributeWithFallback(AttrType &result, Type type,
1042  StringRef attrName, NamedAttrList &attrs) {
1043  SMLoc loc = getCurrentLocation();
1044 
1045  // Parse any kind of attribute.
1046  Attribute attr;
1048  attr, type, [&](Attribute &result, Type type) -> ParseResult {
1049  result = AttrType::parse(*this, type);
1050  if (!result)
1051  return failure();
1052  return success();
1053  }))
1054  return failure();
1055 
1056  // Check for the right kind of attribute.
1057  result = llvm::dyn_cast<AttrType>(attr);
1058  if (!result)
1059  return emitError(loc, "invalid kind of attribute specified");
1060 
1061  attrs.append(attrName, result);
1062  return success();
1063  }
1064 
1065  /// SFINAE parsing method for Attribute that don't implement a parse method.
1066  template <typename AttrType>
1067  std::enable_if_t<!detect_has_parse_method<AttrType>::value, ParseResult>
1068  parseCustomAttributeWithFallback(AttrType &result, Type type,
1069  StringRef attrName, NamedAttrList &attrs) {
1070  return parseAttribute(result, type, attrName, attrs);
1071  }
1072 
1073  /// Parse a custom attribute of a given type unless the next token is `#`, in
1074  /// which case the generic parser is invoked. The parsed attribute is
1075  /// populated in `result`.
1076  template <typename AttrType>
1077  std::enable_if_t<detect_has_parse_method<AttrType>::value, ParseResult>
1078  parseCustomAttributeWithFallback(AttrType &result, Type type = {}) {
1079  SMLoc loc = getCurrentLocation();
1080 
1081  // Parse any kind of attribute.
1082  Attribute attr;
1084  attr, type, [&](Attribute &result, Type type) -> ParseResult {
1085  result = AttrType::parse(*this, type);
1086  return success(!!result);
1087  }))
1088  return failure();
1089 
1090  // Check for the right kind of attribute.
1091  result = llvm::dyn_cast<AttrType>(attr);
1092  if (!result)
1093  return emitError(loc, "invalid kind of attribute specified");
1094  return success();
1095  }
1096 
1097  /// SFINAE parsing method for Attribute that don't implement a parse method.
1098  template <typename AttrType>
1099  std::enable_if_t<!detect_has_parse_method<AttrType>::value, ParseResult>
1100  parseCustomAttributeWithFallback(AttrType &result, Type type = {}) {
1101  return parseAttribute(result, type);
1102  }
1103 
1104  /// Parse an arbitrary optional attribute of a given type and return it in
1105  /// result.
1107  Type type = {}) = 0;
1108 
1109  /// Parse an optional array attribute and return it in result.
1110  virtual OptionalParseResult parseOptionalAttribute(ArrayAttr &result,
1111  Type type = {}) = 0;
1112 
1113  /// Parse an optional string attribute and return it in result.
1114  virtual OptionalParseResult parseOptionalAttribute(StringAttr &result,
1115  Type type = {}) = 0;
1116 
1117  /// Parse an optional symbol ref attribute and return it in result.
1118  virtual OptionalParseResult parseOptionalAttribute(SymbolRefAttr &result,
1119  Type type = {}) = 0;
1120 
1121  /// Parse an optional attribute of a specific type and add it to the list with
1122  /// the specified name.
1123  template <typename AttrType>
1125  StringRef attrName,
1126  NamedAttrList &attrs) {
1127  return parseOptionalAttribute(result, Type(), attrName, attrs);
1128  }
1129 
1130  /// Parse an optional attribute of a specific type and add it to the list with
1131  /// the specified name.
1132  template <typename AttrType>
1134  StringRef attrName,
1135  NamedAttrList &attrs) {
1136  OptionalParseResult parseResult = parseOptionalAttribute(result, type);
1137  if (parseResult.has_value() && succeeded(*parseResult))
1138  attrs.append(attrName, result);
1139  return parseResult;
1140  }
1141 
1142  /// Parse a named dictionary into 'result' if it is present.
1143  virtual ParseResult parseOptionalAttrDict(NamedAttrList &result) = 0;
1144 
1145  /// Parse a named dictionary into 'result' if the `attributes` keyword is
1146  /// present.
1147  virtual ParseResult
1149 
1150  /// Parse an affine map instance into 'map'.
1151  virtual ParseResult parseAffineMap(AffineMap &map) = 0;
1152 
1153  /// Parse an affine expr instance into 'expr' using the already computed
1154  /// mapping from symbols to affine expressions in 'symbolSet'.
1155  virtual ParseResult
1156  parseAffineExpr(ArrayRef<std::pair<StringRef, AffineExpr>> symbolSet,
1157  AffineExpr &expr) = 0;
1158 
1159  /// Parse an integer set instance into 'set'.
1160  virtual ParseResult parseIntegerSet(IntegerSet &set) = 0;
1161 
1162  //===--------------------------------------------------------------------===//
1163  // Identifier Parsing
1164  //===--------------------------------------------------------------------===//
1165 
1166  /// Parse an @-identifier and store it (without the '@' symbol) in a string
1167  /// attribute.
1168  ParseResult parseSymbolName(StringAttr &result) {
1169  if (failed(parseOptionalSymbolName(result)))
1170  return emitError(getCurrentLocation())
1171  << "expected valid '@'-identifier for symbol name";
1172  return success();
1173  }
1174 
1175  /// Parse an @-identifier and store it (without the '@' symbol) in a string
1176  /// attribute named 'attrName'.
1177  ParseResult parseSymbolName(StringAttr &result, StringRef attrName,
1178  NamedAttrList &attrs) {
1179  if (parseSymbolName(result))
1180  return failure();
1181  attrs.append(attrName, result);
1182  return success();
1183  }
1184 
1185  /// Parse an optional @-identifier and store it (without the '@' symbol) in a
1186  /// string attribute.
1187  virtual ParseResult parseOptionalSymbolName(StringAttr &result) = 0;
1188 
1189  /// Parse an optional @-identifier and store it (without the '@' symbol) in a
1190  /// string attribute named 'attrName'.
1191  ParseResult parseOptionalSymbolName(StringAttr &result, StringRef attrName,
1192  NamedAttrList &attrs) {
1193  if (succeeded(parseOptionalSymbolName(result))) {
1194  attrs.append(attrName, result);
1195  return success();
1196  }
1197  return failure();
1198  }
1199 
1200  //===--------------------------------------------------------------------===//
1201  // Resource Parsing
1202  //===--------------------------------------------------------------------===//
1203 
1204  /// Parse a handle to a resource within the assembly format.
1205  template <typename ResourceT>
1206  FailureOr<ResourceT> parseResourceHandle() {
1207  SMLoc handleLoc = getCurrentLocation();
1208 
1209  // Try to load the dialect that owns the handle.
1210  auto *dialect =
1211  getContext()->getOrLoadDialect<typename ResourceT::Dialect>();
1212  if (!dialect) {
1213  return emitError(handleLoc)
1214  << "dialect '" << ResourceT::Dialect::getDialectNamespace()
1215  << "' is unknown";
1216  }
1217 
1218  FailureOr<AsmDialectResourceHandle> handle = parseResourceHandle(dialect);
1219  if (failed(handle))
1220  return failure();
1221  if (auto *result = dyn_cast<ResourceT>(&*handle))
1222  return std::move(*result);
1223  return emitError(handleLoc) << "provided resource handle differs from the "
1224  "expected resource type";
1225  }
1226 
1227  //===--------------------------------------------------------------------===//
1228  // Type Parsing
1229  //===--------------------------------------------------------------------===//
1230 
1231  /// Parse a type.
1232  virtual ParseResult parseType(Type &result) = 0;
1233 
1234  /// Parse a custom type with the provided callback, unless the next
1235  /// token is `#`, in which case the generic parser is invoked.
1236  virtual ParseResult parseCustomTypeWithFallback(
1237  Type &result, function_ref<ParseResult(Type &result)> parseType) = 0;
1238 
1239  /// Parse an optional type.
1241 
1242  /// Parse a type of a specific type.
1243  template <typename TypeT>
1244  ParseResult parseType(TypeT &result) {
1245  SMLoc loc = getCurrentLocation();
1246 
1247  // Parse any kind of type.
1248  Type type;
1249  if (parseType(type))
1250  return failure();
1251 
1252  // Check for the right kind of type.
1253  result = llvm::dyn_cast<TypeT>(type);
1254  if (!result) {
1256  emitError(loc, "invalid kind of type specified");
1257  if constexpr (HasStaticName<TypeT>::value)
1258  diag << ": expected " << TypeT::name << ", but found " << type;
1259  return diag;
1260  }
1261 
1262  return success();
1263  }
1264 
1265  /// Trait to check if `TypeT` provides a `parse` method.
1266  template <typename TypeT>
1268  decltype(TypeT::parse(std::declval<AsmParser &>()));
1269  template <typename TypeT>
1271  llvm::is_detected<type_has_parse_method, TypeT>;
1272 
1273  /// Parse a custom Type of a given type unless the next token is `#`, in
1274  /// which case the generic parser is invoked. The parsed Type is
1275  /// populated in `result`.
1276  template <typename TypeT>
1277  std::enable_if_t<detect_type_has_parse_method<TypeT>::value, ParseResult>
1279  SMLoc loc = getCurrentLocation();
1280 
1281  // Parse any kind of Type.
1282  Type type;
1283  if (parseCustomTypeWithFallback(type, [&](Type &result) -> ParseResult {
1284  result = TypeT::parse(*this);
1285  return success(!!result);
1286  }))
1287  return failure();
1288 
1289  // Check for the right kind of Type.
1290  result = llvm::dyn_cast<TypeT>(type);
1291  if (!result) {
1293  emitError(loc, "invalid kind of type specified");
1294  if constexpr (HasStaticName<TypeT>::value)
1295  diag << ": expected " << TypeT::name << ", but found " << type;
1296  return diag;
1297  }
1298  return success();
1299  }
1300 
1301  /// SFINAE parsing method for Type that don't implement a parse method.
1302  template <typename TypeT>
1303  std::enable_if_t<!detect_type_has_parse_method<TypeT>::value, ParseResult>
1305  return parseType(result);
1306  }
1307 
1308  /// Parse a type list.
1309  ParseResult parseTypeList(SmallVectorImpl<Type> &result);
1310 
1311  /// Parse an arrow followed by a type list.
1312  virtual ParseResult parseArrowTypeList(SmallVectorImpl<Type> &result) = 0;
1313 
1314  /// Parse an optional arrow followed by a type list.
1315  virtual ParseResult
1317 
1318  /// Parse a colon followed by a type.
1319  virtual ParseResult parseColonType(Type &result) = 0;
1320 
1321  /// Parse a colon followed by a type of a specific kind, e.g. a FunctionType.
1322  template <typename TypeType>
1323  ParseResult parseColonType(TypeType &result) {
1324  SMLoc loc = getCurrentLocation();
1325 
1326  // Parse any kind of type.
1327  Type type;
1328  if (parseColonType(type))
1329  return failure();
1330 
1331  // Check for the right kind of type.
1332  result = llvm::dyn_cast<TypeType>(type);
1333  if (!result) {
1335  emitError(loc, "invalid kind of type specified");
1336  if constexpr (HasStaticName<TypeType>::value)
1337  diag << ": expected " << TypeType::name << ", but found " << type;
1338  return diag;
1339  }
1340 
1341  return success();
1342  }
1343 
1344  /// Parse a colon followed by a type list, which must have at least one type.
1345  virtual ParseResult parseColonTypeList(SmallVectorImpl<Type> &result) = 0;
1346 
1347  /// Parse an optional colon followed by a type list, which if present must
1348  /// have at least one type.
1349  virtual ParseResult
1351 
1352  /// Parse a keyword followed by a type.
1353  ParseResult parseKeywordType(const char *keyword, Type &result) {
1354  return failure(parseKeyword(keyword) || parseType(result));
1355  }
1356 
1357  /// Add the specified type to the end of the specified type list and return
1358  /// success. This is a helper designed to allow parse methods to be simple
1359  /// and chain through || operators.
1360  ParseResult addTypeToList(Type type, SmallVectorImpl<Type> &result) {
1361  result.push_back(type);
1362  return success();
1363  }
1364 
1365  /// Add the specified types to the end of the specified type list and return
1366  /// success. This is a helper designed to allow parse methods to be simple
1367  /// and chain through || operators.
1368  ParseResult addTypesToList(ArrayRef<Type> types,
1369  SmallVectorImpl<Type> &result) {
1370  result.append(types.begin(), types.end());
1371  return success();
1372  }
1373 
1374  /// Parse a dimension list of a tensor or memref type. This populates the
1375  /// dimension list, using ShapedType::kDynamic for the `?` dimensions if
1376  /// `allowDynamic` is set and errors out on `?` otherwise. Parsing the
1377  /// trailing `x` is configurable.
1378  ///
1379  /// dimension-list ::= eps | dimension (`x` dimension)*
1380  /// dimension-list-with-trailing-x ::= (dimension `x`)*
1381  /// dimension ::= `?` | decimal-literal
1382  ///
1383  /// When `allowDynamic` is not set, this is used to parse:
1384  ///
1385  /// static-dimension-list ::= eps | decimal-literal (`x` decimal-literal)*
1386  /// static-dimension-list-with-trailing-x ::= (dimension `x`)*
1387  virtual ParseResult parseDimensionList(SmallVectorImpl<int64_t> &dimensions,
1388  bool allowDynamic = true,
1389  bool withTrailingX = true) = 0;
1390 
1391  /// Parse an 'x' token in a dimension list, handling the case where the x is
1392  /// juxtaposed with an element type, as in "xf32", leaving the "f32" as the
1393  /// next token.
1394  virtual ParseResult parseXInDimensionList() = 0;
1395 
1396  /// Class used to automatically end a cyclic region on destruction.
1398  public:
1399  explicit CyclicParseReset(AsmParser *parser) : parser(parser) {}
1400 
1402  if (parser)
1403  parser->popCyclicParsing();
1404  }
1405 
1409  : parser(std::exchange(rhs.parser, nullptr)) {}
1411  parser = std::exchange(rhs.parser, nullptr);
1412  return *this;
1413  }
1414 
1415  private:
1416  AsmParser *parser;
1417  };
1418 
1419  /// Attempts to start a cyclic parsing region for `attrOrType`.
1420  /// A cyclic parsing region starts with this call and ends with the
1421  /// destruction of the returned `CyclicParseReset`. During this time,
1422  /// calling `tryStartCyclicParse` with the same attribute in any parser
1423  /// will lead to returning failure.
1424  ///
1425  /// This makes it possible to parse cyclic attributes or types by parsing a
1426  /// short from if nested within itself.
1427  template <class AttrOrTypeT>
1428  FailureOr<CyclicParseReset> tryStartCyclicParse(AttrOrTypeT attrOrType) {
1429  static_assert(
1430  std::is_base_of_v<AttributeTrait::IsMutable<AttrOrTypeT>,
1431  AttrOrTypeT> ||
1432  std::is_base_of_v<TypeTrait::IsMutable<AttrOrTypeT>, AttrOrTypeT>,
1433  "Only mutable attributes or types can be cyclic");
1434  if (failed(pushCyclicParsing(attrOrType.getAsOpaquePointer())))
1435  return failure();
1436 
1437  return CyclicParseReset(this);
1438  }
1439 
1440 protected:
1441  /// Parse a handle to a resource within the assembly format for the given
1442  /// dialect.
1443  virtual FailureOr<AsmDialectResourceHandle>
1445 
1446  /// Pushes a new attribute or type in the form of a type erased pointer
1447  /// into an internal set.
1448  /// Returns success if the type or attribute was inserted in the set or
1449  /// failure if it was already contained.
1450  virtual LogicalResult pushCyclicParsing(const void *opaquePointer) = 0;
1451 
1452  /// Removes the element that was last inserted with a successful call to
1453  /// `pushCyclicParsing`. There must be exactly one `popCyclicParsing` call
1454  /// in reverse order of all successful `pushCyclicParsing`.
1455  virtual void popCyclicParsing() = 0;
1456 
1457  //===--------------------------------------------------------------------===//
1458  // Code Completion
1459  //===--------------------------------------------------------------------===//
1460 
1461  /// Parse a keyword, or an empty string if the current location signals a code
1462  /// completion.
1463  virtual ParseResult parseKeywordOrCompletion(StringRef *keyword) = 0;
1464 
1465  /// Signal the code completion of a set of expected tokens.
1467 
1468 private:
1469  AsmParser(const AsmParser &) = delete;
1470  void operator=(const AsmParser &) = delete;
1471 };
1472 
1473 //===----------------------------------------------------------------------===//
1474 // OpAsmParser
1475 //===----------------------------------------------------------------------===//
1476 
1477 /// The OpAsmParser has methods for interacting with the asm parser: parsing
1478 /// things from it, emitting errors etc. It has an intentionally high-level API
1479 /// that is designed to reduce/constrain syntax innovation in individual
1480 /// operations.
1481 ///
1482 /// For example, consider an op like this:
1483 ///
1484 /// %x = load %p[%1, %2] : memref<...>
1485 ///
1486 /// The "%x = load" tokens are already parsed and therefore invisible to the
1487 /// custom op parser. This can be supported by calling `parseOperandList` to
1488 /// parse the %p, then calling `parseOperandList` with a `SquareDelimiter` to
1489 /// parse the indices, then calling `parseColonTypeList` to parse the result
1490 /// type.
1491 ///
1492 class OpAsmParser : public AsmParser {
1493 public:
1494  using AsmParser::AsmParser;
1495  ~OpAsmParser() override;
1496 
1497  /// Parse a loc(...) specifier if present, filling in result if so.
1498  /// Location for BlockArgument and Operation may be deferred with an alias, in
1499  /// which case an OpaqueLoc is set and will be resolved when parsing
1500  /// completes.
1501  virtual ParseResult
1502  parseOptionalLocationSpecifier(std::optional<Location> &result) = 0;
1503 
1504  /// Return the name of the specified result in the specified syntax, as well
1505  /// as the sub-element in the name. It returns an empty string and ~0U for
1506  /// invalid result numbers. For example, in this operation:
1507  ///
1508  /// %x, %y:2, %z = foo.op
1509  ///
1510  /// getResultName(0) == {"x", 0 }
1511  /// getResultName(1) == {"y", 0 }
1512  /// getResultName(2) == {"y", 1 }
1513  /// getResultName(3) == {"z", 0 }
1514  /// getResultName(4) == {"", ~0U }
1515  virtual std::pair<StringRef, unsigned>
1516  getResultName(unsigned resultNo) const = 0;
1517 
1518  /// Return the number of declared SSA results. This returns 4 for the foo.op
1519  /// example in the comment for `getResultName`.
1520  virtual size_t getNumResults() const = 0;
1521 
1522  // These methods emit an error and return failure or success. This allows
1523  // these to be chained together into a linear sequence of || expressions in
1524  // many cases.
1525 
1526  /// Parse an operation in its generic form.
1527  /// The parsed operation is parsed in the current context and inserted in the
1528  /// provided block and insertion point. The results produced by this operation
1529  /// aren't mapped to any named value in the parser. Returns nullptr on
1530  /// failure.
1531  virtual Operation *parseGenericOperation(Block *insertBlock,
1532  Block::iterator insertPt) = 0;
1533 
1534  /// Parse the name of an operation, in the custom form. On success, return a
1535  /// an object of type 'OperationName'. Otherwise, failure is returned.
1536  virtual FailureOr<OperationName> parseCustomOperationName() = 0;
1537 
1538  //===--------------------------------------------------------------------===//
1539  // Operand Parsing
1540  //===--------------------------------------------------------------------===//
1541 
1542  /// This is the representation of an operand reference.
1544  SMLoc location; // Location of the token.
1545  StringRef name; // Value name, e.g. %42 or %abc
1546  unsigned number; // Number, e.g. 12 for an operand like %xyz#12
1547  };
1548 
1549  /// Parse different components, viz., use-info of operand(s), successor(s),
1550  /// region(s), attribute(s) and function-type, of the generic form of an
1551  /// operation instance and populate the input operation-state 'result' with
1552  /// those components. If any of the components is explicitly provided, then
1553  /// skip parsing that component.
1555  OperationState &result,
1556  std::optional<ArrayRef<UnresolvedOperand>> parsedOperandType =
1557  std::nullopt,
1558  std::optional<ArrayRef<Block *>> parsedSuccessors = std::nullopt,
1559  std::optional<MutableArrayRef<std::unique_ptr<Region>>> parsedRegions =
1560  std::nullopt,
1561  std::optional<ArrayRef<NamedAttribute>> parsedAttributes = std::nullopt,
1562  std::optional<Attribute> parsedPropertiesAttribute = std::nullopt,
1563  std::optional<FunctionType> parsedFnType = std::nullopt) = 0;
1564 
1565  /// Parse a single SSA value operand name along with a result number if
1566  /// `allowResultNumber` is true.
1567  virtual ParseResult parseOperand(UnresolvedOperand &result,
1568  bool allowResultNumber = true) = 0;
1569 
1570  /// Parse a single operand if present.
1571  virtual OptionalParseResult
1573  bool allowResultNumber = true) = 0;
1574 
1575  /// Parse zero or more SSA comma-separated operand references with a specified
1576  /// surrounding delimiter, and an optional required operand count.
1577  virtual ParseResult
1579  Delimiter delimiter = Delimiter::None,
1580  bool allowResultNumber = true,
1581  int requiredOperandCount = -1) = 0;
1582 
1583  /// Parse a specified number of comma separated operands.
1585  int requiredOperandCount,
1586  Delimiter delimiter = Delimiter::None) {
1587  return parseOperandList(result, delimiter,
1588  /*allowResultNumber=*/true, requiredOperandCount);
1589  }
1590 
1591  /// Parse zero or more trailing SSA comma-separated trailing operand
1592  /// references with a specified surrounding delimiter, and an optional
1593  /// required operand count. A leading comma is expected before the
1594  /// operands.
1595  ParseResult
1597  Delimiter delimiter = Delimiter::None) {
1598  if (failed(parseOptionalComma()))
1599  return success(); // The comma is optional.
1600  return parseOperandList(result, delimiter);
1601  }
1602 
1603  /// Resolve an operand to an SSA value, emitting an error on failure.
1604  virtual ParseResult resolveOperand(const UnresolvedOperand &operand,
1605  Type type,
1606  SmallVectorImpl<Value> &result) = 0;
1607 
1608  /// Resolve a list of operands to SSA values, emitting an error on failure, or
1609  /// appending the results to the list on success. This method should be used
1610  /// when all operands have the same type.
1611  template <typename Operands = ArrayRef<UnresolvedOperand>>
1612  ParseResult resolveOperands(Operands &&operands, Type type,
1613  SmallVectorImpl<Value> &result) {
1614  for (const UnresolvedOperand &operand : operands)
1615  if (resolveOperand(operand, type, result))
1616  return failure();
1617  return success();
1618  }
1619  template <typename Operands = ArrayRef<UnresolvedOperand>>
1620  ParseResult resolveOperands(Operands &&operands, Type type, SMLoc loc,
1621  SmallVectorImpl<Value> &result) {
1622  return resolveOperands(std::forward<Operands>(operands), type, result);
1623  }
1624 
1625  /// Resolve a list of operands and a list of operand types to SSA values,
1626  /// emitting an error and returning failure, or appending the results
1627  /// to the list on success.
1628  template <typename Operands = ArrayRef<UnresolvedOperand>,
1629  typename Types = ArrayRef<Type>>
1630  std::enable_if_t<!std::is_convertible<Types, Type>::value, ParseResult>
1631  resolveOperands(Operands &&operands, Types &&types, SMLoc loc,
1632  SmallVectorImpl<Value> &result) {
1633  size_t operandSize = llvm::range_size(operands);
1634  size_t typeSize = llvm::range_size(types);
1635  if (operandSize != typeSize) {
1636  // If no location was provided, report errors at the beginning of the op.
1637  return emitError(loc.isValid() ? loc : getNameLoc())
1638  << "number of operands and types do not match: got " << operandSize
1639  << " operands and " << typeSize << " types";
1640  }
1641 
1642  for (auto [operand, type] : llvm::zip_equal(operands, types))
1643  if (resolveOperand(operand, type, result))
1644  return failure();
1645  return success();
1646  }
1647 
1648  /// Parses an affine map attribute where dims and symbols are SSA operands.
1649  /// Operand values must come from single-result sources, and be valid
1650  /// dimensions/symbol identifiers according to mlir::isValidDim/Symbol.
1651  virtual ParseResult
1653  Attribute &map, StringRef attrName,
1654  NamedAttrList &attrs,
1655  Delimiter delimiter = Delimiter::Square) = 0;
1656 
1657  /// Parses an affine expression where dims and symbols are SSA operands.
1658  /// Operand values must come from single-result sources, and be valid
1659  /// dimensions/symbol identifiers according to mlir::isValidDim/Symbol.
1660  virtual ParseResult
1662  SmallVectorImpl<UnresolvedOperand> &symbOperands,
1663  AffineExpr &expr) = 0;
1664 
1665  //===--------------------------------------------------------------------===//
1666  // Argument Parsing
1667  //===--------------------------------------------------------------------===//
1668 
1669  struct Argument {
1670  UnresolvedOperand ssaName; // SourceLoc, SSA name, result #.
1671  Type type; // Type.
1672  DictionaryAttr attrs; // Attributes if present.
1673  std::optional<Location> sourceLoc; // Source location specifier if present.
1674  };
1675 
1676  /// Parse a single argument with the following syntax:
1677  ///
1678  /// `%ssaName : !type { optionalAttrDict} loc(optionalSourceLoc)`
1679  ///
1680  /// If `allowType` is false or `allowAttrs` are false then the respective
1681  /// parts of the grammar are not parsed.
1682  virtual ParseResult parseArgument(Argument &result, bool allowType = false,
1683  bool allowAttrs = false) = 0;
1684 
1685  /// Parse a single argument if present.
1686  virtual OptionalParseResult
1687  parseOptionalArgument(Argument &result, bool allowType = false,
1688  bool allowAttrs = false) = 0;
1689 
1690  /// Parse zero or more arguments with a specified surrounding delimiter.
1691  virtual ParseResult parseArgumentList(SmallVectorImpl<Argument> &result,
1692  Delimiter delimiter = Delimiter::None,
1693  bool allowType = false,
1694  bool allowAttrs = false) = 0;
1695 
1696  //===--------------------------------------------------------------------===//
1697  // Region Parsing
1698  //===--------------------------------------------------------------------===//
1699 
1700  /// Parses a region. Any parsed blocks are appended to 'region' and must be
1701  /// moved to the op regions after the op is created. The first block of the
1702  /// region takes 'arguments'.
1703  ///
1704  /// If 'enableNameShadowing' is set to true, the argument names are allowed to
1705  /// shadow the names of other existing SSA values defined above the region
1706  /// scope. 'enableNameShadowing' can only be set to true for regions attached
1707  /// to operations that are 'IsolatedFromAbove'.
1708  virtual ParseResult parseRegion(Region &region,
1709  ArrayRef<Argument> arguments = {},
1710  bool enableNameShadowing = false) = 0;
1711 
1712  /// Parses a region if present.
1713  virtual OptionalParseResult
1715  bool enableNameShadowing = false) = 0;
1716 
1717  /// Parses a region if present. If the region is present, a new region is
1718  /// allocated and placed in `region`. If no region is present or on failure,
1719  /// `region` remains untouched.
1720  virtual OptionalParseResult
1721  parseOptionalRegion(std::unique_ptr<Region> &region,
1722  ArrayRef<Argument> arguments = {},
1723  bool enableNameShadowing = false) = 0;
1724 
1725  //===--------------------------------------------------------------------===//
1726  // Successor Parsing
1727  //===--------------------------------------------------------------------===//
1728 
1729  /// Parse a single operation successor.
1730  virtual ParseResult parseSuccessor(Block *&dest) = 0;
1731 
1732  /// Parse an optional operation successor.
1734 
1735  /// Parse a single operation successor and its operand list.
1736  virtual ParseResult
1738 
1739  //===--------------------------------------------------------------------===//
1740  // Type Parsing
1741  //===--------------------------------------------------------------------===//
1742 
1743  /// Parse a list of assignments of the form
1744  /// (%x1 = %y1, %x2 = %y2, ...)
1748  if (!result.has_value())
1749  return emitError(getCurrentLocation(), "expected '('");
1750  return result.value();
1751  }
1752 
1753  virtual OptionalParseResult
1756 };
1757 
1758 //===--------------------------------------------------------------------===//
1759 // Dialect OpAsm interface.
1760 //===--------------------------------------------------------------------===//
1761 
1763  : public DialectInterface::Base<OpAsmDialectInterface> {
1764 public:
1765  OpAsmDialectInterface(Dialect *dialect) : Base(dialect) {}
1766 
1768 
1769  /// Hooks for getting an alias identifier alias for a given symbol, that is
1770  /// not necessarily a part of this dialect. The identifier is used in place of
1771  /// the symbol when printing textual IR. These aliases must not contain `.` or
1772  /// end with a numeric digit([0-9]+).
1773  virtual AliasResult getAlias(Attribute attr, raw_ostream &os) const {
1774  return AliasResult::NoAlias;
1775  }
1776  virtual AliasResult getAlias(Type type, raw_ostream &os) const {
1777  return AliasResult::NoAlias;
1778  }
1779 
1780  //===--------------------------------------------------------------------===//
1781  // Resources
1782  //===--------------------------------------------------------------------===//
1783 
1784  /// Declare a resource with the given key, returning a handle to use for any
1785  /// references of this resource key within the IR during parsing. The result
1786  /// of `getResourceKey` on the returned handle is permitted to be different
1787  /// than `key`.
1788  virtual FailureOr<AsmDialectResourceHandle>
1789  declareResource(StringRef key) const {
1790  return failure();
1791  }
1792 
1793  /// Return a key to use for the given resource. This key should uniquely
1794  /// identify this resource within the dialect.
1795  virtual std::string
1797  llvm_unreachable(
1798  "Dialect must implement `getResourceKey` when defining resources");
1799  }
1800 
1801  /// Hook for parsing resource entries. Returns failure if the entry was not
1802  /// valid, or could otherwise not be processed correctly. Any necessary errors
1803  /// can be emitted via the provided entry.
1804  virtual LogicalResult parseResource(AsmParsedResourceEntry &entry) const;
1805 
1806  /// Hook for building resources to use during printing. The given `op` may be
1807  /// inspected to help determine what information to include.
1808  /// `referencedResources` contains all of the resources detected when printing
1809  /// 'op'.
1810  virtual void
1812  const SetVector<AsmDialectResourceHandle> &referencedResources,
1813  AsmResourceBuilder &builder) const {}
1814 };
1815 
1816 //===--------------------------------------------------------------------===//
1817 // Custom printers and parsers.
1818 //===--------------------------------------------------------------------===//
1819 
1820 // Handles custom<DimensionList>(...) in TableGen.
1821 void printDimensionList(OpAsmPrinter &printer, Operation *op,
1822  ArrayRef<int64_t> dimensions);
1823 ParseResult parseDimensionList(OpAsmParser &parser,
1824  DenseI64ArrayAttr &dimensions);
1825 
1826 } // namespace mlir
1827 
1828 //===--------------------------------------------------------------------===//
1829 // Operation OpAsm interface.
1830 //===--------------------------------------------------------------------===//
1831 
1832 /// The OpAsmOpInterface, see OpAsmInterface.td for more details.
1833 #include "mlir/IR/OpAsmOpInterface.h.inc"
1834 
1835 namespace llvm {
1836 template <>
1837 struct DenseMapInfo<mlir::AsmDialectResourceHandle> {
1841  }
1845  }
1846  static unsigned getHashValue(const mlir::AsmDialectResourceHandle &handle) {
1848  }
1849  static bool isEqual(const mlir::AsmDialectResourceHandle &lhs,
1850  const mlir::AsmDialectResourceHandle &rhs) {
1851  return lhs.getResource() == rhs.getResource();
1852  }
1853 };
1854 } // namespace llvm
1855 
1856 #endif
static std::string diag(const llvm::Value &value)
static void print(spirv::VerCapExtAttr triple, DialectAsmPrinter &printer)
Base type for affine expression.
Definition: AffineExpr.h:68
A multi-dimensional affine map Affine map's are immutable like Type's, and they are uniqued.
Definition: AffineMap.h:46
This class represents a CRTP base class for dialect resource handles.
const ResourceT * getResource() const
AsmDialectResourceHandleBase(AsmDialectResourceHandle handle)
ResourceT * getResource()
Return the resource referenced by this handle.
static bool classof(const AsmDialectResourceHandle *handle)
Support llvm style casting.
AsmDialectResourceHandleBase(ResourceT *resource, DialectT *dialect)
Construct a handle from a pointer to the resource.
DialectT * getDialect() const
Return the dialect that owns the resource.
This class represents an opaque handle to a dialect resource entry.
Dialect * getDialect() const
Return the dialect that owns the resource.
TypeID getTypeID() const
Return the type ID of the resource.
bool operator==(const AsmDialectResourceHandle &other) const
AsmDialectResourceHandle(void *resource, TypeID resourceID, Dialect *dialect)
void * getResource() const
Return an opaque pointer to the referenced resource.
This class represents a single parsed resource entry.
Definition: AsmState.h:291
Class used to automatically end a cyclic region on destruction.
CyclicParseReset & operator=(CyclicParseReset &&rhs)
CyclicParseReset & operator=(const CyclicParseReset &)=delete
CyclicParseReset(const CyclicParseReset &)=delete
CyclicParseReset(CyclicParseReset &&rhs)
This class represents a StringSwitch like class that is useful for parsing expected keywords.
std::enable_if_t<!std::is_convertible< FnT, ResultT >::value, KeywordSwitch & > Default(FnT &&fn)
KeywordSwitch & Case(StringLiteral str, ResultT value)
Case that uses the provided value when true.
bool hasValue() const
Returns true if this switch has a value yet.
std::enable_if_t<!std::is_convertible< FnT, ResultT >::value, KeywordSwitch & > Case(StringLiteral str, FnT &&fn)
Case that invokes the provided functor when true.
KeywordSwitch & Default(ResultT value)
KeywordSwitch(AsmParser &parser, StringRef *keyword=nullptr)
This base class exposes generic asm parser hooks, usable across the various derived parsers.
virtual ParseResult parseMinus()=0
Parse a '-' token.
llvm::is_detected< has_parse_method, AttrType > detect_has_parse_method
ParseResult parseSymbolName(StringAttr &result)
Parse an -identifier and store it (without the '@' symbol) in a string attribute.
virtual ParseResult parseLBrace()=0
Parse a { token.
Delimiter
These are the supported delimiters around operand lists and region argument lists,...
@ Paren
Parens surrounding zero or more operands.
@ None
Zero or more operands with no delimiters.
@ OptionalLessGreater
<> brackets supporting zero or more ops, or nothing.
@ Braces
{} brackets surrounding zero or more operands.
@ OptionalBraces
{} brackets surrounding zero or more operands, or nothing.
@ OptionalParen
Parens supporting zero or more operands, or nothing.
@ Square
Square brackets surrounding zero or more operands.
@ LessGreater
<> brackets surrounding zero or more operands.
@ OptionalSquare
Square brackets supporting zero or more ops, or nothing.
virtual OptionalParseResult parseOptionalInteger(APInt &result)=0
Parse an optional integer value from the stream.
AsmParser()=default
virtual ParseResult parseColonTypeList(SmallVectorImpl< Type > &result)=0
Parse a colon followed by a type list, which must have at least one type.
virtual ParseResult parseIntegerSet(IntegerSet &set)=0
Parse an integer set instance into 'set'.
virtual ParseResult parseOptionalKeywordOrString(std::string *result)=0
Parse an optional keyword or string.
virtual ParseResult parseOptionalSymbolName(StringAttr &result)=0
Parse an optional -identifier and store it (without the '@' symbol) in a string attribute.
FailureOr< CyclicParseReset > tryStartCyclicParse(AttrOrTypeT attrOrType)
Attempts to start a cyclic parsing region for attrOrType.
virtual ParseResult parseOptionalRBrace()=0
Parse a } token if present.
ParseResult parseDecimalInteger(IntT &result)
Parse a decimal integer value from the stream.
virtual ParseResult parseOptionalMinus()=0
Parse a '-' token if present.
virtual ParseResult parsePlus()=0
Parse a '+' token.
ParseResult parseKeyword(StringRef *keyword)
Parse a keyword into 'keyword'.
virtual ParseResult parseCommaSeparatedList(Delimiter delimiter, function_ref< ParseResult()> parseElementFn, StringRef contextMessage=StringRef())=0
Parse a list of comma-separated items with an optional delimiter.
decltype(AttrType::parse(std::declval< AsmParser & >(), std::declval< Type >())) has_parse_method
Trait to check if AttrType provides a parse method.
virtual void popCyclicParsing()=0
Removes the element that was last inserted with a successful call to pushCyclicParsing.
virtual Builder & getBuilder() const =0
Return a builder which provides useful access to MLIRContext, global objects like types and attribute...
virtual ParseResult parseOptionalAttrDict(NamedAttrList &result)=0
Parse a named dictionary into 'result' if it is present.
virtual ParseResult parseOptionalEqual()=0
Parse a = token if present.
virtual ParseResult parseOptionalKeyword(StringRef keyword)=0
Parse the given keyword if present.
virtual OptionalParseResult parseOptionalType(Type &result)=0
Parse an optional type.
MLIRContext * getContext() const
Definition: AsmPrinter.cpp:73
virtual Location getEncodedSourceLoc(SMLoc loc)=0
Re-encode the given source location as an MLIR location and return it.
std::enable_if_t<!detect_type_has_parse_method< TypeT >::value, ParseResult > parseCustomTypeWithFallback(TypeT &result)
SFINAE parsing method for Type that don't implement a parse method.
virtual ParseResult parseRParen()=0
Parse a ) token.
virtual InFlightDiagnostic emitError(SMLoc loc, const Twine &message={})=0
Emit a diagnostic at the specified location and return failure.
virtual ParseResult parseOptionalColon()=0
Parse a : token if present.
virtual ParseResult parseLSquare()=0
Parse a [ token.
virtual ParseResult parseRSquare()=0
Parse a ] token.
virtual ParseResult parseOptionalColonTypeList(SmallVectorImpl< Type > &result)=0
Parse an optional colon followed by a type list, which if present must have at least one type.
ParseResult parseInteger(IntT &result)
Parse an integer value from the stream.
virtual ParseResult parseOptionalArrow()=0
Parse a '->' token if present.
ParseResult parseOptionalSymbolName(StringAttr &result, StringRef attrName, NamedAttrList &attrs)
Parse an optional -identifier and store it (without the '@' symbol) in a string attribute named 'attr...
virtual OptionalParseResult parseOptionalDecimalInteger(APInt &result)=0
ParseResult parseAttribute(AttrType &result, Type type, StringRef attrName, NamedAttrList &attrs)
Parse an arbitrary attribute of a given type and populate it in result.
ParseResult parseAttribute(AttrType &result, Type type={})
Parse an attribute of a specific kind and type.
ParseResult parseKeywordOrString(std::string *result)
Parse a keyword or a quoted string.
virtual void codeCompleteExpectedTokens(ArrayRef< StringRef > tokens)=0
Signal the code completion of a set of expected tokens.
virtual ParseResult parseRBrace()=0
Parse a } token.
virtual ParseResult parseAffineMap(AffineMap &map)=0
Parse an affine map instance into 'map'.
ParseResult addTypeToList(Type type, SmallVectorImpl< Type > &result)
Add the specified type to the end of the specified type list and return success.
virtual ParseResult parseOptionalRParen()=0
Parse a ) token if present.
virtual ParseResult parseCustomAttributeWithFallback(Attribute &result, Type type, function_ref< ParseResult(Attribute &result, Type type)> parseAttribute)=0
Parse a custom attribute with the provided callback, unless the next token is #, in which case the ge...
virtual ParseResult parseLess()=0
Parse a '<' token.
virtual ParseResult parseDimensionList(SmallVectorImpl< int64_t > &dimensions, bool allowDynamic=true, bool withTrailingX=true)=0
Parse a dimension list of a tensor or memref type.
ParseResult parseString(std::string *string)
Parse a quoted string token.
virtual ParseResult parseOptionalPlus()=0
Parse a '+' token if present.
virtual ParseResult parseOptionalKeyword(StringRef *keyword, ArrayRef< StringRef > allowedValues)=0
Parse a keyword, if present, and if one of the 'allowedValues', into 'keyword'.
virtual ParseResult parseOptionalGreater()=0
Parse a '>' token if present.
virtual ParseResult parseEqual()=0
Parse a = token.
std::enable_if_t<!detect_has_parse_method< AttrType >::value, ParseResult > parseCustomAttributeWithFallback(AttrType &result, Type type, StringRef attrName, NamedAttrList &attrs)
SFINAE parsing method for Attribute that don't implement a parse method.
virtual ParseResult parseCustomTypeWithFallback(Type &result, function_ref< ParseResult(Type &result)> parseType)=0
Parse a custom type with the provided callback, unless the next token is #, in which case the generic...
virtual ParseResult parseFloat(const llvm::fltSemantics &semantics, APFloat &result)=0
Parse a floating point value into APFloat from the stream.
virtual OptionalParseResult parseOptionalAttribute(ArrayAttr &result, Type type={})=0
Parse an optional array attribute and return it in result.
virtual ParseResult parseStar()=0
Parse a '*' token.
virtual ParseResult parseOptionalAttrDictWithKeyword(NamedAttrList &result)=0
Parse a named dictionary into 'result' if the attributes keyword is present.
virtual ParseResult parseColonType(Type &result)=0
Parse a colon followed by a type.
virtual OptionalParseResult parseOptionalAttribute(Attribute &result, Type type={})=0
Parse an arbitrary optional attribute of a given type and return it in result.
std::enable_if_t< detect_has_parse_method< AttrType >::value, ParseResult > parseCustomAttributeWithFallback(AttrType &result, Type type={})
Parse a custom attribute of a given type unless the next token is #, in which case the generic parser...
ParseResult parseCommaSeparatedList(function_ref< ParseResult()> parseElementFn)
Parse a comma separated list of elements that must have at least one entry in it.
virtual ParseResult parseVerticalBar()=0
Parse a '|' token.
virtual SMLoc getCurrentLocation()=0
Get the location of the next token and store it into the argument.
virtual ParseResult parseOptionalComma()=0
Parse a , token if present.
OptionalParseResult parseOptionalAttribute(AttrType &result, StringRef attrName, NamedAttrList &attrs)
Parse an optional attribute of a specific type and add it to the list with the specified name.
auto getChecked(SMLoc loc, ParamsT &&...params)
Invoke the getChecked method of the given Attribute or Type class, using the provided location to emi...
virtual ParseResult parseColon()=0
Parse a : token.
ParseResult addTypesToList(ArrayRef< Type > types, SmallVectorImpl< Type > &result)
Add the specified types to the end of the specified type list and return success.
std::enable_if_t< detect_type_has_parse_method< TypeT >::value, ParseResult > parseCustomTypeWithFallback(TypeT &result)
Parse a custom Type of a given type unless the next token is #, in which case the generic parser is i...
ParseResult parseAttribute(Attribute &result, StringRef attrName, NamedAttrList &attrs)
Parse an arbitrary attribute and return it in result.
virtual OptionalParseResult parseOptionalAttribute(StringAttr &result, Type type={})=0
Parse an optional string attribute and return it in result.
virtual SMLoc getNameLoc() const =0
Return the location of the original name token.
virtual ParseResult parseOptionalString(std::string *string)=0
Parse a quoted string token if present.
OptionalParseResult parseOptionalInteger(IntT &result)
ParseResult getCurrentLocation(SMLoc *loc)
virtual ParseResult parseOptionalLess()=0
Parse a '<' token if present.
virtual ParseResult parseOptionalStar()=0
Parse a '*' token if present.
OptionalParseResult parseOptionalAttribute(AttrType &result, Type type, StringRef attrName, NamedAttrList &attrs)
Parse an optional attribute of a specific type and add it to the list with the specified name.
virtual OptionalParseResult parseOptionalAttribute(SymbolRefAttr &result, Type type={})=0
Parse an optional symbol ref attribute and return it in result.
virtual ParseResult parseQuestion()=0
Parse a '?' token.
ParseResult parseType(TypeT &result)
Parse a type of a specific type.
virtual ParseResult parseOptionalRSquare()=0
Parse a ] token if present.
virtual ParseResult parseArrow()=0
Parse a '->' token.
ParseResult parseColonType(TypeType &result)
Parse a colon followed by a type of a specific kind, e.g. a FunctionType.
virtual ParseResult parseGreater()=0
Parse a '>' token.
OptionalParseResult parseOptionalDecimalInteger(IntT &result)
virtual ParseResult parseLParen()=0
Parse a ( token.
virtual ParseResult parseOptionalEllipsis()=0
Parse a ... token if present;.
std::enable_if_t<!detect_has_parse_method< AttrType >::value, ParseResult > parseCustomAttributeWithFallback(AttrType &result, Type type={})
SFINAE parsing method for Attribute that don't implement a parse method.
virtual ParseResult parseType(Type &result)=0
Parse a type.
ParseResult parseAttribute(AttrType &result, StringRef attrName, NamedAttrList &attrs)
Parse an attribute of a specific kind and type.
virtual ParseResult parseEllipsis()=0
Parse a ... token.
auto getChecked(ParamsT &&...params)
A variant of getChecked that uses the result of getNameLoc to emit errors.
virtual ParseResult parseAffineExpr(ArrayRef< std::pair< StringRef, AffineExpr >> symbolSet, AffineExpr &expr)=0
Parse an affine expr instance into 'expr' using the already computed mapping from symbols to affine e...
virtual ParseResult parseComma()=0
Parse a , token.
virtual ParseResult parseOptionalArrowTypeList(SmallVectorImpl< Type > &result)=0
Parse an optional arrow followed by a type list.
virtual ParseResult parseOptionalLParen()=0
Parse a ( token if present.
ParseResult parseKeywordType(const char *keyword, Type &result)
Parse a keyword followed by a type.
virtual ParseResult parseArrowTypeList(SmallVectorImpl< Type > &result)=0
Parse an arrow followed by a type list.
virtual ~AsmParser()
virtual ParseResult parseOptionalVerticalBar()=0
Parse a '|' token if present.
ParseResult parseTypeList(SmallVectorImpl< Type > &result)
Parse a type list.
Definition: AsmPrinter.cpp:78
virtual ParseResult parseBase64Bytes(std::vector< char > *bytes)=0
Parses a Base64 encoded string of bytes.
llvm::is_detected< type_has_parse_method, TypeT > detect_type_has_parse_method
virtual ParseResult parseKeywordOrCompletion(StringRef *keyword)=0
Parse a keyword, or an empty string if the current location signals a code completion.
virtual ParseResult parseFloat(double &result)=0
Parse a floating point value from the stream.
ParseResult parseSymbolName(StringAttr &result, StringRef attrName, NamedAttrList &attrs)
Parse an -identifier and store it (without the '@' symbol) in a string attribute named 'attrName'.
virtual ParseResult parseOptionalKeyword(StringRef *keyword)=0
Parse a keyword, if present, into 'keyword'.
decltype(TypeT::parse(std::declval< AsmParser & >())) type_has_parse_method
Trait to check if TypeT provides a parse method.
ParseResult parseKeyword(StringRef keyword)
Parse a given keyword.
virtual ParseResult parseOptionalLSquare()=0
Parse a [ token if present.
virtual LogicalResult pushCyclicParsing(const void *opaquePointer)=0
Pushes a new attribute or type in the form of a type erased pointer into an internal set.
virtual FailureOr< AsmDialectResourceHandle > parseResourceHandle(Dialect *dialect)=0
Parse a handle to a resource within the assembly format for the given dialect.
virtual ParseResult parseOptionalQuestion()=0
Parse a '?' token if present.
std::enable_if_t< detect_has_parse_method< AttrType >::value, ParseResult > parseCustomAttributeWithFallback(AttrType &result, Type type, StringRef attrName, NamedAttrList &attrs)
Parse a custom attribute of a given type unless the next token is #, in which case the generic parser...
FailureOr< ResourceT > parseResourceHandle()
Parse a handle to a resource within the assembly format.
virtual ParseResult parseAttribute(Attribute &result, Type type={})=0
Parse an arbitrary attribute of a given type and return it in result.
virtual ParseResult parseXInDimensionList()=0
Parse an 'x' token in a dimension list, handling the case where the x is juxtaposed with an element t...
virtual ParseResult parseOptionalLBrace()=0
Parse a { token if present.
virtual ParseResult parseKeyword(StringRef keyword, const Twine &msg)=0
Class used to automatically end a cyclic region on destruction.
CyclicPrintReset & operator=(const CyclicPrintReset &)=delete
CyclicPrintReset(const CyclicPrintReset &)=delete
CyclicPrintReset & operator=(CyclicPrintReset &&rhs)
CyclicPrintReset(CyclicPrintReset &&rhs)
This base class exposes generic asm printer hooks, usable across the various derived printers.
void printStrippedAttrOrType(ArrayRef< AttrOrType > attrOrTypes)
Print the provided array of attributes or types in the context of an operation custom printer/parser:...
FailureOr< CyclicPrintReset > tryStartCyclicPrint(AttrOrTypeT attrOrType)
Attempts to start a cyclic printing region for attrOrType.
virtual void printAttributeWithoutType(Attribute attr)
Print the given attribute without its type.
virtual LogicalResult printAlias(Attribute attr)
Print the alias for the given attribute, return failure if no alias could be printed.
virtual void popCyclicPrinting()
Removes the element that was last inserted with a successful call to pushCyclicPrinting.
AsmPrinter()=default
Initialize the printer with no internal implementation.
void printFunctionalType(InputRangeT &&inputs, ResultRangeT &&results)
Print the two given type ranges in a functional form.
virtual LogicalResult pushCyclicPrinting(const void *opaquePointer)
Pushes a new attribute or type in the form of a type erased pointer into an internal set.
virtual void printType(Type type)
virtual void printKeywordOrString(StringRef keyword)
Print the given string as a keyword, or a quoted and escaped string if it has any special or non-prin...
llvm::is_detected< has_print_method, AttrOrType > detect_has_print_method
virtual void printSymbolName(StringRef symbolRef)
Print the given string as a symbol reference, i.e.
virtual void printString(StringRef string)
Print the given string as a quoted string, escaping any special or non-printable characters in it.
void printOptionalArrowTypeList(TypeRange &&types)
Print an optional arrow followed by a type list.
virtual void printAttribute(Attribute attr)
void printDimensionList(ArrayRef< int64_t > shape)
void printArrowTypeList(TypeRange &&types)
virtual ~AsmPrinter()
virtual raw_ostream & getStream() const
Return the raw output stream used by this printer.
virtual void printResourceHandle(const AsmDialectResourceHandle &resource)
Print a handle to the given dialect resource.
decltype(std::declval< AttrOrType >().print(std::declval< AsmPrinter & >())) has_print_method
Trait to check if AttrType provides a print method.
virtual void printFloat(const APFloat &value)
Print the given floating point value in a stabilized form that can be roundtripped through the IR.
void printStrippedAttrOrType(AttrOrType attrOrType)
Print the provided attribute in the context of an operation custom printer/parser: this will invoke d...
AsmPrinter(Impl &impl)
Initialize the printer with the given internal implementation.
This class is used to build resource entries for use by the printer.
Definition: AsmState.h:247
Attributes are known-constant values of operations.
Definition: Attributes.h:25
This class represents an argument of a Block.
Definition: Value.h:295
Block represents an ordered list of Operations.
Definition: Block.h:33
OpListType::iterator iterator
Definition: Block.h:140
This class is a general helper class for creating context-global objects like types,...
Definition: Builders.h:51
Dialects are groups of MLIR operations, types and attributes, as well as behavior associated with the...
Definition: Dialect.h:38
This class represents a diagnostic that is inflight and set to be reported.
Definition: Diagnostics.h:314
An integer set representing a conjunction of one or more affine equalities and inequalities.
Definition: IntegerSet.h:44
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition: Location.h:66
MLIRContext is the top-level object for a collection of MLIR operations.
Definition: MLIRContext.h:60
T * getOrLoadDialect()
Get (or create) a dialect for the given derived dialect type.
Definition: MLIRContext.h:97
NamedAttrList is array of NamedAttributes that tracks whether it is sorted and does some basic work t...
void append(StringRef name, Attribute attr)
Add an attribute with the specified name.
virtual void buildResources(Operation *op, const SetVector< AsmDialectResourceHandle > &referencedResources, AsmResourceBuilder &builder) const
Hook for building resources to use during printing.
virtual AliasResult getAlias(Attribute attr, raw_ostream &os) const
Hooks for getting an alias identifier alias for a given symbol, that is not necessarily a part of thi...
OpAsmDialectInterface(Dialect *dialect)
virtual AliasResult getAlias(Type type, raw_ostream &os) const
virtual std::string getResourceKey(const AsmDialectResourceHandle &handle) const
Return a key to use for the given resource.
virtual FailureOr< AsmDialectResourceHandle > declareResource(StringRef key) const
Declare a resource with the given key, returning a handle to use for any references of this resource ...
virtual LogicalResult parseResource(AsmParsedResourceEntry &entry) const
Hook for parsing resource entries.
Definition: AsmPrinter.cpp:133
The OpAsmParser has methods for interacting with the asm parser: parsing things from it,...
virtual std::pair< StringRef, unsigned > getResultName(unsigned resultNo) const =0
Return the name of the specified result in the specified syntax, as well as the sub-element in the na...
virtual size_t getNumResults() const =0
Return the number of declared SSA results.
virtual OptionalParseResult parseOptionalAssignmentList(SmallVectorImpl< Argument > &lhs, SmallVectorImpl< UnresolvedOperand > &rhs)=0
virtual ParseResult parseRegion(Region &region, ArrayRef< Argument > arguments={}, bool enableNameShadowing=false)=0
Parses a region.
~OpAsmParser() override
virtual ParseResult parseSuccessor(Block *&dest)=0
Parse a single operation successor.
virtual ParseResult parseArgument(Argument &result, bool allowType=false, bool allowAttrs=false)=0
Parse a single argument with the following syntax:
virtual ParseResult parseGenericOperationAfterOpName(OperationState &result, std::optional< ArrayRef< UnresolvedOperand >> parsedOperandType=std::nullopt, std::optional< ArrayRef< Block * >> parsedSuccessors=std::nullopt, std::optional< MutableArrayRef< std::unique_ptr< Region >>> parsedRegions=std::nullopt, std::optional< ArrayRef< NamedAttribute >> parsedAttributes=std::nullopt, std::optional< Attribute > parsedPropertiesAttribute=std::nullopt, std::optional< FunctionType > parsedFnType=std::nullopt)=0
Parse different components, viz., use-info of operand(s), successor(s), region(s),...
ParseResult parseTrailingOperandList(SmallVectorImpl< UnresolvedOperand > &result, Delimiter delimiter=Delimiter::None)
Parse zero or more trailing SSA comma-separated trailing operand references with a specified surround...
ParseResult resolveOperands(Operands &&operands, Type type, SMLoc loc, SmallVectorImpl< Value > &result)
virtual ParseResult parseArgumentList(SmallVectorImpl< Argument > &result, Delimiter delimiter=Delimiter::None, bool allowType=false, bool allowAttrs=false)=0
Parse zero or more arguments with a specified surrounding delimiter.
virtual ParseResult parseAffineMapOfSSAIds(SmallVectorImpl< UnresolvedOperand > &operands, Attribute &map, StringRef attrName, NamedAttrList &attrs, Delimiter delimiter=Delimiter::Square)=0
Parses an affine map attribute where dims and symbols are SSA operands.
virtual OptionalParseResult parseOptionalArgument(Argument &result, bool allowType=false, bool allowAttrs=false)=0
Parse a single argument if present.
virtual ParseResult parseOptionalLocationSpecifier(std::optional< Location > &result)=0
Parse a loc(...) specifier if present, filling in result if so.
ParseResult parseAssignmentList(SmallVectorImpl< Argument > &lhs, SmallVectorImpl< UnresolvedOperand > &rhs)
Parse a list of assignments of the form (x1 = y1, x2 = y2, ...)
virtual ParseResult resolveOperand(const UnresolvedOperand &operand, Type type, SmallVectorImpl< Value > &result)=0
Resolve an operand to an SSA value, emitting an error on failure.
virtual OptionalParseResult parseOptionalOperand(UnresolvedOperand &result, bool allowResultNumber=true)=0
Parse a single operand if present.
virtual ParseResult parseSuccessorAndUseList(Block *&dest, SmallVectorImpl< Value > &operands)=0
Parse a single operation successor and its operand list.
virtual OptionalParseResult parseOptionalRegion(Region &region, ArrayRef< Argument > arguments={}, bool enableNameShadowing=false)=0
Parses a region if present.
virtual FailureOr< OperationName > parseCustomOperationName()=0
Parse the name of an operation, in the custom form.
ParseResult parseOperandList(SmallVectorImpl< UnresolvedOperand > &result, int requiredOperandCount, Delimiter delimiter=Delimiter::None)
Parse a specified number of comma separated operands.
ParseResult resolveOperands(Operands &&operands, Type type, SmallVectorImpl< Value > &result)
Resolve a list of operands to SSA values, emitting an error on failure, or appending the results to t...
virtual Operation * parseGenericOperation(Block *insertBlock, Block::iterator insertPt)=0
Parse an operation in its generic form.
virtual ParseResult parseOperand(UnresolvedOperand &result, bool allowResultNumber=true)=0
Parse a single SSA value operand name along with a result number if allowResultNumber is true.
virtual ParseResult parseAffineExprOfSSAIds(SmallVectorImpl< UnresolvedOperand > &dimOperands, SmallVectorImpl< UnresolvedOperand > &symbOperands, AffineExpr &expr)=0
Parses an affine expression where dims and symbols are SSA operands.
virtual OptionalParseResult parseOptionalSuccessor(Block *&dest)=0
Parse an optional operation successor.
std::enable_if_t<!std::is_convertible< Types, Type >::value, ParseResult > resolveOperands(Operands &&operands, Types &&types, SMLoc loc, SmallVectorImpl< Value > &result)
Resolve a list of operands and a list of operand types to SSA values, emitting an error and returning...
virtual OptionalParseResult parseOptionalRegion(std::unique_ptr< Region > &region, ArrayRef< Argument > arguments={}, bool enableNameShadowing=false)=0
Parses a region if present.
virtual ParseResult parseOperandList(SmallVectorImpl< UnresolvedOperand > &result, Delimiter delimiter=Delimiter::None, bool allowResultNumber=true, int requiredOperandCount=-1)=0
Parse zero or more SSA comma-separated operand references with a specified surrounding delimiter,...
This is a pure-virtual base class that exposes the asmprinter hooks necessary to implement a custom p...
void printOperands(IteratorType it, IteratorType end)
Print a comma separated list of operands.
virtual void shadowRegionArgs(Region &region, ValueRange namesToUse)=0
Renumber the arguments for the specified region to the same names as the SSA values in namesToUse.
virtual void printNewline()=0
Print a newline and indent the printer to the start of the current operation.
virtual void increaseIndent()=0
Increase indentation.
virtual void printSuccessorAndUseList(Block *successor, ValueRange succOperands)=0
Print the successor and its operands.
void printOperands(const ContainerType &container)
Print a comma separated list of operands.
virtual void printOptionalAttrDictWithKeyword(ArrayRef< NamedAttribute > attrs, ArrayRef< StringRef > elidedAttrs={})=0
If the specified operation has attributes, print out an attribute dictionary prefixed with 'attribute...
virtual void printOptionalAttrDict(ArrayRef< NamedAttribute > attrs, ArrayRef< StringRef > elidedAttrs={})=0
If the specified operation has attributes, print out an attribute dictionary with their values.
virtual void printOptionalLocationSpecifier(Location loc)=0
Print a loc(...) specifier if printing debug info is enabled.
virtual void printCustomOrGenericOp(Operation *op)=0
Prints the entire operation with the custom assembly form, if available, or the generic assembly form...
virtual void decreaseIndent()=0
Decrease indentation.
virtual void printOperand(Value value, raw_ostream &os)=0
virtual void printSuccessor(Block *successor)=0
Print the given successor.
virtual void printAffineExprOfSSAIds(AffineExpr expr, ValueRange dimOperands, ValueRange symOperands)=0
Prints an affine expression of SSA ids with SSA id names used instead of dims and symbols.
void printFunctionalType(Operation *op)
Print the complete type of an operation in functional form.
Definition: AsmPrinter.cpp:95
virtual void printAffineMapOfSSAIds(AffineMapAttr mapAttr, ValueRange operands)=0
Prints an affine map of SSA ids, where SSA id names are used in place of dims/symbols.
virtual void printGenericOp(Operation *op, bool printOpName=true)=0
Print the entire operation with the default generic assembly form.
~OpAsmPrinter() override
virtual void printRegion(Region &blocks, bool printEntryBlockArgs=true, bool printBlockTerminators=true, bool printEmptyBlock=false)=0
Prints a region.
virtual void printRegionArgument(BlockArgument arg, ArrayRef< NamedAttribute > argAttrs={}, bool omitType=false)=0
Print a block argument in the usual format of: ssaName : type {attr1=42} loc("here") where location p...
virtual void printOperand(Value value)=0
Print implementations for various things an operation contains.
Operation is the basic unit of execution within MLIR.
Definition: Operation.h:88
This class implements Optional functionality for ParseResult.
Definition: OpDefinition.h:39
ParseResult value() const
Access the internal ParseResult value.
Definition: OpDefinition.h:52
bool has_value() const
Returns true if we contain a valid ParseResult value.
Definition: OpDefinition.h:49
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Definition: Region.h:26
This class provides an efficient unique identifier for a specific C++ type.
Definition: TypeID.h:107
This class provides an abstraction over the various different ranges of value types.
Definition: TypeRange.h:37
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition: Types.h:74
This class provides an abstraction over the different types of ranges over Values.
Definition: ValueRange.h:387
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition: Value.h:96
The base class used for all derived interface types.
The OpAsmOpInterface, see OpAsmInterface.td for more details.
Definition: CallGraph.h:229
QueryRef parse(llvm::StringRef line, const QuerySession &qs)
Definition: Query.cpp:20
Include the generated interface declarations.
ParseResult parseDimensionList(OpAsmParser &parser, DenseI64ArrayAttr &dimensions)
void printDimensionList(OpAsmPrinter &printer, Operation *op, ArrayRef< int64_t > dimensions)
detail::DenseArrayAttrImpl< int64_t > DenseI64ArrayAttr
OpAsmAliasResult
Holds the result of OpAsm{Dialect,Attr,Type}Interface::getAlias hook call.
Definition: OpAsmSupport.h:39
@ NoAlias
The object (type or attribute) is not supported by the hook and an alias was not provided.
llvm::hash_code hash_value(const AsmDialectResourceHandle &param)
auto get(MLIRContext *context, Ts &&...params)
Helper method that injects context only if needed, this helps unify some of the attribute constructio...
inline ::llvm::hash_code hash_value(AffineExpr arg)
Make AffineExpr hashable.
Definition: AffineExpr.h:247
raw_ostream & operator<<(raw_ostream &os, const AliasResult &result)
Definition: AliasAnalysis.h:78
static mlir::AsmDialectResourceHandle getTombstoneKey()
static unsigned getHashValue(const mlir::AsmDialectResourceHandle &handle)
static mlir::AsmDialectResourceHandle getEmptyKey()
static bool isEqual(const mlir::AsmDialectResourceHandle &lhs, const mlir::AsmDialectResourceHandle &rhs)
std::optional< Location > sourceLoc
This is the representation of an operand reference.
This represents an operation in an abstracted form, suitable for use with the builder APIs.
This trait is used to determine if a storage user, like Type, is mutable or not.