MLIR 24.0.0git
TosaReduceTransposes.cpp
Go to the documentation of this file.
1//===- TosaReduceTransposes.cpp -------------------------------------------===//
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// ----------
10// Motivation:
11// ----------
12
13// Some legalization pathways introduce redundant tosa.TRANSPOSE
14// operations that result in avoidable data movement. For example,
15// PyTorch -> TOSA contains a lot of unnecessary transposes due
16// to conversions between NCHW and NHWC.
17
18// We wish to remove all the ones that we can, since in general
19// it is possible to remove the overwhelming majority.
20
21// -------------------
22// High-Level Overview:
23// -------------------
24
25// The pass works through the transpose operators in the program. It begins at
26// some transpose operator with an associated permutations tensor. It traverses
27// upwards through the dependencies of this transpose and verifies that we
28// encounter only supported elementwise operators and terminate in either
29// constants, reshapes, or transposes.
30
31// We then evaluate whether there are any additional restrictions (the
32// transposes it terminates in must invert the one we began at, and the reshapes
33// must be ones in which we can fold the transpose into), and then we hoist the
34// transpose through the intervening operators, folding it at the constants,
35// reshapes, and transposes.
36
37// Finally, we ensure that we do not need both the transposed form (the form
38// that had the transpose hoisted through it) and the untransposed form (which
39// it was prior), by analyzing the usages of those dependent operators of a
40// given transpose we are attempting to hoist and replace.
41
42// If they are such that it would require both forms to be necessary, then we do
43// not replace the hoisted transpose, causing the new chain to be dead.
44// Otherwise, we do and the old chain (untransposed form) becomes dead. Only one
45// chain will ever then be live, resulting in no duplication.
46
47// We then perform a simple one-pass DCE, so no canonicalization is necessary.
48
49// -----------
50// Future Work:
51// -----------
52
53// (1) Evaluate tradeoffs with permitting ConstOp to be duplicated across
54// hoisted
55// transposes with different permutation tensors.
56
57// (2) Expand the class of foldable upstream ReshapeOp we permit beyond
58// N -> 1x1x...x1xNx1x...x1x1.
59
60// (3) Enchance the pass to permit folding arbitrary transpose pairs, beyond
61// those that form the identity.
62
63// (4) Add support for more instructions besides TosaElementwiseOperator as
64// the intervening ones (for example, the reduce_* operators).
65
66// (5) Support hoisting transposes up to an input parameter.
67
68//===----------------------------------------------------------------------===//
69
74#include "mlir/IR/Iterators.h"
75#include "llvm/ADT/TypeSwitch.h"
76#include <set>
77#include <stack>
78
79namespace mlir {
80namespace tosa {
81#define GEN_PASS_DEF_TOSAREDUCETRANSPOSES
82#include "mlir/Dialect/Tosa/Transforms/Passes.h.inc"
83} // namespace tosa
84} // namespace mlir
85
86using namespace mlir;
87using namespace mlir::tosa;
88
89//===----------------------------------------------------------------------===//
90// TOSA Reduce Transposes Pass.
91//===----------------------------------------------------------------------===//
92
93namespace {
94
95struct TosaReduceTransposes final
96 : public tosa::impl::TosaReduceTransposesBase<TosaReduceTransposes> {
97 void runOnOperation() override;
98
99private:
100 // This will collect all the data dependencies for the given Operation
101 // up to and including ConstOp, ReshapeOp, and TransposeOp.
102 bool collectFanIn(Operation *op, SetVector<Operation *> &collected);
103 bool convertDependentOps(SetVector<Operation *> &dependentOps,
104 DenseMap<Value, Value> &valuesMap,
105 IRRewriter &rewriter,
106 ArrayRef<int32_t> hoistedPerms);
107
108 // Checks if the two permutations, when applied consecutively, result
109 // in the identity.
110 bool areInvolutionTransposes(ArrayRef<int32_t> perms1,
111 ArrayRef<int32_t> perms2);
112
113 // This is meant to apply to operations with the TosaElementwiseOperator
114 // trait.
115 std::optional<Value>
116 buildMappedToValue(Operation *op, const DenseMap<Value, Value> &valuesMap,
117 IRRewriter &rewriter, ArrayRef<int32_t> hoistedPerms);
118
119 // This updates valuesMap when we encounter another TransposeOp as a
120 // dependency of the hoisted one. %0 = tosa.transpose %arg0 <- applies to
121 // this %1 = tosa.transpose %0 <- when tracking back from this
122 std::optional<Value>
123 buildMappedToValue(TransposeOp transposeOp,
124 const DenseMap<Value, Value> &valuesMap,
125 IRRewriter &rewriter, ArrayRef<int32_t> hoistedPerms);
126
127 // Checks if ReshapeOp can have hoisted TransposeOp folded into it. If so,
128 // it creates new ReshapeOp with that fold.
129 std::optional<Value>
130 buildMappedToValue(ReshapeOp reshapeOp,
131 const DenseMap<Value, Value> &valuesMap,
132 IRRewriter &rewriter, ArrayRef<int32_t> hoistedPerms);
133
134 // We may have something like:
135 // %0 = tosa.const
136 // %1 = tosa.transpose
137 // %2 = tosa.add %0, %1
138 // %3 = tosa.transpose %2
139 // that --tosa-layerwise-const-fold wouldn't handle. This use shows up
140 // in MobilenetV3.
141 std::optional<Value>
142 buildMappedToValue(ConstOp constOp, const DenseMap<Value, Value> &valuesMap,
143 IRRewriter &rewriter, ArrayRef<int32_t> hoistedPerms);
144
145 // Checks which TransposeOp we should "replace", turning their converted
146 // chains of ops, through which they were propagated, "live", and the old code
147 // "dead." Attempts to avoid doing so when doing so would result in the old
148 // code staying "live," resulting in duplication.
149 std::set<TransposeOp> getGoodReplacements(
150 ArrayRef<int32_t> perms,
151 std::vector<std::pair<TransposeOp, SetVector<Operation *>>>
152 &transposeInfo);
153
154 // Helper function for dependenciesAreValid.
155 bool userNotContainedInValidTransposeDependencies(
156 Operation *user, std::set<TransposeOp> &validTransposes,
157 std::vector<std::pair<TransposeOp, SetVector<Operation *>>>
158 &transposeInfo);
159
160 // Helper function for getGoodReplacements to check if some TransposeOp's
161 // dependencies are OK.
162 bool dependenciesAreValid(
163 ArrayRef<int32_t> perms, const SetVector<Operation *> &dependentOps,
164 std::set<TransposeOp> &validTransposes,
165 std::vector<std::pair<TransposeOp, SetVector<Operation *>>>
166 &transposeInfo);
167
168 // Applies perms to the DenseElementsAttr.
169 // If it returns std::nullopt, it also triggers pass failure, since verifier
170 // guarantees from TOSA are not in place (and otherwise, if used elsewhere,
171 // it should fail).
172 // This is a basic API and may benefit from refactor into the core MLIR APIs.
173 std::optional<DenseElementsAttr>
174 transposeDenseAttribute(DenseElementsAttr input, ArrayRef<int32_t> perms);
175};
176
177// Check if shape is of the form 1x1x...x1xNx1x...x1x1 -> 1x1x...x1xNx1x...x1x1
178// Valid examples include:
179// - N -> 1x1xNx1
180// - Nx1x1x1 -> 1x1xNx1
181// - 1x1xNx1 -> 1x1xNx1
182static LogicalResult verifyUnitExpandedVectorShape(ArrayRef<int64_t> shape) {
183 bool nonUnitDimDetected = false;
184 for (const int64_t dim : shape) {
185 if (dim != 1) {
186 if (nonUnitDimDetected)
187 return failure();
188 nonUnitDimDetected = true;
189 }
190 }
191 return success();
192}
193
194std::optional<DenseElementsAttr>
195TosaReduceTransposes::transposeDenseAttribute(DenseElementsAttr input,
196 ArrayRef<int32_t> perms) {
197 RankedTensorType oldType = llvm::cast<RankedTensorType>(input.getType());
198 ArrayRef<int64_t> oldShape = oldType.getShape();
199 int64_t rank = oldType.getRank();
200
201 // Asserted by TransposeOp verifier and TOSA disallowing tensor with dimension
202 // 0. If not in place, something is very wrong.
203 if (rank <= 0 || oldType.getNumElements() <= 0) {
204 signalPassFailure();
205 return std::nullopt;
206 }
207
208 auto newShape = applyTOSAPermutation(oldShape, perms);
209 RankedTensorType newType =
210 RankedTensorType::get(newShape, oldType.getElementType());
211
212 if (input.isSplat()) {
213 return input.reshape(newType);
214 }
215
216 auto rawData = input.getRawData();
217 if (!rawData.data()) {
218 return std::nullopt;
219 }
220
221 // The algorithm is approximately as follows:
222 // 1. Determine the strides of both input and output tensors in row-major
223 // order
224 // 2. Iterate through the output tensor linearly.
225 // 3. For each output position, decompose the linear index into
226 // multi-dimensional coordinates using output strides.
227 // 4. Use the permutation to map output coordinates to input coordinates and
228 // calculate the source linear index.
229
230 // Example: perms [2, 0, 1]; input 2x3x4; output 4x2x3
231 // for output linear index 11: decompose to output[1][1][2]
232 // using output strides [6,3,1]. Map to input coordinates using
233 // perms: dim 0→2, dim 1→0, dim 2→1, giving source position
234 // calculated as 1*inputStrides[2] + 1*inputStrides[0] + 2*inputStrides[1]
235 // = 1*1 + 1*12 + 2*4 = 21
236 size_t elementSize = llvm::divideCeil(oldType.getElementTypeBitWidth(), 8);
237 int64_t numElements = oldType.getNumElements();
238
239 SmallVector<char> outputBuffer(numElements * elementSize);
240 const char *inputPtr = rawData.data();
241 char *outputPtr = outputBuffer.data();
242
243 auto calculateStrides = [](ArrayRef<int64_t> shape) -> SmallVector<int64_t> {
244 int64_t rank = shape.size();
245 SmallVector<int64_t> strides(rank);
246 strides[rank - 1] = 1;
247 for (int64_t i = rank - 2; i >= 0; --i) {
248 strides[i] = strides[i + 1] * shape[i + 1];
249 }
250 return strides;
251 };
252
253 // Calculate strides for both input and output tensors
254 SmallVector<int64_t> inputStrides = calculateStrides(oldShape);
255 SmallVector<int64_t> outputStrides = calculateStrides(newShape);
256
257 auto mapCoordinates = [&](int64_t destLinearIndex) -> int64_t {
258 int64_t tempDestIndex = destLinearIndex;
259 int64_t sourceLinearIndex = 0;
260
261 // Decompose linear destination index into multi-dimensional
262 // coordinates dividing by output strides.
263 // Simultaneously map these coordinates through the permutation
264 // to calculate the corresponding source linear index.
265 for (auto j : llvm::seq<int64_t>(rank)) {
266 int64_t destCoord = tempDestIndex / outputStrides[j];
267 tempDestIndex %= outputStrides[j];
268 sourceLinearIndex += destCoord * inputStrides[perms[j]];
269 }
270
271 return sourceLinearIndex;
272 };
273
274 for (auto destLinearIndex : llvm::seq<int64_t>(numElements)) {
275 int64_t sourceLinearIndex = mapCoordinates(destLinearIndex);
276
277 // Copy the element from source to destination using type-agnostic byte
278 // copying.
279 std::memcpy(outputPtr + destLinearIndex * elementSize,
280 inputPtr + sourceLinearIndex * elementSize, elementSize);
281 }
282
283 return DenseElementsAttr::getFromRawBuffer(newType, outputBuffer);
284}
285
286// Identify operations whose elementwise computation is preserved by a layout
287// permutation. Casts between scalar integer/float element types qualify;
288// compound block-scaled casts require axis-dependent grouping.
289static bool supportsTransposePropagation(Operation *op) {
290 if (auto cast = dyn_cast<tosa::CastOp>(op)) {
291 auto inputType = dyn_cast<RankedTensorType>(cast.getInput().getType());
292 auto outputType = dyn_cast<RankedTensorType>(cast.getOutput().getType());
293 return inputType && outputType &&
294 isa<IntegerType, FloatType>(inputType.getElementType()) &&
295 isa<IntegerType, FloatType>(outputType.getElementType());
296 }
297 return isa<tosa::MulOp>(op) ||
298 op->hasTrait<OpTrait::tosa::TosaElementwiseOperator>();
299}
300
301// If successful, collected contains ConstOp, ReshapeOp and TransposeOp as
302// dependency roots, with supported elementwise operations and scalar casts
303// following them in topological order.
304bool TosaReduceTransposes::collectFanIn(Operation *op,
305 SetVector<Operation *> &collected) {
306 // Can occur if defined through the parameter to a func.func.
307 if (!op)
308 return false;
309
310 if (!llvm::isa_and_present<tosa::TosaDialect>(op->getDialect()))
311 return false;
312
313 // Prevent extra work if already seen.
314 if (collected.contains(op))
315 return true;
316
317 // Throw it out so later don't have to deal with this.
318 if (op->getNumResults() != 1 ||
319 !llvm::isa<RankedTensorType>(op->getResult(0).getType()))
320 return false;
321
322 // We don't wish to traverse up a ReshapeOp, since generally we can't
323 // propagate a TransposeOp through it. TransposeOp, ReshapeOp, ConstOp
324 // will have no in-edges in the data dependency graph we construct for
325 // the downstream TransposeOp.
326 if (!llvm::isa<tosa::TransposeOp>(op) && !llvm::isa<tosa::ReshapeOp>(op) &&
327 !llvm::isa<tosa::ConstOp>(op)) {
328
329 if (!supportsTransposePropagation(op))
330 return false;
331
332 for (Value operand : op->getOperands()) {
333 // If this is a problem in future, think about alternatives to recursion.
334 if (llvm::isa<tosa::MulOp>(op) && operand == op->getOperand(2)) {
335 // do not recurse into MulOp's shift operand
336 continue;
337 }
338 if (!collectFanIn(operand.getDefiningOp(), collected))
339 return false;
340 }
341 }
342
343 // Insert in topological order.
344 collected.insert(op);
345
346 return true;
347}
348
349// Assuming that due to the verification of TransposeOp perms arrays are
350// permutations of 0 - perms.size() - 1.
351bool TosaReduceTransposes::areInvolutionTransposes(ArrayRef<int32_t> perms1,
352 ArrayRef<int32_t> perms2) {
353 if (perms1.size() != perms2.size())
354 return false;
355 int32_t n = perms1.size();
356 for (int32_t i = 0; i < n; i++)
357 if (perms2[perms1[i]] != i)
358 return false;
359 return true;
360}
361
362// Primary overload for supported elementwise operators and scalar casts.
363// The other ones handle the case of the operations that occur at the
364// roots of the data dependency graph (ConstOp, ReshapeOp, TransposeOp).
365std::optional<Value> TosaReduceTransposes::buildMappedToValue(
366 Operation *op, const DenseMap<Value, Value> &valuesMap,
367 IRRewriter &rewriter, ArrayRef<int32_t> hoistedPerms) {
368 if (op->getNumResults() != 1 || !supportsTransposePropagation(op))
369 return std::nullopt;
370
371 auto resultType = llvm::cast<RankedTensorType>(op->getResult(0).getType());
372 SmallVector<Value, 3> operands;
373 for (Value v : op->getOperands()) {
374 if (valuesMap.contains(v)) {
375 operands.push_back(valuesMap.at(v));
376 } else if (llvm::isa<tosa::MulOp>(op) && v == op->getOperand(2)) {
377 // special case for MulOp's shift operand
378 operands.push_back(v);
379 } else {
380 return std::nullopt;
381 }
382 }
383
384 // Conceptually, we propagate the hoisted TransposeOp through
385 // these interveaning operations. For example,
386
387 // %0 = tosa.clamp %input : (tensor<2x3xi32>) -> tensor<2x3xi32>
388 // %1 = tosa.transpose %0 {perms = [1, 0]} : (tensor<2x3xi32>) ->
389 // tensor<3x2xi32>
390
391 // becomes:
392 // %0 = tosa.transpose %input {perms = [1, 0]} : (tensor<2x3xi32>) ->
393 // tensor<3x2xi32>
394 // %1 = tosa.clamp %0 : (tensor<3x2xi32>) -> tensor<3x2xi32>)
395
396 // We construct this new tosa.clamp here, but it doesn't
397 // turn "live" until the transpose being hoisted through this chain
398 // is replaced with the proper value from the new chain.
399
400 Type newResultType = RankedTensorType::get(
401 applyTOSAPermutation(resultType.getShape(), hoistedPerms),
402 resultType.getElementType());
403 OperationState state(op->getLoc(), op->getName(), operands, newResultType,
404 op->getDiscardableAttrDictionary().getValue());
405 state.propertiesAttr = op->getPropertiesAsAttribute();
406 return rewriter.create(state)->getResult(0);
407}
408
409std::optional<Value> TosaReduceTransposes::buildMappedToValue(
410 TransposeOp transposeOp, const DenseMap<Value, Value> &valuesMap,
411 IRRewriter &rewriter, ArrayRef<int32_t> hoistedPerms) {
412 if (!areInvolutionTransposes(hoistedPerms, transposeOp.getPerms()))
413 return std::nullopt;
414 return transposeOp.getInput1();
415}
416
417std::optional<Value> TosaReduceTransposes::buildMappedToValue(
418 ReshapeOp reshapeOp, const DenseMap<Value, Value> &valuesMap,
419 IRRewriter &rewriter, ArrayRef<int32_t> hoistedPerms) {
420 auto reshapeOutput = reshapeOp.getOutput();
421 auto reshapeInputType =
422 llvm::dyn_cast<RankedTensorType>(reshapeOp.getInput1().getType());
423 if (!reshapeInputType)
424 return std::nullopt;
425 auto reshapeInputShape = reshapeInputType.getShape();
426 auto reshapeOutputType =
427 llvm::cast<RankedTensorType>(reshapeOutput.getType());
428 const ArrayRef<int64_t> reshapeOutputShape = reshapeOutputType.getShape();
429
430 // Instead of inserting a TransposeOp here, we check if we can fold it into
431 // the ReshapeOp. There is more complex cases where this is possible, and
432 // this check can be extended.
433 if (failed(verifyUnitExpandedVectorShape(reshapeInputShape)) ||
434 failed(verifyUnitExpandedVectorShape(reshapeOutputShape)))
435 return std::nullopt;
436
437 // Do not insert a TransposeOp, instead we fold the reshape and its attribute.
438 llvm::SmallVector<int64_t> newShape;
439 if (!tosa::getConstShapeValues(reshapeOp.getShape().getDefiningOp(),
440 newShape)) {
441 // this mean shape is not constant
442 return std::nullopt;
443 }
444 ImplicitLocOpBuilder builder(reshapeOp.getLoc(), rewriter);
445 auto foldedReshape = ReshapeOp::create(
446 rewriter, reshapeOp.getLoc(),
447 RankedTensorType::get(
448 applyTOSAPermutation(reshapeOutputShape, hoistedPerms),
449 reshapeOutputType.getElementType()),
450 reshapeOp.getInput1(),
451 getTosaConstShape(builder, applyTOSAPermutation(llvm::ArrayRef(newShape),
452 hoistedPerms)));
453 return foldedReshape->getResult(0);
454}
455
456std::optional<Value> TosaReduceTransposes::buildMappedToValue(
457 ConstOp constOp, const DenseMap<Value, Value> &valuesMap,
458 IRRewriter &rewriter, ArrayRef<int32_t> hoistedPerms) {
459 auto denseAttr = llvm::dyn_cast<DenseElementsAttr>(constOp.getValues());
460 if (!denseAttr)
461 return std::nullopt;
462 auto maybeNewDenseAttr = transposeDenseAttribute(denseAttr, hoistedPerms);
463 if (!maybeNewDenseAttr.has_value())
464 return std::nullopt;
465 auto newDenseAttr = maybeNewDenseAttr.value();
466 auto newConstOp = ConstOp::create(rewriter, constOp.getLoc(),
467 newDenseAttr.getType(), newDenseAttr);
468 return newConstOp->getResult(0);
469}
470
471bool TosaReduceTransposes::convertDependentOps(
472 SetVector<Operation *> &dependentOps, DenseMap<Value, Value> &valuesMap,
473 IRRewriter &rewriter, ArrayRef<int32_t> hoistedPerms) {
474
475 for (Operation *op : dependentOps) {
476 if (!op || op->getNumResults() != 1)
477 return false;
478
479 Value priorValue = op->getResult(0);
480
481 // It's possible on a prior transposeOp we had the same dependency and
482 // already resolved it.
483 if (valuesMap.contains(priorValue))
484 continue;
485
486 // Keep converted ops close to the original.
487 rewriter.setInsertionPointAfter(op);
488
489 std::optional<Value> maybeValue =
490 llvm::TypeSwitch<Operation *, std::optional<Value>>(op)
491 .Case<TransposeOp, ReshapeOp, ConstOp>([&](auto transposeOp) {
492 return buildMappedToValue(transposeOp, valuesMap, rewriter,
493 hoistedPerms);
494 })
495 .Default([&](Operation *op) {
496 return buildMappedToValue(op, valuesMap, rewriter, hoistedPerms);
497 });
498
499 if (!maybeValue.has_value())
500 return false;
501
502 valuesMap[priorValue] = maybeValue.value();
503 }
504
505 return true;
506}
507
508bool TosaReduceTransposes::userNotContainedInValidTransposeDependencies(
509 Operation *user, std::set<TransposeOp> &validTransposes,
510 std::vector<std::pair<TransposeOp, SetVector<Operation *>>>
511 &transposeInfo) {
512 return llvm::none_of(
513 transposeInfo,
514 [&validTransposes,
515 user](const std::pair<TransposeOp, SetVector<Operation *>> &info) {
516 const auto &[transposeOp, dependentOps] = info;
517 return validTransposes.count(transposeOp) &&
518 dependentOps.contains(user);
519 });
520}
521
522// Dependencies are valid for an operation if none of them occur outside
523// of the proper fan-in cones of the hoisted TransposeOp with the same perms
524// that we can replace. Described in more detail within.
525bool TosaReduceTransposes::dependenciesAreValid(
526 ArrayRef<int32_t> perms, const SetVector<Operation *> &dependentOps,
527 std::set<TransposeOp> &validTransposes,
528 std::vector<std::pair<TransposeOp, SetVector<Operation *>>>
529 &transposeInfo) {
530 for (Operation *op : dependentOps) {
531
532 // It's OK wherever ConstOp has uses -- in the worst case, we duplicate.
533 // This can be changed later if we find the memory impact is too high.
534 if (llvm::isa<ConstOp>(op))
535 continue;
536
537 for (OpOperand &use : op->getUses()) {
538 // Want the uses to be (1) contained in the dependentOps of other
539 // validTransposes, or (2) to be directly used in a TransposeOp with the
540 // same perms. For (2) it means the fan-in is a subset of our
541 // dependentOps, so it is also a validTranspose that will eventually be
542 // replaced.
543 Operation *user = use.getOwner();
544 if (auto otherTranspose = llvm::dyn_cast<TransposeOp>(user)) {
545 // Can later think about cases where transpose -> transpose
546 // or reshape -> transpose, where the transposes are not necessarily
547 // the same perms as the hoisted, if implementing a more general
548 // transform. These could be permitted.
549 if (!llvm::equal(perms, otherTranspose.getPerms()))
550 return false;
551 } else if (userNotContainedInValidTransposeDependencies(
552 user, validTransposes, transposeInfo)) {
553 return false;
554 }
555 }
556 }
557
558 return true;
559}
560
561// Getting the set of TransposeOp that we can replace without causing
562// the old fan-in cones of any TransposeOp to remain "live", i.e, -- not being
563// dead code. This is done by iterating the set until convergence, since
564// if you are used outside your own fan-in cone, it's possible to be used
565// in another fan-in cone of a TransposeOp that is being replaced -- unless
566// we find that that one has a usage outside of it too.
567std::set<TransposeOp> TosaReduceTransposes::getGoodReplacements(
568 ArrayRef<int32_t> perms,
569 std::vector<std::pair<TransposeOp, SetVector<Operation *>>>
570 &transposeInfo) {
571 // Initially, we assume they are all good to replace,
572 // and we whittle them down based on our criteria.
573 std::set<TransposeOp> ableToReplace;
574 for (const auto &[transposeOp, _] : transposeInfo)
575 ableToReplace.insert(transposeOp);
576
577 bool gotRid;
578 do {
579 gotRid = false;
580 for (const auto &[transposeOp, dependentOps] : transposeInfo) {
581 // We don't care about it. Already invalidated.
582 if (!ableToReplace.count(transposeOp))
583 continue;
584
585 // Check for validity.
586 if (!dependenciesAreValid(perms, dependentOps, ableToReplace,
587 transposeInfo)) {
588 ableToReplace.erase(transposeOp);
589 gotRid = true;
590 break;
591 }
592 }
593
594 } while (gotRid);
595
596 return ableToReplace;
597}
598
599void TosaReduceTransposes::runOnOperation() {
600 // We want to operate only within a single block.
601 if (!getOperation().getRegion().hasOneBlock())
602 return;
603
604 IRRewriter rewriter(&getContext());
605 // For each perms, maintain a mapping for converted ops, avoid duplication.
606 DenseMap<ArrayRef<int32_t>, DenseMap<Value, Value>> permsToValues;
607 // For each perms, we keep track of which TransposeOp are eligible
608 // for replacement alongside their dependentOps.
610 std::vector<std::pair<TransposeOp, SetVector<Operation *>>>>
611 permsToTransposeInfo;
612
613 // Necessary for lifetime, since DenseMap keeps a copy of the ArrayRef.
614 // Use SmallVector for perms (common-case is <= 4) but std::vector otherwise
615 // since no guarantee of smallness.
616 std::vector<SmallVector<int32_t>> collectedPerms;
617
618 // This keeps track of the order across all eligible-for-replacement
619 // TransposeOp and their perms, a necessity for the final replacements.
620 std::stack<std::pair<TransposeOp, ArrayRef<int32_t>>> totalTransposeOrder;
621
622 // We want to reserve the space up front, since SmallVector stores some data
623 // internally and the ArrayRef can reference that, which we don't want to get
624 // invalidated.
625 size_t expectedMaxPerms = 0;
626 getOperation().walk([&](TransposeOp) { expectedMaxPerms += 1; });
627 collectedPerms.reserve(expectedMaxPerms);
628
629 getOperation().walk([&](TransposeOp transposeOp) {
630 SetVector<Operation *> dependentOps;
631 collectedPerms.emplace_back();
632 SmallVector<int32_t> &perms = collectedPerms.back();
633
634 // Dynamic shapes are OK, but the incompatible ones will be rejected later.
635 auto input = transposeOp.getInput1();
636 auto output = transposeOp.getOutput();
637
638 // However, we don't support unranked tensors.
639 if (!llvm::isa<RankedTensorType>(input.getType()) ||
640 !llvm::isa<RankedTensorType>(output.getType()))
641 return;
642
643 llvm::append_range(perms, transposeOp.getPerms());
644
645 // We let --canonicalize deal with identity transpose.
646 if (llvm::equal(llvm::seq<int32_t>(0, perms.size()), perms))
647 return;
648
649 // Can fail if some set of basic invariants is not met that we want to
650 // perform our conversions.
651 if (!collectFanIn(input.getDefiningOp(), dependentOps))
652 return;
653
654 // Want to associate valuesMap for already converted of the same perms,
655 // since it's possible multiple hoisted transposes w/ different perms
656 // converge on an op, which would result in different transformations.
657 DenseMap<Value, Value> &valuesMap = permsToValues[perms];
658
659 // Attempt to perform the conversions and placements into IR
660 // without turning inserted code "live". Also fills out valuesMap.
661 // Fails if there is an intermediary we do not support.
662 if (!convertDependentOps(dependentOps, valuesMap, rewriter, perms))
663 // Some additional operations may have been inserted, but will be
664 // removed by dead code elimination.
665 return;
666
667 // This should not happen. If it does -- it's unexpected,
668 // so we fail the pass.
669 if (!valuesMap.contains(input))
670 return signalPassFailure();
671
672 // It's possible the types are not compatible (because of dynamic shapes),
673 // and in these cases, want to resolve dynamic shapes before running the
674 // pass.
675 if (output.getType() != valuesMap.at(input).getType())
676 return;
677
678 auto &transposeInfo = permsToTransposeInfo[perms];
679
680 // In general, we might also want to introduce "newDependentOps"
681 // if there are new usages that don't fall inside the original fan-ins
682 // (like the TransposeOp we insert for ReshapeOp),
683 // but in this case, that is specialized enough and overlaps
684 // with another direct-use TransposeOp case we need to cover anyway.
685 transposeInfo.emplace_back(transposeOp, dependentOps);
686
687 // This is for the final replacement across all transposes.
688 totalTransposeOrder.emplace(transposeOp, perms);
689 });
690
691 // We want to do a full fan-in analysis on a perms-level,
692 // since if we do it on a multi-perms level, and they share (due to a shared
693 // dependency on a Reshape) then we would also get duplicate ops.
694 // Const is special cased.
695 std::set<TransposeOp> ableToReplace;
696 for (auto &[perms, transposeInfo] : permsToTransposeInfo) {
697 // Gives us back replacements that would never result in any duplicate
698 // operations being inserted by us in the IR (i.e, our goal is only to
699 // remove transposes, and not create a "new chain" to do so, but replace
700 // the existing chains).
701 // Ideally, --canonicalize is run before this pass, since it helps this
702 // analysis by removing dead code to allow more potentially acceptable
703 // transformations.
704 auto goodReplacementsForPerms = getGoodReplacements(perms, transposeInfo);
705 ableToReplace.insert(goodReplacementsForPerms.begin(),
706 goodReplacementsForPerms.end());
707 }
708
709 // We want to do replacement across all transposes
710 // in reverse order, due to invalidation of valuesMap mappings
711 // if we did it otherwise.
712 while (!totalTransposeOrder.empty()) {
713 auto [transposeOp, perms] = totalTransposeOrder.top();
714 totalTransposeOrder.pop();
715
716 if (ableToReplace.count(transposeOp) == 0)
717 continue;
718
719 auto &valuesMap = permsToValues[perms];
720 auto input = transposeOp.getInput1();
721
722 // The purpose of this reverse iteration
723 // is to avoid valuesMap invalidation. If it happens,
724 // something is wrong.
725 if (!valuesMap.contains(input))
726 return signalPassFailure();
727
728 rewriter.replaceOp(transposeOp, valuesMap.at(input));
729 }
730
731 // We can remove all dead code by going in reverse.
732 // This is because we would remove usages before we
733 // see the users.
734 getOperation().walk<WalkOrder::PostOrder, ReverseIterator>(
735 [&](Operation *op) {
736 if (isOpTriviallyDead(op))
737 rewriter.eraseOp(op);
738 });
739}
740
741} // namespace
return success()
b getContext())
An attribute that represents a reference to a dense vector or tensor object.
static DenseElementsAttr getFromRawBuffer(ShapedType type, ArrayRef< char > rawBuffer)
Construct a dense elements attribute from a raw buffer representing the data for this attribute.
bool isSplat() const
Returns true if this attribute corresponds to a splat, i.e.
ArrayRef< char > getRawData() const
Return the raw storage data held by this attribute.
ShapedType getType() const
Return the type of this ElementsAttr, guaranteed to be a vector or tensor with static shape.
DenseElementsAttr reshape(ShapedType newType)
Return a new DenseElementsAttr that has the same data as the current attribute, but has been reshaped...
Operation * create(const OperationState &state)
Creates an operation given the fields represented as an OperationState.
Definition Builders.cpp:466
void setInsertionPointAfter(Operation *op)
Sets the insertion point to the node after the specified operation, which will cause subsequent inser...
Definition Builders.h:415
Dialect * getDialect()
Return the dialect this operation is associated with, or nullptr if the associated dialect is not loa...
Definition Operation.h:237
Value getOperand(unsigned idx)
Definition Operation.h:377
bool hasTrait()
Returns true if the operation was registered with a particular trait, e.g.
Definition Operation.h:803
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
Definition Operation.h:434
Location getLoc()
The source location the operation was defined or derived from.
Definition Operation.h:240
Attribute getPropertiesAsAttribute()
Return the properties converted to an attribute.
OperationName getName()
The name of an operation is the key identifier for it.
Definition Operation.h:115
DictionaryAttr getDiscardableAttrDictionary()
Return all of the discardable attributes on this operation as a DictionaryAttr.
Definition Operation.h:555
operand_range getOperands()
Returns an iterator on the underlying Value's.
Definition Operation.h:405
use_range getUses()
Returns a range of all uses, which is useful for iterating over all uses.
Definition Operation.h:900
unsigned getNumResults()
Return the number of results held by this operation.
Definition Operation.h:431
virtual void replaceOp(Operation *op, ValueRange newValues)
Replace the results of the given (original) operation with the specified list of values (replacements...
virtual void eraseOp(Operation *op)
This method erases an operation that is known to have no uses.
Type getType() const
Return the type of this value.
Definition Value.h:105
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
SmallVector< T > applyTOSAPermutation(ArrayRef< T > input, ArrayRef< int32_t > perms)
Value getTosaConstShape(ImplicitLocOpBuilder &builder, llvm::ArrayRef< int64_t > shape)
bool getConstShapeValues(Operation *op, llvm::SmallVector< int64_t > &result_shape)
Include the generated interface declarations.
llvm::SetVector< T, Vector, Set, N > SetVector
Definition LLVM.h:128
bool isOpTriviallyDead(Operation *op)
Return true if the given operation is unused, and has no side effects on memory that prevent erasing.
llvm::DenseMap< KeyT, ValueT, KeyInfoT, BucketT > DenseMap
Definition LLVM.h:123