19 #include "llvm/Support/Debug.h"
20 #include "llvm/Support/FormatVariadic.h"
21 #include "llvm/Support/InterleavedRange.h"
25 #define DEBUG_TYPE "linalg-transforms"
26 #define DBGS() (llvm::dbgs() << "[" DEBUG_TYPE "]: ")
36 if (!isa<linalg::LinalgOp>(current)) {
37 if (getFailurePropagationMode().value_or(
38 FailurePropagationMode::Propagate) ==
39 FailurePropagationMode::Propagate) {
40 return emitSilenceableError() <<
"expected a Linalg op";
43 LLVM_DEBUG(
DBGS() <<
"optional nested matcher expected a Linalg op");
49 auto scope = state.make_region_scope(getBodyRegion());
50 if (failed(state.mapBlockArgument(getBody()->getArgument(0),
55 for (
Operation &nested : getBody()->without_terminator()) {
57 state.applyTransform(cast<TransformOpInterface>(nested));
58 if (
diag.isDefiniteFailure())
64 assert(
diag.isSilenceableFailure());
65 if (getFailurePropagationMode().value_or(
66 FailurePropagationMode::Propagate) ==
67 FailurePropagationMode::Propagate) {
79 LLVM_DEBUG(
DBGS() <<
"optional nested matcher failed: " <<
diag.getMessage()
84 getBody()->getTerminator()->getOpOperands()) {
85 Operation *definingOp = terminatorOperand.get().getDefiningOp();
88 if (definingOp->
getBlock() != getBody())
93 undefinedOperands.push_back(&terminatorOperand);
97 auto filtered = llvm::make_filter_range(
98 getBody()->getTerminator()->getOpOperands(), [&](
OpOperand &opOperand) {
99 return !llvm::is_contained(undefinedOperands, &opOperand);
102 filtered, [](
OpOperand &opOperand) {
return opOperand.
get(); }));
104 for (
auto &&[operand, mapping] : llvm::zip_equal(filtered, mappings)) {
117 void transform::MatchStructuredOp::getEffects(
125 if (getBody()->getNumArguments() != 1)
126 return emitOpError() <<
"expected one body argument";
127 if (!isa<TransformHandleTypeInterface>(getBody()->getArgument(0).
getType())) {
128 return emitOpError() <<
"expected body argument to implement "
129 "TransformHandleTypeInterface";
131 for (
Operation &nested : getBody()->without_terminator()) {
132 if (isa<MatchOpInterface>(nested))
136 <<
"expects nested operations to implement MatchOpInterface";
137 diag.attachNote(nested.getLoc()) <<
"offending operation";
149 if (!isa_and_nonnull<MatchStructuredOp>(op->
getParentOp())) {
150 return op->
emitOpError() <<
"expects parent op to be '"
151 << MatchStructuredOp::getOperationName() <<
"'";
162 <<
"expected predicate to apply to the surrounding structured op";
174 auto linalgOp = cast<linalg::LinalgOp>(current);
175 if (std::optional<uint64_t> position = getReductionPosition()) {
179 return emitSilenceableError() <<
"could not match reduction";
181 if (combinerOps.size() != 1) {
182 return emitSilenceableError() <<
"reduction combiner is not a single op";
186 if (getPassthrough()) {
189 return emitSilenceableError() <<
"not a passthrough";
193 if (getElementwise()) {
195 return emitSilenceableError() <<
"not elementwise";
198 if (std::optional<ArrayAttr> contractionOps = getContraction()) {
201 llvm::raw_string_ostream os(message);
205 return elem->
getName().getStringRef() ==
206 cast<StringAttr>((*contractionOps)[0]).getValue() &&
208 cast<StringAttr>((*contractionOps)[1]).getValue();
213 return emitSilenceableError() <<
"contraction: " << message;
219 int64_t numOptions = getReductionPosition().has_value() + getPassthrough() +
220 getElementwise() + getContraction().has_value();
222 if (numOptions > 1) {
223 StringAttr attributeNames[] = {
224 getReductionPositionAttrName(), getPassthroughAttrName(),
225 getElementwiseAttrName(), getContractionAttrName()};
226 return emitOpError() <<
"only one of {" << llvm::interleaved(attributeNames)
230 if (std::optional<ArrayAttr> contractionAttr = getContraction()) {
231 if (contractionAttr->size() != 2) {
232 return emitOpError() <<
"expects " << getContractionAttrName()
233 <<
" to contain two elements";
244 transform::MatchStructuredClassifyContractionDimsOp::matchOperation(
247 FailureOr<linalg::ContractionDimensions> contractionDims =
249 if (failed(contractionDims))
250 return emitSilenceableError() <<
"could not infer contraction dimensions";
255 return llvm::to_vector(
256 llvm::map_range(values, [&](
unsigned value) ->
Attribute {
257 return builder.getI64IntegerAttr(value);
260 results.
setParams(cast<OpResult>(getBatch()),
261 makeI64Attrs(contractionDims->batch));
262 results.
setParams(cast<OpResult>(
getM()), makeI64Attrs(contractionDims->m));
263 results.
setParams(cast<OpResult>(
getN()), makeI64Attrs(contractionDims->n));
264 results.
setParams(cast<OpResult>(getK()), makeI64Attrs(contractionDims->k));
273 transform::MatchStructuredClassifyConvolutionDimsOp::matchOperation(
276 FailureOr<linalg::ConvolutionDimensions> convolutionDims =
278 if (failed(convolutionDims))
279 return emitSilenceableError() <<
"could not infer convolution dimensions";
284 return llvm::to_vector(
285 llvm::map_range(values, [&](
unsigned value) ->
Attribute {
286 return builder.getI64IntegerAttr(value);
289 results.
setParams(cast<OpResult>(getBatch()),
290 makeI64Attrs(convolutionDims->batch));
291 results.
setParams(cast<OpResult>(getOutputImage()),
292 makeI64Attrs(convolutionDims->outputImage));
293 results.
setParams(cast<OpResult>(getOutputChannel()),
294 makeI64Attrs(convolutionDims->outputChannel));
295 results.
setParams(cast<OpResult>(getFilterLoop()),
296 makeI64Attrs(convolutionDims->filterLoop));
297 results.
setParams(cast<OpResult>(getInputChannel()),
298 makeI64Attrs(convolutionDims->inputChannel));
299 results.
setParams(cast<OpResult>(getDepth()),
300 makeI64Attrs(convolutionDims->depth));
303 return llvm::to_vector(
304 llvm::map_range(values, [&](int64_t value) ->
Attribute {
305 return builder.getI64IntegerAttr(value);
308 results.
setParams(cast<OpResult>(getStrides()),
309 makeI64AttrsFromI64(convolutionDims->strides));
310 results.
setParams(cast<OpResult>(getDilations()),
311 makeI64AttrsFromI64(convolutionDims->dilations));
327 const char *message) {
328 for (int64_t value : list) {
329 if (llvm::any_of(reference, [&](
unsigned ref) {
330 return static_cast<int64_t
>(ref) == value;
346 auto linalgOp = cast<linalg::LinalgOp>(current);
349 if (!
diag.succeeded())
353 if (getParallel() || getReduction()) {
356 linalgOp.getParallelDims(reference);
357 else if (getReduction())
358 linalgOp.getReductionDims(reference);
362 getParallel() ?
"expects dimension #{0} to be parallel"
363 :
"expects dimension #{0} to be reduction");
364 if (!
diag.succeeded())
375 llvm::map_range(dimensions, [&](int64_t dim) ->
Attribute {
376 return builder.getI64IntegerAttr(ranges[dim]);
378 results.
setParams(cast<OpResult>(getResult()), captured);
386 getRawDimList(), op.getNumLoops(), dims);
387 if (
diag.isSilenceableFailure()) {
388 diag.attachNote(op->getLoc())
389 <<
"while considering dimensions of this payload operation";
395 if (getParallel() && getReduction()) {
396 return emitOpError() <<
"cannot request the same dimension to be both "
397 "parallel and reduction";
400 getIsInverted(), getIsAll());
408 transform::MatchStructuredElementalBitwidthOp::matchValue(
411 auto setupResult = [&](int64_t bitwidth) {
413 results.
setParams(cast<OpResult>(getResult()), {attr});
421 if (
auto shapedType = dyn_cast<ShapedType>(type)) {
422 if (shapedType.getElementType().isIntOrFloat())
423 return setupResult(shapedType.getElementTypeBitWidth());
425 return emitSilenceableError()
426 <<
"unsupported type for bitwidth extraction: " << type;
436 auto linalgOp = cast<linalg::LinalgOp>(current);
439 if (!
diag.succeeded())
443 operandMapping.reserve(positions.size());
444 for (int64_t position : positions) {
446 linalgOp.getMatchingIndexingMap(linalgOp.getDpsInputOperand(position));
448 return emitSilenceableError() <<
"the indexing map for input #"
449 << position <<
" is not a permutation";
452 return emitSilenceableError()
453 <<
"the indexing map for input #" << position
454 <<
" is not a projected permutation";
461 if (isa<AffineMapParamType>(getResult().
getType())) {
466 Value operand = linalgOp.getDpsInputOperand(position)->get();
467 if (isa<TransformValueHandleTypeInterface>(getResult().
getType())) {
468 operandMapping.emplace_back(operand);
473 if (!operandProducer) {
474 return emitSilenceableError()
475 <<
"input #" << position <<
" is not produced by an operation";
477 operandMapping.emplace_back(operandProducer);
487 getLoc(), getIsAll(), getIsInverted(), getRawPositionList(),
488 op.getNumDpsInputs(), positions);
489 if (
diag.isSilenceableFailure()) {
490 diag.attachNote(op->getLoc())
491 <<
"while considering DPS inputs of this payload operation";
498 template <
typename OpTy>
500 if (op.getPermutation() && op.getProjectedPermutation()) {
501 return op.emitOpError()
502 << op.getPermutationAttrName() <<
" and "
503 << op.getProjectedPermutationAttrName() <<
" are mutually exclusive";
505 if (op.getRawPositionList().size() > 1 && op.getResult()) {
506 return op.emitOpError()
507 <<
"cannot bind multiple inputs/inits to the same value";
517 getIsInverted(), getIsAll());
527 auto linalgOp = cast<linalg::LinalgOp>(current);
530 if (!
diag.succeeded())
534 operandMapping.reserve(positions.size());
535 for (int64_t position : positions) {
537 linalgOp.getMatchingIndexingMap(linalgOp.getDpsInitOperand(position));
539 return emitSilenceableError() <<
"the indexing map for output(init) #"
540 << position <<
" is not a permutation";
543 return emitSilenceableError() <<
"the indexing map for output(init) #"
544 << position <<
" is not a permutation";
551 if (isa<AffineMapParamType>(getResult().
getType())) {
556 Value operand = linalgOp.getDpsInitOperand(position)->get();
557 if (isa<TransformValueHandleTypeInterface>(getResult().
getType())) {
558 operandMapping.emplace_back(operand);
563 if (!operandProducer) {
564 return emitSilenceableError() <<
"output(init) #" << position
565 <<
" is not produced by an operation";
567 operandMapping.emplace_back(operandProducer);
577 getLoc(), getIsAll(), getIsInverted(), getRawPositionList(),
578 op.getNumDpsInits(), positions);
579 if (
diag.isSilenceableFailure()) {
580 diag.attachNote(op->getLoc())
581 <<
"while considering DPS inits (outputs) of this payload operation";
590 getIsInverted(), getIsAll());
598 transform::MatchStructuredNumInputsOp::matchOperation(
601 auto linalgOp = cast<linalg::LinalgOp>(current);
604 results.
setParams(cast<OpResult>(getResult()), {attr});
613 transform::MatchStructuredNumInitsOp::matchOperation(
616 auto linalgOp = cast<linalg::LinalgOp>(current);
619 results.
setParams(cast<OpResult>(getResult()), {attr});
630 auto linalgOp = cast<linalg::LinalgOp>(current);
631 int64_t numLoops = linalgOp.getNumLoops();
633 results.
setParams(cast<OpResult>(getRank()), {attr});
644 auto linalgOp = cast<linalg::LinalgOp>(op);
647 if (!
diag.succeeded())
650 Value result = linalgOp.getTiedOpResult(linalgOp.getDpsInitOperand(position));
651 if (isa<TransformValueHandleTypeInterface>(getResult().
getType())) {
652 results.
setValues(cast<OpResult>(getResult()), {result});
657 return emitSilenceableError()
658 <<
"no users of the result #" << getPosition();
662 results.
set(cast<OpResult>(getResult()), {firstUser});
666 if (!llvm::hasSingleElement(result.
getUsers())) {
667 return emitSilenceableError()
668 <<
"more than one result user with single user requested";
670 results.
set(cast<OpResult>(getResult()), {firstUser});
678 transform::MatchStructuredResultOp::getPositionFor(linalg::LinalgOp op,
680 auto rawPosition =
static_cast<int64_t
>(getPosition());
681 position = rawPosition < 0 ? op.getNumDpsInits() + rawPosition : rawPosition;
682 if (position >= op.getNumDpsInits() || position < 0) {
683 return emitSilenceableError()
684 <<
"position " << rawPosition
685 <<
" overflows the number of results(ints) of the payload operation";
691 if ((getAny() || getSingle()) ^
692 isa<TransformHandleTypeInterface>(getResult().
getType())) {
693 return emitOpError() <<
"expects either the any/single keyword or the type "
694 "value handle result type";
696 if (getAny() && getSingle()) {
697 return emitOpError() <<
"'any' and 'single' are mutually exclusive";
706 void transform::MatchStructuredYieldOp::getEffects(
712 void transform::MatchStructuredYieldOp::build(
OpBuilder &builder,
717 #define GET_OP_CLASSES
718 #include "mlir/Dialect/Linalg/TransformOps/LinalgMatchOps.cpp.inc"
static DiagnosedSilenceableFailure containsAll(ArrayRef< unsigned > reference, ArrayRef< int64_t > list, Location loc, const char *message)
Checks if all values from list are also contained in reference.
LogicalResult verifyStructuredOperandOp(OpTy op)
Verifies a matcher op for structured input or output, specifically the attributes specifying the oper...
static std::string diag(const llvm::Value &value)
A multi-dimensional affine map Affine map's are immutable like Type's, and they are uniqued.
bool isProjectedPermutation(bool allowZeroInResults=false) const
Returns true if the AffineMap represents a subset (i.e.
bool isPermutation() const
Returns true if the AffineMap represents a symbol-less permutation map.
Attributes are known-constant values of operations.
Block represents an ordered list of Operations.
BlockArgument getArgument(unsigned i)
unsigned getNumArguments()
Operation * getTerminator()
Get the terminator operation of this block.
This class is a general helper class for creating context-global objects like types,...
IntegerAttr getI64IntegerAttr(int64_t value)
The result of a transform IR operation application.
static DiagnosedSilenceableFailure success()
Constructs a DiagnosedSilenceableFailure in the success state.
static DiagnosedSilenceableFailure definiteFailure()
Constructs a DiagnosedSilenceableFailure in the failure state.
IRValueT get() const
Return the current value being used by this operand.
This class represents a diagnostic that is inflight and set to be reported.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
MLIRContext is the top-level object for a collection of MLIR operations.
This class helps build Operations.
This class represents an operand of an operation.
StringRef getStringRef() const
Return the name of this operation. This always succeeds.
Operation is the basic unit of execution within MLIR.
bool isBeforeInBlock(Operation *other)
Given an operation 'other' that is within the same parent block, return whether the current operation...
MLIRContext * getContext()
Return the context this operation is associated with.
unsigned getNumRegions()
Returns the number of regions held by this operation.
Operation * getParentOp()
Returns the closest surrounding operation that contains this operation or nullptr if this is a top-le...
Block * getBlock()
Returns the operation block that contains this operation.
Region & getRegion(unsigned index)
Returns the region held by this operation at position 'index'.
OperationName getName()
The name of an operation is the key identifier for it.
operand_range getOperands()
Returns an iterator on the underlying Value's.
InFlightDiagnostic emitOpError(const Twine &message={})
Emit an error with the op name prefixed, like "'dim' op " which is convenient for verifiers.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
bool isIntOrFloat() const
Return true if this is an integer (of any signedness) or a float type.
unsigned getIntOrFloatBitWidth() const
Return the bit width of an integer or a float type, assert failure on other types.
This class provides an abstraction over the different types of ranges over Values.
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
MLIRContext * getContext() const
Utility to get the associated MLIRContext that this value is defined in.
Type getType() const
Return the type of this value.
user_range getUsers() const
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
bool isContractionBody(Block &block, function_ref< bool(Operation *, Operation *)> isaPair, llvm::raw_ostream &errs=mlir::thread_safe_nulls())
Returns true if the block contains a contraction of the following form:
FailureOr< ConvolutionDimensions > inferConvolutionDims(LinalgOp linalgOp)
Find at least 1 parallel (output_image) and reduction (filter_loop) dimension candidates that form a ...
bool isElementwise(LinalgOp op)
Check if a LinalgOp is an element-wise operation.
FailureOr< ContractionDimensions > inferContractionDims(LinalgOp linalgOp)
Find at least 2 parallel (m and n) and 1 reduction (k) dimension candidates that form a matmul subcom...
uint64_t getN(LevelType lt)
uint64_t getM(LevelType lt)
Include the generated interface declarations.
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
DiagnosedSilenceableFailure emitSilenceableFailure(Location loc, const Twine &message={})
Emits a silenceable failure with the given message.
Value matchReduction(ArrayRef< BlockArgument > iterCarriedArgs, unsigned redPos, SmallVectorImpl< Operation * > &combinerOps)
Utility to match a generic reduction given a list of iteration-carried arguments, iterCarriedArgs and...
DiagnosedDefiniteFailure emitDefiniteFailure(Location loc, const Twine &message={})
Emits a definite failure with the given message.
auto get(MLIRContext *context, Ts &&...params)
Helper method that injects context only if needed, this helps unify some of the attribute constructio...
LogicalResult verify(Operation *op, bool verifyRecursively=true)
Perform (potentially expensive) checks of invariants, used to detect compiler bugs,...
This represents an operation in an abstracted form, suitable for use with the builder APIs.