1 //===- Attributes.cpp - MLIR Affine Expr 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/Attributes.h"
10 #include "AttributeDetail.h"
11 #include "mlir/IR/AffineMap.h"
12 #include "mlir/IR/Diagnostics.h"
13 #include "mlir/IR/Dialect.h"
14 #include "mlir/IR/Function.h"
15 #include "mlir/IR/IntegerSet.h"
16 #include "mlir/IR/Types.h"
17 #include "mlir/Interfaces/DecodeAttributesInterfaces.h"
18 #include "llvm/ADT/Sequence.h"
19 #include "llvm/ADT/Twine.h"
20 #include "llvm/Support/Endian.h"
21 
22 using namespace mlir;
23 using namespace mlir::detail;
24 
25 //===----------------------------------------------------------------------===//
26 // AttributeStorage
27 //===----------------------------------------------------------------------===//
28 
29 AttributeStorage::AttributeStorage(Type type)
30     : type(type.getAsOpaquePointer()) {}
31 AttributeStorage::AttributeStorage() : type(nullptr) {}
32 
33 Type AttributeStorage::getType() const {
34   return Type::getFromOpaquePointer(type);
35 }
36 void AttributeStorage::setType(Type newType) {
37   type = newType.getAsOpaquePointer();
38 }
39 
40 //===----------------------------------------------------------------------===//
41 // Attribute
42 //===----------------------------------------------------------------------===//
43 
44 /// Return the type of this attribute.
45 Type Attribute::getType() const { return impl->getType(); }
46 
47 /// Return the context this attribute belongs to.
48 MLIRContext *Attribute::getContext() const { return getType().getContext(); }
49 
50 /// Get the dialect this attribute is registered to.
51 Dialect &Attribute::getDialect() const {
52   return impl->getAbstractAttribute().getDialect();
53 }
54 
55 //===----------------------------------------------------------------------===//
56 // AffineMapAttr
57 //===----------------------------------------------------------------------===//
58 
59 AffineMapAttr AffineMapAttr::get(AffineMap value) {
60   return Base::get(value.getContext(), StandardAttributes::AffineMap, value);
61 }
62 
63 AffineMap AffineMapAttr::getValue() const { return getImpl()->value; }
64 
65 //===----------------------------------------------------------------------===//
66 // ArrayAttr
67 //===----------------------------------------------------------------------===//
68 
69 ArrayAttr ArrayAttr::get(ArrayRef<Attribute> value, MLIRContext *context) {
70   return Base::get(context, StandardAttributes::Array, value);
71 }
72 
73 ArrayRef<Attribute> ArrayAttr::getValue() const { return getImpl()->value; }
74 
75 Attribute ArrayAttr::operator[](unsigned idx) const {
76   assert(idx < size() && "index out of bounds");
77   return getValue()[idx];
78 }
79 
80 //===----------------------------------------------------------------------===//
81 // DictionaryAttr
82 //===----------------------------------------------------------------------===//
83 
84 /// Helper function that does either an in place sort or sorts from source array
85 /// into destination. If inPlace then storage is both the source and the
86 /// destination, else value is the source and storage destination. Returns
87 /// whether source was sorted.
88 template <bool inPlace>
89 static bool dictionaryAttrSort(ArrayRef<NamedAttribute> value,
90                                SmallVectorImpl<NamedAttribute> &storage) {
91   // Specialize for the common case.
92   switch (value.size()) {
93   case 0:
94     // Zero already sorted.
95     break;
96   case 1:
97     // One already sorted but may need to be copied.
98     if (!inPlace)
99       storage.assign({value[0]});
100     break;
101   case 2: {
102     assert(value[0].first != value[1].first &&
103            "DictionaryAttr element names must be unique");
104     bool isSorted = value[0] < value[1];
105     if (inPlace) {
106       if (!isSorted)
107         std::swap(storage[0], storage[1]);
108     } else if (isSorted) {
109       storage.assign({value[0], value[1]});
110     } else {
111       storage.assign({value[1], value[0]});
112     }
113     return !isSorted;
114   }
115   default:
116     if (!inPlace)
117       storage.assign(value.begin(), value.end());
118     // Check to see they are sorted already.
119     bool isSorted = llvm::is_sorted(value);
120     if (!isSorted) {
121       // If not, do a general sort.
122       llvm::array_pod_sort(storage.begin(), storage.end());
123       value = storage;
124     }
125 
126     // Ensure that the attribute elements are unique.
127     assert(std::adjacent_find(value.begin(), value.end(),
128                               [](NamedAttribute l, NamedAttribute r) {
129                                 return l.first == r.first;
130                               }) == value.end() &&
131            "DictionaryAttr element names must be unique");
132     return !isSorted;
133   }
134   return false;
135 }
136 
137 bool DictionaryAttr::sort(ArrayRef<NamedAttribute> value,
138                           SmallVectorImpl<NamedAttribute> &storage) {
139   return dictionaryAttrSort</*inPlace=*/false>(value, storage);
140 }
141 
142 bool DictionaryAttr::sortInPlace(SmallVectorImpl<NamedAttribute> &array) {
143   return dictionaryAttrSort</*inPlace=*/true>(array, array);
144 }
145 
146 DictionaryAttr DictionaryAttr::get(ArrayRef<NamedAttribute> value,
147                                    MLIRContext *context) {
148   if (value.empty())
149     return DictionaryAttr::getEmpty(context);
150   assert(llvm::all_of(value,
151                       [](const NamedAttribute &attr) { return attr.second; }) &&
152          "value cannot have null entries");
153 
154   // We need to sort the element list to canonicalize it.
155   SmallVector<NamedAttribute, 8> storage;
156   if (dictionaryAttrSort</*inPlace=*/false>(value, storage))
157     value = storage;
158 
159   return Base::get(context, StandardAttributes::Dictionary, value);
160 }
161 /// Construct a dictionary with an array of values that is known to already be
162 /// sorted by name and uniqued.
163 DictionaryAttr DictionaryAttr::getWithSorted(ArrayRef<NamedAttribute> value,
164                                              MLIRContext *context) {
165   if (value.empty())
166     return DictionaryAttr::getEmpty(context);
167   // Ensure that the attribute elements are unique and sorted.
168   assert(llvm::is_sorted(value,
169                          [](NamedAttribute l, NamedAttribute r) {
170                            return l.first.strref() < r.first.strref();
171                          }) &&
172          "expected attribute values to be sorted");
173   assert(std::adjacent_find(value.begin(), value.end(),
174                             [](NamedAttribute l, NamedAttribute r) {
175                               return l.first == r.first;
176                             }) == value.end() &&
177          "DictionaryAttr element names must be unique");
178   return Base::get(context, StandardAttributes::Dictionary, value);
179 }
180 
181 ArrayRef<NamedAttribute> DictionaryAttr::getValue() const {
182   return getImpl()->getElements();
183 }
184 
185 /// Return the specified attribute if present, null otherwise.
186 Attribute DictionaryAttr::get(StringRef name) const {
187   Optional<NamedAttribute> attr = getNamed(name);
188   return attr ? attr->second : nullptr;
189 }
190 Attribute DictionaryAttr::get(Identifier name) const {
191   Optional<NamedAttribute> attr = getNamed(name);
192   return attr ? attr->second : nullptr;
193 }
194 
195 /// Return the specified named attribute if present, None otherwise.
196 Optional<NamedAttribute> DictionaryAttr::getNamed(StringRef name) const {
197   ArrayRef<NamedAttribute> values = getValue();
198   const auto *it = llvm::lower_bound(values, name);
199   return it != values.end() && it->first == name ? *it
200                                                  : Optional<NamedAttribute>();
201 }
202 Optional<NamedAttribute> DictionaryAttr::getNamed(Identifier name) const {
203   for (auto elt : getValue())
204     if (elt.first == name)
205       return elt;
206   return llvm::None;
207 }
208 
209 DictionaryAttr::iterator DictionaryAttr::begin() const {
210   return getValue().begin();
211 }
212 DictionaryAttr::iterator DictionaryAttr::end() const {
213   return getValue().end();
214 }
215 size_t DictionaryAttr::size() const { return getValue().size(); }
216 
217 //===----------------------------------------------------------------------===//
218 // FloatAttr
219 //===----------------------------------------------------------------------===//
220 
221 FloatAttr FloatAttr::get(Type type, double value) {
222   return Base::get(type.getContext(), StandardAttributes::Float, type, value);
223 }
224 
225 FloatAttr FloatAttr::getChecked(Type type, double value, Location loc) {
226   return Base::getChecked(loc, StandardAttributes::Float, type, value);
227 }
228 
229 FloatAttr FloatAttr::get(Type type, const APFloat &value) {
230   return Base::get(type.getContext(), StandardAttributes::Float, type, value);
231 }
232 
233 FloatAttr FloatAttr::getChecked(Type type, const APFloat &value, Location loc) {
234   return Base::getChecked(loc, StandardAttributes::Float, type, value);
235 }
236 
237 APFloat FloatAttr::getValue() const { return getImpl()->getValue(); }
238 
239 double FloatAttr::getValueAsDouble() const {
240   return getValueAsDouble(getValue());
241 }
242 double FloatAttr::getValueAsDouble(APFloat value) {
243   if (&value.getSemantics() != &APFloat::IEEEdouble()) {
244     bool losesInfo = false;
245     value.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven,
246                   &losesInfo);
247   }
248   return value.convertToDouble();
249 }
250 
251 /// Verify construction invariants.
252 static LogicalResult verifyFloatTypeInvariants(Location loc, Type type) {
253   if (!type.isa<FloatType>())
254     return emitError(loc, "expected floating point type");
255   return success();
256 }
257 
258 LogicalResult FloatAttr::verifyConstructionInvariants(Location loc, Type type,
259                                                       double value) {
260   return verifyFloatTypeInvariants(loc, type);
261 }
262 
263 LogicalResult FloatAttr::verifyConstructionInvariants(Location loc, Type type,
264                                                       const APFloat &value) {
265   // Verify that the type is correct.
266   if (failed(verifyFloatTypeInvariants(loc, type)))
267     return failure();
268 
269   // Verify that the type semantics match that of the value.
270   if (&type.cast<FloatType>().getFloatSemantics() != &value.getSemantics()) {
271     return emitError(
272         loc, "FloatAttr type doesn't match the type implied by its value");
273   }
274   return success();
275 }
276 
277 //===----------------------------------------------------------------------===//
278 // SymbolRefAttr
279 //===----------------------------------------------------------------------===//
280 
281 FlatSymbolRefAttr SymbolRefAttr::get(StringRef value, MLIRContext *ctx) {
282   return Base::get(ctx, StandardAttributes::SymbolRef, value, llvm::None)
283       .cast<FlatSymbolRefAttr>();
284 }
285 
286 SymbolRefAttr SymbolRefAttr::get(StringRef value,
287                                  ArrayRef<FlatSymbolRefAttr> nestedReferences,
288                                  MLIRContext *ctx) {
289   return Base::get(ctx, StandardAttributes::SymbolRef, value, nestedReferences);
290 }
291 
292 StringRef SymbolRefAttr::getRootReference() const { return getImpl()->value; }
293 
294 StringRef SymbolRefAttr::getLeafReference() const {
295   ArrayRef<FlatSymbolRefAttr> nestedRefs = getNestedReferences();
296   return nestedRefs.empty() ? getRootReference() : nestedRefs.back().getValue();
297 }
298 
299 ArrayRef<FlatSymbolRefAttr> SymbolRefAttr::getNestedReferences() const {
300   return getImpl()->getNestedRefs();
301 }
302 
303 //===----------------------------------------------------------------------===//
304 // IntegerAttr
305 //===----------------------------------------------------------------------===//
306 
307 IntegerAttr IntegerAttr::get(Type type, const APInt &value) {
308   if (type.isSignlessInteger(1))
309     return BoolAttr::get(value.getBoolValue(), type.getContext());
310   return Base::get(type.getContext(), StandardAttributes::Integer, type, value);
311 }
312 
313 IntegerAttr IntegerAttr::get(Type type, int64_t value) {
314   // This uses 64 bit APInts by default for index type.
315   if (type.isIndex())
316     return get(type, APInt(IndexType::kInternalStorageBitWidth, value));
317 
318   auto intType = type.cast<IntegerType>();
319   return get(type, APInt(intType.getWidth(), value, intType.isSignedInteger()));
320 }
321 
322 APInt IntegerAttr::getValue() const { return getImpl()->getValue(); }
323 
324 int64_t IntegerAttr::getInt() const {
325   assert((getImpl()->getType().isIndex() ||
326           getImpl()->getType().isSignlessInteger()) &&
327          "must be signless integer");
328   return getValue().getSExtValue();
329 }
330 
331 int64_t IntegerAttr::getSInt() const {
332   assert(getImpl()->getType().isSignedInteger() && "must be signed integer");
333   return getValue().getSExtValue();
334 }
335 
336 uint64_t IntegerAttr::getUInt() const {
337   assert(getImpl()->getType().isUnsignedInteger() &&
338          "must be unsigned integer");
339   return getValue().getZExtValue();
340 }
341 
342 static LogicalResult verifyIntegerTypeInvariants(Location loc, Type type) {
343   if (type.isa<IntegerType, IndexType>())
344     return success();
345   return emitError(loc, "expected integer or index type");
346 }
347 
348 LogicalResult IntegerAttr::verifyConstructionInvariants(Location loc, Type type,
349                                                         int64_t value) {
350   return verifyIntegerTypeInvariants(loc, type);
351 }
352 
353 LogicalResult IntegerAttr::verifyConstructionInvariants(Location loc, Type type,
354                                                         const APInt &value) {
355   if (failed(verifyIntegerTypeInvariants(loc, type)))
356     return failure();
357   if (auto integerType = type.dyn_cast<IntegerType>())
358     if (integerType.getWidth() != value.getBitWidth())
359       return emitError(loc, "integer type bit width (")
360              << integerType.getWidth() << ") doesn't match value bit width ("
361              << value.getBitWidth() << ")";
362   return success();
363 }
364 
365 //===----------------------------------------------------------------------===//
366 // BoolAttr
367 
368 bool BoolAttr::getValue() const {
369   auto *storage = reinterpret_cast<IntegerAttributeStorage *>(impl);
370   return storage->getValue().getBoolValue();
371 }
372 
373 bool BoolAttr::classof(Attribute attr) {
374   IntegerAttr intAttr = attr.dyn_cast<IntegerAttr>();
375   return intAttr && intAttr.getType().isSignlessInteger(1);
376 }
377 
378 //===----------------------------------------------------------------------===//
379 // IntegerSetAttr
380 //===----------------------------------------------------------------------===//
381 
382 IntegerSetAttr IntegerSetAttr::get(IntegerSet value) {
383   return Base::get(value.getConstraint(0).getContext(),
384                    StandardAttributes::IntegerSet, value);
385 }
386 
387 IntegerSet IntegerSetAttr::getValue() const { return getImpl()->value; }
388 
389 //===----------------------------------------------------------------------===//
390 // OpaqueAttr
391 //===----------------------------------------------------------------------===//
392 
393 OpaqueAttr OpaqueAttr::get(Identifier dialect, StringRef attrData, Type type,
394                            MLIRContext *context) {
395   return Base::get(context, StandardAttributes::Opaque, dialect, attrData,
396                    type);
397 }
398 
399 OpaqueAttr OpaqueAttr::getChecked(Identifier dialect, StringRef attrData,
400                                   Type type, Location location) {
401   return Base::getChecked(location, StandardAttributes::Opaque, dialect,
402                           attrData, type);
403 }
404 
405 /// Returns the dialect namespace of the opaque attribute.
406 Identifier OpaqueAttr::getDialectNamespace() const {
407   return getImpl()->dialectNamespace;
408 }
409 
410 /// Returns the raw attribute data of the opaque attribute.
411 StringRef OpaqueAttr::getAttrData() const { return getImpl()->attrData; }
412 
413 /// Verify the construction of an opaque attribute.
414 LogicalResult OpaqueAttr::verifyConstructionInvariants(Location loc,
415                                                        Identifier dialect,
416                                                        StringRef attrData,
417                                                        Type type) {
418   if (!Dialect::isValidNamespace(dialect.strref()))
419     return emitError(loc, "invalid dialect namespace '") << dialect << "'";
420   return success();
421 }
422 
423 //===----------------------------------------------------------------------===//
424 // StringAttr
425 //===----------------------------------------------------------------------===//
426 
427 StringAttr StringAttr::get(StringRef bytes, MLIRContext *context) {
428   return get(bytes, NoneType::get(context));
429 }
430 
431 /// Get an instance of a StringAttr with the given string and Type.
432 StringAttr StringAttr::get(StringRef bytes, Type type) {
433   return Base::get(type.getContext(), StandardAttributes::String, bytes, type);
434 }
435 
436 StringRef StringAttr::getValue() const { return getImpl()->value; }
437 
438 //===----------------------------------------------------------------------===//
439 // TypeAttr
440 //===----------------------------------------------------------------------===//
441 
442 TypeAttr TypeAttr::get(Type value) {
443   return Base::get(value.getContext(), StandardAttributes::Type, value);
444 }
445 
446 Type TypeAttr::getValue() const { return getImpl()->value; }
447 
448 //===----------------------------------------------------------------------===//
449 // ElementsAttr
450 //===----------------------------------------------------------------------===//
451 
452 ShapedType ElementsAttr::getType() const {
453   return Attribute::getType().cast<ShapedType>();
454 }
455 
456 /// Returns the number of elements held by this attribute.
457 int64_t ElementsAttr::getNumElements() const {
458   return getType().getNumElements();
459 }
460 
461 /// Return the value at the given index. If index does not refer to a valid
462 /// element, then a null attribute is returned.
463 Attribute ElementsAttr::getValue(ArrayRef<uint64_t> index) const {
464   if (auto denseAttr = dyn_cast<DenseElementsAttr>())
465     return denseAttr.getValue(index);
466   if (auto opaqueAttr = dyn_cast<OpaqueElementsAttr>())
467     return opaqueAttr.getValue(index);
468   return cast<SparseElementsAttr>().getValue(index);
469 }
470 
471 /// Return if the given 'index' refers to a valid element in this attribute.
472 bool ElementsAttr::isValidIndex(ArrayRef<uint64_t> index) const {
473   auto type = getType();
474 
475   // Verify that the rank of the indices matches the held type.
476   auto rank = type.getRank();
477   if (rank != static_cast<int64_t>(index.size()))
478     return false;
479 
480   // Verify that all of the indices are within the shape dimensions.
481   auto shape = type.getShape();
482   return llvm::all_of(llvm::seq<int>(0, rank), [&](int i) {
483     return static_cast<int64_t>(index[i]) < shape[i];
484   });
485 }
486 
487 ElementsAttr
488 ElementsAttr::mapValues(Type newElementType,
489                         function_ref<APInt(const APInt &)> mapping) const {
490   if (auto intOrFpAttr = dyn_cast<DenseElementsAttr>())
491     return intOrFpAttr.mapValues(newElementType, mapping);
492   llvm_unreachable("unsupported ElementsAttr subtype");
493 }
494 
495 ElementsAttr
496 ElementsAttr::mapValues(Type newElementType,
497                         function_ref<APInt(const APFloat &)> mapping) const {
498   if (auto intOrFpAttr = dyn_cast<DenseElementsAttr>())
499     return intOrFpAttr.mapValues(newElementType, mapping);
500   llvm_unreachable("unsupported ElementsAttr subtype");
501 }
502 
503 /// Method for support type inquiry through isa, cast and dyn_cast.
504 bool ElementsAttr::classof(Attribute attr) {
505   return attr.isa<DenseIntOrFPElementsAttr, DenseStringElementsAttr,
506                   OpaqueElementsAttr, SparseElementsAttr>();
507 }
508 
509 /// Returns the 1 dimensional flattened row-major index from the given
510 /// multi-dimensional index.
511 uint64_t ElementsAttr::getFlattenedIndex(ArrayRef<uint64_t> index) const {
512   assert(isValidIndex(index) && "expected valid multi-dimensional index");
513   auto type = getType();
514 
515   // Reduce the provided multidimensional index into a flattended 1D row-major
516   // index.
517   auto rank = type.getRank();
518   auto shape = type.getShape();
519   uint64_t valueIndex = 0;
520   uint64_t dimMultiplier = 1;
521   for (int i = rank - 1; i >= 0; --i) {
522     valueIndex += index[i] * dimMultiplier;
523     dimMultiplier *= shape[i];
524   }
525   return valueIndex;
526 }
527 
528 //===----------------------------------------------------------------------===//
529 // DenseElementAttr Utilities
530 //===----------------------------------------------------------------------===//
531 
532 /// Get the bitwidth of a dense element type within the buffer.
533 /// DenseElementsAttr requires bitwidths greater than 1 to be aligned by 8.
534 static size_t getDenseElementStorageWidth(size_t origWidth) {
535   return origWidth == 1 ? origWidth : llvm::alignTo<8>(origWidth);
536 }
537 static size_t getDenseElementStorageWidth(Type elementType) {
538   return getDenseElementStorageWidth(getDenseElementBitWidth(elementType));
539 }
540 
541 /// Set a bit to a specific value.
542 static void setBit(char *rawData, size_t bitPos, bool value) {
543   if (value)
544     rawData[bitPos / CHAR_BIT] |= (1 << (bitPos % CHAR_BIT));
545   else
546     rawData[bitPos / CHAR_BIT] &= ~(1 << (bitPos % CHAR_BIT));
547 }
548 
549 /// Return the value of the specified bit.
550 static bool getBit(const char *rawData, size_t bitPos) {
551   return (rawData[bitPos / CHAR_BIT] & (1 << (bitPos % CHAR_BIT))) != 0;
552 }
553 
554 /// Get start position of actual data in `value`. Actual data is
555 /// stored in last `bitWidth`/CHAR_BIT bytes in big endian.
556 static char *getAPIntDataPos(APInt &value, size_t bitWidth) {
557   char *dataPos =
558       const_cast<char *>(reinterpret_cast<const char *>(value.getRawData()));
559   if (llvm::support::endian::system_endianness() ==
560       llvm::support::endianness::big)
561     dataPos = dataPos + 8 - llvm::divideCeil(bitWidth, CHAR_BIT);
562   return dataPos;
563 }
564 
565 /// Read APInt `value` from appropriate position.
566 static void readAPInt(APInt &value, size_t bitWidth, char *outData) {
567   char *dataPos = getAPIntDataPos(value, bitWidth);
568   std::copy_n(dataPos, llvm::divideCeil(bitWidth, CHAR_BIT), outData);
569 }
570 
571 /// Write `inData` to appropriate position of APInt `value`.
572 static void writeAPInt(const char *inData, size_t bitWidth, APInt &value) {
573   char *dataPos = getAPIntDataPos(value, bitWidth);
574   std::copy_n(inData, llvm::divideCeil(bitWidth, CHAR_BIT), dataPos);
575 }
576 
577 /// Writes value to the bit position `bitPos` in array `rawData`.
578 static void writeBits(char *rawData, size_t bitPos, APInt value) {
579   size_t bitWidth = value.getBitWidth();
580 
581   // If the bitwidth is 1 we just toggle the specific bit.
582   if (bitWidth == 1)
583     return setBit(rawData, bitPos, value.isOneValue());
584 
585   // Otherwise, the bit position is guaranteed to be byte aligned.
586   assert((bitPos % CHAR_BIT) == 0 && "expected bitPos to be 8-bit aligned");
587   readAPInt(value, bitWidth, rawData + (bitPos / CHAR_BIT));
588 }
589 
590 /// Reads the next `bitWidth` bits from the bit position `bitPos` in array
591 /// `rawData`.
592 static APInt readBits(const char *rawData, size_t bitPos, size_t bitWidth) {
593   // Handle a boolean bit position.
594   if (bitWidth == 1)
595     return APInt(1, getBit(rawData, bitPos) ? 1 : 0);
596 
597   // Otherwise, the bit position must be 8-bit aligned.
598   assert((bitPos % CHAR_BIT) == 0 && "expected bitPos to be 8-bit aligned");
599   APInt result(bitWidth, 0);
600   writeAPInt(rawData + (bitPos / CHAR_BIT), bitWidth, result);
601   return result;
602 }
603 
604 /// Returns if 'values' corresponds to a splat, i.e. one element, or has the
605 /// same element count as 'type'.
606 template <typename Values>
607 static bool hasSameElementsOrSplat(ShapedType type, const Values &values) {
608   return (values.size() == 1) ||
609          (type.getNumElements() == static_cast<int64_t>(values.size()));
610 }
611 
612 //===----------------------------------------------------------------------===//
613 // DenseElementAttr Iterators
614 //===----------------------------------------------------------------------===//
615 
616 //===----------------------------------------------------------------------===//
617 // AttributeElementIterator
618 
619 DenseElementsAttr::AttributeElementIterator::AttributeElementIterator(
620     DenseElementsAttr attr, size_t index)
621     : llvm::indexed_accessor_iterator<AttributeElementIterator, const void *,
622                                       Attribute, Attribute, Attribute>(
623           attr.getAsOpaquePointer(), index) {}
624 
625 Attribute DenseElementsAttr::AttributeElementIterator::operator*() const {
626   auto owner = getFromOpaquePointer(base).cast<DenseElementsAttr>();
627   Type eltTy = owner.getType().getElementType();
628   if (auto intEltTy = eltTy.dyn_cast<IntegerType>())
629     return IntegerAttr::get(eltTy, *IntElementIterator(owner, index));
630   if (eltTy.isa<IndexType>())
631     return IntegerAttr::get(eltTy, *IntElementIterator(owner, index));
632   if (auto floatEltTy = eltTy.dyn_cast<FloatType>()) {
633     IntElementIterator intIt(owner, index);
634     FloatElementIterator floatIt(floatEltTy.getFloatSemantics(), intIt);
635     return FloatAttr::get(eltTy, *floatIt);
636   }
637   if (owner.isa<DenseStringElementsAttr>()) {
638     ArrayRef<StringRef> vals = owner.getRawStringData();
639     return StringAttr::get(owner.isSplat() ? vals.front() : vals[index], eltTy);
640   }
641   llvm_unreachable("unexpected element type");
642 }
643 
644 //===----------------------------------------------------------------------===//
645 // BoolElementIterator
646 
647 DenseElementsAttr::BoolElementIterator::BoolElementIterator(
648     DenseElementsAttr attr, size_t dataIndex)
649     : DenseElementIndexedIteratorImpl<BoolElementIterator, bool, bool, bool>(
650           attr.getRawData().data(), attr.isSplat(), dataIndex) {}
651 
652 bool DenseElementsAttr::BoolElementIterator::operator*() const {
653   return getBit(getData(), getDataIndex());
654 }
655 
656 //===----------------------------------------------------------------------===//
657 // IntElementIterator
658 
659 DenseElementsAttr::IntElementIterator::IntElementIterator(
660     DenseElementsAttr attr, size_t dataIndex)
661     : DenseElementIndexedIteratorImpl<IntElementIterator, APInt, APInt, APInt>(
662           attr.getRawData().data(), attr.isSplat(), dataIndex),
663       bitWidth(getDenseElementBitWidth(attr.getType().getElementType())) {}
664 
665 APInt DenseElementsAttr::IntElementIterator::operator*() const {
666   return readBits(getData(),
667                   getDataIndex() * getDenseElementStorageWidth(bitWidth),
668                   bitWidth);
669 }
670 
671 //===----------------------------------------------------------------------===//
672 // ComplexIntElementIterator
673 
674 DenseElementsAttr::ComplexIntElementIterator::ComplexIntElementIterator(
675     DenseElementsAttr attr, size_t dataIndex)
676     : DenseElementIndexedIteratorImpl<ComplexIntElementIterator,
677                                       std::complex<APInt>, std::complex<APInt>,
678                                       std::complex<APInt>>(
679           attr.getRawData().data(), attr.isSplat(), dataIndex) {
680   auto complexType = attr.getType().getElementType().cast<ComplexType>();
681   bitWidth = getDenseElementBitWidth(complexType.getElementType());
682 }
683 
684 std::complex<APInt>
685 DenseElementsAttr::ComplexIntElementIterator::operator*() const {
686   size_t storageWidth = getDenseElementStorageWidth(bitWidth);
687   size_t offset = getDataIndex() * storageWidth * 2;
688   return {readBits(getData(), offset, bitWidth),
689           readBits(getData(), offset + storageWidth, bitWidth)};
690 }
691 
692 //===----------------------------------------------------------------------===//
693 // FloatElementIterator
694 
695 DenseElementsAttr::FloatElementIterator::FloatElementIterator(
696     const llvm::fltSemantics &smt, IntElementIterator it)
697     : llvm::mapped_iterator<IntElementIterator,
698                             std::function<APFloat(const APInt &)>>(
699           it, [&](const APInt &val) { return APFloat(smt, val); }) {}
700 
701 //===----------------------------------------------------------------------===//
702 // ComplexFloatElementIterator
703 
704 DenseElementsAttr::ComplexFloatElementIterator::ComplexFloatElementIterator(
705     const llvm::fltSemantics &smt, ComplexIntElementIterator it)
706     : llvm::mapped_iterator<
707           ComplexIntElementIterator,
708           std::function<std::complex<APFloat>(const std::complex<APInt> &)>>(
709           it, [&](const std::complex<APInt> &val) -> std::complex<APFloat> {
710             return {APFloat(smt, val.real()), APFloat(smt, val.imag())};
711           }) {}
712 
713 //===----------------------------------------------------------------------===//
714 // DenseElementsAttr
715 //===----------------------------------------------------------------------===//
716 
717 /// Method for support type inquiry through isa, cast and dyn_cast.
718 bool DenseElementsAttr::classof(Attribute attr) {
719   return attr.isa<DenseIntOrFPElementsAttr, DenseStringElementsAttr>();
720 }
721 
722 DenseElementsAttr DenseElementsAttr::get(ShapedType type,
723                                          ArrayRef<Attribute> values) {
724   assert(hasSameElementsOrSplat(type, values));
725 
726   // If the element type is not based on int/float/index, assume it is a string
727   // type.
728   auto eltType = type.getElementType();
729   if (!type.getElementType().isIntOrIndexOrFloat()) {
730     SmallVector<StringRef, 8> stringValues;
731     stringValues.reserve(values.size());
732     for (Attribute attr : values) {
733       assert(attr.isa<StringAttr>() &&
734              "expected string value for non integer/index/float element");
735       stringValues.push_back(attr.cast<StringAttr>().getValue());
736     }
737     return get(type, stringValues);
738   }
739 
740   // Otherwise, get the raw storage width to use for the allocation.
741   size_t bitWidth = getDenseElementBitWidth(eltType);
742   size_t storageBitWidth = getDenseElementStorageWidth(bitWidth);
743 
744   // Compress the attribute values into a character buffer.
745   SmallVector<char, 8> data(llvm::divideCeil(storageBitWidth, CHAR_BIT) *
746                             values.size());
747   APInt intVal;
748   for (unsigned i = 0, e = values.size(); i < e; ++i) {
749     assert(eltType == values[i].getType() &&
750            "expected attribute value to have element type");
751     if (eltType.isa<FloatType>())
752       intVal = values[i].cast<FloatAttr>().getValue().bitcastToAPInt();
753     else if (eltType.isa<IntegerType>())
754       intVal = values[i].cast<IntegerAttr>().getValue();
755     else
756       llvm_unreachable("unexpected element type");
757 
758     assert(intVal.getBitWidth() == bitWidth &&
759            "expected value to have same bitwidth as element type");
760     writeBits(data.data(), i * storageBitWidth, intVal);
761   }
762   return DenseIntOrFPElementsAttr::getRaw(type, data,
763                                           /*isSplat=*/(values.size() == 1));
764 }
765 
766 DenseElementsAttr DenseElementsAttr::get(ShapedType type,
767                                          ArrayRef<bool> values) {
768   assert(hasSameElementsOrSplat(type, values));
769   assert(type.getElementType().isInteger(1));
770 
771   std::vector<char> buff(llvm::divideCeil(values.size(), CHAR_BIT));
772   for (int i = 0, e = values.size(); i != e; ++i)
773     setBit(buff.data(), i, values[i]);
774   return DenseIntOrFPElementsAttr::getRaw(type, buff,
775                                           /*isSplat=*/(values.size() == 1));
776 }
777 
778 DenseElementsAttr DenseElementsAttr::get(ShapedType type,
779                                          ArrayRef<StringRef> values) {
780   assert(!type.getElementType().isIntOrFloat());
781   return DenseStringElementsAttr::get(type, values);
782 }
783 
784 /// Constructs a dense integer elements attribute from an array of APInt
785 /// values. Each APInt value is expected to have the same bitwidth as the
786 /// element type of 'type'.
787 DenseElementsAttr DenseElementsAttr::get(ShapedType type,
788                                          ArrayRef<APInt> values) {
789   assert(type.getElementType().isIntOrIndex());
790   assert(hasSameElementsOrSplat(type, values));
791   size_t storageBitWidth = getDenseElementStorageWidth(type.getElementType());
792   return DenseIntOrFPElementsAttr::getRaw(type, storageBitWidth, values,
793                                           /*isSplat=*/(values.size() == 1));
794 }
795 DenseElementsAttr DenseElementsAttr::get(ShapedType type,
796                                          ArrayRef<std::complex<APInt>> values) {
797   ComplexType complex = type.getElementType().cast<ComplexType>();
798   assert(complex.getElementType().isa<IntegerType>());
799   assert(hasSameElementsOrSplat(type, values));
800   size_t storageBitWidth = getDenseElementStorageWidth(complex) / 2;
801   ArrayRef<APInt> intVals(reinterpret_cast<const APInt *>(values.data()),
802                           values.size() * 2);
803   return DenseIntOrFPElementsAttr::getRaw(type, storageBitWidth, intVals,
804                                           /*isSplat=*/(values.size() == 1));
805 }
806 
807 // Constructs a dense float elements attribute from an array of APFloat
808 // values. Each APFloat value is expected to have the same bitwidth as the
809 // element type of 'type'.
810 DenseElementsAttr DenseElementsAttr::get(ShapedType type,
811                                          ArrayRef<APFloat> values) {
812   assert(type.getElementType().isa<FloatType>());
813   assert(hasSameElementsOrSplat(type, values));
814   size_t storageBitWidth = getDenseElementStorageWidth(type.getElementType());
815   return DenseIntOrFPElementsAttr::getRaw(type, storageBitWidth, values,
816                                           /*isSplat=*/(values.size() == 1));
817 }
818 DenseElementsAttr
819 DenseElementsAttr::get(ShapedType type,
820                        ArrayRef<std::complex<APFloat>> values) {
821   ComplexType complex = type.getElementType().cast<ComplexType>();
822   assert(complex.getElementType().isa<FloatType>());
823   assert(hasSameElementsOrSplat(type, values));
824   ArrayRef<APFloat> apVals(reinterpret_cast<const APFloat *>(values.data()),
825                            values.size() * 2);
826   size_t storageBitWidth = getDenseElementStorageWidth(complex) / 2;
827   return DenseIntOrFPElementsAttr::getRaw(type, storageBitWidth, apVals,
828                                           /*isSplat=*/(values.size() == 1));
829 }
830 
831 /// Construct a dense elements attribute from a raw buffer representing the
832 /// data for this attribute. Users should generally not use this methods as
833 /// the expected buffer format may not be a form the user expects.
834 DenseElementsAttr DenseElementsAttr::getFromRawBuffer(ShapedType type,
835                                                       ArrayRef<char> rawBuffer,
836                                                       bool isSplatBuffer) {
837   return DenseIntOrFPElementsAttr::getRaw(type, rawBuffer, isSplatBuffer);
838 }
839 
840 /// Returns true if the given buffer is a valid raw buffer for the given type.
841 bool DenseElementsAttr::isValidRawBuffer(ShapedType type,
842                                          ArrayRef<char> rawBuffer,
843                                          bool &detectedSplat) {
844   size_t storageWidth = getDenseElementStorageWidth(type.getElementType());
845   size_t rawBufferWidth = rawBuffer.size() * CHAR_BIT;
846 
847   // Storage width of 1 is special as it is packed by the bit.
848   if (storageWidth == 1) {
849     // Check for a splat, or a buffer equal to the number of elements.
850     if ((detectedSplat = rawBuffer.size() == 1))
851       return true;
852     return rawBufferWidth == llvm::alignTo<8>(type.getNumElements());
853   }
854   // All other types are 8-bit aligned.
855   if ((detectedSplat = rawBufferWidth == storageWidth))
856     return true;
857   return rawBufferWidth == (storageWidth * type.getNumElements());
858 }
859 
860 /// Check the information for a C++ data type, check if this type is valid for
861 /// the current attribute. This method is used to verify specific type
862 /// invariants that the templatized 'getValues' method cannot.
863 static bool isValidIntOrFloat(Type type, int64_t dataEltSize, bool isInt,
864                               bool isSigned) {
865   // Make sure that the data element size is the same as the type element width.
866   if (getDenseElementBitWidth(type) !=
867       static_cast<size_t>(dataEltSize * CHAR_BIT))
868     return false;
869 
870   // Check that the element type is either float or integer or index.
871   if (!isInt)
872     return type.isa<FloatType>();
873   if (type.isIndex())
874     return true;
875 
876   auto intType = type.dyn_cast<IntegerType>();
877   if (!intType)
878     return false;
879 
880   // Make sure signedness semantics is consistent.
881   if (intType.isSignless())
882     return true;
883   return intType.isSigned() ? isSigned : !isSigned;
884 }
885 
886 /// Defaults down the subclass implementation.
887 DenseElementsAttr DenseElementsAttr::getRawComplex(ShapedType type,
888                                                    ArrayRef<char> data,
889                                                    int64_t dataEltSize,
890                                                    bool isInt, bool isSigned) {
891   return DenseIntOrFPElementsAttr::getRawComplex(type, data, dataEltSize, isInt,
892                                                  isSigned);
893 }
894 DenseElementsAttr DenseElementsAttr::getRawIntOrFloat(ShapedType type,
895                                                       ArrayRef<char> data,
896                                                       int64_t dataEltSize,
897                                                       bool isInt,
898                                                       bool isSigned) {
899   return DenseIntOrFPElementsAttr::getRawIntOrFloat(type, data, dataEltSize,
900                                                     isInt, isSigned);
901 }
902 
903 /// A method used to verify specific type invariants that the templatized 'get'
904 /// method cannot.
905 bool DenseElementsAttr::isValidIntOrFloat(int64_t dataEltSize, bool isInt,
906                                           bool isSigned) const {
907   return ::isValidIntOrFloat(getType().getElementType(), dataEltSize, isInt,
908                              isSigned);
909 }
910 
911 /// Check the information for a C++ data type, check if this type is valid for
912 /// the current attribute.
913 bool DenseElementsAttr::isValidComplex(int64_t dataEltSize, bool isInt,
914                                        bool isSigned) const {
915   return ::isValidIntOrFloat(
916       getType().getElementType().cast<ComplexType>().getElementType(),
917       dataEltSize / 2, isInt, isSigned);
918 }
919 
920 /// Returns if this attribute corresponds to a splat, i.e. if all element
921 /// values are the same.
922 bool DenseElementsAttr::isSplat() const {
923   return static_cast<DenseElementsAttributeStorage *>(impl)->isSplat;
924 }
925 
926 /// Return the held element values as a range of Attributes.
927 auto DenseElementsAttr::getAttributeValues() const
928     -> llvm::iterator_range<AttributeElementIterator> {
929   return {attr_value_begin(), attr_value_end()};
930 }
931 auto DenseElementsAttr::attr_value_begin() const -> AttributeElementIterator {
932   return AttributeElementIterator(*this, 0);
933 }
934 auto DenseElementsAttr::attr_value_end() const -> AttributeElementIterator {
935   return AttributeElementIterator(*this, getNumElements());
936 }
937 
938 /// Return the held element values as a range of bool. The element type of
939 /// this attribute must be of integer type of bitwidth 1.
940 auto DenseElementsAttr::getBoolValues() const
941     -> llvm::iterator_range<BoolElementIterator> {
942   auto eltType = getType().getElementType().dyn_cast<IntegerType>();
943   assert(eltType && eltType.getWidth() == 1 && "expected i1 integer type");
944   (void)eltType;
945   return {BoolElementIterator(*this, 0),
946           BoolElementIterator(*this, getNumElements())};
947 }
948 
949 /// Return the held element values as a range of APInts. The element type of
950 /// this attribute must be of integer type.
951 auto DenseElementsAttr::getIntValues() const
952     -> llvm::iterator_range<IntElementIterator> {
953   assert(getType().getElementType().isIntOrIndex() && "expected integral type");
954   return {raw_int_begin(), raw_int_end()};
955 }
956 auto DenseElementsAttr::int_value_begin() const -> IntElementIterator {
957   assert(getType().getElementType().isIntOrIndex() && "expected integral type");
958   return raw_int_begin();
959 }
960 auto DenseElementsAttr::int_value_end() const -> IntElementIterator {
961   assert(getType().getElementType().isIntOrIndex() && "expected integral type");
962   return raw_int_end();
963 }
964 auto DenseElementsAttr::getComplexIntValues() const
965     -> llvm::iterator_range<ComplexIntElementIterator> {
966   Type eltTy = getType().getElementType().cast<ComplexType>().getElementType();
967   (void)eltTy;
968   assert(eltTy.isa<IntegerType>() && "expected complex integral type");
969   return {ComplexIntElementIterator(*this, 0),
970           ComplexIntElementIterator(*this, getNumElements())};
971 }
972 
973 /// Return the held element values as a range of APFloat. The element type of
974 /// this attribute must be of float type.
975 auto DenseElementsAttr::getFloatValues() const
976     -> llvm::iterator_range<FloatElementIterator> {
977   auto elementType = getType().getElementType().cast<FloatType>();
978   const auto &elementSemantics = elementType.getFloatSemantics();
979   return {FloatElementIterator(elementSemantics, raw_int_begin()),
980           FloatElementIterator(elementSemantics, raw_int_end())};
981 }
982 auto DenseElementsAttr::float_value_begin() const -> FloatElementIterator {
983   return getFloatValues().begin();
984 }
985 auto DenseElementsAttr::float_value_end() const -> FloatElementIterator {
986   return getFloatValues().end();
987 }
988 auto DenseElementsAttr::getComplexFloatValues() const
989     -> llvm::iterator_range<ComplexFloatElementIterator> {
990   Type eltTy = getType().getElementType().cast<ComplexType>().getElementType();
991   assert(eltTy.isa<FloatType>() && "expected complex float type");
992   const auto &semantics = eltTy.cast<FloatType>().getFloatSemantics();
993   return {{semantics, {*this, 0}},
994           {semantics, {*this, static_cast<size_t>(getNumElements())}}};
995 }
996 
997 /// Return the raw storage data held by this attribute.
998 ArrayRef<char> DenseElementsAttr::getRawData() const {
999   return static_cast<DenseIntOrFPElementsAttributeStorage *>(impl)->data;
1000 }
1001 
1002 ArrayRef<StringRef> DenseElementsAttr::getRawStringData() const {
1003   return static_cast<DenseStringElementsAttributeStorage *>(impl)->data;
1004 }
1005 
1006 /// Return a new DenseElementsAttr that has the same data as the current
1007 /// attribute, but has been reshaped to 'newType'. The new type must have the
1008 /// same total number of elements as well as element type.
1009 DenseElementsAttr DenseElementsAttr::reshape(ShapedType newType) {
1010   ShapedType curType = getType();
1011   if (curType == newType)
1012     return *this;
1013 
1014   (void)curType;
1015   assert(newType.getElementType() == curType.getElementType() &&
1016          "expected the same element type");
1017   assert(newType.getNumElements() == curType.getNumElements() &&
1018          "expected the same number of elements");
1019   return DenseIntOrFPElementsAttr::getRaw(newType, getRawData(), isSplat());
1020 }
1021 
1022 DenseElementsAttr
1023 DenseElementsAttr::mapValues(Type newElementType,
1024                              function_ref<APInt(const APInt &)> mapping) const {
1025   return cast<DenseIntElementsAttr>().mapValues(newElementType, mapping);
1026 }
1027 
1028 DenseElementsAttr DenseElementsAttr::mapValues(
1029     Type newElementType, function_ref<APInt(const APFloat &)> mapping) const {
1030   return cast<DenseFPElementsAttr>().mapValues(newElementType, mapping);
1031 }
1032 
1033 //===----------------------------------------------------------------------===//
1034 // DenseStringElementsAttr
1035 //===----------------------------------------------------------------------===//
1036 
1037 DenseStringElementsAttr
1038 DenseStringElementsAttr::get(ShapedType type, ArrayRef<StringRef> values) {
1039   return Base::get(type.getContext(), StandardAttributes::DenseStringElements,
1040                    type, values, (values.size() == 1));
1041 }
1042 
1043 //===----------------------------------------------------------------------===//
1044 // DenseIntOrFPElementsAttr
1045 //===----------------------------------------------------------------------===//
1046 
1047 /// Utility method to write a range of APInt values to a buffer.
1048 template <typename APRangeT>
1049 static void writeAPIntsToBuffer(size_t storageWidth, std::vector<char> &data,
1050                                 APRangeT &&values) {
1051   data.resize(llvm::divideCeil(storageWidth, CHAR_BIT) * llvm::size(values));
1052   size_t offset = 0;
1053   for (auto it = values.begin(), e = values.end(); it != e;
1054        ++it, offset += storageWidth) {
1055     assert((*it).getBitWidth() <= storageWidth);
1056     writeBits(data.data(), offset, *it);
1057   }
1058 }
1059 
1060 /// Constructs a dense elements attribute from an array of raw APFloat values.
1061 /// Each APFloat value is expected to have the same bitwidth as the element
1062 /// type of 'type'. 'type' must be a vector or tensor with static shape.
1063 DenseElementsAttr DenseIntOrFPElementsAttr::getRaw(ShapedType type,
1064                                                    size_t storageWidth,
1065                                                    ArrayRef<APFloat> values,
1066                                                    bool isSplat) {
1067   std::vector<char> data;
1068   auto unwrapFloat = [](const APFloat &val) { return val.bitcastToAPInt(); };
1069   writeAPIntsToBuffer(storageWidth, data, llvm::map_range(values, unwrapFloat));
1070   return DenseIntOrFPElementsAttr::getRaw(type, data, isSplat);
1071 }
1072 
1073 /// Constructs a dense elements attribute from an array of raw APInt values.
1074 /// Each APInt value is expected to have the same bitwidth as the element type
1075 /// of 'type'.
1076 DenseElementsAttr DenseIntOrFPElementsAttr::getRaw(ShapedType type,
1077                                                    size_t storageWidth,
1078                                                    ArrayRef<APInt> values,
1079                                                    bool isSplat) {
1080   std::vector<char> data;
1081   writeAPIntsToBuffer(storageWidth, data, values);
1082   return DenseIntOrFPElementsAttr::getRaw(type, data, isSplat);
1083 }
1084 
1085 DenseElementsAttr DenseIntOrFPElementsAttr::getRaw(ShapedType type,
1086                                                    ArrayRef<char> data,
1087                                                    bool isSplat) {
1088   assert((type.isa<RankedTensorType, VectorType>()) &&
1089          "type must be ranked tensor or vector");
1090   assert(type.hasStaticShape() && "type must have static shape");
1091   return Base::get(type.getContext(), StandardAttributes::DenseIntOrFPElements,
1092                    type, data, isSplat);
1093 }
1094 
1095 /// Overload of the raw 'get' method that asserts that the given type is of
1096 /// complex type. This method is used to verify type invariants that the
1097 /// templatized 'get' method cannot.
1098 DenseElementsAttr DenseIntOrFPElementsAttr::getRawComplex(ShapedType type,
1099                                                           ArrayRef<char> data,
1100                                                           int64_t dataEltSize,
1101                                                           bool isInt,
1102                                                           bool isSigned) {
1103   assert(::isValidIntOrFloat(
1104       type.getElementType().cast<ComplexType>().getElementType(),
1105       dataEltSize / 2, isInt, isSigned));
1106 
1107   int64_t numElements = data.size() / dataEltSize;
1108   assert(numElements == 1 || numElements == type.getNumElements());
1109   return getRaw(type, data, /*isSplat=*/numElements == 1);
1110 }
1111 
1112 /// Overload of the 'getRaw' method that asserts that the given type is of
1113 /// integer type. This method is used to verify type invariants that the
1114 /// templatized 'get' method cannot.
1115 DenseElementsAttr
1116 DenseIntOrFPElementsAttr::getRawIntOrFloat(ShapedType type, ArrayRef<char> data,
1117                                            int64_t dataEltSize, bool isInt,
1118                                            bool isSigned) {
1119   assert(
1120       ::isValidIntOrFloat(type.getElementType(), dataEltSize, isInt, isSigned));
1121 
1122   int64_t numElements = data.size() / dataEltSize;
1123   assert(numElements == 1 || numElements == type.getNumElements());
1124   return getRaw(type, data, /*isSplat=*/numElements == 1);
1125 }
1126 
1127 //===----------------------------------------------------------------------===//
1128 // DenseFPElementsAttr
1129 //===----------------------------------------------------------------------===//
1130 
1131 template <typename Fn, typename Attr>
1132 static ShapedType mappingHelper(Fn mapping, Attr &attr, ShapedType inType,
1133                                 Type newElementType,
1134                                 llvm::SmallVectorImpl<char> &data) {
1135   size_t bitWidth = getDenseElementBitWidth(newElementType);
1136   size_t storageBitWidth = getDenseElementStorageWidth(bitWidth);
1137 
1138   ShapedType newArrayType;
1139   if (inType.isa<RankedTensorType>())
1140     newArrayType = RankedTensorType::get(inType.getShape(), newElementType);
1141   else if (inType.isa<UnrankedTensorType>())
1142     newArrayType = RankedTensorType::get(inType.getShape(), newElementType);
1143   else if (inType.isa<VectorType>())
1144     newArrayType = VectorType::get(inType.getShape(), newElementType);
1145   else
1146     assert(newArrayType && "Unhandled tensor type");
1147 
1148   size_t numRawElements = attr.isSplat() ? 1 : newArrayType.getNumElements();
1149   data.resize(llvm::divideCeil(storageBitWidth, CHAR_BIT) * numRawElements);
1150 
1151   // Functor used to process a single element value of the attribute.
1152   auto processElt = [&](decltype(*attr.begin()) value, size_t index) {
1153     auto newInt = mapping(value);
1154     assert(newInt.getBitWidth() == bitWidth);
1155     writeBits(data.data(), index * storageBitWidth, newInt);
1156   };
1157 
1158   // Check for the splat case.
1159   if (attr.isSplat()) {
1160     processElt(*attr.begin(), /*index=*/0);
1161     return newArrayType;
1162   }
1163 
1164   // Otherwise, process all of the element values.
1165   uint64_t elementIdx = 0;
1166   for (auto value : attr)
1167     processElt(value, elementIdx++);
1168   return newArrayType;
1169 }
1170 
1171 DenseElementsAttr DenseFPElementsAttr::mapValues(
1172     Type newElementType, function_ref<APInt(const APFloat &)> mapping) const {
1173   llvm::SmallVector<char, 8> elementData;
1174   auto newArrayType =
1175       mappingHelper(mapping, *this, getType(), newElementType, elementData);
1176 
1177   return getRaw(newArrayType, elementData, isSplat());
1178 }
1179 
1180 /// Method for supporting type inquiry through isa, cast and dyn_cast.
1181 bool DenseFPElementsAttr::classof(Attribute attr) {
1182   return attr.isa<DenseElementsAttr>() &&
1183          attr.getType().cast<ShapedType>().getElementType().isa<FloatType>();
1184 }
1185 
1186 //===----------------------------------------------------------------------===//
1187 // DenseIntElementsAttr
1188 //===----------------------------------------------------------------------===//
1189 
1190 DenseElementsAttr DenseIntElementsAttr::mapValues(
1191     Type newElementType, function_ref<APInt(const APInt &)> mapping) const {
1192   llvm::SmallVector<char, 8> elementData;
1193   auto newArrayType =
1194       mappingHelper(mapping, *this, getType(), newElementType, elementData);
1195 
1196   return getRaw(newArrayType, elementData, isSplat());
1197 }
1198 
1199 /// Method for supporting type inquiry through isa, cast and dyn_cast.
1200 bool DenseIntElementsAttr::classof(Attribute attr) {
1201   return attr.isa<DenseElementsAttr>() &&
1202          attr.getType().cast<ShapedType>().getElementType().isIntOrIndex();
1203 }
1204 
1205 //===----------------------------------------------------------------------===//
1206 // OpaqueElementsAttr
1207 //===----------------------------------------------------------------------===//
1208 
1209 OpaqueElementsAttr OpaqueElementsAttr::get(Dialect *dialect, ShapedType type,
1210                                            StringRef bytes) {
1211   assert(TensorType::isValidElementType(type.getElementType()) &&
1212          "Input element type should be a valid tensor element type");
1213   return Base::get(type.getContext(), StandardAttributes::OpaqueElements, type,
1214                    dialect, bytes);
1215 }
1216 
1217 StringRef OpaqueElementsAttr::getValue() const { return getImpl()->bytes; }
1218 
1219 /// Return the value at the given index. If index does not refer to a valid
1220 /// element, then a null attribute is returned.
1221 Attribute OpaqueElementsAttr::getValue(ArrayRef<uint64_t> index) const {
1222   assert(isValidIndex(index) && "expected valid multi-dimensional index");
1223   return Attribute();
1224 }
1225 
1226 Dialect *OpaqueElementsAttr::getDialect() const { return getImpl()->dialect; }
1227 
1228 bool OpaqueElementsAttr::decode(ElementsAttr &result) {
1229   auto *d = getDialect();
1230   if (!d)
1231     return true;
1232   auto *interface =
1233       d->getRegisteredInterface<DialectDecodeAttributesInterface>();
1234   if (!interface)
1235     return true;
1236   return failed(interface->decode(*this, result));
1237 }
1238 
1239 //===----------------------------------------------------------------------===//
1240 // SparseElementsAttr
1241 //===----------------------------------------------------------------------===//
1242 
1243 SparseElementsAttr SparseElementsAttr::get(ShapedType type,
1244                                            DenseElementsAttr indices,
1245                                            DenseElementsAttr values) {
1246   assert(indices.getType().getElementType().isInteger(64) &&
1247          "expected sparse indices to be 64-bit integer values");
1248   assert((type.isa<RankedTensorType, VectorType>()) &&
1249          "type must be ranked tensor or vector");
1250   assert(type.hasStaticShape() && "type must have static shape");
1251   return Base::get(type.getContext(), StandardAttributes::SparseElements, type,
1252                    indices.cast<DenseIntElementsAttr>(), values);
1253 }
1254 
1255 DenseIntElementsAttr SparseElementsAttr::getIndices() const {
1256   return getImpl()->indices;
1257 }
1258 
1259 DenseElementsAttr SparseElementsAttr::getValues() const {
1260   return getImpl()->values;
1261 }
1262 
1263 /// Return the value of the element at the given index.
1264 Attribute SparseElementsAttr::getValue(ArrayRef<uint64_t> index) const {
1265   assert(isValidIndex(index) && "expected valid multi-dimensional index");
1266   auto type = getType();
1267 
1268   // The sparse indices are 64-bit integers, so we can reinterpret the raw data
1269   // as a 1-D index array.
1270   auto sparseIndices = getIndices();
1271   auto sparseIndexValues = sparseIndices.getValues<uint64_t>();
1272 
1273   // Check to see if the indices are a splat.
1274   if (sparseIndices.isSplat()) {
1275     // If the index is also not a splat of the index value, we know that the
1276     // value is zero.
1277     auto splatIndex = *sparseIndexValues.begin();
1278     if (llvm::any_of(index, [=](uint64_t i) { return i != splatIndex; }))
1279       return getZeroAttr();
1280 
1281     // If the indices are a splat, we also expect the values to be a splat.
1282     assert(getValues().isSplat() && "expected splat values");
1283     return getValues().getSplatValue();
1284   }
1285 
1286   // Build a mapping between known indices and the offset of the stored element.
1287   llvm::SmallDenseMap<llvm::ArrayRef<uint64_t>, size_t> mappedIndices;
1288   auto numSparseIndices = sparseIndices.getType().getDimSize(0);
1289   size_t rank = type.getRank();
1290   for (size_t i = 0, e = numSparseIndices; i != e; ++i)
1291     mappedIndices.try_emplace(
1292         {&*std::next(sparseIndexValues.begin(), i * rank), rank}, i);
1293 
1294   // Look for the provided index key within the mapped indices. If the provided
1295   // index is not found, then return a zero attribute.
1296   auto it = mappedIndices.find(index);
1297   if (it == mappedIndices.end())
1298     return getZeroAttr();
1299 
1300   // Otherwise, return the held sparse value element.
1301   return getValues().getValue(it->second);
1302 }
1303 
1304 /// Get a zero APFloat for the given sparse attribute.
1305 APFloat SparseElementsAttr::getZeroAPFloat() const {
1306   auto eltType = getType().getElementType().cast<FloatType>();
1307   return APFloat(eltType.getFloatSemantics());
1308 }
1309 
1310 /// Get a zero APInt for the given sparse attribute.
1311 APInt SparseElementsAttr::getZeroAPInt() const {
1312   auto eltType = getType().getElementType().cast<IntegerType>();
1313   return APInt::getNullValue(eltType.getWidth());
1314 }
1315 
1316 /// Get a zero attribute for the given attribute type.
1317 Attribute SparseElementsAttr::getZeroAttr() const {
1318   auto eltType = getType().getElementType();
1319 
1320   // Handle floating point elements.
1321   if (eltType.isa<FloatType>())
1322     return FloatAttr::get(eltType, 0);
1323 
1324   // Otherwise, this is an integer.
1325   // TODO: Handle StringAttr here.
1326   return IntegerAttr::get(eltType, 0);
1327 }
1328 
1329 /// Flatten, and return, all of the sparse indices in this attribute in
1330 /// row-major order.
1331 std::vector<ptrdiff_t> SparseElementsAttr::getFlattenedSparseIndices() const {
1332   std::vector<ptrdiff_t> flatSparseIndices;
1333 
1334   // The sparse indices are 64-bit integers, so we can reinterpret the raw data
1335   // as a 1-D index array.
1336   auto sparseIndices = getIndices();
1337   auto sparseIndexValues = sparseIndices.getValues<uint64_t>();
1338   if (sparseIndices.isSplat()) {
1339     SmallVector<uint64_t, 8> indices(getType().getRank(),
1340                                      *sparseIndexValues.begin());
1341     flatSparseIndices.push_back(getFlattenedIndex(indices));
1342     return flatSparseIndices;
1343   }
1344 
1345   // Otherwise, reinterpret each index as an ArrayRef when flattening.
1346   auto numSparseIndices = sparseIndices.getType().getDimSize(0);
1347   size_t rank = getType().getRank();
1348   for (size_t i = 0, e = numSparseIndices; i != e; ++i)
1349     flatSparseIndices.push_back(getFlattenedIndex(
1350         {&*std::next(sparseIndexValues.begin(), i * rank), rank}));
1351   return flatSparseIndices;
1352 }
1353 
1354 //===----------------------------------------------------------------------===//
1355 // MutableDictionaryAttr
1356 //===----------------------------------------------------------------------===//
1357 
1358 MutableDictionaryAttr::MutableDictionaryAttr(
1359     ArrayRef<NamedAttribute> attributes) {
1360   setAttrs(attributes);
1361 }
1362 
1363 /// Return the underlying dictionary attribute.
1364 DictionaryAttr
1365 MutableDictionaryAttr::getDictionary(MLIRContext *context) const {
1366   // Construct empty DictionaryAttr if needed.
1367   if (!attrs)
1368     return DictionaryAttr::get({}, context);
1369   return attrs;
1370 }
1371 
1372 ArrayRef<NamedAttribute> MutableDictionaryAttr::getAttrs() const {
1373   return attrs ? attrs.getValue() : llvm::None;
1374 }
1375 
1376 /// Replace the held attributes with ones provided in 'newAttrs'.
1377 void MutableDictionaryAttr::setAttrs(ArrayRef<NamedAttribute> attributes) {
1378   // Don't create an attribute list if there are no attributes.
1379   if (attributes.empty())
1380     attrs = nullptr;
1381   else
1382     attrs = DictionaryAttr::get(attributes, attributes[0].second.getContext());
1383 }
1384 
1385 /// Return the specified attribute if present, null otherwise.
1386 Attribute MutableDictionaryAttr::get(StringRef name) const {
1387   return attrs ? attrs.get(name) : nullptr;
1388 }
1389 
1390 /// Return the specified attribute if present, null otherwise.
1391 Attribute MutableDictionaryAttr::get(Identifier name) const {
1392   return attrs ? attrs.get(name) : nullptr;
1393 }
1394 
1395 /// Return the specified named attribute if present, None otherwise.
1396 Optional<NamedAttribute> MutableDictionaryAttr::getNamed(StringRef name) const {
1397   return attrs ? attrs.getNamed(name) : Optional<NamedAttribute>();
1398 }
1399 Optional<NamedAttribute>
1400 MutableDictionaryAttr::getNamed(Identifier name) const {
1401   return attrs ? attrs.getNamed(name) : Optional<NamedAttribute>();
1402 }
1403 
1404 /// If the an attribute exists with the specified name, change it to the new
1405 /// value.  Otherwise, add a new attribute with the specified name/value.
1406 void MutableDictionaryAttr::set(Identifier name, Attribute value) {
1407   assert(value && "attributes may never be null");
1408 
1409   // Look for an existing value for the given name, and set it in-place.
1410   ArrayRef<NamedAttribute> values = getAttrs();
1411   const auto *it = llvm::find_if(
1412       values, [name](NamedAttribute attr) { return attr.first == name; });
1413   if (it != values.end()) {
1414     // Bail out early if the value is the same as what we already have.
1415     if (it->second == value)
1416       return;
1417 
1418     SmallVector<NamedAttribute, 8> newAttrs(values.begin(), values.end());
1419     newAttrs[it - values.begin()].second = value;
1420     attrs = DictionaryAttr::getWithSorted(newAttrs, value.getContext());
1421     return;
1422   }
1423 
1424   // Otherwise, insert the new attribute into its sorted position.
1425   it = llvm::lower_bound(values, name);
1426   SmallVector<NamedAttribute, 8> newAttrs;
1427   newAttrs.reserve(values.size() + 1);
1428   newAttrs.append(values.begin(), it);
1429   newAttrs.push_back({name, value});
1430   newAttrs.append(it, values.end());
1431   attrs = DictionaryAttr::getWithSorted(newAttrs, value.getContext());
1432 }
1433 
1434 /// Remove the attribute with the specified name if it exists.  The return
1435 /// value indicates whether the attribute was present or not.
1436 auto MutableDictionaryAttr::remove(Identifier name) -> RemoveResult {
1437   auto origAttrs = getAttrs();
1438   for (unsigned i = 0, e = origAttrs.size(); i != e; ++i) {
1439     if (origAttrs[i].first == name) {
1440       // Handle the simple case of removing the only attribute in the list.
1441       if (e == 1) {
1442         attrs = nullptr;
1443         return RemoveResult::Removed;
1444       }
1445 
1446       SmallVector<NamedAttribute, 8> newAttrs;
1447       newAttrs.reserve(origAttrs.size() - 1);
1448       newAttrs.append(origAttrs.begin(), origAttrs.begin() + i);
1449       newAttrs.append(origAttrs.begin() + i + 1, origAttrs.end());
1450       attrs = DictionaryAttr::getWithSorted(newAttrs,
1451                                             newAttrs[0].second.getContext());
1452       return RemoveResult::Removed;
1453     }
1454   }
1455   return RemoveResult::NotFound;
1456 }
1457 
1458 bool mlir::operator<(const NamedAttribute &lhs, const NamedAttribute &rhs) {
1459   return strcmp(lhs.first.data(), rhs.first.data()) < 0;
1460 }
1461 bool mlir::operator<(const NamedAttribute &lhs, StringRef rhs) {
1462   // This is correct even when attr.first.data()[name.size()] is not a zero
1463   // string terminator, because we only care about a less than comparison.
1464   // This can't use memcmp, because it doesn't guarantee that it will stop
1465   // reading both buffers if one is shorter than the other, even if there is
1466   // a difference.
1467   return strncmp(lhs.first.data(), rhs.data(), rhs.size()) < 0;
1468 }
1469