23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/SmallVector.h"
38 template <
class SrcValType,
class TargetValType,
class TargetType>
41 const std::function<TargetValType(
const SrcValType &)> &toApply,
42 TargetType targetType) {
47 for (
auto val : toTransform.
getValues<SrcValType>()) {
48 auto transformedVal = toApply(val);
49 transformedValues.push_back(transformedVal);
53 auto inShape = toTransform.
getType();
54 auto outTy = inShape.cloneWith({}, targetType);
61 const std::function<APFloat(
const APFloat &)> &toApply,
62 FloatType targetType);
67 if (isa<FloatType>(toCheck.getType().getElementType())) {
71 "Unexpected input tensor type: the "
72 "TOSA spec only allows floats");
86 "Non-const or non-dense input tensor");
91 if (isa<ConstOp>(toCheck.getDefiningOp())) {
96 "The reciprocal can only be folded if "
97 "it operates on a TOSA constant");
104 auto floatCheck = notifyIfNotFloat(toCheck, location, rewriter);
108 return notifyIfNoTosaDenseConstantTensor(toCheck, location, rewriter);
120 assert(unaryOp->getNumOperands() == 1);
121 auto inputOp = unaryOp->getOperand(0);
124 if (isa<SplatElementsAttr>(values)) {
130 return inputOp.hasOneUse();
133 template <
typename RangeType>
135 ShapedType outputType,
137 using ElementType = std::decay_t<decltype(*std::begin(data))>;
139 assert(inputType.getElementType() == outputType.getElementType());
141 if (inputType.getNumElements() == 0)
144 auto inputShape = inputType.getShape();
152 auto initialValue = *std::begin(data);
157 auto srcLinearIndex = it.index();
159 uint64_t dstLinearIndex = 0;
160 for (int64_t dim = inputShape.size() - 1; dim >= 0; --dim) {
162 auto sourceIndexForDim = srcLinearIndex % inputShape[dim];
163 srcLinearIndex /= inputShape[dim];
168 outputStrides[invertedPermValues[dim]] * sourceIndexForDim;
171 outputValues[dstLinearIndex] = it.value();
179 template <
typename T>
180 std::optional<ArrayRef<T>> tryGetDenseResourceValues(ElementsAttr attr) {
181 if (
auto denseResource = dyn_cast<DenseResourceElementsAttr>(attr)) {
188 bool isSplat =
false;
194 return blob->template getDataAs<T>();
205 ShapedType outputType,
208 if (
auto data = attr.tryGetValues<
bool>())
209 return transposeType(*data, inputType, outputType, permValues);
211 if (
auto data = attr.tryGetValues<int8_t>())
212 return transposeType(*data, inputType, outputType, permValues);
214 if (
auto data = attr.tryGetValues<int16_t>())
215 return transposeType(*data, inputType, outputType, permValues);
217 if (
auto data = attr.tryGetValues<int32_t>())
218 return transposeType(*data, inputType, outputType, permValues);
220 if (
auto data = attr.tryGetValues<int64_t>())
221 return transposeType(*data, inputType, outputType, permValues);
223 if (
auto data = attr.tryGetValues<
float>())
224 return transposeType(*data, inputType, outputType, permValues);
226 if (
auto data = attr.tryGetValues<APFloat>())
227 return transposeType(*data, inputType, outputType, permValues);
230 if (isa<DenseResourceElementsAttr>(attr)) {
231 auto elementTy = attr.getElementType();
233 if (
auto data = tryGetDenseResourceValues<bool>(attr);
234 data && elementTy.isInteger(1))
235 return transposeType(*data, inputType, outputType, permValues);
237 if (
auto data = tryGetDenseResourceValues<int8_t>(attr);
238 data && elementTy.isInteger(8))
239 return transposeType(*data, inputType, outputType, permValues);
241 if (
auto data = tryGetDenseResourceValues<int16_t>(attr);
242 data && elementTy.isInteger(16))
243 return transposeType(*data, inputType, outputType, permValues);
245 if (
auto data = tryGetDenseResourceValues<int32_t>(attr);
246 data && elementTy.isInteger(32))
247 return transposeType(*data, inputType, outputType, permValues);
249 if (
auto data = tryGetDenseResourceValues<int64_t>(attr);
250 data && elementTy.isInteger(64))
251 return transposeType(*data, inputType, outputType, permValues);
253 if (
auto data = tryGetDenseResourceValues<float>(attr);
254 data && elementTy.isF32())
255 return transposeType(*data, inputType, outputType, permValues);
261 struct TosaFoldConstantTranspose :
public OpRewritePattern<tosa::TransposeOp> {
264 LogicalResult matchAndRewrite(tosa::TransposeOp op,
266 auto outputType = cast<ShapedType>(op.getType());
268 if (!outputType.getElementType().isIntOrIndexOrFloat())
271 ElementsAttr inputValues;
275 if (!llvm::hasSingleElement(op.getInput1().getDefiningOp()->getUsers()))
278 auto permValues = llvm::map_to_vector(
279 op.getPerms(), [](
const int32_t v) { return static_cast<int64_t>(v); });
281 auto inputType = cast<ShapedType>(op.getInput1().getType());
283 auto resultAttr = transpose(inputValues, inputType, outputType, permValues);
286 op,
"unsupported attribute or element type");
298 LogicalResult matchAndRewrite(ReciprocalOp recip,
300 auto inputTensor = recip.getInput1();
304 notifyIfNotConstantFloatTosaTensor(inputTensor, recip, rewriter);
305 if (
failed(preCondCheck)) {
314 if (!constantUnaryOpShouldBeFolded(recip, inputValues)) {
316 recip,
"Currently, reciprocals will only be folded if the input "
317 "tensor has a single user");
321 auto newTensor = applyElementWise<APFloat, APFloat, FloatType>(
322 inputValues, &ReciprocalOp::calcOneElement,
336 int64_t remaining = index;
338 for (int64_t i = tensorShape.size() - 1; i >= 0; --i) {
339 position[i] = remaining % tensorShape[i];
340 remaining /= tensorShape[i];
351 int64_t multiplierTmp = 1;
352 for (int64_t i = position.size() - 1; i >= 0; --i) {
353 index += position[i] * multiplierTmp;
354 multiplierTmp *= tensorShape[i];
359 template <
typename OperationType>
360 llvm::APInt calculateReducedValue(
const mlir::ElementsAttr &oldTensorAttr,
362 int64_t reductionAxis,
363 int64_t reductionIndex) {
366 newShape[reductionAxis] = 1;
369 getPositionFromIndex(reductionIndex, newShape);
370 auto oldTensor = oldTensorAttr.getValues<llvm::APInt>();
372 position[reductionAxis] = 0;
373 int64_t indexAtOldTensor = getIndexFromPosition(position, oldShape);
374 llvm::APInt reducedValue = oldTensor[indexAtOldTensor];
376 for (int64_t reductionAxisVal = 1; reductionAxisVal < oldShape[reductionAxis];
377 ++reductionAxisVal) {
379 int64_t stride = llvm::product_of(oldShape.drop_front(reductionAxis + 1));
380 int64_t index = indexAtOldTensor + stride * reductionAxisVal;
382 OperationType::calcOneElement(reducedValue, oldTensor[index]);
387 template <
typename OperationType>
388 struct ReduceConstantOptimization :
public OpRewritePattern<OperationType> {
391 bool aggressiveReduceConstant)
393 aggressiveReduceConstant(aggressiveReduceConstant) {}
397 LogicalResult matchAndRewrite(OperationType op,
399 Value inputOp = op.getInput();
404 op,
"reduce input must be const operation");
406 if (!inputOp.
hasOneUse() && !this->aggressiveReduceConstant)
408 op,
"input operation has more than one user");
410 auto resultType = cast<ShapedType>(op.getOutput().getType());
412 if (!resultType.hasStaticShape())
415 auto reductionAxis = op.getAxis();
416 const auto denseElementsAttr = constOp.getValues();
417 const auto shapedOldElementsValues =
418 cast<ShapedType>(denseElementsAttr.getType());
420 if (!llvm::isa<IntegerType>(shapedOldElementsValues.getElementType()))
422 op,
"reduce input currently supported with integer type");
424 auto oldShape = shapedOldElementsValues.getShape();
425 auto newShape = resultType.getShape();
427 int64_t newNumOfElements = llvm::product_of(newShape);
430 for (int64_t reductionIndex = 0; reductionIndex < newNumOfElements;
434 newReducedTensor[reductionIndex] = calculateReducedValue<OperationType>(
435 denseElementsAttr, oldShape, reductionAxis, reductionIndex);
438 auto rankedTensorType = cast<RankedTensorType>(resultType);
444 const bool aggressiveReduceConstant;
451 bool aggressiveReduceConstant) {
452 patterns.add<ReduceConstantOptimization<ReduceAllOp>>(
453 ctx, aggressiveReduceConstant);
454 patterns.add<ReduceConstantOptimization<ReduceAnyOp>>(
455 ctx, aggressiveReduceConstant);
456 patterns.add<ReduceConstantOptimization<ReduceMaxOp>>(
457 ctx, aggressiveReduceConstant);
458 patterns.add<ReduceConstantOptimization<ReduceMinOp>>(
459 ctx, aggressiveReduceConstant);
460 patterns.add<ReduceConstantOptimization<ReduceProductOp>>(
461 ctx, aggressiveReduceConstant);
462 patterns.add<ReduceConstantOptimization<ReduceSumOp>>(
463 ctx, aggressiveReduceConstant);
468 patterns.add<TosaFoldConstantTranspose>(ctx);
473 patterns.add<TosaFoldConstantReciprocal>(ctx);
This class represents a processed binary blob of data.
ArrayRef< char > getData() const
Return the raw underlying data of this blob.
An attribute that represents a reference to a dense vector or tensor object.
auto getValues() const
Return the held element values as a range of the given type.
int64_t getNumElements() const
Returns the number of elements held by this attribute.
Type getElementType() const
Return the element type of this DenseElementsAttr.
static DenseElementsAttr get(ShapedType type, ArrayRef< Attribute > values)
Constructs a dense elements attribute from an array of element values.
ShapedType getType() const
Return the type of this ElementsAttr, guaranteed to be a vector or tensor with static shape.
static bool isValidRawBuffer(ShapedType type, ArrayRef< char > rawBuffer, bool &detectedSplat)
Returns true if the given buffer is a valid raw buffer for the given type.
MLIRContext is the top-level object for a collection of MLIR operations.
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
std::enable_if_t<!std::is_convertible< CallbackT, Twine >::value, LogicalResult > notifyMatchFailure(Location loc, CallbackT &&reasonCallback)
Used to notify the listener that the IR failed to be rewritten because of a match failure,...
OpTy replaceOpWithNewOp(Operation *op, Args &&...args)
Replace the results of the given (original) op with a new op that is created without verification (re...
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
bool hasOneUse() const
Returns true if this value has exactly one use.
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
constexpr void enumerate(std::tuple< Tys... > &tuple, CallbackT &&callback)
void populateTosaConstantReduction(MLIRContext *ctx, RewritePatternSet &patterns, bool aggressiveReduceConstant)
void populateTosaFoldConstantReciprocalPatterns(MLIRContext *ctx, RewritePatternSet &patterns)
void populateTosaFoldConstantTransposePatterns(MLIRContext *ctx, RewritePatternSet &patterns)
Include the generated interface declarations.
bool matchPattern(Value value, const Pattern &pattern)
Entry point for matching a pattern over a Value.
std::conditional_t< std::is_same_v< Ty, mlir::Type >, mlir::Value, detail::TypedValue< Ty > > TypedValue
If Ty is mlir::Type this will select Value instead of having a wrapper around it.
SmallVector< int64_t > computeStrides(ArrayRef< int64_t > sizes)
const FrozenRewritePatternSet & patterns
detail::constant_op_matcher m_Constant()
Matches a constant foldable operation.
SmallVector< int64_t > invertPermutationVector(ArrayRef< int64_t > permutation)
Helper method to apply to inverse a permutation.
OpRewritePattern is a wrapper around RewritePattern that allows for matching and rewriting against an...
OpRewritePattern(MLIRContext *context, PatternBenefit benefit=1, ArrayRef< StringRef > generatedNames={})
Patterns must specify the root operation name they match against, and can also specify the benefit of...