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 
9 #include "mlir/IR/BuiltinTypes.h"
10 #include "TypeDetail.h"
11 #include "mlir/IR/AffineExpr.h"
12 #include "mlir/IR/AffineMap.h"
13 #include "mlir/IR/BuiltinAttributes.h"
14 #include "mlir/IR/BuiltinDialect.h"
15 #include "mlir/IR/Diagnostics.h"
16 #include "mlir/IR/Dialect.h"
17 #include "mlir/IR/TensorEncoding.h"
18 #include "llvm/ADT/APFloat.h"
19 #include "llvm/ADT/BitVector.h"
20 #include "llvm/ADT/Sequence.h"
21 #include "llvm/ADT/Twine.h"
22 #include "llvm/ADT/TypeSwitch.h"
23 
24 using namespace mlir;
25 using namespace mlir::detail;
26 
27 //===----------------------------------------------------------------------===//
28 /// Tablegen Type Definitions
29 //===----------------------------------------------------------------------===//
30 
31 #define GET_TYPEDEF_CLASSES
32 #include "mlir/IR/BuiltinTypes.cpp.inc"
33 
34 //===----------------------------------------------------------------------===//
35 /// Tablegen Interface Definitions
36 //===----------------------------------------------------------------------===//
37 
38 #include "mlir/IR/BuiltinTypeInterfaces.cpp.inc"
39 
40 //===----------------------------------------------------------------------===//
41 // BuiltinDialect
42 //===----------------------------------------------------------------------===//
43 
44 void BuiltinDialect::registerTypes() {
45   addTypes<
46 #define GET_TYPEDEF_LIST
47 #include "mlir/IR/BuiltinTypes.cpp.inc"
48       >();
49 }
50 
51 //===----------------------------------------------------------------------===//
52 /// ComplexType
53 //===----------------------------------------------------------------------===//
54 
55 /// Verify the construction of an integer type.
56 LogicalResult ComplexType::verify(function_ref<InFlightDiagnostic()> emitError,
57                                   Type elementType) {
58   if (!elementType.isIntOrFloat())
59     return emitError() << "invalid element type for complex";
60   return success();
61 }
62 
63 //===----------------------------------------------------------------------===//
64 // Integer Type
65 //===----------------------------------------------------------------------===//
66 
67 // static constexpr must have a definition (until in C++17 and inline variable).
68 constexpr unsigned IntegerType::kMaxWidth;
69 
70 /// Verify the construction of an integer type.
71 LogicalResult IntegerType::verify(function_ref<InFlightDiagnostic()> emitError,
72                                   unsigned width,
73                                   SignednessSemantics signedness) {
74   if (width > IntegerType::kMaxWidth) {
75     return emitError() << "integer bitwidth is limited to "
76                        << IntegerType::kMaxWidth << " bits";
77   }
78   return success();
79 }
80 
81 unsigned IntegerType::getWidth() const { return getImpl()->width; }
82 
83 IntegerType::SignednessSemantics IntegerType::getSignedness() const {
84   return getImpl()->signedness;
85 }
86 
87 IntegerType IntegerType::scaleElementBitwidth(unsigned scale) {
88   if (!scale)
89     return IntegerType();
90   return IntegerType::get(getContext(), scale * getWidth(), getSignedness());
91 }
92 
93 //===----------------------------------------------------------------------===//
94 // Float Type
95 //===----------------------------------------------------------------------===//
96 
97 unsigned FloatType::getWidth() {
98   if (isa<Float16Type, BFloat16Type>())
99     return 16;
100   if (isa<Float32Type>())
101     return 32;
102   if (isa<Float64Type>())
103     return 64;
104   if (isa<Float80Type>())
105     return 80;
106   if (isa<Float128Type>())
107     return 128;
108   llvm_unreachable("unexpected float type");
109 }
110 
111 /// Returns the floating semantics for the given type.
112 const llvm::fltSemantics &FloatType::getFloatSemantics() {
113   if (isa<BFloat16Type>())
114     return APFloat::BFloat();
115   if (isa<Float16Type>())
116     return APFloat::IEEEhalf();
117   if (isa<Float32Type>())
118     return APFloat::IEEEsingle();
119   if (isa<Float64Type>())
120     return APFloat::IEEEdouble();
121   if (isa<Float80Type>())
122     return APFloat::x87DoubleExtended();
123   if (isa<Float128Type>())
124     return APFloat::IEEEquad();
125   llvm_unreachable("non-floating point type used");
126 }
127 
128 FloatType FloatType::scaleElementBitwidth(unsigned scale) {
129   if (!scale)
130     return FloatType();
131   MLIRContext *ctx = getContext();
132   if (isF16() || isBF16()) {
133     if (scale == 2)
134       return FloatType::getF32(ctx);
135     if (scale == 4)
136       return FloatType::getF64(ctx);
137   }
138   if (isF32())
139     if (scale == 2)
140       return FloatType::getF64(ctx);
141   return FloatType();
142 }
143 
144 //===----------------------------------------------------------------------===//
145 // FunctionType
146 //===----------------------------------------------------------------------===//
147 
148 unsigned FunctionType::getNumInputs() const { return getImpl()->numInputs; }
149 
150 ArrayRef<Type> FunctionType::getInputs() const {
151   return getImpl()->getInputs();
152 }
153 
154 unsigned FunctionType::getNumResults() const { return getImpl()->numResults; }
155 
156 ArrayRef<Type> FunctionType::getResults() const {
157   return getImpl()->getResults();
158 }
159 
160 /// Helper to call a callback once on each index in the range
161 /// [0, `totalIndices`), *except* for the indices given in `indices`.
162 /// `indices` is allowed to have duplicates and can be in any order.
163 inline void iterateIndicesExcept(unsigned totalIndices,
164                                  ArrayRef<unsigned> indices,
165                                  function_ref<void(unsigned)> callback) {
166   llvm::BitVector skipIndices(totalIndices);
167   for (unsigned i : indices)
168     skipIndices.set(i);
169 
170   for (unsigned i = 0; i < totalIndices; ++i)
171     if (!skipIndices.test(i))
172       callback(i);
173 }
174 
175 /// Returns a new function type with the specified arguments and results
176 /// inserted.
177 FunctionType FunctionType::getWithArgsAndResults(
178     ArrayRef<unsigned> argIndices, TypeRange argTypes,
179     ArrayRef<unsigned> resultIndices, TypeRange resultTypes) {
180   assert(argIndices.size() == argTypes.size());
181   assert(resultIndices.size() == resultTypes.size());
182 
183   ArrayRef<Type> newInputTypes = getInputs();
184   SmallVector<Type, 4> newInputTypesBuffer;
185   if (!argIndices.empty()) {
186     const auto *fromIt = newInputTypes.begin();
187     for (auto it : llvm::zip(argIndices, argTypes)) {
188       const auto *toIt = newInputTypes.begin() + std::get<0>(it);
189       newInputTypesBuffer.append(fromIt, toIt);
190       newInputTypesBuffer.push_back(std::get<1>(it));
191       fromIt = toIt;
192     }
193     newInputTypesBuffer.append(fromIt, newInputTypes.end());
194     newInputTypes = newInputTypesBuffer;
195   }
196 
197   ArrayRef<Type> newResultTypes = getResults();
198   SmallVector<Type, 4> newResultTypesBuffer;
199   if (!resultIndices.empty()) {
200     const auto *fromIt = newResultTypes.begin();
201     for (auto it : llvm::zip(resultIndices, resultTypes)) {
202       const auto *toIt = newResultTypes.begin() + std::get<0>(it);
203       newResultTypesBuffer.append(fromIt, toIt);
204       newResultTypesBuffer.push_back(std::get<1>(it));
205       fromIt = toIt;
206     }
207     newResultTypesBuffer.append(fromIt, newResultTypes.end());
208     newResultTypes = newResultTypesBuffer;
209   }
210 
211   return FunctionType::get(getContext(), newInputTypes, newResultTypes);
212 }
213 
214 /// Returns a new function type without the specified arguments and results.
215 FunctionType
216 FunctionType::getWithoutArgsAndResults(ArrayRef<unsigned> argIndices,
217                                        ArrayRef<unsigned> resultIndices) {
218   ArrayRef<Type> newInputTypes = getInputs();
219   SmallVector<Type, 4> newInputTypesBuffer;
220   if (!argIndices.empty()) {
221     unsigned originalNumArgs = getNumInputs();
222     iterateIndicesExcept(originalNumArgs, argIndices, [&](unsigned i) {
223       newInputTypesBuffer.emplace_back(getInput(i));
224     });
225     newInputTypes = newInputTypesBuffer;
226   }
227 
228   ArrayRef<Type> newResultTypes = getResults();
229   SmallVector<Type, 4> newResultTypesBuffer;
230   if (!resultIndices.empty()) {
231     unsigned originalNumResults = getNumResults();
232     iterateIndicesExcept(originalNumResults, resultIndices, [&](unsigned i) {
233       newResultTypesBuffer.emplace_back(getResult(i));
234     });
235     newResultTypes = newResultTypesBuffer;
236   }
237 
238   return get(getContext(), newInputTypes, newResultTypes);
239 }
240 
241 void FunctionType::walkImmediateSubElements(
242     function_ref<void(Attribute)> walkAttrsFn,
243     function_ref<void(Type)> walkTypesFn) const {
244   for (Type type : llvm::concat<const Type>(getInputs(), getResults()))
245     walkTypesFn(type);
246 }
247 
248 //===----------------------------------------------------------------------===//
249 // OpaqueType
250 //===----------------------------------------------------------------------===//
251 
252 /// Verify the construction of an opaque type.
253 LogicalResult OpaqueType::verify(function_ref<InFlightDiagnostic()> emitError,
254                                  Identifier dialect, StringRef typeData) {
255   if (!Dialect::isValidNamespace(dialect.strref()))
256     return emitError() << "invalid dialect namespace '" << dialect << "'";
257 
258   // Check that the dialect is actually registered.
259   MLIRContext *context = dialect.getContext();
260   if (!context->allowsUnregisteredDialects() &&
261       !context->getLoadedDialect(dialect.strref())) {
262     return emitError()
263            << "`!" << dialect << "<\"" << typeData << "\">"
264            << "` type created with unregistered dialect. If this is "
265               "intended, please call allowUnregisteredDialects() on the "
266               "MLIRContext, or use -allow-unregistered-dialect with "
267               "mlir-opt";
268   }
269 
270   return success();
271 }
272 
273 //===----------------------------------------------------------------------===//
274 // ShapedType
275 //===----------------------------------------------------------------------===//
276 constexpr int64_t ShapedType::kDynamicSize;
277 constexpr int64_t ShapedType::kDynamicStrideOrOffset;
278 
279 ShapedType ShapedType::clone(ArrayRef<int64_t> shape, Type elementType) {
280   if (auto other = dyn_cast<MemRefType>()) {
281     MemRefType::Builder b(other);
282     b.setShape(shape);
283     b.setElementType(elementType);
284     return b;
285   }
286 
287   if (auto other = dyn_cast<UnrankedMemRefType>()) {
288     MemRefType::Builder b(shape, elementType);
289     b.setMemorySpace(other.getMemorySpace());
290     return b;
291   }
292 
293   if (isa<TensorType>())
294     return RankedTensorType::get(shape, elementType);
295 
296   if (isa<VectorType>())
297     return VectorType::get(shape, elementType);
298 
299   llvm_unreachable("Unhandled ShapedType clone case");
300 }
301 
302 ShapedType ShapedType::clone(ArrayRef<int64_t> shape) {
303   if (auto other = dyn_cast<MemRefType>()) {
304     MemRefType::Builder b(other);
305     b.setShape(shape);
306     return b;
307   }
308 
309   if (auto other = dyn_cast<UnrankedMemRefType>()) {
310     MemRefType::Builder b(shape, other.getElementType());
311     b.setShape(shape);
312     b.setMemorySpace(other.getMemorySpace());
313     return b;
314   }
315 
316   if (isa<TensorType>())
317     return RankedTensorType::get(shape, getElementType());
318 
319   if (isa<VectorType>())
320     return VectorType::get(shape, getElementType());
321 
322   llvm_unreachable("Unhandled ShapedType clone case");
323 }
324 
325 ShapedType ShapedType::clone(Type elementType) {
326   if (auto other = dyn_cast<MemRefType>()) {
327     MemRefType::Builder b(other);
328     b.setElementType(elementType);
329     return b;
330   }
331 
332   if (auto other = dyn_cast<UnrankedMemRefType>()) {
333     return UnrankedMemRefType::get(elementType, other.getMemorySpace());
334   }
335 
336   if (isa<TensorType>()) {
337     if (hasRank())
338       return RankedTensorType::get(getShape(), elementType);
339     return UnrankedTensorType::get(elementType);
340   }
341 
342   if (isa<VectorType>())
343     return VectorType::get(getShape(), elementType);
344 
345   llvm_unreachable("Unhandled ShapedType clone hit");
346 }
347 
348 Type ShapedType::getElementType() const {
349   return TypeSwitch<Type, Type>(*this)
350       .Case<VectorType, RankedTensorType, UnrankedTensorType, MemRefType,
351             UnrankedMemRefType>([](auto ty) { return ty.getElementType(); });
352 }
353 
354 unsigned ShapedType::getElementTypeBitWidth() const {
355   return getElementType().getIntOrFloatBitWidth();
356 }
357 
358 int64_t ShapedType::getNumElements() const {
359   assert(hasStaticShape() && "cannot get element count of dynamic shaped type");
360   auto shape = getShape();
361   int64_t num = 1;
362   for (auto dim : shape) {
363     num *= dim;
364     assert(num >= 0 && "integer overflow in element count computation");
365   }
366   return num;
367 }
368 
369 int64_t ShapedType::getRank() const {
370   assert(hasRank() && "cannot query rank of unranked shaped type");
371   return getShape().size();
372 }
373 
374 bool ShapedType::hasRank() const {
375   return !isa<UnrankedMemRefType, UnrankedTensorType>();
376 }
377 
378 int64_t ShapedType::getDimSize(unsigned idx) const {
379   assert(idx < getRank() && "invalid index for shaped type");
380   return getShape()[idx];
381 }
382 
383 bool ShapedType::isDynamicDim(unsigned idx) const {
384   assert(idx < getRank() && "invalid index for shaped type");
385   return isDynamic(getShape()[idx]);
386 }
387 
388 unsigned ShapedType::getDynamicDimIndex(unsigned index) const {
389   assert(index < getRank() && "invalid index");
390   assert(ShapedType::isDynamic(getDimSize(index)) && "invalid index");
391   return llvm::count_if(getShape().take_front(index), ShapedType::isDynamic);
392 }
393 
394 /// Get the number of bits require to store a value of the given shaped type.
395 /// Compute the value recursively since tensors are allowed to have vectors as
396 /// elements.
397 int64_t ShapedType::getSizeInBits() const {
398   assert(hasStaticShape() &&
399          "cannot get the bit size of an aggregate with a dynamic shape");
400 
401   auto elementType = getElementType();
402   if (elementType.isIntOrFloat())
403     return elementType.getIntOrFloatBitWidth() * getNumElements();
404 
405   if (auto complexType = elementType.dyn_cast<ComplexType>()) {
406     elementType = complexType.getElementType();
407     return elementType.getIntOrFloatBitWidth() * getNumElements() * 2;
408   }
409 
410   // Tensors can have vectors and other tensors as elements, other shaped types
411   // cannot.
412   assert(isa<TensorType>() && "unsupported element type");
413   assert((elementType.isa<VectorType, TensorType>()) &&
414          "unsupported tensor element type");
415   return getNumElements() * elementType.cast<ShapedType>().getSizeInBits();
416 }
417 
418 ArrayRef<int64_t> ShapedType::getShape() const {
419   if (auto vectorType = dyn_cast<VectorType>())
420     return vectorType.getShape();
421   if (auto tensorType = dyn_cast<RankedTensorType>())
422     return tensorType.getShape();
423   return cast<MemRefType>().getShape();
424 }
425 
426 int64_t ShapedType::getNumDynamicDims() const {
427   return llvm::count_if(getShape(), isDynamic);
428 }
429 
430 int64_t ShapedType::getRelativeIndexOfDynamicDim(unsigned dim) const {
431   assert(isDynamicDim(dim) && "expected a dynamic dim");
432   int nthDynamicIndex = -1;
433   for (unsigned idx = 0; idx <= dim; ++idx)
434     if (isDynamicDim(idx))
435       ++nthDynamicIndex;
436   return nthDynamicIndex;
437 }
438 
439 bool ShapedType::hasStaticShape() const {
440   return hasRank() && llvm::none_of(getShape(), isDynamic);
441 }
442 
443 bool ShapedType::hasStaticShape(ArrayRef<int64_t> shape) const {
444   return hasStaticShape() && getShape() == shape;
445 }
446 
447 //===----------------------------------------------------------------------===//
448 // VectorType
449 //===----------------------------------------------------------------------===//
450 
451 LogicalResult VectorType::verify(function_ref<InFlightDiagnostic()> emitError,
452                                  ArrayRef<int64_t> shape, Type elementType) {
453   if (shape.empty())
454     return emitError() << "vector types must have at least one dimension";
455 
456   if (!isValidElementType(elementType))
457     return emitError() << "vector elements must be int/index/float type";
458 
459   if (any_of(shape, [](int64_t i) { return i <= 0; }))
460     return emitError() << "vector types must have positive constant sizes";
461 
462   return success();
463 }
464 
465 VectorType VectorType::scaleElementBitwidth(unsigned scale) {
466   if (!scale)
467     return VectorType();
468   if (auto et = getElementType().dyn_cast<IntegerType>())
469     if (auto scaledEt = et.scaleElementBitwidth(scale))
470       return VectorType::get(getShape(), scaledEt);
471   if (auto et = getElementType().dyn_cast<FloatType>())
472     if (auto scaledEt = et.scaleElementBitwidth(scale))
473       return VectorType::get(getShape(), scaledEt);
474   return VectorType();
475 }
476 
477 void VectorType::walkImmediateSubElements(
478     function_ref<void(Attribute)> walkAttrsFn,
479     function_ref<void(Type)> walkTypesFn) const {
480   walkTypesFn(getElementType());
481 }
482 
483 //===----------------------------------------------------------------------===//
484 // TensorType
485 //===----------------------------------------------------------------------===//
486 
487 // Check if "elementType" can be an element type of a tensor.
488 static LogicalResult
489 checkTensorElementType(function_ref<InFlightDiagnostic()> emitError,
490                        Type elementType) {
491   if (!TensorType::isValidElementType(elementType))
492     return emitError() << "invalid tensor element type: " << elementType;
493   return success();
494 }
495 
496 /// Return true if the specified element type is ok in a tensor.
497 bool TensorType::isValidElementType(Type type) {
498   // Note: Non standard/builtin types are allowed to exist within tensor
499   // types. Dialects are expected to verify that tensor types have a valid
500   // element type within that dialect.
501   return type.isa<ComplexType, FloatType, IntegerType, OpaqueType, VectorType,
502                   IndexType>() ||
503          !type.getDialect().getNamespace().empty();
504 }
505 
506 //===----------------------------------------------------------------------===//
507 // RankedTensorType
508 //===----------------------------------------------------------------------===//
509 
510 LogicalResult
511 RankedTensorType::verify(function_ref<InFlightDiagnostic()> emitError,
512                          ArrayRef<int64_t> shape, Type elementType,
513                          Attribute encoding) {
514   for (int64_t s : shape)
515     if (s < -1)
516       return emitError() << "invalid tensor dimension size";
517   if (auto v = encoding.dyn_cast_or_null<VerifiableTensorEncoding>())
518     if (failed(v.verifyEncoding(shape, elementType, emitError)))
519       return failure();
520   return checkTensorElementType(emitError, elementType);
521 }
522 
523 void RankedTensorType::walkImmediateSubElements(
524     function_ref<void(Attribute)> walkAttrsFn,
525     function_ref<void(Type)> walkTypesFn) const {
526   walkTypesFn(getElementType());
527 }
528 
529 //===----------------------------------------------------------------------===//
530 // UnrankedTensorType
531 //===----------------------------------------------------------------------===//
532 
533 LogicalResult
534 UnrankedTensorType::verify(function_ref<InFlightDiagnostic()> emitError,
535                            Type elementType) {
536   return checkTensorElementType(emitError, elementType);
537 }
538 
539 void UnrankedTensorType::walkImmediateSubElements(
540     function_ref<void(Attribute)> walkAttrsFn,
541     function_ref<void(Type)> walkTypesFn) const {
542   walkTypesFn(getElementType());
543 }
544 
545 //===----------------------------------------------------------------------===//
546 // BaseMemRefType
547 //===----------------------------------------------------------------------===//
548 
549 Attribute BaseMemRefType::getMemorySpace() const {
550   if (auto rankedMemRefTy = dyn_cast<MemRefType>())
551     return rankedMemRefTy.getMemorySpace();
552   return cast<UnrankedMemRefType>().getMemorySpace();
553 }
554 
555 unsigned BaseMemRefType::getMemorySpaceAsInt() const {
556   if (auto rankedMemRefTy = dyn_cast<MemRefType>())
557     return rankedMemRefTy.getMemorySpaceAsInt();
558   return cast<UnrankedMemRefType>().getMemorySpaceAsInt();
559 }
560 
561 //===----------------------------------------------------------------------===//
562 // MemRefType
563 //===----------------------------------------------------------------------===//
564 
565 /// Given an `originalShape` and a `reducedShape` assumed to be a subset of
566 /// `originalShape` with some `1` entries erased, return the set of indices
567 /// that specifies which of the entries of `originalShape` are dropped to obtain
568 /// `reducedShape`. The returned mask can be applied as a projection to
569 /// `originalShape` to obtain the `reducedShape`. This mask is useful to track
570 /// which dimensions must be kept when e.g. compute MemRef strides under
571 /// rank-reducing operations. Return None if reducedShape cannot be obtained
572 /// by dropping only `1` entries in `originalShape`.
573 llvm::Optional<llvm::SmallDenseSet<unsigned>>
574 mlir::computeRankReductionMask(ArrayRef<int64_t> originalShape,
575                                ArrayRef<int64_t> reducedShape) {
576   size_t originalRank = originalShape.size(), reducedRank = reducedShape.size();
577   llvm::SmallDenseSet<unsigned> unusedDims;
578   unsigned reducedIdx = 0;
579   for (unsigned originalIdx = 0; originalIdx < originalRank; ++originalIdx) {
580     // Greedily insert `originalIdx` if no match.
581     if (reducedIdx < reducedRank &&
582         originalShape[originalIdx] == reducedShape[reducedIdx]) {
583       reducedIdx++;
584       continue;
585     }
586 
587     unusedDims.insert(originalIdx);
588     // If no match on `originalIdx`, the `originalShape` at this dimension
589     // must be 1, otherwise we bail.
590     if (originalShape[originalIdx] != 1)
591       return llvm::None;
592   }
593   // The whole reducedShape must be scanned, otherwise we bail.
594   if (reducedIdx != reducedRank)
595     return llvm::None;
596   return unusedDims;
597 }
598 
599 bool mlir::detail::isSupportedMemorySpace(Attribute memorySpace) {
600   // Empty attribute is allowed as default memory space.
601   if (!memorySpace)
602     return true;
603 
604   // Supported built-in attributes.
605   if (memorySpace.isa<IntegerAttr, StringAttr, DictionaryAttr>())
606     return true;
607 
608   // Allow custom dialect attributes.
609   if (!::mlir::isa<BuiltinDialect>(memorySpace.getDialect()))
610     return true;
611 
612   return false;
613 }
614 
615 Attribute mlir::detail::wrapIntegerMemorySpace(unsigned memorySpace,
616                                                MLIRContext *ctx) {
617   if (memorySpace == 0)
618     return nullptr;
619 
620   return IntegerAttr::get(IntegerType::get(ctx, 64), memorySpace);
621 }
622 
623 Attribute mlir::detail::skipDefaultMemorySpace(Attribute memorySpace) {
624   IntegerAttr intMemorySpace = memorySpace.dyn_cast_or_null<IntegerAttr>();
625   if (intMemorySpace && intMemorySpace.getValue() == 0)
626     return nullptr;
627 
628   return memorySpace;
629 }
630 
631 unsigned mlir::detail::getMemorySpaceAsInt(Attribute memorySpace) {
632   if (!memorySpace)
633     return 0;
634 
635   assert(memorySpace.isa<IntegerAttr>() &&
636          "Using `getMemorySpaceInteger` with non-Integer attribute");
637 
638   return static_cast<unsigned>(memorySpace.cast<IntegerAttr>().getInt());
639 }
640 
641 MemRefType::Builder &
642 MemRefType::Builder::setMemorySpace(unsigned newMemorySpace) {
643   memorySpace =
644       wrapIntegerMemorySpace(newMemorySpace, elementType.getContext());
645   return *this;
646 }
647 
648 unsigned MemRefType::getMemorySpaceAsInt() const {
649   return detail::getMemorySpaceAsInt(getMemorySpace());
650 }
651 
652 LogicalResult MemRefType::verify(function_ref<InFlightDiagnostic()> emitError,
653                                  ArrayRef<int64_t> shape, Type elementType,
654                                  ArrayRef<AffineMap> affineMapComposition,
655                                  Attribute memorySpace) {
656   if (!BaseMemRefType::isValidElementType(elementType))
657     return emitError() << "invalid memref element type";
658 
659   // Negative sizes are not allowed except for `-1` that means dynamic size.
660   for (int64_t s : shape)
661     if (s < -1)
662       return emitError() << "invalid memref size";
663 
664   // Check that the structure of the composition is valid, i.e. that each
665   // subsequent affine map has as many inputs as the previous map has results.
666   // Take the dimensionality of the MemRef for the first map.
667   size_t dim = shape.size();
668   for (auto it : llvm::enumerate(affineMapComposition)) {
669     AffineMap map = it.value();
670     if (map.getNumDims() == dim) {
671       dim = map.getNumResults();
672       continue;
673     }
674     return emitError() << "memref affine map dimension mismatch between "
675                        << (it.index() == 0 ? Twine("memref rank")
676                                            : "affine map " + Twine(it.index()))
677                        << " and affine map" << it.index() + 1 << ": " << dim
678                        << " != " << map.getNumDims();
679   }
680 
681   if (!isSupportedMemorySpace(memorySpace)) {
682     return emitError() << "unsupported memory space Attribute";
683   }
684 
685   return success();
686 }
687 
688 void MemRefType::walkImmediateSubElements(
689     function_ref<void(Attribute)> walkAttrsFn,
690     function_ref<void(Type)> walkTypesFn) const {
691   walkTypesFn(getElementType());
692   walkAttrsFn(getMemorySpace());
693   for (AffineMap map : getAffineMaps())
694     walkAttrsFn(AffineMapAttr::get(map));
695 }
696 
697 //===----------------------------------------------------------------------===//
698 // UnrankedMemRefType
699 //===----------------------------------------------------------------------===//
700 
701 unsigned UnrankedMemRefType::getMemorySpaceAsInt() const {
702   return detail::getMemorySpaceAsInt(getMemorySpace());
703 }
704 
705 LogicalResult
706 UnrankedMemRefType::verify(function_ref<InFlightDiagnostic()> emitError,
707                            Type elementType, Attribute memorySpace) {
708   if (!BaseMemRefType::isValidElementType(elementType))
709     return emitError() << "invalid memref element type";
710 
711   if (!isSupportedMemorySpace(memorySpace))
712     return emitError() << "unsupported memory space Attribute";
713 
714   return success();
715 }
716 
717 // Fallback cases for terminal dim/sym/cst that are not part of a binary op (
718 // i.e. single term). Accumulate the AffineExpr into the existing one.
719 static void extractStridesFromTerm(AffineExpr e,
720                                    AffineExpr multiplicativeFactor,
721                                    MutableArrayRef<AffineExpr> strides,
722                                    AffineExpr &offset) {
723   if (auto dim = e.dyn_cast<AffineDimExpr>())
724     strides[dim.getPosition()] =
725         strides[dim.getPosition()] + multiplicativeFactor;
726   else
727     offset = offset + e * multiplicativeFactor;
728 }
729 
730 /// Takes a single AffineExpr `e` and populates the `strides` array with the
731 /// strides expressions for each dim position.
732 /// The convention is that the strides for dimensions d0, .. dn appear in
733 /// order to make indexing intuitive into the result.
734 static LogicalResult extractStrides(AffineExpr e,
735                                     AffineExpr multiplicativeFactor,
736                                     MutableArrayRef<AffineExpr> strides,
737                                     AffineExpr &offset) {
738   auto bin = e.dyn_cast<AffineBinaryOpExpr>();
739   if (!bin) {
740     extractStridesFromTerm(e, multiplicativeFactor, strides, offset);
741     return success();
742   }
743 
744   if (bin.getKind() == AffineExprKind::CeilDiv ||
745       bin.getKind() == AffineExprKind::FloorDiv ||
746       bin.getKind() == AffineExprKind::Mod)
747     return failure();
748 
749   if (bin.getKind() == AffineExprKind::Mul) {
750     auto dim = bin.getLHS().dyn_cast<AffineDimExpr>();
751     if (dim) {
752       strides[dim.getPosition()] =
753           strides[dim.getPosition()] + bin.getRHS() * multiplicativeFactor;
754       return success();
755     }
756     // LHS and RHS may both contain complex expressions of dims. Try one path
757     // and if it fails try the other. This is guaranteed to succeed because
758     // only one path may have a `dim`, otherwise this is not an AffineExpr in
759     // the first place.
760     if (bin.getLHS().isSymbolicOrConstant())
761       return extractStrides(bin.getRHS(), multiplicativeFactor * bin.getLHS(),
762                             strides, offset);
763     return extractStrides(bin.getLHS(), multiplicativeFactor * bin.getRHS(),
764                           strides, offset);
765   }
766 
767   if (bin.getKind() == AffineExprKind::Add) {
768     auto res1 =
769         extractStrides(bin.getLHS(), multiplicativeFactor, strides, offset);
770     auto res2 =
771         extractStrides(bin.getRHS(), multiplicativeFactor, strides, offset);
772     return success(succeeded(res1) && succeeded(res2));
773   }
774 
775   llvm_unreachable("unexpected binary operation");
776 }
777 
778 LogicalResult mlir::getStridesAndOffset(MemRefType t,
779                                         SmallVectorImpl<AffineExpr> &strides,
780                                         AffineExpr &offset) {
781   auto affineMaps = t.getAffineMaps();
782 
783   if (!affineMaps.empty() && affineMaps.back().getNumResults() != 1)
784     return failure();
785 
786   AffineMap m;
787   if (!affineMaps.empty()) {
788     m = affineMaps.back();
789     for (size_t i = affineMaps.size() - 1; i > 0; --i)
790       m = m.compose(affineMaps[i - 1]);
791     assert(!m.isIdentity() && "unexpected identity map");
792   }
793 
794   auto zero = getAffineConstantExpr(0, t.getContext());
795   auto one = getAffineConstantExpr(1, t.getContext());
796   offset = zero;
797   strides.assign(t.getRank(), zero);
798 
799   // Canonical case for empty map.
800   if (!m) {
801     // 0-D corner case, offset is already 0.
802     if (t.getRank() == 0)
803       return success();
804     auto stridedExpr =
805         makeCanonicalStridedLayoutExpr(t.getShape(), t.getContext());
806     if (succeeded(extractStrides(stridedExpr, one, strides, offset)))
807       return success();
808     assert(false && "unexpected failure: extract strides in canonical layout");
809   }
810 
811   // Non-canonical case requires more work.
812   auto stridedExpr =
813       simplifyAffineExpr(m.getResult(0), m.getNumDims(), m.getNumSymbols());
814   if (failed(extractStrides(stridedExpr, one, strides, offset))) {
815     offset = AffineExpr();
816     strides.clear();
817     return failure();
818   }
819 
820   // Simplify results to allow folding to constants and simple checks.
821   unsigned numDims = m.getNumDims();
822   unsigned numSymbols = m.getNumSymbols();
823   offset = simplifyAffineExpr(offset, numDims, numSymbols);
824   for (auto &stride : strides)
825     stride = simplifyAffineExpr(stride, numDims, numSymbols);
826 
827   /// In practice, a strided memref must be internally non-aliasing. Test
828   /// against 0 as a proxy.
829   /// TODO: static cases can have more advanced checks.
830   /// TODO: dynamic cases would require a way to compare symbolic
831   /// expressions and would probably need an affine set context propagated
832   /// everywhere.
833   if (llvm::any_of(strides, [](AffineExpr e) {
834         return e == getAffineConstantExpr(0, e.getContext());
835       })) {
836     offset = AffineExpr();
837     strides.clear();
838     return failure();
839   }
840 
841   return success();
842 }
843 
844 LogicalResult mlir::getStridesAndOffset(MemRefType t,
845                                         SmallVectorImpl<int64_t> &strides,
846                                         int64_t &offset) {
847   AffineExpr offsetExpr;
848   SmallVector<AffineExpr, 4> strideExprs;
849   if (failed(::getStridesAndOffset(t, strideExprs, offsetExpr)))
850     return failure();
851   if (auto cst = offsetExpr.dyn_cast<AffineConstantExpr>())
852     offset = cst.getValue();
853   else
854     offset = ShapedType::kDynamicStrideOrOffset;
855   for (auto e : strideExprs) {
856     if (auto c = e.dyn_cast<AffineConstantExpr>())
857       strides.push_back(c.getValue());
858     else
859       strides.push_back(ShapedType::kDynamicStrideOrOffset);
860   }
861   return success();
862 }
863 
864 void UnrankedMemRefType::walkImmediateSubElements(
865     function_ref<void(Attribute)> walkAttrsFn,
866     function_ref<void(Type)> walkTypesFn) const {
867   walkTypesFn(getElementType());
868   walkAttrsFn(getMemorySpace());
869 }
870 
871 //===----------------------------------------------------------------------===//
872 /// TupleType
873 //===----------------------------------------------------------------------===//
874 
875 /// Return the elements types for this tuple.
876 ArrayRef<Type> TupleType::getTypes() const { return getImpl()->getTypes(); }
877 
878 /// Accumulate the types contained in this tuple and tuples nested within it.
879 /// Note that this only flattens nested tuples, not any other container type,
880 /// e.g. a tuple<i32, tensor<i32>, tuple<f32, tuple<i64>>> is flattened to
881 /// (i32, tensor<i32>, f32, i64)
882 void TupleType::getFlattenedTypes(SmallVectorImpl<Type> &types) {
883   for (Type type : getTypes()) {
884     if (auto nestedTuple = type.dyn_cast<TupleType>())
885       nestedTuple.getFlattenedTypes(types);
886     else
887       types.push_back(type);
888   }
889 }
890 
891 /// Return the number of element types.
892 size_t TupleType::size() const { return getImpl()->size(); }
893 
894 void TupleType::walkImmediateSubElements(
895     function_ref<void(Attribute)> walkAttrsFn,
896     function_ref<void(Type)> walkTypesFn) const {
897   for (Type type : getTypes())
898     walkTypesFn(type);
899 }
900 
901 //===----------------------------------------------------------------------===//
902 // Type Utilities
903 //===----------------------------------------------------------------------===//
904 
905 AffineMap mlir::makeStridedLinearLayoutMap(ArrayRef<int64_t> strides,
906                                            int64_t offset,
907                                            MLIRContext *context) {
908   AffineExpr expr;
909   unsigned nSymbols = 0;
910 
911   // AffineExpr for offset.
912   // Static case.
913   if (offset != MemRefType::getDynamicStrideOrOffset()) {
914     auto cst = getAffineConstantExpr(offset, context);
915     expr = cst;
916   } else {
917     // Dynamic case, new symbol for the offset.
918     auto sym = getAffineSymbolExpr(nSymbols++, context);
919     expr = sym;
920   }
921 
922   // AffineExpr for strides.
923   for (auto en : llvm::enumerate(strides)) {
924     auto dim = en.index();
925     auto stride = en.value();
926     assert(stride != 0 && "Invalid stride specification");
927     auto d = getAffineDimExpr(dim, context);
928     AffineExpr mult;
929     // Static case.
930     if (stride != MemRefType::getDynamicStrideOrOffset())
931       mult = getAffineConstantExpr(stride, context);
932     else
933       // Dynamic case, new symbol for each new stride.
934       mult = getAffineSymbolExpr(nSymbols++, context);
935     expr = expr + d * mult;
936   }
937 
938   return AffineMap::get(strides.size(), nSymbols, expr);
939 }
940 
941 /// Return a version of `t` with identity layout if it can be determined
942 /// statically that the layout is the canonical contiguous strided layout.
943 /// Otherwise pass `t`'s layout into `simplifyAffineMap` and return a copy of
944 /// `t` with simplified layout.
945 /// If `t` has multiple layout maps or a multi-result layout, just return `t`.
946 MemRefType mlir::canonicalizeStridedLayout(MemRefType t) {
947   auto affineMaps = t.getAffineMaps();
948   // Already in canonical form.
949   if (affineMaps.empty())
950     return t;
951 
952   // Can't reduce to canonical identity form, return in canonical form.
953   if (affineMaps.size() > 1 || affineMaps[0].getNumResults() > 1)
954     return t;
955 
956   // Corner-case for 0-D affine maps.
957   auto m = affineMaps[0];
958   if (m.getNumDims() == 0 && m.getNumSymbols() == 0) {
959     if (auto cst = m.getResult(0).dyn_cast<AffineConstantExpr>())
960       if (cst.getValue() == 0)
961         return MemRefType::Builder(t).setAffineMaps({});
962     return t;
963   }
964 
965   // 0-D corner case for empty shape that still have an affine map. Example:
966   // `memref<f32, affine_map<()[s0] -> (s0)>>`. This is a 1 element memref whose
967   // offset needs to remain, just return t.
968   if (t.getShape().empty())
969     return t;
970 
971   // If the canonical strided layout for the sizes of `t` is equal to the
972   // simplified layout of `t` we can just return an empty layout. Otherwise,
973   // just simplify the existing layout.
974   AffineExpr expr =
975       makeCanonicalStridedLayoutExpr(t.getShape(), t.getContext());
976   auto simplifiedLayoutExpr =
977       simplifyAffineExpr(m.getResult(0), m.getNumDims(), m.getNumSymbols());
978   if (expr != simplifiedLayoutExpr)
979     return MemRefType::Builder(t).setAffineMaps({AffineMap::get(
980         m.getNumDims(), m.getNumSymbols(), simplifiedLayoutExpr)});
981   return MemRefType::Builder(t).setAffineMaps({});
982 }
983 
984 AffineExpr mlir::makeCanonicalStridedLayoutExpr(ArrayRef<int64_t> sizes,
985                                                 ArrayRef<AffineExpr> exprs,
986                                                 MLIRContext *context) {
987   assert(!sizes.empty() && !exprs.empty() &&
988          "expected non-empty sizes and exprs");
989 
990   // Size 0 corner case is useful for canonicalizations.
991   if (llvm::is_contained(sizes, 0))
992     return getAffineConstantExpr(0, context);
993 
994   auto maps = AffineMap::inferFromExprList(exprs);
995   assert(!maps.empty() && "Expected one non-empty map");
996   unsigned numDims = maps[0].getNumDims(), nSymbols = maps[0].getNumSymbols();
997 
998   AffineExpr expr;
999   bool dynamicPoisonBit = false;
1000   int64_t runningSize = 1;
1001   for (auto en : llvm::zip(llvm::reverse(exprs), llvm::reverse(sizes))) {
1002     int64_t size = std::get<1>(en);
1003     // Degenerate case, no size =-> no stride
1004     if (size == 0)
1005       continue;
1006     AffineExpr dimExpr = std::get<0>(en);
1007     AffineExpr stride = dynamicPoisonBit
1008                             ? getAffineSymbolExpr(nSymbols++, context)
1009                             : getAffineConstantExpr(runningSize, context);
1010     expr = expr ? expr + dimExpr * stride : dimExpr * stride;
1011     if (size > 0) {
1012       runningSize *= size;
1013       assert(runningSize > 0 && "integer overflow in size computation");
1014     } else {
1015       dynamicPoisonBit = true;
1016     }
1017   }
1018   return simplifyAffineExpr(expr, numDims, nSymbols);
1019 }
1020 
1021 /// Return a version of `t` with a layout that has all dynamic offset and
1022 /// strides. This is used to erase the static layout.
1023 MemRefType mlir::eraseStridedLayout(MemRefType t) {
1024   auto val = ShapedType::kDynamicStrideOrOffset;
1025   return MemRefType::Builder(t).setAffineMaps(makeStridedLinearLayoutMap(
1026       SmallVector<int64_t, 4>(t.getRank(), val), val, t.getContext()));
1027 }
1028 
1029 AffineExpr mlir::makeCanonicalStridedLayoutExpr(ArrayRef<int64_t> sizes,
1030                                                 MLIRContext *context) {
1031   SmallVector<AffineExpr, 4> exprs;
1032   exprs.reserve(sizes.size());
1033   for (auto dim : llvm::seq<unsigned>(0, sizes.size()))
1034     exprs.push_back(getAffineDimExpr(dim, context));
1035   return makeCanonicalStridedLayoutExpr(sizes, exprs, context);
1036 }
1037 
1038 /// Return true if the layout for `t` is compatible with strided semantics.
1039 bool mlir::isStrided(MemRefType t) {
1040   int64_t offset;
1041   SmallVector<int64_t, 4> strides;
1042   auto res = getStridesAndOffset(t, strides, offset);
1043   return succeeded(res);
1044 }
1045 
1046 /// Return the layout map in strided linear layout AffineMap form.
1047 /// Return null if the layout is not compatible with a strided layout.
1048 AffineMap mlir::getStridedLinearLayoutMap(MemRefType t) {
1049   int64_t offset;
1050   SmallVector<int64_t, 4> strides;
1051   if (failed(getStridesAndOffset(t, strides, offset)))
1052     return AffineMap();
1053   return makeStridedLinearLayoutMap(strides, offset, t.getContext());
1054 }
1055