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