1 //===- OperationSupport.cpp -----------------------------------------------===// 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 // This file contains out-of-line implementations of the support types that 10 // Operation and related classes build on top of. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "mlir/IR/OperationSupport.h" 15 #include "mlir/IR/Block.h" 16 #include "mlir/IR/OpDefinition.h" 17 #include "mlir/IR/Operation.h" 18 #include "mlir/IR/StandardTypes.h" 19 using namespace mlir; 20 21 //===----------------------------------------------------------------------===// 22 // NamedAttrList 23 //===----------------------------------------------------------------------===// 24 25 NamedAttrList::NamedAttrList(ArrayRef<NamedAttribute> attributes) { 26 assign(attributes.begin(), attributes.end()); 27 } 28 29 NamedAttrList::NamedAttrList(const_iterator in_start, const_iterator in_end) { 30 assign(in_start, in_end); 31 } 32 33 ArrayRef<NamedAttribute> NamedAttrList::getAttrs() const { return attrs; } 34 35 DictionaryAttr NamedAttrList::getDictionary(MLIRContext *context) const { 36 if (!isSorted()) { 37 DictionaryAttr::sortInPlace(attrs); 38 dictionarySorted.setPointerAndInt(nullptr, true); 39 } 40 if (!dictionarySorted.getPointer()) 41 dictionarySorted.setPointer(DictionaryAttr::getWithSorted(attrs, context)); 42 return dictionarySorted.getPointer().cast<DictionaryAttr>(); 43 } 44 45 NamedAttrList::operator MutableDictionaryAttr() const { 46 if (attrs.empty()) 47 return MutableDictionaryAttr(); 48 return getDictionary(attrs.front().second.getContext()); 49 } 50 51 /// Add an attribute with the specified name. 52 void NamedAttrList::append(StringRef name, Attribute attr) { 53 append(Identifier::get(name, attr.getContext()), attr); 54 } 55 56 /// Add an attribute with the specified name. 57 void NamedAttrList::append(Identifier name, Attribute attr) { 58 push_back({name, attr}); 59 } 60 61 /// Add an array of named attributes. 62 void NamedAttrList::append(ArrayRef<NamedAttribute> newAttributes) { 63 append(newAttributes.begin(), newAttributes.end()); 64 } 65 66 /// Add a range of named attributes. 67 void NamedAttrList::append(const_iterator in_start, const_iterator in_end) { 68 // TODO: expand to handle case where values appended are in order & after 69 // end of current list. 70 dictionarySorted.setPointerAndInt(nullptr, false); 71 attrs.append(in_start, in_end); 72 } 73 74 /// Replaces the attributes with new list of attributes. 75 void NamedAttrList::assign(const_iterator in_start, const_iterator in_end) { 76 DictionaryAttr::sort(ArrayRef<NamedAttribute>{in_start, in_end}, attrs); 77 dictionarySorted.setPointerAndInt(nullptr, true); 78 } 79 80 void NamedAttrList::push_back(NamedAttribute newAttribute) { 81 if (isSorted()) 82 dictionarySorted.setInt( 83 attrs.empty() || 84 strcmp(attrs.back().first.data(), newAttribute.first.data()) < 0); 85 dictionarySorted.setPointer(nullptr); 86 attrs.push_back(newAttribute); 87 } 88 89 /// Helper function to find attribute in possible sorted vector of 90 /// NamedAttributes. 91 template <typename T> 92 static auto *findAttr(SmallVectorImpl<NamedAttribute> &attrs, T name, 93 bool sorted) { 94 if (!sorted) { 95 return llvm::find_if( 96 attrs, [name](NamedAttribute attr) { return attr.first == name; }); 97 } 98 99 auto *it = llvm::lower_bound(attrs, name); 100 if (it == attrs.end() || it->first != name) 101 return attrs.end(); 102 return it; 103 } 104 105 /// Return the specified attribute if present, null otherwise. 106 Attribute NamedAttrList::get(StringRef name) const { 107 auto *it = findAttr(attrs, name, isSorted()); 108 return it != attrs.end() ? it->second : nullptr; 109 } 110 111 /// Return the specified attribute if present, null otherwise. 112 Attribute NamedAttrList::get(Identifier name) const { 113 auto *it = findAttr(attrs, name, isSorted()); 114 return it != attrs.end() ? it->second : nullptr; 115 } 116 117 /// Return the specified named attribute if present, None otherwise. 118 Optional<NamedAttribute> NamedAttrList::getNamed(StringRef name) const { 119 auto *it = findAttr(attrs, name, isSorted()); 120 return it != attrs.end() ? *it : Optional<NamedAttribute>(); 121 } 122 Optional<NamedAttribute> NamedAttrList::getNamed(Identifier name) const { 123 auto *it = findAttr(attrs, name, isSorted()); 124 return it != attrs.end() ? *it : Optional<NamedAttribute>(); 125 } 126 127 /// If the an attribute exists with the specified name, change it to the new 128 /// value. Otherwise, add a new attribute with the specified name/value. 129 void NamedAttrList::set(Identifier name, Attribute value) { 130 assert(value && "attributes may never be null"); 131 132 // Look for an existing value for the given name, and set it in-place. 133 auto *it = findAttr(attrs, name, isSorted()); 134 if (it != attrs.end()) { 135 // Bail out early if the value is the same as what we already have. 136 if (it->second == value) 137 return; 138 dictionarySorted.setPointer(nullptr); 139 it->second = value; 140 return; 141 } 142 143 // Otherwise, insert the new attribute into its sorted position. 144 it = llvm::lower_bound(attrs, name); 145 dictionarySorted.setPointer(nullptr); 146 attrs.insert(it, {name, value}); 147 } 148 void NamedAttrList::set(StringRef name, Attribute value) { 149 assert(value && "setting null attribute not supported"); 150 return set(mlir::Identifier::get(name, value.getContext()), value); 151 } 152 153 NamedAttrList & 154 NamedAttrList::operator=(const SmallVectorImpl<NamedAttribute> &rhs) { 155 assign(rhs.begin(), rhs.end()); 156 return *this; 157 } 158 159 NamedAttrList::operator ArrayRef<NamedAttribute>() const { return attrs; } 160 161 //===----------------------------------------------------------------------===// 162 // OperationState 163 //===----------------------------------------------------------------------===// 164 165 OperationState::OperationState(Location location, StringRef name) 166 : location(location), name(name, location->getContext()) {} 167 168 OperationState::OperationState(Location location, OperationName name) 169 : location(location), name(name) {} 170 171 OperationState::OperationState(Location location, StringRef name, 172 ValueRange operands, ArrayRef<Type> types, 173 ArrayRef<NamedAttribute> attributes, 174 ArrayRef<Block *> successors, 175 MutableArrayRef<std::unique_ptr<Region>> regions) 176 : location(location), name(name, location->getContext()), 177 operands(operands.begin(), operands.end()), 178 types(types.begin(), types.end()), 179 attributes(attributes.begin(), attributes.end()), 180 successors(successors.begin(), successors.end()) { 181 for (std::unique_ptr<Region> &r : regions) 182 this->regions.push_back(std::move(r)); 183 } 184 185 void OperationState::addOperands(ValueRange newOperands) { 186 operands.append(newOperands.begin(), newOperands.end()); 187 } 188 189 void OperationState::addSuccessors(SuccessorRange newSuccessors) { 190 successors.append(newSuccessors.begin(), newSuccessors.end()); 191 } 192 193 Region *OperationState::addRegion() { 194 regions.emplace_back(new Region); 195 return regions.back().get(); 196 } 197 198 void OperationState::addRegion(std::unique_ptr<Region> &®ion) { 199 regions.push_back(std::move(region)); 200 } 201 202 //===----------------------------------------------------------------------===// 203 // OperandStorage 204 //===----------------------------------------------------------------------===// 205 206 detail::OperandStorage::OperandStorage(Operation *owner, ValueRange values) 207 : representation(0) { 208 auto &inlineStorage = getInlineStorage(); 209 inlineStorage.numOperands = inlineStorage.capacity = values.size(); 210 auto *operandPtrBegin = getTrailingObjects<OpOperand>(); 211 for (unsigned i = 0, e = inlineStorage.numOperands; i < e; ++i) 212 new (&operandPtrBegin[i]) OpOperand(owner, values[i]); 213 } 214 215 detail::OperandStorage::~OperandStorage() { 216 // Destruct the current storage container. 217 if (isDynamicStorage()) { 218 TrailingOperandStorage &storage = getDynamicStorage(); 219 storage.~TrailingOperandStorage(); 220 free(&storage); 221 } else { 222 getInlineStorage().~TrailingOperandStorage(); 223 } 224 } 225 226 /// Replace the operands contained in the storage with the ones provided in 227 /// 'values'. 228 void detail::OperandStorage::setOperands(Operation *owner, ValueRange values) { 229 MutableArrayRef<OpOperand> storageOperands = resize(owner, values.size()); 230 for (unsigned i = 0, e = values.size(); i != e; ++i) 231 storageOperands[i].set(values[i]); 232 } 233 234 /// Replace the operands beginning at 'start' and ending at 'start' + 'length' 235 /// with the ones provided in 'operands'. 'operands' may be smaller or larger 236 /// than the range pointed to by 'start'+'length'. 237 void detail::OperandStorage::setOperands(Operation *owner, unsigned start, 238 unsigned length, ValueRange operands) { 239 // If the new size is the same, we can update inplace. 240 unsigned newSize = operands.size(); 241 if (newSize == length) { 242 MutableArrayRef<OpOperand> storageOperands = getOperands(); 243 for (unsigned i = 0, e = length; i != e; ++i) 244 storageOperands[start + i].set(operands[i]); 245 return; 246 } 247 // If the new size is greater, remove the extra operands and set the rest 248 // inplace. 249 if (newSize < length) { 250 eraseOperands(start + operands.size(), length - newSize); 251 setOperands(owner, start, newSize, operands); 252 return; 253 } 254 // Otherwise, the new size is greater so we need to grow the storage. 255 auto storageOperands = resize(owner, size() + (newSize - length)); 256 257 // Shift operands to the right to make space for the new operands. 258 unsigned rotateSize = storageOperands.size() - (start + length); 259 auto rbegin = storageOperands.rbegin(); 260 std::rotate(rbegin, std::next(rbegin, newSize - length), rbegin + rotateSize); 261 262 // Update the operands inplace. 263 for (unsigned i = 0, e = operands.size(); i != e; ++i) 264 storageOperands[start + i].set(operands[i]); 265 } 266 267 /// Erase an operand held by the storage. 268 void detail::OperandStorage::eraseOperands(unsigned start, unsigned length) { 269 TrailingOperandStorage &storage = getStorage(); 270 MutableArrayRef<OpOperand> operands = storage.getOperands(); 271 assert((start + length) <= operands.size()); 272 storage.numOperands -= length; 273 274 // Shift all operands down if the operand to remove is not at the end. 275 if (start != storage.numOperands) { 276 auto *indexIt = std::next(operands.begin(), start); 277 std::rotate(indexIt, std::next(indexIt, length), operands.end()); 278 } 279 for (unsigned i = 0; i != length; ++i) 280 operands[storage.numOperands + i].~OpOperand(); 281 } 282 283 /// Resize the storage to the given size. Returns the array containing the new 284 /// operands. 285 MutableArrayRef<OpOperand> detail::OperandStorage::resize(Operation *owner, 286 unsigned newSize) { 287 TrailingOperandStorage &storage = getStorage(); 288 289 // If the number of operands is less than or equal to the current amount, we 290 // can just update in place. 291 unsigned &numOperands = storage.numOperands; 292 MutableArrayRef<OpOperand> operands = storage.getOperands(); 293 if (newSize <= numOperands) { 294 // If the number of new size is less than the current, remove any extra 295 // operands. 296 for (unsigned i = newSize; i != numOperands; ++i) 297 operands[i].~OpOperand(); 298 numOperands = newSize; 299 return operands.take_front(newSize); 300 } 301 302 // If the new size is within the original inline capacity, grow inplace. 303 if (newSize <= storage.capacity) { 304 OpOperand *opBegin = operands.data(); 305 for (unsigned e = newSize; numOperands != e; ++numOperands) 306 new (&opBegin[numOperands]) OpOperand(owner); 307 return MutableArrayRef<OpOperand>(opBegin, newSize); 308 } 309 310 // Otherwise, we need to allocate a new storage. 311 unsigned newCapacity = 312 std::max(unsigned(llvm::NextPowerOf2(storage.capacity + 2)), newSize); 313 auto *newStorageMem = 314 malloc(TrailingOperandStorage::totalSizeToAlloc<OpOperand>(newCapacity)); 315 auto *newStorage = ::new (newStorageMem) TrailingOperandStorage(); 316 newStorage->numOperands = newSize; 317 newStorage->capacity = newCapacity; 318 319 // Move the current operands to the new storage. 320 MutableArrayRef<OpOperand> newOperands = newStorage->getOperands(); 321 std::uninitialized_copy(std::make_move_iterator(operands.begin()), 322 std::make_move_iterator(operands.end()), 323 newOperands.begin()); 324 325 // Destroy the original operands. 326 for (auto &operand : operands) 327 operand.~OpOperand(); 328 329 // Initialize any new operands. 330 for (unsigned e = newSize; numOperands != e; ++numOperands) 331 new (&newOperands[numOperands]) OpOperand(owner); 332 333 // If the current storage is also dynamic, free it. 334 if (isDynamicStorage()) 335 free(&storage); 336 337 // Update the storage representation to use the new dynamic storage. 338 representation = reinterpret_cast<intptr_t>(newStorage); 339 representation |= DynamicStorageBit; 340 return newOperands; 341 } 342 343 //===----------------------------------------------------------------------===// 344 // ResultStorage 345 //===----------------------------------------------------------------------===// 346 347 /// Returns the parent operation of this trailing result. 348 Operation *detail::TrailingOpResult::getOwner() { 349 // We need to do some arithmetic to get the operation pointer. Move the 350 // trailing owner to the start of the array. 351 TrailingOpResult *trailingIt = this - trailingResultNumber; 352 353 // Move the owner past the inline op results to get to the operation. 354 auto *inlineResultIt = reinterpret_cast<InLineOpResult *>(trailingIt) - 355 OpResult::getMaxInlineResults(); 356 return reinterpret_cast<Operation *>(inlineResultIt) - 1; 357 } 358 359 //===----------------------------------------------------------------------===// 360 // Operation Value-Iterators 361 //===----------------------------------------------------------------------===// 362 363 //===----------------------------------------------------------------------===// 364 // OperandRange 365 366 OperandRange::OperandRange(Operation *op) 367 : OperandRange(op->getOpOperands().data(), op->getNumOperands()) {} 368 369 /// Return the operand index of the first element of this range. The range 370 /// must not be empty. 371 unsigned OperandRange::getBeginOperandIndex() const { 372 assert(!empty() && "range must not be empty"); 373 return base->getOperandNumber(); 374 } 375 376 //===----------------------------------------------------------------------===// 377 // MutableOperandRange 378 379 /// Construct a new mutable range from the given operand, operand start index, 380 /// and range length. 381 MutableOperandRange::MutableOperandRange( 382 Operation *owner, unsigned start, unsigned length, 383 ArrayRef<OperandSegment> operandSegments) 384 : owner(owner), start(start), length(length), 385 operandSegments(operandSegments.begin(), operandSegments.end()) { 386 assert((start + length) <= owner->getNumOperands() && "invalid range"); 387 } 388 MutableOperandRange::MutableOperandRange(Operation *owner) 389 : MutableOperandRange(owner, /*start=*/0, owner->getNumOperands()) {} 390 391 /// Slice this range into a sub range, with the additional operand segment. 392 MutableOperandRange 393 MutableOperandRange::slice(unsigned subStart, unsigned subLen, 394 Optional<OperandSegment> segment) { 395 assert((subStart + subLen) <= length && "invalid sub-range"); 396 MutableOperandRange subSlice(owner, start + subStart, subLen, 397 operandSegments); 398 if (segment) 399 subSlice.operandSegments.push_back(*segment); 400 return subSlice; 401 } 402 403 /// Append the given values to the range. 404 void MutableOperandRange::append(ValueRange values) { 405 if (values.empty()) 406 return; 407 owner->insertOperands(start + length, values); 408 updateLength(length + values.size()); 409 } 410 411 /// Assign this range to the given values. 412 void MutableOperandRange::assign(ValueRange values) { 413 owner->setOperands(start, length, values); 414 if (length != values.size()) 415 updateLength(/*newLength=*/values.size()); 416 } 417 418 /// Assign the range to the given value. 419 void MutableOperandRange::assign(Value value) { 420 if (length == 1) { 421 owner->setOperand(start, value); 422 } else { 423 owner->setOperands(start, length, value); 424 updateLength(/*newLength=*/1); 425 } 426 } 427 428 /// Erase the operands within the given sub-range. 429 void MutableOperandRange::erase(unsigned subStart, unsigned subLen) { 430 assert((subStart + subLen) <= length && "invalid sub-range"); 431 if (length == 0) 432 return; 433 owner->eraseOperands(start + subStart, subLen); 434 updateLength(length - subLen); 435 } 436 437 /// Clear this range and erase all of the operands. 438 void MutableOperandRange::clear() { 439 if (length != 0) { 440 owner->eraseOperands(start, length); 441 updateLength(/*newLength=*/0); 442 } 443 } 444 445 /// Allow implicit conversion to an OperandRange. 446 MutableOperandRange::operator OperandRange() const { 447 return owner->getOperands().slice(start, length); 448 } 449 450 /// Update the length of this range to the one provided. 451 void MutableOperandRange::updateLength(unsigned newLength) { 452 int32_t diff = int32_t(newLength) - int32_t(length); 453 length = newLength; 454 455 // Update any of the provided segment attributes. 456 for (OperandSegment &segment : operandSegments) { 457 auto attr = segment.second.second.cast<DenseIntElementsAttr>(); 458 SmallVector<int32_t, 8> segments(attr.getValues<int32_t>()); 459 segments[segment.first] += diff; 460 segment.second.second = DenseIntElementsAttr::get(attr.getType(), segments); 461 owner->setAttr(segment.second.first, segment.second.second); 462 } 463 } 464 465 //===----------------------------------------------------------------------===// 466 // ResultRange 467 468 ResultRange::ResultRange(Operation *op) 469 : ResultRange(op, /*startIndex=*/0, op->getNumResults()) {} 470 471 ArrayRef<Type> ResultRange::getTypes() const { 472 return getBase()->getResultTypes().slice(getStartIndex(), size()); 473 } 474 475 /// See `llvm::indexed_accessor_range` for details. 476 OpResult ResultRange::dereference(Operation *op, ptrdiff_t index) { 477 return op->getResult(index); 478 } 479 480 //===----------------------------------------------------------------------===// 481 // ValueRange 482 483 ValueRange::ValueRange(ArrayRef<Value> values) 484 : ValueRange(values.data(), values.size()) {} 485 ValueRange::ValueRange(OperandRange values) 486 : ValueRange(values.begin().getBase(), values.size()) {} 487 ValueRange::ValueRange(ResultRange values) 488 : ValueRange( 489 {values.getBase(), static_cast<unsigned>(values.getStartIndex())}, 490 values.size()) {} 491 492 /// See `llvm::detail::indexed_accessor_range_base` for details. 493 ValueRange::OwnerT ValueRange::offset_base(const OwnerT &owner, 494 ptrdiff_t index) { 495 if (auto *value = owner.ptr.dyn_cast<const Value *>()) 496 return {value + index}; 497 if (auto *operand = owner.ptr.dyn_cast<OpOperand *>()) 498 return {operand + index}; 499 Operation *operation = reinterpret_cast<Operation *>(owner.ptr.get<void *>()); 500 return {operation, owner.startIndex + static_cast<unsigned>(index)}; 501 } 502 /// See `llvm::detail::indexed_accessor_range_base` for details. 503 Value ValueRange::dereference_iterator(const OwnerT &owner, ptrdiff_t index) { 504 if (auto *value = owner.ptr.dyn_cast<const Value *>()) 505 return value[index]; 506 if (auto *operand = owner.ptr.dyn_cast<OpOperand *>()) 507 return operand[index].get(); 508 Operation *operation = reinterpret_cast<Operation *>(owner.ptr.get<void *>()); 509 return operation->getResult(owner.startIndex + index); 510 } 511 512 //===----------------------------------------------------------------------===// 513 // Operation Equivalency 514 //===----------------------------------------------------------------------===// 515 516 llvm::hash_code OperationEquivalence::computeHash(Operation *op, Flags flags) { 517 // Hash operations based upon their: 518 // - Operation Name 519 // - Attributes 520 llvm::hash_code hash = 521 llvm::hash_combine(op->getName(), op->getMutableAttrDict()); 522 523 // - Result Types 524 ArrayRef<Type> resultTypes = op->getResultTypes(); 525 switch (resultTypes.size()) { 526 case 0: 527 // We don't need to add anything to the hash. 528 break; 529 case 1: 530 // Add in the result type. 531 hash = llvm::hash_combine(hash, resultTypes.front()); 532 break; 533 default: 534 // Use the type buffer as the hash, as we can guarantee it is the same for 535 // any given range of result types. This takes advantage of the fact the 536 // result types >1 are stored in a TupleType and uniqued. 537 hash = llvm::hash_combine(hash, resultTypes.data()); 538 break; 539 } 540 541 // - Operands 542 bool ignoreOperands = flags & Flags::IgnoreOperands; 543 if (!ignoreOperands) { 544 // TODO: Allow commutative operations to have different ordering. 545 hash = llvm::hash_combine( 546 hash, llvm::hash_combine_range(op->operand_begin(), op->operand_end())); 547 } 548 return hash; 549 } 550 551 bool OperationEquivalence::isEquivalentTo(Operation *lhs, Operation *rhs, 552 Flags flags) { 553 if (lhs == rhs) 554 return true; 555 556 // Compare the operation name. 557 if (lhs->getName() != rhs->getName()) 558 return false; 559 // Check operand counts. 560 if (lhs->getNumOperands() != rhs->getNumOperands()) 561 return false; 562 // Compare attributes. 563 if (lhs->getMutableAttrDict() != rhs->getMutableAttrDict()) 564 return false; 565 // Compare result types. 566 ArrayRef<Type> lhsResultTypes = lhs->getResultTypes(); 567 ArrayRef<Type> rhsResultTypes = rhs->getResultTypes(); 568 if (lhsResultTypes.size() != rhsResultTypes.size()) 569 return false; 570 switch (lhsResultTypes.size()) { 571 case 0: 572 break; 573 case 1: 574 // Compare the single result type. 575 if (lhsResultTypes.front() != rhsResultTypes.front()) 576 return false; 577 break; 578 default: 579 // Use the type buffer for the comparison, as we can guarantee it is the 580 // same for any given range of result types. This takes advantage of the 581 // fact the result types >1 are stored in a TupleType and uniqued. 582 if (lhsResultTypes.data() != rhsResultTypes.data()) 583 return false; 584 break; 585 } 586 // Compare operands. 587 bool ignoreOperands = flags & Flags::IgnoreOperands; 588 if (ignoreOperands) 589 return true; 590 // TODO: Allow commutative operations to have different ordering. 591 return std::equal(lhs->operand_begin(), lhs->operand_end(), 592 rhs->operand_begin()); 593 } 594