MLIR 24.0.0git
BuiltinTypes.cpp
Go to the documentation of this file.
1//===- BuiltinTypes.cpp - MLIR Builtin Type Classes -----------------------===//
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
10#include "TypeDetail.h"
12#include "mlir/IR/AffineExpr.h"
13#include "mlir/IR/AffineMap.h"
17#include "mlir/IR/Diagnostics.h"
18#include "mlir/IR/Dialect.h"
21#include "llvm/ADT/APFixedPoint.h"
22#include "llvm/ADT/APFloat.h"
23#include "llvm/ADT/APInt.h"
24#include "llvm/ADT/Sequence.h"
25#include "llvm/ADT/TypeSwitch.h"
26#include "llvm/Support/CheckedArithmetic.h"
27#include <cstring>
28
29using namespace mlir;
30using namespace mlir::detail;
31
32//===----------------------------------------------------------------------===//
33/// Tablegen Type Definitions
34//===----------------------------------------------------------------------===//
35
36#define GET_TYPEDEF_CLASSES
37#include "mlir/IR/BuiltinTypes.cpp.inc"
38
39namespace mlir {
40#include "mlir/IR/BuiltinTypeConstraints.cpp.inc"
41} // namespace mlir
42
43//===----------------------------------------------------------------------===//
44/// ComplexType
45//===----------------------------------------------------------------------===//
46
47/// Verify the construction of an integer type.
48LogicalResult ComplexType::verify(function_ref<InFlightDiagnostic()> emitError,
49 Type elementType) {
50 if (!elementType.isIntOrFloat())
51 return emitError() << "invalid element type for complex";
52 return success();
53}
54
55size_t ComplexType::getDenseElementBitSize() const {
56 auto elemTy = cast<DenseElementType>(getElementType());
57 return llvm::alignTo<8>(elemTy.getDenseElementBitSize()) * 2;
58}
59
60Attribute ComplexType::convertToAttribute(ArrayRef<char> rawData) const {
61 auto elemTy = cast<DenseElementType>(getElementType());
62 size_t singleElementBytes =
63 llvm::alignTo<8>(elemTy.getDenseElementBitSize()) / 8;
65 elemTy.convertToAttribute(rawData.take_front(singleElementBytes));
67 elemTy.convertToAttribute(rawData.take_back(singleElementBytes));
68 return ArrayAttr::get(getContext(), {real, imag});
69}
70
71LogicalResult
72ComplexType::convertFromAttribute(Attribute attr,
74 auto arrayAttr = dyn_cast<ArrayAttr>(attr);
75 if (!arrayAttr || arrayAttr.size() != 2)
76 return failure();
77 auto elemTy = cast<DenseElementType>(getElementType());
78 SmallVector<char> realData, imagData;
79 if (failed(elemTy.convertFromAttribute(arrayAttr[0], realData)))
80 return failure();
81 if (failed(elemTy.convertFromAttribute(arrayAttr[1], imagData)))
82 return failure();
83 result.append(realData);
84 result.append(imagData);
85 return success();
86}
87
88//===----------------------------------------------------------------------===//
89// Integer Type
90//===----------------------------------------------------------------------===//
91
92/// Verify the construction of an integer type.
93LogicalResult IntegerType::verify(function_ref<InFlightDiagnostic()> emitError,
94 unsigned width,
95 SignednessSemantics signedness) {
96 if (width > IntegerType::kMaxWidth) {
97 return emitError() << "integer bitwidth is limited to "
98 << IntegerType::kMaxWidth << " bits";
99 }
100 return success();
101}
102
103unsigned IntegerType::getWidth() const { return getImpl()->width; }
104
105IntegerType::SignednessSemantics IntegerType::getSignedness() const {
106 return getImpl()->signedness;
107}
108
109IntegerType IntegerType::scaleElementBitwidth(unsigned scale) {
110 if (!scale)
111 return IntegerType();
112 return IntegerType::get(getContext(), scale * getWidth(), getSignedness());
113}
114
115size_t IntegerType::getDenseElementBitSize() const {
116 // Return the actual bit width. Storage alignment is handled separately.
117 return getWidth();
118}
119
120Attribute IntegerType::convertToAttribute(ArrayRef<char> rawData) const {
121 APInt value = detail::readBits(rawData.data(), /*bitPos=*/0, getWidth());
122 return IntegerAttr::get(*this, value);
123}
124
126 size_t byteSize = llvm::divideCeil(apInt.getBitWidth(), CHAR_BIT);
127 size_t bitPos = result.size() * CHAR_BIT;
128 result.resize(result.size() + byteSize);
129 detail::writeBits(result.data(), bitPos, apInt);
130}
131
132LogicalResult
133IntegerType::convertFromAttribute(Attribute attr,
135 auto intAttr = dyn_cast<IntegerAttr>(attr);
136 if (!intAttr || intAttr.getType() != *this)
137 return failure();
138 writeAPIntToVector(intAttr.getValue(), result);
139 return success();
140}
141
142//===----------------------------------------------------------------------===//
143// MXI8 Type
144//===----------------------------------------------------------------------===//
145
146llvm::FixedPointSemantics MXI8Type::getFixedPointSemantics() {
147 // Saturation is selected by a conversion operation, not by the value type.
148 return {/*Width=*/8, /*Scale=*/6, /*IsSigned=*/true,
149 /*IsSaturated=*/false, /*HasUnsignedPadding=*/false};
150}
151
152size_t MXI8Type::getDenseElementBitSize() const { return 8; }
153
154Attribute MXI8Type::convertToAttribute(ArrayRef<char> rawData) const {
155 return IntegerType::get(getContext(), 8).convertToAttribute(rawData);
156}
157
158LogicalResult
159MXI8Type::convertFromAttribute(Attribute attr,
161 auto intAttr = dyn_cast<IntegerAttr>(attr);
162 if (!intAttr || !intAttr.getType().isSignlessInteger(8))
163 return failure();
164 return cast<IntegerType>(intAttr.getType())
165 .convertFromAttribute(attr, result);
166}
167
168//===----------------------------------------------------------------------===//
169// Index Type
170//===----------------------------------------------------------------------===//
171
172size_t IndexType::getDenseElementBitSize() const {
173 return kInternalStorageBitWidth;
174}
175
176Attribute IndexType::convertToAttribute(ArrayRef<char> rawData) const {
177 APInt value =
178 detail::readBits(rawData.data(), /*bitPos=*/0, kInternalStorageBitWidth);
179 return IntegerAttr::get(*this, value);
180}
181
182LogicalResult
183IndexType::convertFromAttribute(Attribute attr,
185 auto intAttr = dyn_cast<IntegerAttr>(attr);
186 if (!intAttr || intAttr.getType() != *this)
187 return failure();
188 writeAPIntToVector(intAttr.getValue(), result);
189 return success();
190}
191
192//===----------------------------------------------------------------------===//
193// Float Types
194//===----------------------------------------------------------------------===//
195
196// Mapping from MLIR FloatType to APFloat semantics.
197#define FLOAT_TYPE_SEMANTICS(TYPE, SEM) \
198 const llvm::fltSemantics &TYPE::getFloatSemantics() const { \
199 return APFloat::SEM(); \
200 }
201FLOAT_TYPE_SEMANTICS(Float4E2M1FNType, Float4E2M1FN)
202FLOAT_TYPE_SEMANTICS(Float6E2M3FNType, Float6E2M3FN)
203FLOAT_TYPE_SEMANTICS(Float6E3M2FNType, Float6E3M2FN)
204FLOAT_TYPE_SEMANTICS(Float8E5M2Type, Float8E5M2)
205FLOAT_TYPE_SEMANTICS(Float8E4M3Type, Float8E4M3)
206FLOAT_TYPE_SEMANTICS(Float8E4M3FNType, Float8E4M3FN)
207FLOAT_TYPE_SEMANTICS(Float8E5M2FNUZType, Float8E5M2FNUZ)
208FLOAT_TYPE_SEMANTICS(Float8E4M3FNUZType, Float8E4M3FNUZ)
209FLOAT_TYPE_SEMANTICS(Float8E4M3B11FNUZType, Float8E4M3B11FNUZ)
210FLOAT_TYPE_SEMANTICS(Float8E3M4Type, Float8E3M4)
211FLOAT_TYPE_SEMANTICS(Float8E8M0FNUType, Float8E8M0FNU)
212FLOAT_TYPE_SEMANTICS(Float8E5M3FNUType, Float8E5M3FNU)
213FLOAT_TYPE_SEMANTICS(BFloat16Type, BFloat)
214FLOAT_TYPE_SEMANTICS(Float16Type, IEEEhalf)
215FLOAT_TYPE_SEMANTICS(FloatTF32Type, FloatTF32)
216FLOAT_TYPE_SEMANTICS(Float32Type, IEEEsingle)
217FLOAT_TYPE_SEMANTICS(Float64Type, IEEEdouble)
218FLOAT_TYPE_SEMANTICS(Float80Type, x87DoubleExtended)
219FLOAT_TYPE_SEMANTICS(Float128Type, IEEEquad)
220#undef FLOAT_TYPE_SEMANTICS
221
222FloatType Float16Type::scaleElementBitwidth(unsigned scale) const {
223 if (scale == 2)
224 return Float32Type::get(getContext());
225 if (scale == 4)
226 return Float64Type::get(getContext());
227 return FloatType();
228}
229
230FloatType BFloat16Type::scaleElementBitwidth(unsigned scale) const {
231 if (scale == 2)
232 return Float32Type::get(getContext());
233 if (scale == 4)
234 return Float64Type::get(getContext());
235 return FloatType();
236}
237
238FloatType Float32Type::scaleElementBitwidth(unsigned scale) const {
239 if (scale == 2)
240 return Float64Type::get(getContext());
241 return FloatType();
242}
243
244//===----------------------------------------------------------------------===//
245// FunctionType
246//===----------------------------------------------------------------------===//
247
248unsigned FunctionType::getNumInputs() const { return getImpl()->numInputs; }
249
250ArrayRef<Type> FunctionType::getInputs() const {
251 return getImpl()->getInputs();
252}
253
254unsigned FunctionType::getNumResults() const { return getImpl()->numResults; }
255
256ArrayRef<Type> FunctionType::getResults() const {
257 return getImpl()->getResults();
258}
259
260FunctionType FunctionType::clone(TypeRange inputs, TypeRange results) const {
261 return get(getContext(), inputs, results);
262}
263
264/// Returns a new function type with the specified arguments and results
265/// inserted.
266FunctionType FunctionType::getWithArgsAndResults(
267 ArrayRef<unsigned> argIndices, TypeRange argTypes,
268 ArrayRef<unsigned> resultIndices, TypeRange resultTypes) {
269 SmallVector<Type> argStorage, resultStorage;
270 TypeRange newArgTypes =
271 insertTypesInto(getInputs(), argIndices, argTypes, argStorage);
272 TypeRange newResultTypes =
273 insertTypesInto(getResults(), resultIndices, resultTypes, resultStorage);
274 return clone(newArgTypes, newResultTypes);
275}
276
277/// Returns a new function type without the specified arguments and results.
278FunctionType
279FunctionType::getWithoutArgsAndResults(const BitVector &argIndices,
280 const BitVector &resultIndices) {
281 SmallVector<Type> argStorage, resultStorage;
282 TypeRange newArgTypes = filterTypesOut(getInputs(), argIndices, argStorage);
283 TypeRange newResultTypes =
284 filterTypesOut(getResults(), resultIndices, resultStorage);
285 return clone(newArgTypes, newResultTypes);
286}
287
288//===----------------------------------------------------------------------===//
289// GraphType
290//===----------------------------------------------------------------------===//
291
292unsigned GraphType::getNumInputs() const { return getImpl()->numInputs; }
293
294ArrayRef<Type> GraphType::getInputs() const { return getImpl()->getInputs(); }
295
296unsigned GraphType::getNumResults() const { return getImpl()->numResults; }
297
298ArrayRef<Type> GraphType::getResults() const { return getImpl()->getResults(); }
299
300GraphType GraphType::clone(TypeRange inputs, TypeRange results) const {
301 return get(getContext(), inputs, results);
302}
303
304/// Returns a new function type with the specified arguments and results
305/// inserted.
306GraphType GraphType::getWithArgsAndResults(ArrayRef<unsigned> argIndices,
307 TypeRange argTypes,
308 ArrayRef<unsigned> resultIndices,
309 TypeRange resultTypes) {
310 SmallVector<Type> argStorage, resultStorage;
311 TypeRange newArgTypes =
312 insertTypesInto(getInputs(), argIndices, argTypes, argStorage);
313 TypeRange newResultTypes =
314 insertTypesInto(getResults(), resultIndices, resultTypes, resultStorage);
315 return clone(newArgTypes, newResultTypes);
316}
317
318/// Returns a new function type without the specified arguments and results.
319GraphType GraphType::getWithoutArgsAndResults(const BitVector &argIndices,
320 const BitVector &resultIndices) {
321 SmallVector<Type> argStorage, resultStorage;
322 TypeRange newArgTypes = filterTypesOut(getInputs(), argIndices, argStorage);
323 TypeRange newResultTypes =
324 filterTypesOut(getResults(), resultIndices, resultStorage);
325 return clone(newArgTypes, newResultTypes);
326}
327//===----------------------------------------------------------------------===//
328// OpaqueType
329//===----------------------------------------------------------------------===//
330
331/// Verify the construction of an opaque type.
332LogicalResult OpaqueType::verify(function_ref<InFlightDiagnostic()> emitError,
333 StringAttr dialect, StringRef typeData) {
334 if (!Dialect::isValidNamespace(dialect.strref()))
335 return emitError() << "invalid dialect namespace '" << dialect << "'";
336
337 // Check that the dialect is actually registered.
338 MLIRContext *context = dialect.getContext();
339 if (!context->allowsUnregisteredDialects() &&
340 !context->getLoadedDialect(dialect.strref())) {
341 return emitError()
342 << "`!" << dialect << "<\"" << typeData << "\">"
343 << "` type created with unregistered dialect. If this is "
344 "intended, please call allowUnregisteredDialects() on the "
345 "MLIRContext, or use -allow-unregistered-dialect with "
346 "the MLIR opt tool used";
347 }
348
349 return success();
350}
351
352//===----------------------------------------------------------------------===//
353// VectorType
354//===----------------------------------------------------------------------===//
355
356bool VectorType::isValidElementType(Type t) {
357 return isValidVectorTypeElementType(t);
358}
359
360LogicalResult VectorType::verify(function_ref<InFlightDiagnostic()> emitError,
361 ArrayRef<int64_t> shape, Type elementType,
362 ArrayRef<bool> scalableDims) {
363 if (!isValidElementType(elementType))
364 return emitError()
365 << "vector elements must be int/index/float type but got "
366 << elementType;
367
368 if (any_of(shape, [](int64_t i) { return i <= 0; }))
369 return emitError()
370 << "vector types must have positive constant sizes but got "
371 << shape;
372
373 if (scalableDims.size() != shape.size())
374 return emitError() << "number of dims must match, got "
375 << scalableDims.size() << " and " << shape.size();
376
377 return success();
378}
379
380VectorType VectorType::scaleElementBitwidth(unsigned scale) {
381 if (!scale)
382 return VectorType();
383 if (auto et = llvm::dyn_cast<IntegerType>(getElementType()))
384 if (auto scaledEt = et.scaleElementBitwidth(scale))
385 return VectorType::get(getShape(), scaledEt, getScalableDims());
386 if (auto et = llvm::dyn_cast<FloatType>(getElementType()))
387 if (auto scaledEt = et.scaleElementBitwidth(scale))
388 return VectorType::get(getShape(), scaledEt, getScalableDims());
389 return VectorType();
390}
391
392VectorType VectorType::cloneWith(std::optional<ArrayRef<int64_t>> shape,
393 Type elementType) const {
394 return VectorType::get(shape.value_or(getShape()), elementType,
395 getScalableDims());
396}
397
398//===----------------------------------------------------------------------===//
399// TensorType
400//===----------------------------------------------------------------------===//
401
404 .Case<RankedTensorType, UnrankedTensorType>(
405 [](auto type) { return type.getElementType(); });
406}
407
409 return !llvm::isa<UnrankedTensorType>(*this);
410}
411
413 return llvm::cast<RankedTensorType>(*this).getShape();
414}
415
417 Type elementType) const {
418 if (llvm::dyn_cast<UnrankedTensorType>(*this)) {
419 if (shape)
420 return RankedTensorType::get(*shape, elementType);
421 return UnrankedTensorType::get(elementType);
422 }
423
424 auto rankedTy = llvm::cast<RankedTensorType>(*this);
425 if (!shape)
426 return RankedTensorType::get(rankedTy.getShape(), elementType,
427 rankedTy.getEncoding());
428 return RankedTensorType::get(shape.value_or(rankedTy.getShape()), elementType,
429 rankedTy.getEncoding());
430}
431
433 Type elementType) const {
434 return ::llvm::cast<RankedTensorType>(cloneWith(shape, elementType));
435}
436
437RankedTensorType TensorType::clone(::llvm::ArrayRef<int64_t> shape) const {
438 return ::llvm::cast<RankedTensorType>(cloneWith(shape, getElementType()));
439}
440
441// Check if "elementType" can be an element type of a tensor.
442static LogicalResult
444 Type elementType) {
445 if (!TensorType::isValidElementType(elementType))
446 return emitError() << "invalid tensor element type: " << elementType;
447 return success();
448}
449
450/// Return true if the specified element type is ok in a tensor.
452 // Note: Non standard/builtin types are allowed to exist within tensor
453 // types. Dialects are expected to verify that tensor types have a valid
454 // element type within that dialect.
455 return llvm::isa<ComplexType, FloatType, IntegerType, OpaqueType, VectorType,
456 IndexType, MXI8Type>(type) ||
457 !llvm::isa<BuiltinDialect>(type.getDialect());
458}
459
460//===----------------------------------------------------------------------===//
461// RankedTensorType
462//===----------------------------------------------------------------------===//
463
464LogicalResult
465RankedTensorType::verify(function_ref<InFlightDiagnostic()> emitError,
466 ArrayRef<int64_t> shape, Type elementType,
467 Attribute encoding) {
468 for (int64_t s : shape)
469 if (s < 0 && ShapedType::isStatic(s))
470 return emitError() << "invalid tensor dimension size";
471 if (auto v = llvm::dyn_cast_or_null<VerifiableTensorEncoding>(encoding))
472 if (failed(v.verifyEncoding(shape, elementType, emitError)))
473 return failure();
474 return checkTensorElementType(emitError, elementType);
475}
476
477//===----------------------------------------------------------------------===//
478// UnrankedTensorType
479//===----------------------------------------------------------------------===//
480
481LogicalResult
482UnrankedTensorType::verify(function_ref<InFlightDiagnostic()> emitError,
483 Type elementType) {
484 return checkTensorElementType(emitError, elementType);
485}
486
487//===----------------------------------------------------------------------===//
488// BaseMemRefType
489//===----------------------------------------------------------------------===//
490
493 .Case<MemRefType, UnrankedMemRefType>(
494 [](auto type) { return type.getElementType(); });
495}
496
498 return !llvm::isa<UnrankedMemRefType>(*this);
499}
500
502 return llvm::cast<MemRefType>(*this).getShape();
503}
504
506 Type elementType) const {
507 if (llvm::dyn_cast<UnrankedMemRefType>(*this)) {
508 if (!shape)
509 return UnrankedMemRefType::get(elementType, getMemorySpace());
510 MemRefType::Builder builder(*shape, elementType);
512 return builder;
513 }
514
515 MemRefType::Builder builder(llvm::cast<MemRefType>(*this));
516 if (shape)
517 builder.setShape(*shape);
518 builder.setElementType(elementType);
519 return builder;
520}
521
522FailureOr<PtrLikeTypeInterface>
524 std::optional<Type> elementType) const {
525 Type eTy = elementType ? *elementType : getElementType();
526 if (llvm::dyn_cast<UnrankedMemRefType>(*this))
527 return cast<PtrLikeTypeInterface>(
528 UnrankedMemRefType::get(eTy, memorySpace));
529
530 MemRefType::Builder builder(llvm::cast<MemRefType>(*this));
531 builder.setElementType(eTy);
532 builder.setMemorySpace(memorySpace);
533 return cast<PtrLikeTypeInterface>(static_cast<MemRefType>(builder));
534}
535
537 Type elementType) const {
538 return ::llvm::cast<MemRefType>(cloneWith(shape, elementType));
539}
540
542 return ::llvm::cast<MemRefType>(cloneWith(shape, getElementType()));
543}
544
546 if (auto rankedMemRefTy = llvm::dyn_cast<MemRefType>(*this))
547 return rankedMemRefTy.getMemorySpace();
548 return llvm::cast<UnrankedMemRefType>(*this).getMemorySpace();
549}
550
552 if (auto rankedMemRefTy = llvm::dyn_cast<MemRefType>(*this))
553 return rankedMemRefTy.getMemorySpaceAsInt();
554 return llvm::cast<UnrankedMemRefType>(*this).getMemorySpaceAsInt();
555}
556
557//===----------------------------------------------------------------------===//
558// MemRefType
559//===----------------------------------------------------------------------===//
560
561std::optional<llvm::SmallDenseSet<unsigned>>
563 ArrayRef<int64_t> reducedShape,
564 bool matchDynamic) {
565 size_t originalRank = originalShape.size(), reducedRank = reducedShape.size();
566 llvm::SmallDenseSet<unsigned> unusedDims;
567 unsigned reducedIdx = 0;
568 for (unsigned originalIdx = 0; originalIdx < originalRank; ++originalIdx) {
569 // Greedily insert `originalIdx` if match.
570 int64_t origSize = originalShape[originalIdx];
571 // if `matchDynamic`, count dynamic dims as a match, unless `origSize` is 1.
572 if (matchDynamic && reducedIdx < reducedRank && origSize != 1 &&
573 (ShapedType::isDynamic(reducedShape[reducedIdx]) ||
574 ShapedType::isDynamic(origSize))) {
575 reducedIdx++;
576 continue;
577 }
578 if (reducedIdx < reducedRank && origSize == reducedShape[reducedIdx]) {
579 reducedIdx++;
580 continue;
581 }
582
583 unusedDims.insert(originalIdx);
584 // If no match on `originalIdx`, the `originalShape` at this dimension
585 // must be 1, otherwise we bail.
586 if (origSize != 1)
587 return std::nullopt;
588 }
589 // The whole reducedShape must be scanned, otherwise we bail.
590 if (reducedIdx != reducedRank)
591 return std::nullopt;
592 return unusedDims;
593}
594
596mlir::isRankReducedType(ShapedType originalType,
597 ShapedType candidateReducedType) {
598 if (originalType == candidateReducedType)
600
601 ShapedType originalShapedType = llvm::cast<ShapedType>(originalType);
602 ShapedType candidateReducedShapedType =
603 llvm::cast<ShapedType>(candidateReducedType);
604
605 // Rank and size logic is valid for all ShapedTypes.
606 ArrayRef<int64_t> originalShape = originalShapedType.getShape();
607 ArrayRef<int64_t> candidateReducedShape =
608 candidateReducedShapedType.getShape();
609 unsigned originalRank = originalShape.size(),
610 candidateReducedRank = candidateReducedShape.size();
611 if (candidateReducedRank > originalRank)
613
614 auto optionalUnusedDimsMask =
615 computeRankReductionMask(originalShape, candidateReducedShape);
616
617 // Sizes cannot be matched in case empty vector is returned.
618 if (!optionalUnusedDimsMask)
620
621 if (originalShapedType.getElementType() !=
622 candidateReducedShapedType.getElementType())
624
626}
627
629 MLIRContext *ctx) {
630 if (memorySpace == 0)
631 return nullptr;
632
633 return IntegerAttr::get(IntegerType::get(ctx, 64), memorySpace);
634}
635
637 IntegerAttr intMemorySpace = llvm::dyn_cast_or_null<IntegerAttr>(memorySpace);
638 if (intMemorySpace && intMemorySpace.getValue() == 0)
639 return nullptr;
640
641 return memorySpace;
642}
643
645 if (!memorySpace)
646 return 0;
647
648 assert(llvm::isa<IntegerAttr>(memorySpace) &&
649 "Using `getMemorySpaceInteger` with non-Integer attribute");
650
651 return static_cast<unsigned>(llvm::cast<IntegerAttr>(memorySpace).getInt());
652}
653
654unsigned MemRefType::getMemorySpaceAsInt() const {
655 return detail::getMemorySpaceAsInt(getMemorySpace());
656}
657
658MemRefType MemRefType::get(ArrayRef<int64_t> shape, Type elementType,
659 MemRefLayoutAttrInterface layout,
660 Attribute memorySpace) {
661 // Use default layout for empty attribute.
662 if (!layout)
663 layout = AffineMapAttr::get(AffineMap::getMultiDimIdentityMap(
664 shape.size(), elementType.getContext()));
665
666 // Drop default memory space value and replace it with empty attribute.
667 memorySpace = skipDefaultMemorySpace(memorySpace);
668
669 return Base::get(elementType.getContext(), shape, elementType, layout,
670 memorySpace);
671}
672
673MemRefType MemRefType::getChecked(
675 Type elementType, MemRefLayoutAttrInterface layout, Attribute memorySpace) {
676
677 // Use default layout for empty attribute.
678 if (!layout)
679 layout = AffineMapAttr::get(AffineMap::getMultiDimIdentityMap(
680 shape.size(), elementType.getContext()));
681
682 // Drop default memory space value and replace it with empty attribute.
683 memorySpace = skipDefaultMemorySpace(memorySpace);
684
685 return Base::getChecked(emitErrorFn, elementType.getContext(), shape,
686 elementType, layout, memorySpace);
687}
688
689MemRefType MemRefType::get(ArrayRef<int64_t> shape, Type elementType,
690 AffineMap map, Attribute memorySpace) {
691
692 // Use default layout for empty map.
693 if (!map)
695 elementType.getContext());
696
697 // Wrap AffineMap into Attribute.
698 auto layout = AffineMapAttr::get(map);
699
700 // Drop default memory space value and replace it with empty attribute.
701 memorySpace = skipDefaultMemorySpace(memorySpace);
702
703 return Base::get(elementType.getContext(), shape, elementType, layout,
704 memorySpace);
705}
706
707MemRefType
708MemRefType::getChecked(function_ref<InFlightDiagnostic()> emitErrorFn,
709 ArrayRef<int64_t> shape, Type elementType, AffineMap map,
710 Attribute memorySpace) {
711
712 // Use default layout for empty map.
713 if (!map)
715 elementType.getContext());
716
717 // Wrap AffineMap into Attribute.
718 auto layout = AffineMapAttr::get(map);
719
720 // Drop default memory space value and replace it with empty attribute.
721 memorySpace = skipDefaultMemorySpace(memorySpace);
722
723 return Base::getChecked(emitErrorFn, elementType.getContext(), shape,
724 elementType, layout, memorySpace);
725}
726
727MemRefType MemRefType::get(ArrayRef<int64_t> shape, Type elementType,
728 AffineMap map, unsigned memorySpaceInd) {
729
730 // Use default layout for empty map.
731 if (!map)
733 elementType.getContext());
734
735 // Wrap AffineMap into Attribute.
736 auto layout = AffineMapAttr::get(map);
737
738 // Convert deprecated integer-like memory space to Attribute.
739 Attribute memorySpace =
740 wrapIntegerMemorySpace(memorySpaceInd, elementType.getContext());
741
742 return Base::get(elementType.getContext(), shape, elementType, layout,
743 memorySpace);
744}
745
746MemRefType
747MemRefType::getChecked(function_ref<InFlightDiagnostic()> emitErrorFn,
748 ArrayRef<int64_t> shape, Type elementType, AffineMap map,
749 unsigned memorySpaceInd) {
750
751 // Use default layout for empty map.
752 if (!map)
754 elementType.getContext());
755
756 // Wrap AffineMap into Attribute.
757 auto layout = AffineMapAttr::get(map);
758
759 // Convert deprecated integer-like memory space to Attribute.
760 Attribute memorySpace =
761 wrapIntegerMemorySpace(memorySpaceInd, elementType.getContext());
762
763 return Base::getChecked(emitErrorFn, elementType.getContext(), shape,
764 elementType, layout, memorySpace);
765}
766
767LogicalResult MemRefType::verify(function_ref<InFlightDiagnostic()> emitError,
768 ArrayRef<int64_t> shape, Type elementType,
769 MemRefLayoutAttrInterface layout,
770 Attribute memorySpace) {
771 if (!BaseMemRefType::isValidElementType(elementType))
772 return emitError() << "invalid memref element type";
773
774 // Negative sizes are not allowed except for `kDynamic`.
775 for (int64_t s : shape)
776 if (s < 0 && ShapedType::isStatic(s))
777 return emitError() << "invalid memref size";
778
779 assert(layout && "missing layout specification");
780 if (failed(layout.verifyLayout(shape, emitError)))
781 return failure();
782
783 return success();
784}
785
786bool MemRefType::areTrailingDimsContiguous(int64_t n) {
787 assert(n <= getRank() &&
788 "number of dimensions to check must not exceed rank");
789 return n <= getNumContiguousTrailingDims();
790}
791
792int64_t MemRefType::getNumContiguousTrailingDims() {
793 const int64_t n = getRank();
794
795 // memrefs with identity layout are entirely contiguous.
796 if (getLayout().isIdentity())
797 return n;
798
799 // Get the strides (if any). Failing to do that, conservatively assume a
800 // non-contiguous layout.
801 int64_t offset;
802 SmallVector<int64_t> strides;
803 if (!succeeded(getStridesAndOffset(strides, offset)))
804 return 0;
805
807
808 // A memref with dimensions `d0, d1, ..., dn-1` and strides
809 // `s0, s1, ..., sn-1` is contiguous up to dimension `k`
810 // if each stride `si` is the product of the dimensions `di+1, ..., dn-1`,
811 // for `i` in `[k, n-1]`.
812 // Ignore stride elements if the corresponding dimension is 1, as they are
813 // of no consequence.
814 int64_t dimProduct = 1;
815 for (int64_t i = n - 1; i >= 0; --i) {
816 if (shape[i] == 1)
817 continue;
818 if (strides[i] != dimProduct)
819 return n - i - 1;
820 if (shape[i] == ShapedType::kDynamic)
821 return n - i;
822 dimProduct *= shape[i];
823 }
824
825 return n;
826}
827
828MemRefType MemRefType::canonicalizeStridedLayout() {
829 AffineMap m = getLayout().getAffineMap();
830
831 // Already in canonical form.
832 if (m.isIdentity())
833 return *this;
834
835 // Can't reduce to canonical identity form, return in canonical form.
836 if (m.getNumResults() > 1)
837 return *this;
838
839 // Corner-case for 0-D affine maps.
840 if (m.getNumDims() == 0 && m.getNumSymbols() == 0) {
841 if (auto cst = llvm::dyn_cast<AffineConstantExpr>(m.getResult(0)))
842 if (cst.getValue() == 0)
843 return MemRefType::Builder(*this).setLayout({});
844 return *this;
845 }
846
847 // 0-D corner case for empty shape that still have an affine map. Example:
848 // `memref<f32, affine_map<()[s0] -> (s0)>>`. This is a 1 element memref whose
849 // offset needs to remain, just return t.
850 if (getShape().empty())
851 return *this;
852
853 // If the canonical strided layout for the sizes of `t` is equal to the
854 // simplified layout of `t` we can just return an empty layout. Otherwise,
855 // just simplify the existing layout.
857 auto simplifiedLayoutExpr =
859 if (expr != simplifiedLayoutExpr)
860 return MemRefType::Builder(*this).setLayout(
861 AffineMapAttr::get(AffineMap::get(m.getNumDims(), m.getNumSymbols(),
862 simplifiedLayoutExpr)));
863 return MemRefType::Builder(*this).setLayout({});
864}
865
866LogicalResult MemRefType::getStridesAndOffset(SmallVectorImpl<int64_t> &strides,
867 int64_t &offset) const {
868 return getLayout().getStridesAndOffset(getShape(), strides, offset);
869}
870
871std::pair<SmallVector<int64_t>, int64_t>
872MemRefType::getStridesAndOffset() const {
873 SmallVector<int64_t> strides;
874 int64_t offset;
875 LogicalResult status = getStridesAndOffset(strides, offset);
876 (void)status;
877 assert(succeeded(status) && "Invalid use of check-free getStridesAndOffset");
878 return {strides, offset};
879}
880
881bool MemRefType::isStrided() {
882 int64_t offset;
884 auto res = getStridesAndOffset(strides, offset);
885 return succeeded(res);
886}
887
888bool MemRefType::isLastDimUnitStride() {
889 int64_t offset;
890 SmallVector<int64_t> strides;
891 auto successStrides = getStridesAndOffset(strides, offset);
892 return succeeded(successStrides) && (strides.empty() || strides.back() == 1);
893}
894
895//===----------------------------------------------------------------------===//
896// UnrankedMemRefType
897//===----------------------------------------------------------------------===//
898
899unsigned UnrankedMemRefType::getMemorySpaceAsInt() const {
900 return detail::getMemorySpaceAsInt(getMemorySpace());
901}
902
903LogicalResult
904UnrankedMemRefType::verify(function_ref<InFlightDiagnostic()> emitError,
905 Type elementType, Attribute memorySpace) {
906 if (!BaseMemRefType::isValidElementType(elementType))
907 return emitError() << "invalid memref element type";
908
909 return success();
910}
911
912//===----------------------------------------------------------------------===//
913/// TupleType
914//===----------------------------------------------------------------------===//
915
916/// Return the elements types for this tuple.
917ArrayRef<Type> TupleType::getTypes() const { return getImpl()->getTypes(); }
918
919/// Accumulate the types contained in this tuple and tuples nested within it.
920/// Note that this only flattens nested tuples, not any other container type,
921/// e.g. a tuple<i32, tensor<i32>, tuple<f32, tuple<i64>>> is flattened to
922/// (i32, tensor<i32>, f32, i64)
923void TupleType::getFlattenedTypes(SmallVectorImpl<Type> &types) {
924 for (Type type : getTypes()) {
925 if (auto nestedTuple = llvm::dyn_cast<TupleType>(type))
926 nestedTuple.getFlattenedTypes(types);
927 else
928 types.push_back(type);
929 }
930}
931
932/// Return the number of element types.
933size_t TupleType::size() const { return getImpl()->size(); }
934
935//===----------------------------------------------------------------------===//
936// Type Utilities
937//===----------------------------------------------------------------------===//
938
941 MLIRContext *context) {
942 // Size 0 corner case is useful for canonicalizations.
943 if (sizes.empty())
944 return getAffineConstantExpr(0, context);
945
946 assert(!exprs.empty() && "expected exprs");
947 auto maps = AffineMap::inferFromExprList(exprs, context);
948 assert(!maps.empty() && "Expected one non-empty map");
949 unsigned numDims = maps[0].getNumDims(), nSymbols = maps[0].getNumSymbols();
950
951 AffineExpr expr;
952 bool dynamicPoisonBit = false;
953 int64_t runningSize = 1;
954 for (auto en : llvm::zip(llvm::reverse(exprs), llvm::reverse(sizes))) {
955 int64_t size = std::get<1>(en);
956 AffineExpr dimExpr = std::get<0>(en);
957 AffineExpr stride = dynamicPoisonBit
958 ? getAffineSymbolExpr(nSymbols++, context)
959 : getAffineConstantExpr(runningSize, context);
960 expr = expr ? expr + dimExpr * stride : dimExpr * stride;
961 if (size > 0) {
962 auto result = llvm::checkedMul(runningSize, size);
963 if (!result) {
964 // Overflow occurred, treat as dynamic
965 dynamicPoisonBit = true;
966 } else {
967 runningSize = *result;
968 }
969 } else {
970 dynamicPoisonBit = true;
971 }
972 }
973 return simplifyAffineExpr(expr, numDims, nSymbols);
974}
975
977 MLIRContext *context) {
979 exprs.reserve(sizes.size());
980 for (auto dim : llvm::seq<unsigned>(0, sizes.size()))
981 exprs.push_back(getAffineDimExpr(dim, context));
982 return makeCanonicalStridedLayoutExpr(sizes, exprs, context);
983}
return success()
static LogicalResult getStridesAndOffset(AffineMap m, ArrayRef< int64_t > shape, SmallVectorImpl< AffineExpr > &strides, AffineExpr &offset)
A stride specification is a list of integer values that are either static or dynamic (encoded with Sh...
static void writeAPIntToVector(APInt apInt, SmallVectorImpl< char > &result)
static LogicalResult checkTensorElementType(function_ref< InFlightDiagnostic()> emitError, Type elementType)
#define FLOAT_TYPE_SEMANTICS(TYPE, SEM)
b getContext())
static Type getElementType(Type type, ArrayRef< int32_t > indices, function_ref< InFlightDiagnostic(StringRef)> emitErrorFn)
Walks the given type hierarchy with the given indices, potentially down to component granularity,...
Definition SPIRVOps.cpp:230
static ArrayRef< int64_t > getShape(Type type)
Returns the shape of the given type.
Definition Traits.cpp:117
Base type for affine expression.
Definition AffineExpr.h:68
A multi-dimensional affine map Affine map's are immutable like Type's, and they are uniqued.
Definition AffineMap.h:46
static AffineMap getMultiDimIdentityMap(unsigned numDims, MLIRContext *context)
Returns an AffineMap with 'numDims' identity result dim exprs.
static AffineMap get(MLIRContext *context)
Returns a zero result affine map with no dimensions or symbols: () -> ().
unsigned getNumSymbols() const
unsigned getNumDims() const
unsigned getNumResults() const
static SmallVector< AffineMap, 4 > inferFromExprList(ArrayRef< ArrayRef< AffineExpr > > exprsList, MLIRContext *context)
Returns a vector of AffineMaps; each with as many results as exprs.size(), as many dims as the larges...
AffineExpr getResult(unsigned idx) const
bool isIdentity() const
Returns true if this affine map is an identity affine map.
Attributes are known-constant values of operations.
Definition Attributes.h:25
This class provides a shared interface for ranked and unranked memref types.
ArrayRef< int64_t > getShape() const
Returns the shape of this memref type.
static bool isValidElementType(Type type)
Return true if the specified element type is ok in a memref.
FailureOr< PtrLikeTypeInterface > clonePtrWith(Attribute memorySpace, std::optional< Type > elementType) const
Clone this type with the given memory space and element type.
constexpr Type()=default
Attribute getMemorySpace() const
Returns the memory space in which data referred to by this memref resides.
unsigned getMemorySpaceAsInt() const
[deprecated] Returns the memory space in old raw integer representation.
BaseMemRefType cloneWith(std::optional< ArrayRef< int64_t > > shape, Type elementType) const
Clone this type with the given shape and element type.
bool hasRank() const
Returns if this type is ranked, i.e. it has a known number of dimensions.
Type getElementType() const
Returns the element type of this memref type.
MemRefType clone(ArrayRef< int64_t > shape, Type elementType) const
Return a clone of this type with the given new shape and element type.
static bool isValidNamespace(StringRef str)
Utility function that returns if the given string is a valid dialect namespace.
Definition Dialect.cpp:95
This class represents a diagnostic that is inflight and set to be reported.
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:71
Dialect * getLoadedDialect(StringRef name)
Get a registered IR dialect with the given namespace.
bool allowsUnregisteredDialects()
Return true if we allow to create operation for unregistered dialects.
This is a builder type that keeps local references to arguments.
Builder & setShape(ArrayRef< int64_t > newShape)
Builder & setMemorySpace(Attribute newMemorySpace)
Builder & setElementType(Type newElementType)
Builder & setLayout(MemRefLayoutAttrInterface newLayout)
Tensor types represent multi-dimensional arrays, and have two variants: RankedTensorType and Unranked...
TensorType cloneWith(std::optional< ArrayRef< int64_t > > shape, Type elementType) const
Clone this type with the given shape and element type.
constexpr Type()=default
static bool isValidElementType(Type type)
Return true if the specified element type is ok in a tensor.
ArrayRef< int64_t > getShape() const
Returns the shape of this tensor type.
bool hasRank() const
Returns if this type is ranked, i.e. it has a known number of dimensions.
RankedTensorType clone(ArrayRef< int64_t > shape, Type elementType) const
Return a clone of this type with the given new shape and element type.
Type getElementType() const
Returns the element type of this tensor type.
This class provides an abstraction over the various different ranges of value types.
Definition TypeRange.h:40
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
Dialect & getDialect() const
Get the dialect this type is registered to.
Definition Types.h:107
MLIRContext * getContext() const
Return the MLIRContext in which this type was uniqued.
Definition Types.cpp:35
bool isIntOrFloat() const
Return true if this is an integer (of any signedness) or a float type.
Definition Types.cpp:118
AttrTypeReplacer.
Attribute wrapIntegerMemorySpace(unsigned memorySpace, MLIRContext *ctx)
Wraps deprecated integer memory space to the new Attribute form.
unsigned getMemorySpaceAsInt(Attribute memorySpace)
[deprecated] Returns the memory space in old raw integer representation.
Attribute skipDefaultMemorySpace(Attribute memorySpace)
Replaces default memorySpace (integer == 0) with empty Attribute.
void writeBits(char *rawData, size_t bitPos, llvm::APInt value)
Write value to byte-aligned position bitPos in rawData.
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
Include the generated interface declarations.
SliceVerificationResult
Enum that captures information related to verifier error conditions on slice insert/extract type of o...
constexpr T real(const NonFloatComplex< T > &x)
Definition Complex.h:255
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
TypeRange filterTypesOut(TypeRange types, const BitVector &indices, SmallVectorImpl< Type > &storage)
Filters out any elements referenced by indices.
constexpr T imag(const NonFloatComplex< T > &x)
Definition Complex.h:260
Operation * clone(OpBuilder &b, Operation *op, TypeRange newResultTypes, ValueRange newOperands)
AffineExpr getAffineConstantExpr(int64_t constant, MLIRContext *context)
auto get(MLIRContext *context, Ts &&...params)
Helper method that injects context only if needed, this helps unify some of the attribute constructio...
AffineExpr makeCanonicalStridedLayoutExpr(ArrayRef< int64_t > sizes, ArrayRef< AffineExpr > exprs, MLIRContext *context)
Given MemRef sizes that are either static or dynamic, returns the canonical "contiguous" strides Affi...
std::optional< llvm::SmallDenseSet< unsigned > > computeRankReductionMask(ArrayRef< int64_t > originalShape, ArrayRef< int64_t > reducedShape, bool matchDynamic=false)
Given an originalShape and a reducedShape assumed to be a subset of originalShape with some 1 entries...
AffineExpr simplifyAffineExpr(AffineExpr expr, unsigned numDims, unsigned numSymbols)
Simplify an affine expression by flattening and some amount of simple analysis.
AffineExpr getAffineDimExpr(unsigned position, MLIRContext *context)
These free functions allow clients of the API to not use classes in detail.
SliceVerificationResult isRankReducedType(ShapedType originalType, ShapedType candidateReducedType)
Check if originalType can be rank reduced to candidateReducedType type by dropping some dimensions wi...
TypeRange insertTypesInto(TypeRange oldTypes, ArrayRef< unsigned > indices, TypeRange newTypes, SmallVectorImpl< Type > &storage)
Insert a set of newTypes into oldTypes at the given indices.
llvm::function_ref< Fn > function_ref
Definition LLVM.h:155
AffineExpr getAffineSymbolExpr(unsigned position, MLIRContext *context)