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 without the specified arguments and results.
176 FunctionType
177 FunctionType::getWithoutArgsAndResults(ArrayRef<unsigned> argIndices,
178                                        ArrayRef<unsigned> resultIndices) {
179   ArrayRef<Type> newInputTypes = getInputs();
180   SmallVector<Type, 4> newInputTypesBuffer;
181   if (!argIndices.empty()) {
182     unsigned originalNumArgs = getNumInputs();
183     iterateIndicesExcept(originalNumArgs, argIndices, [&](unsigned i) {
184       newInputTypesBuffer.emplace_back(getInput(i));
185     });
186     newInputTypes = newInputTypesBuffer;
187   }
188 
189   ArrayRef<Type> newResultTypes = getResults();
190   SmallVector<Type, 4> newResultTypesBuffer;
191   if (!resultIndices.empty()) {
192     unsigned originalNumResults = getNumResults();
193     iterateIndicesExcept(originalNumResults, resultIndices, [&](unsigned i) {
194       newResultTypesBuffer.emplace_back(getResult(i));
195     });
196     newResultTypes = newResultTypesBuffer;
197   }
198 
199   return get(getContext(), newInputTypes, newResultTypes);
200 }
201 
202 //===----------------------------------------------------------------------===//
203 // OpaqueType
204 //===----------------------------------------------------------------------===//
205 
206 /// Verify the construction of an opaque type.
207 LogicalResult OpaqueType::verify(function_ref<InFlightDiagnostic()> emitError,
208                                  Identifier dialect, StringRef typeData) {
209   if (!Dialect::isValidNamespace(dialect.strref()))
210     return emitError() << "invalid dialect namespace '" << dialect << "'";
211 
212   // Check that the dialect is actually registered.
213   MLIRContext *context = dialect.getContext();
214   if (!context->allowsUnregisteredDialects() &&
215       !context->getLoadedDialect(dialect.strref())) {
216     return emitError()
217            << "`!" << dialect << "<\"" << typeData << "\">"
218            << "` type created with unregistered dialect. If this is "
219               "intended, please call allowUnregisteredDialects() on the "
220               "MLIRContext, or use -allow-unregistered-dialect with "
221               "mlir-opt";
222   }
223 
224   return success();
225 }
226 
227 //===----------------------------------------------------------------------===//
228 // ShapedType
229 //===----------------------------------------------------------------------===//
230 constexpr int64_t ShapedType::kDynamicSize;
231 constexpr int64_t ShapedType::kDynamicStrideOrOffset;
232 
233 ShapedType ShapedType::clone(ArrayRef<int64_t> shape, Type elementType) {
234   if (auto other = dyn_cast<MemRefType>()) {
235     MemRefType::Builder b(other);
236     b.setShape(shape);
237     b.setElementType(elementType);
238     return b;
239   }
240 
241   if (auto other = dyn_cast<UnrankedMemRefType>()) {
242     MemRefType::Builder b(shape, elementType);
243     b.setMemorySpace(other.getMemorySpace());
244     return b;
245   }
246 
247   if (isa<TensorType>())
248     return RankedTensorType::get(shape, elementType);
249 
250   if (isa<VectorType>())
251     return VectorType::get(shape, elementType);
252 
253   llvm_unreachable("Unhandled ShapedType clone case");
254 }
255 
256 ShapedType ShapedType::clone(ArrayRef<int64_t> shape) {
257   if (auto other = dyn_cast<MemRefType>()) {
258     MemRefType::Builder b(other);
259     b.setShape(shape);
260     return b;
261   }
262 
263   if (auto other = dyn_cast<UnrankedMemRefType>()) {
264     MemRefType::Builder b(shape, other.getElementType());
265     b.setShape(shape);
266     b.setMemorySpace(other.getMemorySpace());
267     return b;
268   }
269 
270   if (isa<TensorType>())
271     return RankedTensorType::get(shape, getElementType());
272 
273   if (isa<VectorType>())
274     return VectorType::get(shape, getElementType());
275 
276   llvm_unreachable("Unhandled ShapedType clone case");
277 }
278 
279 ShapedType ShapedType::clone(Type elementType) {
280   if (auto other = dyn_cast<MemRefType>()) {
281     MemRefType::Builder b(other);
282     b.setElementType(elementType);
283     return b;
284   }
285 
286   if (auto other = dyn_cast<UnrankedMemRefType>()) {
287     return UnrankedMemRefType::get(elementType, other.getMemorySpace());
288   }
289 
290   if (isa<TensorType>()) {
291     if (hasRank())
292       return RankedTensorType::get(getShape(), elementType);
293     return UnrankedTensorType::get(elementType);
294   }
295 
296   if (isa<VectorType>())
297     return VectorType::get(getShape(), elementType);
298 
299   llvm_unreachable("Unhandled ShapedType clone hit");
300 }
301 
302 Type ShapedType::getElementType() const {
303   return TypeSwitch<Type, Type>(*this)
304       .Case<VectorType, RankedTensorType, UnrankedTensorType, MemRefType,
305             UnrankedMemRefType>([](auto ty) { return ty.getElementType(); });
306 }
307 
308 unsigned ShapedType::getElementTypeBitWidth() const {
309   return getElementType().getIntOrFloatBitWidth();
310 }
311 
312 int64_t ShapedType::getNumElements() const {
313   assert(hasStaticShape() && "cannot get element count of dynamic shaped type");
314   auto shape = getShape();
315   int64_t num = 1;
316   for (auto dim : shape) {
317     num *= dim;
318     assert(num >= 0 && "integer overflow in element count computation");
319   }
320   return num;
321 }
322 
323 int64_t ShapedType::getRank() const {
324   assert(hasRank() && "cannot query rank of unranked shaped type");
325   return getShape().size();
326 }
327 
328 bool ShapedType::hasRank() const {
329   return !isa<UnrankedMemRefType, UnrankedTensorType>();
330 }
331 
332 int64_t ShapedType::getDimSize(unsigned idx) const {
333   assert(idx < getRank() && "invalid index for shaped type");
334   return getShape()[idx];
335 }
336 
337 bool ShapedType::isDynamicDim(unsigned idx) const {
338   assert(idx < getRank() && "invalid index for shaped type");
339   return isDynamic(getShape()[idx]);
340 }
341 
342 unsigned ShapedType::getDynamicDimIndex(unsigned index) const {
343   assert(index < getRank() && "invalid index");
344   assert(ShapedType::isDynamic(getDimSize(index)) && "invalid index");
345   return llvm::count_if(getShape().take_front(index), ShapedType::isDynamic);
346 }
347 
348 /// Get the number of bits require to store a value of the given shaped type.
349 /// Compute the value recursively since tensors are allowed to have vectors as
350 /// elements.
351 int64_t ShapedType::getSizeInBits() const {
352   assert(hasStaticShape() &&
353          "cannot get the bit size of an aggregate with a dynamic shape");
354 
355   auto elementType = getElementType();
356   if (elementType.isIntOrFloat())
357     return elementType.getIntOrFloatBitWidth() * getNumElements();
358 
359   if (auto complexType = elementType.dyn_cast<ComplexType>()) {
360     elementType = complexType.getElementType();
361     return elementType.getIntOrFloatBitWidth() * getNumElements() * 2;
362   }
363 
364   // Tensors can have vectors and other tensors as elements, other shaped types
365   // cannot.
366   assert(isa<TensorType>() && "unsupported element type");
367   assert((elementType.isa<VectorType, TensorType>()) &&
368          "unsupported tensor element type");
369   return getNumElements() * elementType.cast<ShapedType>().getSizeInBits();
370 }
371 
372 ArrayRef<int64_t> ShapedType::getShape() const {
373   if (auto vectorType = dyn_cast<VectorType>())
374     return vectorType.getShape();
375   if (auto tensorType = dyn_cast<RankedTensorType>())
376     return tensorType.getShape();
377   return cast<MemRefType>().getShape();
378 }
379 
380 int64_t ShapedType::getNumDynamicDims() const {
381   return llvm::count_if(getShape(), isDynamic);
382 }
383 
384 bool ShapedType::hasStaticShape() const {
385   return hasRank() && llvm::none_of(getShape(), isDynamic);
386 }
387 
388 bool ShapedType::hasStaticShape(ArrayRef<int64_t> shape) const {
389   return hasStaticShape() && getShape() == shape;
390 }
391 
392 //===----------------------------------------------------------------------===//
393 // VectorType
394 //===----------------------------------------------------------------------===//
395 
396 LogicalResult VectorType::verify(function_ref<InFlightDiagnostic()> emitError,
397                                  ArrayRef<int64_t> shape, Type elementType) {
398   if (shape.empty())
399     return emitError() << "vector types must have at least one dimension";
400 
401   if (!isValidElementType(elementType))
402     return emitError() << "vector elements must be int/index/float type";
403 
404   if (any_of(shape, [](int64_t i) { return i <= 0; }))
405     return emitError() << "vector types must have positive constant sizes";
406 
407   return success();
408 }
409 
410 VectorType VectorType::scaleElementBitwidth(unsigned scale) {
411   if (!scale)
412     return VectorType();
413   if (auto et = getElementType().dyn_cast<IntegerType>())
414     if (auto scaledEt = et.scaleElementBitwidth(scale))
415       return VectorType::get(getShape(), scaledEt);
416   if (auto et = getElementType().dyn_cast<FloatType>())
417     if (auto scaledEt = et.scaleElementBitwidth(scale))
418       return VectorType::get(getShape(), scaledEt);
419   return VectorType();
420 }
421 
422 //===----------------------------------------------------------------------===//
423 // TensorType
424 //===----------------------------------------------------------------------===//
425 
426 // Check if "elementType" can be an element type of a tensor.
427 static LogicalResult
428 checkTensorElementType(function_ref<InFlightDiagnostic()> emitError,
429                        Type elementType) {
430   if (!TensorType::isValidElementType(elementType))
431     return emitError() << "invalid tensor element type: " << elementType;
432   return success();
433 }
434 
435 /// Return true if the specified element type is ok in a tensor.
436 bool TensorType::isValidElementType(Type type) {
437   // Note: Non standard/builtin types are allowed to exist within tensor
438   // types. Dialects are expected to verify that tensor types have a valid
439   // element type within that dialect.
440   return type.isa<ComplexType, FloatType, IntegerType, OpaqueType, VectorType,
441                   IndexType>() ||
442          !type.getDialect().getNamespace().empty();
443 }
444 
445 //===----------------------------------------------------------------------===//
446 // RankedTensorType
447 //===----------------------------------------------------------------------===//
448 
449 LogicalResult
450 RankedTensorType::verify(function_ref<InFlightDiagnostic()> emitError,
451                          ArrayRef<int64_t> shape, Type elementType,
452                          Attribute encoding) {
453   for (int64_t s : shape)
454     if (s < -1)
455       return emitError() << "invalid tensor dimension size";
456   if (auto v = encoding.dyn_cast_or_null<VerifiableTensorEncoding>())
457     if (failed(v.verifyEncoding(shape, elementType, emitError)))
458       return failure();
459   return checkTensorElementType(emitError, elementType);
460 }
461 
462 //===----------------------------------------------------------------------===//
463 // UnrankedTensorType
464 //===----------------------------------------------------------------------===//
465 
466 LogicalResult
467 UnrankedTensorType::verify(function_ref<InFlightDiagnostic()> emitError,
468                            Type elementType) {
469   return checkTensorElementType(emitError, elementType);
470 }
471 
472 //===----------------------------------------------------------------------===//
473 // BaseMemRefType
474 //===----------------------------------------------------------------------===//
475 
476 Attribute BaseMemRefType::getMemorySpace() const {
477   if (auto rankedMemRefTy = dyn_cast<MemRefType>())
478     return rankedMemRefTy.getMemorySpace();
479   return cast<UnrankedMemRefType>().getMemorySpace();
480 }
481 
482 unsigned BaseMemRefType::getMemorySpaceAsInt() const {
483   if (auto rankedMemRefTy = dyn_cast<MemRefType>())
484     return rankedMemRefTy.getMemorySpaceAsInt();
485   return cast<UnrankedMemRefType>().getMemorySpaceAsInt();
486 }
487 
488 //===----------------------------------------------------------------------===//
489 // MemRefType
490 //===----------------------------------------------------------------------===//
491 
492 /// Given an `originalShape` and a `reducedShape` assumed to be a subset of
493 /// `originalShape` with some `1` entries erased, return the set of indices
494 /// that specifies which of the entries of `originalShape` are dropped to obtain
495 /// `reducedShape`. The returned mask can be applied as a projection to
496 /// `originalShape` to obtain the `reducedShape`. This mask is useful to track
497 /// which dimensions must be kept when e.g. compute MemRef strides under
498 /// rank-reducing operations. Return None if reducedShape cannot be obtained
499 /// by dropping only `1` entries in `originalShape`.
500 llvm::Optional<llvm::SmallDenseSet<unsigned>>
501 mlir::computeRankReductionMask(ArrayRef<int64_t> originalShape,
502                                ArrayRef<int64_t> reducedShape) {
503   size_t originalRank = originalShape.size(), reducedRank = reducedShape.size();
504   llvm::SmallDenseSet<unsigned> unusedDims;
505   unsigned reducedIdx = 0;
506   for (unsigned originalIdx = 0; originalIdx < originalRank; ++originalIdx) {
507     // Greedily insert `originalIdx` if no match.
508     if (reducedIdx < reducedRank &&
509         originalShape[originalIdx] == reducedShape[reducedIdx]) {
510       reducedIdx++;
511       continue;
512     }
513 
514     unusedDims.insert(originalIdx);
515     // If no match on `originalIdx`, the `originalShape` at this dimension
516     // must be 1, otherwise we bail.
517     if (originalShape[originalIdx] != 1)
518       return llvm::None;
519   }
520   // The whole reducedShape must be scanned, otherwise we bail.
521   if (reducedIdx != reducedRank)
522     return llvm::None;
523   return unusedDims;
524 }
525 
526 bool mlir::detail::isSupportedMemorySpace(Attribute memorySpace) {
527   // Empty attribute is allowed as default memory space.
528   if (!memorySpace)
529     return true;
530 
531   // Supported built-in attributes.
532   if (memorySpace.isa<IntegerAttr, StringAttr, DictionaryAttr>())
533     return true;
534 
535   // Allow custom dialect attributes.
536   if (!::mlir::isa<BuiltinDialect>(memorySpace.getDialect()))
537     return true;
538 
539   return false;
540 }
541 
542 Attribute mlir::detail::wrapIntegerMemorySpace(unsigned memorySpace,
543                                                MLIRContext *ctx) {
544   if (memorySpace == 0)
545     return nullptr;
546 
547   return IntegerAttr::get(IntegerType::get(ctx, 64), memorySpace);
548 }
549 
550 Attribute mlir::detail::skipDefaultMemorySpace(Attribute memorySpace) {
551   IntegerAttr intMemorySpace = memorySpace.dyn_cast_or_null<IntegerAttr>();
552   if (intMemorySpace && intMemorySpace.getValue() == 0)
553     return nullptr;
554 
555   return memorySpace;
556 }
557 
558 unsigned mlir::detail::getMemorySpaceAsInt(Attribute memorySpace) {
559   if (!memorySpace)
560     return 0;
561 
562   assert(memorySpace.isa<IntegerAttr>() &&
563          "Using `getMemorySpaceInteger` with non-Integer attribute");
564 
565   return static_cast<unsigned>(memorySpace.cast<IntegerAttr>().getInt());
566 }
567 
568 MemRefType::Builder &
569 MemRefType::Builder::setMemorySpace(unsigned newMemorySpace) {
570   memorySpace =
571       wrapIntegerMemorySpace(newMemorySpace, elementType.getContext());
572   return *this;
573 }
574 
575 unsigned MemRefType::getMemorySpaceAsInt() const {
576   return detail::getMemorySpaceAsInt(getMemorySpace());
577 }
578 
579 LogicalResult MemRefType::verify(function_ref<InFlightDiagnostic()> emitError,
580                                  ArrayRef<int64_t> shape, Type elementType,
581                                  ArrayRef<AffineMap> affineMapComposition,
582                                  Attribute memorySpace) {
583   if (!BaseMemRefType::isValidElementType(elementType))
584     return emitError() << "invalid memref element type";
585 
586   // Negative sizes are not allowed except for `-1` that means dynamic size.
587   for (int64_t s : shape)
588     if (s < -1)
589       return emitError() << "invalid memref size";
590 
591   // Check that the structure of the composition is valid, i.e. that each
592   // subsequent affine map has as many inputs as the previous map has results.
593   // Take the dimensionality of the MemRef for the first map.
594   size_t dim = shape.size();
595   for (auto it : llvm::enumerate(affineMapComposition)) {
596     AffineMap map = it.value();
597     if (map.getNumDims() == dim) {
598       dim = map.getNumResults();
599       continue;
600     }
601     return emitError() << "memref affine map dimension mismatch between "
602                        << (it.index() == 0 ? Twine("memref rank")
603                                            : "affine map " + Twine(it.index()))
604                        << " and affine map" << it.index() + 1 << ": " << dim
605                        << " != " << map.getNumDims();
606   }
607 
608   if (!isSupportedMemorySpace(memorySpace)) {
609     return emitError() << "unsupported memory space Attribute";
610   }
611 
612   return success();
613 }
614 
615 //===----------------------------------------------------------------------===//
616 // UnrankedMemRefType
617 //===----------------------------------------------------------------------===//
618 
619 unsigned UnrankedMemRefType::getMemorySpaceAsInt() const {
620   return detail::getMemorySpaceAsInt(getMemorySpace());
621 }
622 
623 LogicalResult
624 UnrankedMemRefType::verify(function_ref<InFlightDiagnostic()> emitError,
625                            Type elementType, Attribute memorySpace) {
626   if (!BaseMemRefType::isValidElementType(elementType))
627     return emitError() << "invalid memref element type";
628 
629   if (!isSupportedMemorySpace(memorySpace))
630     return emitError() << "unsupported memory space Attribute";
631 
632   return success();
633 }
634 
635 // Fallback cases for terminal dim/sym/cst that are not part of a binary op (
636 // i.e. single term). Accumulate the AffineExpr into the existing one.
637 static void extractStridesFromTerm(AffineExpr e,
638                                    AffineExpr multiplicativeFactor,
639                                    MutableArrayRef<AffineExpr> strides,
640                                    AffineExpr &offset) {
641   if (auto dim = e.dyn_cast<AffineDimExpr>())
642     strides[dim.getPosition()] =
643         strides[dim.getPosition()] + multiplicativeFactor;
644   else
645     offset = offset + e * multiplicativeFactor;
646 }
647 
648 /// Takes a single AffineExpr `e` and populates the `strides` array with the
649 /// strides expressions for each dim position.
650 /// The convention is that the strides for dimensions d0, .. dn appear in
651 /// order to make indexing intuitive into the result.
652 static LogicalResult extractStrides(AffineExpr e,
653                                     AffineExpr multiplicativeFactor,
654                                     MutableArrayRef<AffineExpr> strides,
655                                     AffineExpr &offset) {
656   auto bin = e.dyn_cast<AffineBinaryOpExpr>();
657   if (!bin) {
658     extractStridesFromTerm(e, multiplicativeFactor, strides, offset);
659     return success();
660   }
661 
662   if (bin.getKind() == AffineExprKind::CeilDiv ||
663       bin.getKind() == AffineExprKind::FloorDiv ||
664       bin.getKind() == AffineExprKind::Mod)
665     return failure();
666 
667   if (bin.getKind() == AffineExprKind::Mul) {
668     auto dim = bin.getLHS().dyn_cast<AffineDimExpr>();
669     if (dim) {
670       strides[dim.getPosition()] =
671           strides[dim.getPosition()] + bin.getRHS() * multiplicativeFactor;
672       return success();
673     }
674     // LHS and RHS may both contain complex expressions of dims. Try one path
675     // and if it fails try the other. This is guaranteed to succeed because
676     // only one path may have a `dim`, otherwise this is not an AffineExpr in
677     // the first place.
678     if (bin.getLHS().isSymbolicOrConstant())
679       return extractStrides(bin.getRHS(), multiplicativeFactor * bin.getLHS(),
680                             strides, offset);
681     return extractStrides(bin.getLHS(), multiplicativeFactor * bin.getRHS(),
682                           strides, offset);
683   }
684 
685   if (bin.getKind() == AffineExprKind::Add) {
686     auto res1 =
687         extractStrides(bin.getLHS(), multiplicativeFactor, strides, offset);
688     auto res2 =
689         extractStrides(bin.getRHS(), multiplicativeFactor, strides, offset);
690     return success(succeeded(res1) && succeeded(res2));
691   }
692 
693   llvm_unreachable("unexpected binary operation");
694 }
695 
696 LogicalResult mlir::getStridesAndOffset(MemRefType t,
697                                         SmallVectorImpl<AffineExpr> &strides,
698                                         AffineExpr &offset) {
699   auto affineMaps = t.getAffineMaps();
700 
701   if (!affineMaps.empty() && affineMaps.back().getNumResults() != 1)
702     return failure();
703 
704   AffineMap m;
705   if (!affineMaps.empty()) {
706     m = affineMaps.back();
707     for (size_t i = affineMaps.size() - 1; i > 0; --i)
708       m = m.compose(affineMaps[i - 1]);
709     assert(!m.isIdentity() && "unexpected identity map");
710   }
711 
712   auto zero = getAffineConstantExpr(0, t.getContext());
713   auto one = getAffineConstantExpr(1, t.getContext());
714   offset = zero;
715   strides.assign(t.getRank(), zero);
716 
717   // Canonical case for empty map.
718   if (!m) {
719     // 0-D corner case, offset is already 0.
720     if (t.getRank() == 0)
721       return success();
722     auto stridedExpr =
723         makeCanonicalStridedLayoutExpr(t.getShape(), t.getContext());
724     if (succeeded(extractStrides(stridedExpr, one, strides, offset)))
725       return success();
726     assert(false && "unexpected failure: extract strides in canonical layout");
727   }
728 
729   // Non-canonical case requires more work.
730   auto stridedExpr =
731       simplifyAffineExpr(m.getResult(0), m.getNumDims(), m.getNumSymbols());
732   if (failed(extractStrides(stridedExpr, one, strides, offset))) {
733     offset = AffineExpr();
734     strides.clear();
735     return failure();
736   }
737 
738   // Simplify results to allow folding to constants and simple checks.
739   unsigned numDims = m.getNumDims();
740   unsigned numSymbols = m.getNumSymbols();
741   offset = simplifyAffineExpr(offset, numDims, numSymbols);
742   for (auto &stride : strides)
743     stride = simplifyAffineExpr(stride, numDims, numSymbols);
744 
745   /// In practice, a strided memref must be internally non-aliasing. Test
746   /// against 0 as a proxy.
747   /// TODO: static cases can have more advanced checks.
748   /// TODO: dynamic cases would require a way to compare symbolic
749   /// expressions and would probably need an affine set context propagated
750   /// everywhere.
751   if (llvm::any_of(strides, [](AffineExpr e) {
752         return e == getAffineConstantExpr(0, e.getContext());
753       })) {
754     offset = AffineExpr();
755     strides.clear();
756     return failure();
757   }
758 
759   return success();
760 }
761 
762 LogicalResult mlir::getStridesAndOffset(MemRefType t,
763                                         SmallVectorImpl<int64_t> &strides,
764                                         int64_t &offset) {
765   AffineExpr offsetExpr;
766   SmallVector<AffineExpr, 4> strideExprs;
767   if (failed(::getStridesAndOffset(t, strideExprs, offsetExpr)))
768     return failure();
769   if (auto cst = offsetExpr.dyn_cast<AffineConstantExpr>())
770     offset = cst.getValue();
771   else
772     offset = ShapedType::kDynamicStrideOrOffset;
773   for (auto e : strideExprs) {
774     if (auto c = e.dyn_cast<AffineConstantExpr>())
775       strides.push_back(c.getValue());
776     else
777       strides.push_back(ShapedType::kDynamicStrideOrOffset);
778   }
779   return success();
780 }
781 
782 //===----------------------------------------------------------------------===//
783 /// TupleType
784 //===----------------------------------------------------------------------===//
785 
786 /// Return the elements types for this tuple.
787 ArrayRef<Type> TupleType::getTypes() const { return getImpl()->getTypes(); }
788 
789 /// Accumulate the types contained in this tuple and tuples nested within it.
790 /// Note that this only flattens nested tuples, not any other container type,
791 /// e.g. a tuple<i32, tensor<i32>, tuple<f32, tuple<i64>>> is flattened to
792 /// (i32, tensor<i32>, f32, i64)
793 void TupleType::getFlattenedTypes(SmallVectorImpl<Type> &types) {
794   for (Type type : getTypes()) {
795     if (auto nestedTuple = type.dyn_cast<TupleType>())
796       nestedTuple.getFlattenedTypes(types);
797     else
798       types.push_back(type);
799   }
800 }
801 
802 /// Return the number of element types.
803 size_t TupleType::size() const { return getImpl()->size(); }
804 
805 //===----------------------------------------------------------------------===//
806 // Type Utilities
807 //===----------------------------------------------------------------------===//
808 
809 AffineMap mlir::makeStridedLinearLayoutMap(ArrayRef<int64_t> strides,
810                                            int64_t offset,
811                                            MLIRContext *context) {
812   AffineExpr expr;
813   unsigned nSymbols = 0;
814 
815   // AffineExpr for offset.
816   // Static case.
817   if (offset != MemRefType::getDynamicStrideOrOffset()) {
818     auto cst = getAffineConstantExpr(offset, context);
819     expr = cst;
820   } else {
821     // Dynamic case, new symbol for the offset.
822     auto sym = getAffineSymbolExpr(nSymbols++, context);
823     expr = sym;
824   }
825 
826   // AffineExpr for strides.
827   for (auto en : llvm::enumerate(strides)) {
828     auto dim = en.index();
829     auto stride = en.value();
830     assert(stride != 0 && "Invalid stride specification");
831     auto d = getAffineDimExpr(dim, context);
832     AffineExpr mult;
833     // Static case.
834     if (stride != MemRefType::getDynamicStrideOrOffset())
835       mult = getAffineConstantExpr(stride, context);
836     else
837       // Dynamic case, new symbol for each new stride.
838       mult = getAffineSymbolExpr(nSymbols++, context);
839     expr = expr + d * mult;
840   }
841 
842   return AffineMap::get(strides.size(), nSymbols, expr);
843 }
844 
845 /// Return a version of `t` with identity layout if it can be determined
846 /// statically that the layout is the canonical contiguous strided layout.
847 /// Otherwise pass `t`'s layout into `simplifyAffineMap` and return a copy of
848 /// `t` with simplified layout.
849 /// If `t` has multiple layout maps or a multi-result layout, just return `t`.
850 MemRefType mlir::canonicalizeStridedLayout(MemRefType t) {
851   auto affineMaps = t.getAffineMaps();
852   // Already in canonical form.
853   if (affineMaps.empty())
854     return t;
855 
856   // Can't reduce to canonical identity form, return in canonical form.
857   if (affineMaps.size() > 1 || affineMaps[0].getNumResults() > 1)
858     return t;
859 
860   // Corner-case for 0-D affine maps.
861   auto m = affineMaps[0];
862   if (m.getNumDims() == 0 && m.getNumSymbols() == 0) {
863     if (auto cst = m.getResult(0).dyn_cast<AffineConstantExpr>())
864       if (cst.getValue() == 0)
865         return MemRefType::Builder(t).setAffineMaps({});
866     return t;
867   }
868 
869   // 0-D corner case for empty shape that still have an affine map. Example:
870   // `memref<f32, affine_map<()[s0] -> (s0)>>`. This is a 1 element memref whose
871   // offset needs to remain, just return t.
872   if (t.getShape().empty())
873     return t;
874 
875   // If the canonical strided layout for the sizes of `t` is equal to the
876   // simplified layout of `t` we can just return an empty layout. Otherwise,
877   // just simplify the existing layout.
878   AffineExpr expr =
879       makeCanonicalStridedLayoutExpr(t.getShape(), t.getContext());
880   auto simplifiedLayoutExpr =
881       simplifyAffineExpr(m.getResult(0), m.getNumDims(), m.getNumSymbols());
882   if (expr != simplifiedLayoutExpr)
883     return MemRefType::Builder(t).setAffineMaps({AffineMap::get(
884         m.getNumDims(), m.getNumSymbols(), simplifiedLayoutExpr)});
885   return MemRefType::Builder(t).setAffineMaps({});
886 }
887 
888 AffineExpr mlir::makeCanonicalStridedLayoutExpr(ArrayRef<int64_t> sizes,
889                                                 ArrayRef<AffineExpr> exprs,
890                                                 MLIRContext *context) {
891   assert(!sizes.empty() && !exprs.empty() &&
892          "expected non-empty sizes and exprs");
893 
894   // Size 0 corner case is useful for canonicalizations.
895   if (llvm::is_contained(sizes, 0))
896     return getAffineConstantExpr(0, context);
897 
898   auto maps = AffineMap::inferFromExprList(exprs);
899   assert(!maps.empty() && "Expected one non-empty map");
900   unsigned numDims = maps[0].getNumDims(), nSymbols = maps[0].getNumSymbols();
901 
902   AffineExpr expr;
903   bool dynamicPoisonBit = false;
904   int64_t runningSize = 1;
905   for (auto en : llvm::zip(llvm::reverse(exprs), llvm::reverse(sizes))) {
906     int64_t size = std::get<1>(en);
907     // Degenerate case, no size =-> no stride
908     if (size == 0)
909       continue;
910     AffineExpr dimExpr = std::get<0>(en);
911     AffineExpr stride = dynamicPoisonBit
912                             ? getAffineSymbolExpr(nSymbols++, context)
913                             : getAffineConstantExpr(runningSize, context);
914     expr = expr ? expr + dimExpr * stride : dimExpr * stride;
915     if (size > 0) {
916       runningSize *= size;
917       assert(runningSize > 0 && "integer overflow in size computation");
918     } else {
919       dynamicPoisonBit = true;
920     }
921   }
922   return simplifyAffineExpr(expr, numDims, nSymbols);
923 }
924 
925 /// Return a version of `t` with a layout that has all dynamic offset and
926 /// strides. This is used to erase the static layout.
927 MemRefType mlir::eraseStridedLayout(MemRefType t) {
928   auto val = ShapedType::kDynamicStrideOrOffset;
929   return MemRefType::Builder(t).setAffineMaps(makeStridedLinearLayoutMap(
930       SmallVector<int64_t, 4>(t.getRank(), val), val, t.getContext()));
931 }
932 
933 AffineExpr mlir::makeCanonicalStridedLayoutExpr(ArrayRef<int64_t> sizes,
934                                                 MLIRContext *context) {
935   SmallVector<AffineExpr, 4> exprs;
936   exprs.reserve(sizes.size());
937   for (auto dim : llvm::seq<unsigned>(0, sizes.size()))
938     exprs.push_back(getAffineDimExpr(dim, context));
939   return makeCanonicalStridedLayoutExpr(sizes, exprs, context);
940 }
941 
942 /// Return true if the layout for `t` is compatible with strided semantics.
943 bool mlir::isStrided(MemRefType t) {
944   int64_t offset;
945   SmallVector<int64_t, 4> strides;
946   auto res = getStridesAndOffset(t, strides, offset);
947   return succeeded(res);
948 }
949 
950 /// Return the layout map in strided linear layout AffineMap form.
951 /// Return null if the layout is not compatible with a strided layout.
952 AffineMap mlir::getStridedLinearLayoutMap(MemRefType t) {
953   int64_t offset;
954   SmallVector<int64_t, 4> strides;
955   if (failed(getStridesAndOffset(t, strides, offset)))
956     return AffineMap();
957   return makeStridedLinearLayoutMap(strides, offset, t.getContext());
958 }
959