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