41 llvm_unreachable(
"Unsupported overhead bitwidth");
47 if (
auto intTp = dyn_cast<IntegerType>(tp))
49 llvm_unreachable(
"Unknown overhead type");
65 llvm_unreachable(
"Unknown OverheadType");
90#define CASE(ONAME, O) \
91 case OverheadType::kU##ONAME: \
96 llvm_unreachable(
"Unknown OverheadType");
120 if (
auto complexTp = dyn_cast<ComplexType>(elemTp)) {
121 auto complexEltTp = complexTp.getElementType();
122 if (complexEltTp.isF64())
124 if (complexEltTp.isF32())
127 llvm_unreachable(
"Unknown primary type");
132#define CASE(VNAME, V) \
133 case PrimaryType::k##VNAME: \
138 llvm_unreachable(
"Unknown PrimaryType");
156 if (isa<IndexType>(srcTp) || isa<IndexType>(dstTp))
157 return arith::IndexCastOp::create(builder, loc, dstTp, value);
159 const auto srcIntTp = dyn_cast_or_null<IntegerType>(srcTp);
160 const bool isUnsignedCast = srcIntTp ? srcIntTp.isUnsigned() :
false;
166 if (
auto rtp = dyn_cast<RankedTensorType>(dstTp)) {
168 assert(rtp.getRank() == 0);
170 return tensor::FromElementsOp::create(builder, loc, rtp, elem);
177 Value load = memref::LoadOp::create(builder, loc, mem, s);
178 if (!isa<IndexType>(
load.getType())) {
179 if (
load.getType().getIntOrFloatBitWidth() < 64)
188 if (isa<FloatType>(tp))
190 if (isa<IndexType>(tp))
192 if (
auto intTp = dyn_cast<IntegerType>(tp))
194 if (isa<RankedTensorType, VectorType>(tp)) {
195 auto shapedTp = cast<ShapedType>(tp);
196 if (
auto one =
getOneAttr(builder, shapedTp.getElementType()))
199 llvm_unreachable(
"Unsupported attribute type");
206 if (isa<FloatType>(tp))
207 return arith::CmpFOp::create(builder, loc, arith::CmpFPredicate::UNE, v,
210 return arith::CmpIOp::create(builder, loc, arith::CmpIPredicate::ne, v,
212 if (isa<ComplexType>(tp))
213 return complex::NotEqualOp::create(builder, loc, v, zero);
214 llvm_unreachable(
"Non-numeric type");
222 if (reassociation.size() < srcShape.size()) {
224 for (
const auto &map : llvm::enumerate(reassociation)) {
226 for (
unsigned i = start; i < start + map.value().size(); i++) {
227 dstDim = arith::MulIOp::create(builder, loc, dstDim, srcShape[i]);
229 dstShape.push_back(dstDim);
230 start = start + map.value().size();
232 assert(start == srcShape.size());
237 assert(reassociation.size() == srcShape.size());
240 for (
unsigned i = 0, size = srcShape.size(); i < size; i++) {
241 const auto &map = reassociation[i];
242 auto srcDim = srcShape[i];
244 for (
unsigned j = start;
j < start + map.size();
j++) {
249 if (staticDstShape[
j] == ShapedType::kDynamic) {
253 for (
unsigned k = start; k < start + map.size(); k++) {
254 if (staticDstShape[k] != ShapedType::kDynamic) {
261 arith::DivUIOp::create(builder, loc, srcDim, productVal);
262 dstShape.push_back(dynamicSize);
265 dstShape.push_back(
constantIndex(builder, loc, staticDstShape[
j]));
268 start = start + map.size();
270 assert(start == staticDstShape.size());
278 const unsigned srcRank = srcSizes.size();
279 const unsigned dstRank = dstSizes.size();
280 assert(srcRank == srcCvs.size() &&
"Source rank mismatch");
281 const bool isCollapse = srcRank > dstRank;
282 const ValueRange sizes = isCollapse ? srcSizes : dstSizes;
286 for (
const auto &map : llvm::enumerate(reassociation)) {
289 for (
unsigned j = start, end = start + map.value().size();
j < end;
j++) {
290 linear = arith::MulIOp::create(builder, loc, linear, sizes[
j]);
297 for (
unsigned j = start, end = start + map.value().size();
j < end;
j++) {
298 linear = arith::DivUIOp::create(builder, loc, linear, sizes[
j]);
301 arith::MulIOp::create(builder, loc, srcCvs[
j], linear);
302 val = val ? arith::AddIOp::create(builder, loc, val,
mul) :
mul;
304 const Value old = val;
305 val = arith::DivUIOp::create(builder, loc, val, linear);
306 assert(dstCvs.size() ==
j);
307 dstCvs.push_back(val);
308 val = arith::RemUIOp::create(builder, loc, old, linear);
313 assert(dstCvs.size() == i);
314 dstCvs.push_back(val);
316 start += map.value().size();
319 assert(dstCvs.size() == dstRank);
327 auto result = SymbolRefAttr::get(context, name);
328 auto func =
module.lookupSymbol<func::FuncOp>(result.getAttr());
330 OpBuilder moduleBuilder(module.getBodyRegion());
331 func = func::FuncOp::create(
332 moduleBuilder, module.getLoc(), name,
333 FunctionType::get(context, operands.
getTypes(), resultType));
335 if (
static_cast<bool>(emitCInterface))
336 func->setDiscardableAttr(LLVM::LLVMDialect::getEmitCWrapperAttrName(),
337 UnitAttr::get(context));
345 auto module = builder.getBlock()->getParentOp()->getParentOfType<ModuleOp>();
347 getFunc(module, name, resultType, operands, emitCInterface);
348 return func::CallOp::create(builder, loc, resultType, fn, operands);
352 return LLVM::LLVMPointerType::get(ctx);
360 unsigned sz,
Type tp,
bool staticShape) {
362 auto memTp = MemRefType::get({sz}, tp);
363 return memref::AllocaOp::create(builder, loc, memTp);
370 auto memTp = MemRefType::get({ShapedType::kDynamic}, tp);
371 return memref::AllocaOp::create(builder, loc, memTp,
ValueRange{sz});
376 return memref::AllocaOp::create(builder, loc, MemRefType::get({}, tp));
381 const unsigned sz = values.size();
384 for (
unsigned i = 0; i < sz; i++) {
386 memref::StoreOp::create(builder, loc, values[i], buffer, idx);
392 RankedTensorType tensorTp,
394 Type elemTp = tensorTp.getElementType();
395 auto shape = tensorTp.getShape();
396 auto memTp = MemRefType::get(
shape, elemTp);
398 for (
unsigned i = 0, rank = tensorTp.getRank(); i < rank; i++) {
399 if (
shape[i] == ShapedType::kDynamic)
400 dynamicSizes.push_back(sizes[i]);
402 Value mem = memref::AllocOp::create(builder, loc, memTp, dynamicSizes);
410 memref::DeallocOp::create(builder, loc, buffer);
422 for (; isa<scf::ForOp, scf::WhileOp, scf::ParallelOp, scf::IfOp>(
436 const Dimension dimRank = stt.getDimRank();
437 const auto coordinates = attr.getIndices().getValues<IntegerAttr>();
438 const auto values = attr.getValues().getValues<
Attribute>();
445 using ElementAttr = std::pair<SmallVector<IntegerAttr>,
Attribute>;
449 for (
size_t i = 0, nse = values.size(); i < nse; i++) {
450 elems.emplace_back();
451 elems.back().second = values[i];
452 auto &coords = elems.back().first;
453 coords.reserve(dimRank);
455 coords.push_back(coordinates[i * dimRank + d]);
459 llvm::sort(elems, [order](
const ElementAttr &lhs,
const ElementAttr &rhs) {
460 if (std::addressof(lhs) == std::addressof(rhs))
463 auto lhsCoords = llvm::map_to_vector(
464 lhs.first, [](IntegerAttr i) { return i.getInt(); });
465 auto rhsCoords = llvm::map_to_vector(
466 rhs.first, [](IntegerAttr i) { return i.getInt(); });
472 if (lhsLvlCrds[l] == rhsLvlCrds[l])
474 return lhsLvlCrds[l] < rhsLvlCrds[l];
476 llvm_unreachable(
"no equal coordinate in sparse element attr");
480 cvs.reserve(dimRank);
481 for (
size_t i = 0, nse = values.size(); i < nse; i++) {
484 for (
Dimension d = 0; d < dimRank; d++) {
485 auto crd = elems[i].first[d].getInt();
490 if (isa<ComplexType>(attr.getElementType())) {
491 auto valAttr = cast<ArrayAttr>(elems[i].second);
492 val = complex::ConstantOp::create(builder, loc, attr.getElementType(),
495 auto valAttr = cast<TypedAttr>(elems[i].second);
496 val = arith::ConstantOp::create(builder, loc, valAttr);
504 size_t size,
Value mem,
505 size_t offsetIdx,
Value offsetVal) {
507 const auto memTp = cast<MemRefType>(mem.
getType());
508 assert(memTp.getRank() == 1);
509 const Size memSh = memTp.getDimSize(0);
510 assert(ShapedType::isDynamic(memSh) || memSh >=
static_cast<Size>(size));
511 assert(offsetIdx == 0 || offsetIdx < size);
515 for (
unsigned i = 0; i < size; i++) {
516 Value v = memref::LoadOp::create(builder, loc, mem,
518 if (i == offsetIdx && offsetVal)
519 v = arith::AddIOp::create(builder, loc, v, offsetVal);
528 const size_t vsize = vs.size();
529 const auto memTp = cast<MemRefType>(mem.
getType());
530 assert(memTp.getRank() == 1);
531 const Size memSh = memTp.getDimSize(0);
532 assert(ShapedType::isDynamic(memSh) || memSh >=
static_cast<Size>(vsize));
533 assert(offsetIdx == 0 || offsetIdx < vsize);
535 for (
const auto &v : llvm::enumerate(vs)) {
537 (offsetIdx == v.index() && offsetVal)
538 ? arith::AddIOp::create(builder, loc, v.value(), offsetVal)
540 memref::StoreOp::create(builder, loc, w, mem,
547 auto tTp = llvm::cast<TensorType>(
tensor.getType());
548 auto mTp = MemRefType::get(tTp.getShape(), tTp.getElementType());
549 return cast<TypedValue<BaseMemRefType>>(
550 bufferization::ToBufferOp::create(builder, loc, mTp,
tensor).getResult());
556 assert(enc && enc.isSlice());
557 std::optional<unsigned> offset = enc.getStaticDimSliceOffset(dim);
558 if (offset.has_value())
560 return ToSliceOffsetOp::create(builder, loc,
tensor, APInt(64, dim));
566 assert(enc && enc.isSlice());
567 std::optional<unsigned> stride = enc.getStaticDimSliceStride(dim);
568 if (stride.has_value())
570 return ToSliceStrideOp::create(builder, loc,
tensor, APInt(64, dim));
576 Value &dimSizesBuffer) {
580 dimSizesValues.clear();
581 dimSizesValues.reserve(dimRank);
583 const auto s = ShapedType::isDynamic(sz) ? 0 : sz;
594 createFuncCall(builder, loc,
"createCheckedSparseTensorReader", opaqueTp,
600 dimSizesBuffer = dimShapesBuffer;
603 auto memTp = MemRefType::get({ShapedType::kDynamic}, indexTp);
605 createFuncCall(builder, loc,
"getSparseTensorReaderDimSizes", memTp,
610 for (
Dimension d = 0; d < dimRank; d++) {
612 dimSizesValues[d] = memref::LoadOp::create(
613 builder, loc, dimSizesBuffer,
constantIndex(builder, loc, d));
623 Value &dim2lvlBuffer,
624 Value &lvl2dimBuffer) {
627 lvlSizesValues.clear();
628 lvlSizesValues.reserve(lvlRank);
633 assert(dimRank == lvlRank);
635 iotaValues.reserve(lvlRank);
636 for (
Level l = 0; l < lvlRank; l++) {
638 lvlSizesValues.push_back(dimSizesValues[l]);
640 dim2lvlBuffer = lvl2dimBuffer =
allocaBuffer(builder, loc, iotaValues);
641 return dimSizesBuffer;
651 assert(lvlRank == dimToLvl.getNumResults());
652 for (
Level l = 0; l < lvlRank; l++) {
659 uint64_t
cf = 0, cm = 0;
662 d = cast<AffineDimExpr>(exp).getPosition();
666 auto floor = cast<AffineBinaryOpExpr>(exp);
667 d = cast<AffineDimExpr>(floor.getLHS()).getPosition();
668 cf = cast<AffineConstantExpr>(floor.getRHS()).getValue();
672 auto mod = cast<AffineBinaryOpExpr>(exp);
673 d = cast<AffineDimExpr>(mod.getLHS()).getPosition();
674 cm = cast<AffineConstantExpr>(mod.getRHS()).getValue();
678 llvm::report_fatal_error(
"unsupported dim2lvl in sparse tensor type");
687 lvlSz = dimSizesValues[d];
689 lvlSz = arith::DivUIOp::create(builder, loc, lvlSz,
694 lvlSizesValues.push_back(lvlSz);
697 assert(dimRank == lvlToDim.getNumResults());
698 for (
Dimension d = 0; d < dimRank; d++) {
707 l = cast<AffineDimExpr>(exp).getPosition();
712 auto add = cast<AffineBinaryOpExpr>(exp);
714 auto mul = cast<AffineBinaryOpExpr>(
add.getLHS());
715 ll = cast<AffineDimExpr>(
mul.getLHS()).getPosition();
716 c = cast<AffineConstantExpr>(
mul.getRHS()).getValue();
717 l = cast<AffineDimExpr>(
add.getRHS()).getPosition();
721 llvm::report_fatal_error(
"unsupported lvl2dim in sparse tensor type");
726 dim2lvlBuffer =
allocaBuffer(builder, loc, dim2lvlValues);
727 lvl2dimBuffer =
allocaBuffer(builder, loc, lvl2dimValues);
#define MLIR_SPARSETENSOR_FOREVERY_FIXED_O(DO)
#define MLIR_SPARSETENSOR_FOREVERY_V(DO)
static int64_t product(ArrayRef< int64_t > vals)
Base type for affine expression.
AffineExprKind getKind() const
Return the classification for this type.
A multi-dimensional affine map Affine map's are immutable like Type's, and they are uniqued.
unsigned getNumResults() const
AffineMap compose(AffineMap map) const
Returns the AffineMap resulting from composing this with map.
Attributes are known-constant values of operations.
This class is a general helper class for creating context-global objects like types,...
IntegerAttr getIndexAttr(int64_t value)
IntegerAttr getIntegerAttr(Type type, int64_t value)
AffineMap getMultiDimIdentityMap(unsigned rank)
FloatAttr getFloatAttr(Type type, double value)
IntegerType getIntegerType(unsigned width)
MLIRContext * getContext() const
static DenseElementsAttr get(ShapedType type, ArrayRef< Attribute > values)
Constructs a dense elements attribute from an array of element values.
A symbol reference with a reference path containing a single element.
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.
Operation is the basic unit of execution within MLIR.
Operation * getParentOp()
Returns the closest surrounding operation that contains this operation or nullptr if this is a top-le...
This class provides an abstraction over the various different ranges of value types.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
bool isIntOrIndex() const
Return true if this is an integer (of any signedness) or an index type.
bool isInteger() const
Return true if this is an integer type (with the specified width).
This class provides an abstraction over the different types of ranges over Values.
type_range getTypes() const
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Type getType() const
Return the type of this value.
static ConstantIndexOp create(OpBuilder &builder, Location location, int64_t value)
A wrapper around RankedTensorType, which has three goals:
Type getElementType() const
Dimension getDimRank() const
Returns the dimension-rank.
AffineMap getLvlToDim() const
Returns the lvlToDiml mapping (or the null-map for the identity).
bool isIdentity() const
Returns true if the dimToLvl mapping is the identity.
bool hasDynamicDimShape() const
Returns true if any dimension has dynamic size.
ArrayRef< Size > getDimShape() const
Returns the dimension-shape.
Level getLvlRank() const
Returns the level-rank.
bool isDynamicDim(Dimension d) const
Returns true if the given dimension has dynamic size.
AffineMap getDimToLvl() const
Returns the dimToLvl mapping (or the null-map for the identity).
Value createOrFoldDimOp(OpBuilder &b, Location loc, Value val, int64_t dim)
Create one memref::DimOp or tensor::DimOp depending on the type of val.
TypedAttr getOneAttr(Builder &builder, Type tp)
Generates a 1-valued attribute of the given type.
FlatSymbolRefAttr getFunc(ModuleOp module, StringRef name, TypeRange resultType, ValueRange operands, EmitCInterface emitCInterface)
Returns a function reference (first hit also inserts into module).
Value genAllocaScalar(OpBuilder &builder, Location loc, Type tp)
Generates an uninitialized temporary buffer with room for one value of the given type,...
Value constantIndex(OpBuilder &builder, Location loc, int64_t i)
Generates a constant of index type.
void foreachInSparseConstant(OpBuilder &builder, Location loc, SparseElementsAttr attr, AffineMap order, function_ref< void(ArrayRef< Value >, Value)> callback)
Iterate over a sparse constant, generates constantOp for value and coordinates.
Value constantZero(OpBuilder &builder, Location loc, Type tp)
Generates a 0-valued constant of the given type.
uint64_t Dimension
The type of dimension identifiers and dimension-ranks.
Value allocaBuffer(OpBuilder &builder, Location loc, ValueRange values)
Generates a temporary buffer, initializes it with the given contents, and returns it as type memref<?
OverheadType posTypeEncoding(SparseTensorEncodingAttr enc)
Returns the OverheadType for position overhead storage.
OverheadType
Encoding of overhead types (both position overhead and coordinate overhead), for "overloading" @newSp...
OverheadType crdTypeEncoding(SparseTensorEncodingAttr enc)
Returns the OverheadType for coordinate overhead storage.
TypedValue< BaseMemRefType > genToMemref(OpBuilder &builder, Location loc, Value tensor)
OverheadType overheadTypeEncoding(unsigned width)
Converts an overhead storage bitwidth to its internal type-encoding.
Value genIndexLoad(OpBuilder &builder, Location loc, Value mem, ValueRange s)
Generates a pointer/index load from the sparse storage scheme.
StringRef overheadTypeFunctionSuffix(OverheadType ot)
Convert OverheadType to its function-name suffix.
PrimaryType
Encoding of the elemental type, for "overloading" @newSparseTensor.
RankedTensorType getRankedTensorType(T &&t)
Convenience method to abbreviate casting getType().
uint64_t Level
The type of level identifiers and level-ranks.
PrimaryType primaryTypeEncoding(Type elemTp)
Converts a primary storage type to its internal type-encoding.
Operation * getTop(Operation *op)
Scans to top of generated loop.
Value createOrFoldSliceStrideOp(OpBuilder &builder, Location loc, Value tensor, Dimension dim)
Generates code to retrieve the slice slice for the sparse tensor slice, return a constant if the offs...
Type getOpaquePointerType(MLIRContext *ctx)
Returns the equivalent of void* for opaque arguments to the execution engine.
SparseTensorEncodingAttr getSparseTensorEncoding(Type type)
Convenience method to get a sparse encoding attribute from a type.
Value genMapBuffers(OpBuilder &builder, Location loc, SparseTensorType stt, ArrayRef< Value > dimSizesValues, Value dimSizesBuffer, SmallVectorImpl< Value > &lvlSizesValues, Value &dim2lvlBuffer, Value &lvl2dimBuffer)
Generates code to set up the buffer parameters for a map.
Value genIsNonzero(OpBuilder &builder, Location loc, Value v)
Generates the comparison v != 0 where v is of numeric type.
Value genReader(OpBuilder &builder, Location loc, SparseTensorType stt, Value tensor, SmallVectorImpl< Value > &dimSizesValues, Value &dimSizesBuffer)
Generates code that opens a reader and sets the dimension sizes.
Value genScalarToTensor(OpBuilder &builder, Location loc, Value elem, Type dstTp)
Add conversion from scalar to given type (possibly a 0-rank tensor).
void deallocDenseTensor(OpBuilder &builder, Location loc, Value buffer)
Generates code to deallocate a dense buffer.
Value genAlloca(OpBuilder &builder, Location loc, Value sz, Type tp)
Generates an uninitialized temporary buffer of the given size and type, but returns it as type memref...
constexpr uint64_t encodeLvl(uint64_t i, uint64_t c, uint64_t ii)
SmallVector< Value > loadAll(OpBuilder &builder, Location loc, size_t size, Value mem, size_t offsetIdx=0, Value offsetVal=Value())
Loads size-many values from the memref, which must have rank-1 and size greater-or-equal to size.
int64_t Size
The type for individual components of a compile-time shape, including the value ShapedType::kDynamic ...
constexpr uint64_t encodeDim(uint64_t i, uint64_t cf, uint64_t cm)
Bit manipulations for affine encoding.
void genReshapeDstShape(OpBuilder &builder, Location loc, SmallVectorImpl< Value > &dstShape, ArrayRef< Value > srcShape, ArrayRef< Size > staticDstShape, ArrayRef< ReassociationIndices > reassociation)
Computes the shape of destination tensor of a reshape operator.
SparseTensorType getSparseTensorType(Value val)
Convenience methods to obtain a SparseTensorType from a Value.
void reshapeCvs(OpBuilder &builder, Location loc, ArrayRef< ReassociationIndices > reassociation, ValueRange srcSizes, ValueRange srcCvs, ValueRange dstSizes, SmallVectorImpl< Value > &dstCvs)
Reshape coordinates during a reshaping operation.
func::CallOp createFuncCall(OpBuilder &builder, Location loc, StringRef name, TypeRange resultType, ValueRange operands, EmitCInterface emitCInterface)
Creates a CallOp to the function reference returned by getFunc() in the builder's module.
Value genCast(OpBuilder &builder, Location loc, Value value, Type dstTy)
Add type casting between arith and index types when needed.
StringRef primaryTypeFunctionSuffix(PrimaryType pt)
Convert PrimaryType to its function-name suffix.
Value createOrFoldSliceOffsetOp(OpBuilder &builder, Location loc, Value tensor, Dimension dim)
Generates code to retrieve the slice offset for the sparse tensor slice, return a constant if the off...
Value constantPrimaryTypeEncoding(OpBuilder &builder, Location loc, Type elemTp)
Generates a constant of the internal type-encoding for primary storage.
void sizesFromSrc(OpBuilder &builder, SmallVectorImpl< Value > &sizes, Location loc, Value src)
Populates given sizes array from dense tensor or sparse tensor constant.
Type getOverheadType(Builder &builder, OverheadType ot)
Converts the internal type-encoding for overhead storage to an mlir::Type.
EmitCInterface
Shorthand aliases for the emitCInterface argument to getFunc(), createFuncCall(), and replaceOpWithFu...
Value allocDenseTensor(OpBuilder &builder, Location loc, RankedTensorType tensorTp, ValueRange sizes)
Generates code to allocate a buffer of the given type, and zero initialize it.
void storeAll(OpBuilder &builder, Location loc, Value mem, ValueRange vs, size_t offsetIdx=0, Value offsetVal=Value())
Stores all the values of vs into the memref mem, which must have rank-1 and size greater-or-equal to ...
Include the generated interface declarations.
Value convertScalarToDtype(OpBuilder &b, Location loc, Value operand, Type toType, bool isUnsignedCast)
Converts a scalar value operand to type toType.
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
@ Mul
RHS of mul is always a constant or a symbolic expression.
@ Mod
RHS of mod is always a constant or a symbolic expression with a positive value.
@ DimId
Dimensional identifier.
@ FloorDiv
RHS of floordiv is always a constant or a symbolic expression.
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.
llvm::function_ref< Fn > function_ref
Eliminates variable at the specified position using Fourier-Motzkin variable elimination.