23 #include "llvm/ADT/SmallVector.h"
37 template <
class SrcValType,
class TargetValType,
class TargetType>
40 const std::function<TargetValType(
const SrcValType &)> &toApply,
41 TargetType targetType) {
46 for (
auto val : toTransform.
getValues<SrcValType>()) {
47 auto transformedVal = toApply(val);
48 transformedValues.push_back(transformedVal);
52 auto inShape = toTransform.
getType();
53 auto outTy = inShape.cloneWith({}, targetType);
60 const std::function<APFloat(
const APFloat &)> &toApply,
61 FloatType targetType);
66 if (isa<FloatType>(toCheck.getType().getElementType())) {
70 "Unexpected input tensor type: the "
71 "TOSA spec only allows floats");
85 "Non-const or non-dense input tensor");
90 if (isa<ConstOp>(toCheck.getDefiningOp())) {
95 "The reciprocal can only be folded if "
96 "it operates on a TOSA constant");
103 auto floatCheck = notifyIfNotFloat(toCheck, location, rewriter);
107 return notifyIfNoTosaDenseConstantTensor(toCheck, location, rewriter);
119 assert(unaryOp->getNumOperands() == 1);
120 auto inputOp = unaryOp->getOperand(0);
123 if (isa<SplatElementsAttr>(values)) {
129 return inputOp.hasOneUse();
132 template <
typename RangeType>
134 ShapedType outputType,
136 using ElementType = std::decay_t<decltype(*std::begin(data))>;
138 assert(inputType.getElementType() == outputType.getElementType());
140 if (inputType.getNumElements() == 0)
143 auto inputShape = inputType.getShape();
151 auto initialValue = *std::begin(data);
156 auto srcLinearIndex = it.index();
158 uint64_t dstLinearIndex = 0;
159 for (int64_t dim = inputShape.size() - 1; dim >= 0; --dim) {
161 auto sourceIndexForDim = srcLinearIndex % inputShape[dim];
162 srcLinearIndex /= inputShape[dim];
167 outputStrides[invertedPermValues[dim]] * sourceIndexForDim;
170 outputValues[dstLinearIndex] = it.value();
178 template <
typename T>
179 std::optional<ArrayRef<T>> tryGetDenseResourceValues(ElementsAttr attr) {
180 if (
auto denseResource = dyn_cast<DenseResourceElementsAttr>(attr)) {
187 bool isSplat =
false;
193 return blob->template getDataAs<T>();
204 ShapedType outputType,
207 if (
auto data = attr.tryGetValues<
bool>())
208 return transposeType(*data, inputType, outputType, permValues);
210 if (
auto data = attr.tryGetValues<int8_t>())
211 return transposeType(*data, inputType, outputType, permValues);
213 if (
auto data = attr.tryGetValues<int16_t>())
214 return transposeType(*data, inputType, outputType, permValues);
216 if (
auto data = attr.tryGetValues<int32_t>())
217 return transposeType(*data, inputType, outputType, permValues);
219 if (
auto data = attr.tryGetValues<int64_t>())
220 return transposeType(*data, inputType, outputType, permValues);
222 if (
auto data = attr.tryGetValues<
float>())
223 return transposeType(*data, inputType, outputType, permValues);
225 if (
auto data = attr.tryGetValues<APFloat>())
226 return transposeType(*data, inputType, outputType, permValues);
229 if (isa<DenseResourceElementsAttr>(attr)) {
230 auto elementTy = attr.getElementType();
232 if (
auto data = tryGetDenseResourceValues<bool>(attr);
233 data && elementTy.isInteger(1))
234 return transposeType(*data, inputType, outputType, permValues);
236 if (
auto data = tryGetDenseResourceValues<int8_t>(attr);
237 data && elementTy.isInteger(8))
238 return transposeType(*data, inputType, outputType, permValues);
240 if (
auto data = tryGetDenseResourceValues<int16_t>(attr);
241 data && elementTy.isInteger(16))
242 return transposeType(*data, inputType, outputType, permValues);
244 if (
auto data = tryGetDenseResourceValues<int32_t>(attr);
245 data && elementTy.isInteger(32))
246 return transposeType(*data, inputType, outputType, permValues);
248 if (
auto data = tryGetDenseResourceValues<int64_t>(attr);
249 data && elementTy.isInteger(64))
250 return transposeType(*data, inputType, outputType, permValues);
252 if (
auto data = tryGetDenseResourceValues<float>(attr);
253 data && elementTy.isF32())
254 return transposeType(*data, inputType, outputType, permValues);
260 struct TosaFoldConstantTranspose :
public OpRewritePattern<tosa::TransposeOp> {
263 LogicalResult matchAndRewrite(tosa::TransposeOp op,
265 auto outputType = cast<ShapedType>(op.getType());
267 if (!outputType.getElementType().isIntOrIndexOrFloat())
270 ElementsAttr inputValues;
274 if (!llvm::hasSingleElement(op.getInput1().getDefiningOp()->getUsers()))
277 auto permValues = llvm::map_to_vector(
278 op.getPerms(), [](
const int32_t v) { return static_cast<int64_t>(v); });
280 auto inputType = cast<ShapedType>(op.getInput1().getType());
282 auto resultAttr = transpose(inputValues, inputType, outputType, permValues);
285 op,
"unsupported attribute or element type");
297 LogicalResult matchAndRewrite(ReciprocalOp recip,
299 auto inputTensor = recip.getInput1();
303 notifyIfNotConstantFloatTosaTensor(inputTensor, recip, rewriter);
304 if (
failed(preCondCheck)) {
313 if (!constantUnaryOpShouldBeFolded(recip, inputValues)) {
315 recip,
"Currently, reciprocals will only be folded if the input "
316 "tensor has a single user");
320 auto newTensor = applyElementWise<APFloat, APFloat, FloatType>(
321 inputValues, &ReciprocalOp::calcOneElement,
335 int64_t remaining = index;
337 for (int64_t i = tensorShape.size() - 1; i >= 0; --i) {
338 position[i] = remaining % tensorShape[i];
339 remaining /= tensorShape[i];
350 int64_t multiplierTmp = 1;
351 for (int64_t i = position.size() - 1; i >= 0; --i) {
352 index += position[i] * multiplierTmp;
353 multiplierTmp *= tensorShape[i];
358 template <
typename OperationType>
359 llvm::APInt calculateReducedValue(
const mlir::ElementsAttr &oldTensorAttr,
361 int64_t reductionAxis,
362 int64_t reductionIndex) {
365 newShape[reductionAxis] = 1;
368 getPositionFromIndex(reductionIndex, newShape);
369 auto oldTensor = oldTensorAttr.getValues<llvm::APInt>();
371 position[reductionAxis] = 0;
372 int64_t indexAtOldTensor = getIndexFromPosition(position, oldShape);
373 llvm::APInt reducedValue = oldTensor[indexAtOldTensor];
375 for (int64_t reductionAxisVal = 1; reductionAxisVal < oldShape[reductionAxis];
376 ++reductionAxisVal) {
378 int64_t stride = std::accumulate(oldShape.begin() + reductionAxis + 1,
379 oldShape.end(), 1, std::multiplies<int>());
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 auto newNumOfElements = std::accumulate(newShape.begin(), newShape.end(), 1,
428 std::multiplies<int>());
431 for (int64_t reductionIndex = 0; reductionIndex < newNumOfElements;
435 newReducedTensor[reductionIndex] = calculateReducedValue<OperationType>(
436 denseElementsAttr, oldShape, reductionAxis, reductionIndex);
439 auto rankedTensorType = cast<RankedTensorType>(resultType);
445 const bool aggressiveReduceConstant;
452 bool aggressiveReduceConstant) {
453 patterns.add<ReduceConstantOptimization<ReduceAllOp>>(
454 ctx, aggressiveReduceConstant);
455 patterns.add<ReduceConstantOptimization<ReduceAnyOp>>(
456 ctx, aggressiveReduceConstant);
457 patterns.add<ReduceConstantOptimization<ReduceMaxOp>>(
458 ctx, aggressiveReduceConstant);
459 patterns.add<ReduceConstantOptimization<ReduceMinOp>>(
460 ctx, aggressiveReduceConstant);
461 patterns.add<ReduceConstantOptimization<ReduceProductOp>>(
462 ctx, aggressiveReduceConstant);
463 patterns.add<ReduceConstantOptimization<ReduceSumOp>>(
464 ctx, aggressiveReduceConstant);
469 patterns.add<TosaFoldConstantTranspose>(ctx);
474 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...