MLIR  20.0.0git
TransformDialect.cpp
Go to the documentation of this file.
1 //===- TransformDialect.cpp - Transform Dialect Definition ----------------===//
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 
16 #include "llvm/ADT/SCCIterator.h"
17 
18 using namespace mlir;
19 
20 #include "mlir/Dialect/Transform/IR/TransformDialect.cpp.inc"
21 
22 #ifndef NDEBUG
24  StringRef name, MLIRContext *context) {
25  // Since the operation is being inserted into the Transform dialect and the
26  // dialect does not implement the interface fallback, only check for the op
27  // itself having the interface implementation.
29  *RegisteredOperationName::lookup(name, context);
30  assert((opName.hasInterface<TransformOpInterface>() ||
31  opName.hasInterface<PatternDescriptorOpInterface>() ||
32  opName.hasInterface<ConversionPatternDescriptorOpInterface>() ||
33  opName.hasInterface<TypeConverterBuilderOpInterface>() ||
34  opName.hasTrait<OpTrait::IsTerminator>()) &&
35  "non-terminator ops injected into the transform dialect must "
36  "implement TransformOpInterface or PatternDescriptorOpInterface or "
37  "ConversionPatternDescriptorOpInterface");
38  if (!opName.hasInterface<PatternDescriptorOpInterface>() &&
39  !opName.hasInterface<ConversionPatternDescriptorOpInterface>() &&
40  !opName.hasInterface<TypeConverterBuilderOpInterface>()) {
41  assert(opName.hasInterface<MemoryEffectOpInterface>() &&
42  "ops injected into the transform dialect must implement "
43  "MemoryEffectsOpInterface");
44  }
45 }
46 
48  TypeID typeID, MLIRContext *context) {
49  const auto &abstractType = AbstractType::lookup(typeID, context);
50  assert((abstractType.hasInterface(
51  TransformHandleTypeInterface::getInterfaceID()) ||
52  abstractType.hasInterface(
53  TransformParamTypeInterface::getInterfaceID()) ||
54  abstractType.hasInterface(
55  TransformValueHandleTypeInterface::getInterfaceID())) &&
56  "expected Transform dialect type to implement one of the three "
57  "interfaces");
58 }
59 #endif // NDEBUG
60 
61 void transform::TransformDialect::initialize() {
62  // Using the checked versions to enable the same assertions as for the ops
63  // from extensions.
64  addOperationsChecked<
65 #define GET_OP_LIST
66 #include "mlir/Dialect/Transform/IR/TransformOps.cpp.inc"
67  >();
68  initializeTypes();
69  initializeLibraryModule();
70 }
71 
73  StringRef keyword;
74  SMLoc loc = parser.getCurrentLocation();
75  if (failed(parser.parseKeyword(&keyword)))
76  return nullptr;
77 
78  auto it = typeParsingHooks.find(keyword);
79  if (it == typeParsingHooks.end()) {
80  parser.emitError(loc) << "unknown type mnemonic: " << keyword;
81  return nullptr;
82  }
83 
84  return it->getValue()(parser);
85 }
86 
88  DialectAsmPrinter &printer) const {
89  auto it = typePrintingHooks.find(type.getTypeID());
90  assert(it != typePrintingHooks.end() && "printing unknown type");
91  it->getSecond()(type, printer);
92 }
93 
94 LogicalResult transform::TransformDialect::loadIntoLibraryModule(
96  return detail::mergeSymbolsInto(getLibraryModule(), std::move(library));
97 }
98 
99 void transform::TransformDialect::initializeLibraryModule() {
100  MLIRContext *context = getContext();
101  auto loc =
102  FileLineColLoc::get(context, "<transform-dialect-library-module>", 0, 0);
103  libraryModule = ModuleOp::create(loc, "__transform_library");
104  libraryModule.get()->setAttr(TransformDialect::kWithNamedSequenceAttrName,
105  UnitAttr::get(context));
106 }
107 
108 void transform::TransformDialect::reportDuplicateTypeRegistration(
109  StringRef mnemonic) {
110  std::string buffer;
111  llvm::raw_string_ostream msg(buffer);
112  msg << "extensible dialect type '" << mnemonic
113  << "' is already registered with a different implementation";
114  llvm::report_fatal_error(StringRef(buffer));
115 }
116 
117 void transform::TransformDialect::reportDuplicateOpRegistration(
118  StringRef opName) {
119  std::string buffer;
120  llvm::raw_string_ostream msg(buffer);
121  msg << "extensible dialect operation '" << opName
122  << "' is already registered with a mismatching TypeID";
123  llvm::report_fatal_error(StringRef(buffer));
124 }
125 
126 LogicalResult transform::TransformDialect::verifyOperationAttribute(
127  Operation *op, NamedAttribute attribute) {
128  if (attribute.getName().getValue() == kWithNamedSequenceAttrName) {
129  if (!op->hasTrait<OpTrait::SymbolTable>()) {
130  return emitError(op->getLoc()) << attribute.getName()
131  << " attribute can only be attached to "
132  "operations with symbol tables";
133  }
134 
135  const mlir::CallGraph callgraph(op);
136  for (auto scc = llvm::scc_begin(&callgraph); !scc.isAtEnd(); ++scc) {
137  if (!scc.hasCycle())
138  continue;
139 
140  // Need to check this here additionally because this verification may run
141  // before we check the nested operations.
142  if ((*scc->begin())->isExternal())
143  return op->emitOpError() << "contains a call to an external operation, "
144  "which is not allowed";
145 
146  Operation *first = (*scc->begin())->getCallableRegion()->getParentOp();
148  << "recursion not allowed in named sequences";
149  for (auto it = std::next(scc->begin()); it != scc->end(); ++it) {
150  // Need to check this here additionally because this verification may
151  // run before we check the nested operations.
152  if ((*it)->isExternal()) {
153  return op->emitOpError() << "contains a call to an external "
154  "operation, which is not allowed";
155  }
156 
157  Operation *current = (*it)->getCallableRegion()->getParentOp();
158  diag.attachNote(current->getLoc()) << "operation on recursion stack";
159  }
160  return diag;
161  }
162  return success();
163  }
164  if (attribute.getName().getValue() == kTargetTagAttrName) {
165  if (!llvm::isa<StringAttr>(attribute.getValue())) {
166  return op->emitError()
167  << attribute.getName() << " attribute must be a string";
168  }
169  return success();
170  }
171  if (attribute.getName().getValue() == kArgConsumedAttrName ||
172  attribute.getName().getValue() == kArgReadOnlyAttrName) {
173  if (!llvm::isa<UnitAttr>(attribute.getValue())) {
174  return op->emitError()
175  << attribute.getName() << " must be a unit attribute";
176  }
177  return success();
178  }
179  if (attribute.getName().getValue() ==
180  FindPayloadReplacementOpInterface::kSilenceTrackingFailuresAttrName) {
181  if (!llvm::isa<UnitAttr>(attribute.getValue())) {
182  return op->emitError()
183  << attribute.getName() << " must be a unit attribute";
184  }
185  return success();
186  }
187  return emitError(op->getLoc())
188  << "unknown attribute: " << attribute.getName();
189 }
static MLIRContext * getContext(OpFoldResult val)
static std::string diag(const llvm::Value &value)
static const AbstractType & lookup(TypeID typeID, MLIRContext *context)
Look up the specified abstract type in the MLIRContext and return a reference to it.
virtual InFlightDiagnostic emitError(SMLoc loc, const Twine &message={})=0
Emit a diagnostic at the specified location and return failure.
virtual SMLoc getCurrentLocation()=0
Get the location of the next token and store it into the argument.
ParseResult parseKeyword(StringRef keyword)
Parse a given keyword.
The DialectAsmParser has methods for interacting with the asm parser when parsing attributes and type...
This is a pure-virtual base class that exposes the asmprinter hooks necessary to implement a custom p...
static FileLineColLoc get(StringAttr filename, unsigned line, unsigned column)
Definition: Location.cpp:160
This class represents a diagnostic that is inflight and set to be reported.
Definition: Diagnostics.h:314
MLIRContext is the top-level object for a collection of MLIR operations.
Definition: MLIRContext.h:60
NamedAttribute represents a combination of a name and an Attribute value.
Definition: Attributes.h:207
StringAttr getName() const
Return the name of the attribute.
Definition: Attributes.cpp:49
Attribute getValue() const
Return the value of the attribute.
Definition: Attributes.h:221
This class provides the API for ops that are known to be terminators.
Definition: OpDefinition.h:764
A trait used to provide symbol table functionalities to a region operation.
Definition: SymbolTable.h:435
bool hasTrait() const
Returns true if the operation was registered with a particular trait, e.g.
bool hasInterface() const
Returns true if this operation has the given interface registered to it.
Operation is the basic unit of execution within MLIR.
Definition: Operation.h:88
bool hasTrait()
Returns true if the operation was registered with a particular trait, e.g.
Definition: Operation.h:745
Location getLoc()
The source location the operation was defined or derived from.
Definition: Operation.h:223
Operation * getParentOp()
Returns the closest surrounding operation that contains this operation or nullptr if this is a top-le...
Definition: Operation.h:234
InFlightDiagnostic emitError(const Twine &message={})
Emit an error about fatal conditions with this operation, reporting up to any diagnostic handlers tha...
Definition: Operation.cpp:268
InFlightDiagnostic emitOpError(const Twine &message={})
Emit an error with the op name prefixed, like "'dim' op " which is convenient for verifiers.
Definition: Operation.cpp:671
This class acts as an owning reference to an op, and will automatically destroy the held op on destru...
Definition: OwningOpRef.h:29
This is a "type erased" representation of a registered operation.
static std::optional< RegisteredOperationName > lookup(StringRef name, MLIRContext *ctx)
Lookup the registered operation information for the given operation.
This class provides an efficient unique identifier for a specific C++ type.
Definition: TypeID.h:104
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition: Types.h:74
TypeID getTypeID()
Return a unique identifier for the concrete type.
Definition: Types.h:117
void printType(Type type, AsmPrinter &printer)
Prints an LLVM Dialect type.
InFlightDiagnostic mergeSymbolsInto(Operation *target, OwningOpRef< Operation * > other)
Merge all symbols from other into target.
Definition: Utils.cpp:79
void checkImplementsTransformHandleTypeInterface(TypeID typeID, MLIRContext *context)
Asserts that the type provided as template argument implements the TransformHandleTypeInterface.
void checkImplementsTransformOpInterface(StringRef name, MLIRContext *context)
Asserts that the operations provided as template arguments implement the TransformOpInterface and Mem...
Include the generated interface declarations.
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
auto get(MLIRContext *context, Ts &&...params)
Helper method that injects context only if needed, this helps unify some of the attribute constructio...
Type parseType(llvm::StringRef typeStr, MLIRContext *context, size_t *numRead=nullptr, bool isKnownNullTerminated=false)
This parses a single MLIR type to an MLIR context if it was valid.