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/BuiltinTypes.h"
17 #include "mlir/IR/OpDefinition.h"
18 #include "mlir/IR/Operation.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(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     : representation(0) {
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     free(&storage);
241   } else {
242     getInlineStorage().~TrailingOperandStorage();
243   }
244 }
245 
246 /// Replace the operands contained in the storage with the ones provided in
247 /// 'values'.
248 void detail::OperandStorage::setOperands(Operation *owner, ValueRange values) {
249   MutableArrayRef<OpOperand> storageOperands = resize(owner, values.size());
250   for (unsigned i = 0, e = values.size(); i != e; ++i)
251     storageOperands[i].set(values[i]);
252 }
253 
254 /// Replace the operands beginning at 'start' and ending at 'start' + 'length'
255 /// with the ones provided in 'operands'. 'operands' may be smaller or larger
256 /// than the range pointed to by 'start'+'length'.
257 void detail::OperandStorage::setOperands(Operation *owner, unsigned start,
258                                          unsigned length, ValueRange operands) {
259   // If the new size is the same, we can update inplace.
260   unsigned newSize = operands.size();
261   if (newSize == length) {
262     MutableArrayRef<OpOperand> storageOperands = getOperands();
263     for (unsigned i = 0, e = length; i != e; ++i)
264       storageOperands[start + i].set(operands[i]);
265     return;
266   }
267   // If the new size is greater, remove the extra operands and set the rest
268   // inplace.
269   if (newSize < length) {
270     eraseOperands(start + operands.size(), length - newSize);
271     setOperands(owner, start, newSize, operands);
272     return;
273   }
274   // Otherwise, the new size is greater so we need to grow the storage.
275   auto storageOperands = resize(owner, size() + (newSize - length));
276 
277   // Shift operands to the right to make space for the new operands.
278   unsigned rotateSize = storageOperands.size() - (start + length);
279   auto rbegin = storageOperands.rbegin();
280   std::rotate(rbegin, std::next(rbegin, newSize - length), rbegin + rotateSize);
281 
282   // Update the operands inplace.
283   for (unsigned i = 0, e = operands.size(); i != e; ++i)
284     storageOperands[start + i].set(operands[i]);
285 }
286 
287 /// Erase an operand held by the storage.
288 void detail::OperandStorage::eraseOperands(unsigned start, unsigned length) {
289   TrailingOperandStorage &storage = getStorage();
290   MutableArrayRef<OpOperand> operands = storage.getOperands();
291   assert((start + length) <= operands.size());
292   storage.numOperands -= length;
293 
294   // Shift all operands down if the operand to remove is not at the end.
295   if (start != storage.numOperands) {
296     auto *indexIt = std::next(operands.begin(), start);
297     std::rotate(indexIt, std::next(indexIt, length), operands.end());
298   }
299   for (unsigned i = 0; i != length; ++i)
300     operands[storage.numOperands + i].~OpOperand();
301 }
302 
303 /// Resize the storage to the given size. Returns the array containing the new
304 /// operands.
305 MutableArrayRef<OpOperand> detail::OperandStorage::resize(Operation *owner,
306                                                           unsigned newSize) {
307   TrailingOperandStorage &storage = getStorage();
308 
309   // If the number of operands is less than or equal to the current amount, we
310   // can just update in place.
311   unsigned &numOperands = storage.numOperands;
312   MutableArrayRef<OpOperand> operands = storage.getOperands();
313   if (newSize <= numOperands) {
314     // If the number of new size is less than the current, remove any extra
315     // operands.
316     for (unsigned i = newSize; i != numOperands; ++i)
317       operands[i].~OpOperand();
318     numOperands = newSize;
319     return operands.take_front(newSize);
320   }
321 
322   // If the new size is within the original inline capacity, grow inplace.
323   if (newSize <= storage.capacity) {
324     OpOperand *opBegin = operands.data();
325     for (unsigned e = newSize; numOperands != e; ++numOperands)
326       new (&opBegin[numOperands]) OpOperand(owner);
327     return MutableArrayRef<OpOperand>(opBegin, newSize);
328   }
329 
330   // Otherwise, we need to allocate a new storage.
331   unsigned newCapacity =
332       std::max(unsigned(llvm::NextPowerOf2(storage.capacity + 2)), newSize);
333   auto *newStorageMem =
334       malloc(TrailingOperandStorage::totalSizeToAlloc<OpOperand>(newCapacity));
335   auto *newStorage = ::new (newStorageMem) TrailingOperandStorage();
336   newStorage->numOperands = newSize;
337   newStorage->capacity = newCapacity;
338 
339   // Move the current operands to the new storage.
340   MutableArrayRef<OpOperand> newOperands = newStorage->getOperands();
341   std::uninitialized_copy(std::make_move_iterator(operands.begin()),
342                           std::make_move_iterator(operands.end()),
343                           newOperands.begin());
344 
345   // Destroy the original operands.
346   for (auto &operand : operands)
347     operand.~OpOperand();
348 
349   // Initialize any new operands.
350   for (unsigned e = newSize; numOperands != e; ++numOperands)
351     new (&newOperands[numOperands]) OpOperand(owner);
352 
353   // If the current storage is also dynamic, free it.
354   if (isDynamicStorage())
355     free(&storage);
356 
357   // Update the storage representation to use the new dynamic storage.
358   representation = reinterpret_cast<intptr_t>(newStorage);
359   representation |= DynamicStorageBit;
360   return newOperands;
361 }
362 
363 //===----------------------------------------------------------------------===//
364 // Operation Value-Iterators
365 //===----------------------------------------------------------------------===//
366 
367 //===----------------------------------------------------------------------===//
368 // OperandRange
369 
370 OperandRange::OperandRange(Operation *op)
371     : OperandRange(op->getOpOperands().data(), op->getNumOperands()) {}
372 
373 /// Return the operand index of the first element of this range. The range
374 /// must not be empty.
375 unsigned OperandRange::getBeginOperandIndex() const {
376   assert(!empty() && "range must not be empty");
377   return base->getOperandNumber();
378 }
379 
380 //===----------------------------------------------------------------------===//
381 // MutableOperandRange
382 
383 /// Construct a new mutable range from the given operand, operand start index,
384 /// and range length.
385 MutableOperandRange::MutableOperandRange(
386     Operation *owner, unsigned start, unsigned length,
387     ArrayRef<OperandSegment> operandSegments)
388     : owner(owner), start(start), length(length),
389       operandSegments(operandSegments.begin(), operandSegments.end()) {
390   assert((start + length) <= owner->getNumOperands() && "invalid range");
391 }
392 MutableOperandRange::MutableOperandRange(Operation *owner)
393     : MutableOperandRange(owner, /*start=*/0, owner->getNumOperands()) {}
394 
395 /// Slice this range into a sub range, with the additional operand segment.
396 MutableOperandRange
397 MutableOperandRange::slice(unsigned subStart, unsigned subLen,
398                            Optional<OperandSegment> segment) {
399   assert((subStart + subLen) <= length && "invalid sub-range");
400   MutableOperandRange subSlice(owner, start + subStart, subLen,
401                                operandSegments);
402   if (segment)
403     subSlice.operandSegments.push_back(*segment);
404   return subSlice;
405 }
406 
407 /// Append the given values to the range.
408 void MutableOperandRange::append(ValueRange values) {
409   if (values.empty())
410     return;
411   owner->insertOperands(start + length, values);
412   updateLength(length + values.size());
413 }
414 
415 /// Assign this range to the given values.
416 void MutableOperandRange::assign(ValueRange values) {
417   owner->setOperands(start, length, values);
418   if (length != values.size())
419     updateLength(/*newLength=*/values.size());
420 }
421 
422 /// Assign the range to the given value.
423 void MutableOperandRange::assign(Value value) {
424   if (length == 1) {
425     owner->setOperand(start, value);
426   } else {
427     owner->setOperands(start, length, value);
428     updateLength(/*newLength=*/1);
429   }
430 }
431 
432 /// Erase the operands within the given sub-range.
433 void MutableOperandRange::erase(unsigned subStart, unsigned subLen) {
434   assert((subStart + subLen) <= length && "invalid sub-range");
435   if (length == 0)
436     return;
437   owner->eraseOperands(start + subStart, subLen);
438   updateLength(length - subLen);
439 }
440 
441 /// Clear this range and erase all of the operands.
442 void MutableOperandRange::clear() {
443   if (length != 0) {
444     owner->eraseOperands(start, length);
445     updateLength(/*newLength=*/0);
446   }
447 }
448 
449 /// Allow implicit conversion to an OperandRange.
450 MutableOperandRange::operator OperandRange() const {
451   return owner->getOperands().slice(start, length);
452 }
453 
454 /// Update the length of this range to the one provided.
455 void MutableOperandRange::updateLength(unsigned newLength) {
456   int32_t diff = int32_t(newLength) - int32_t(length);
457   length = newLength;
458 
459   // Update any of the provided segment attributes.
460   for (OperandSegment &segment : operandSegments) {
461     auto attr = segment.second.second.cast<DenseIntElementsAttr>();
462     SmallVector<int32_t, 8> segments(attr.getValues<int32_t>());
463     segments[segment.first] += diff;
464     segment.second.second = DenseIntElementsAttr::get(attr.getType(), segments);
465     owner->setAttr(segment.second.first, segment.second.second);
466   }
467 }
468 
469 //===----------------------------------------------------------------------===//
470 // ValueRange
471 
472 ValueRange::ValueRange(ArrayRef<Value> values)
473     : ValueRange(values.data(), values.size()) {}
474 ValueRange::ValueRange(OperandRange values)
475     : ValueRange(values.begin().getBase(), values.size()) {}
476 ValueRange::ValueRange(ResultRange values)
477     : ValueRange(values.getBase(), values.size()) {}
478 
479 /// See `llvm::detail::indexed_accessor_range_base` for details.
480 ValueRange::OwnerT ValueRange::offset_base(const OwnerT &owner,
481                                            ptrdiff_t index) {
482   if (const auto *value = owner.dyn_cast<const Value *>())
483     return {value + index};
484   if (auto *operand = owner.dyn_cast<OpOperand *>())
485     return {operand + index};
486   return owner.get<detail::OpResultImpl *>()->getNextResultAtOffset(index);
487 }
488 /// See `llvm::detail::indexed_accessor_range_base` for details.
489 Value ValueRange::dereference_iterator(const OwnerT &owner, ptrdiff_t index) {
490   if (const auto *value = owner.dyn_cast<const Value *>())
491     return value[index];
492   if (auto *operand = owner.dyn_cast<OpOperand *>())
493     return operand[index].get();
494   return owner.get<detail::OpResultImpl *>()->getNextResultAtOffset(index);
495 }
496 
497 //===----------------------------------------------------------------------===//
498 // Operation Equivalency
499 //===----------------------------------------------------------------------===//
500 
501 llvm::hash_code OperationEquivalence::computeHash(Operation *op, Flags flags) {
502   // Hash operations based upon their:
503   //   - Operation Name
504   //   - Attributes
505   //   - Result Types
506   llvm::hash_code hash = llvm::hash_combine(
507       op->getName(), op->getAttrDictionary(), op->getResultTypes());
508 
509   //   - Operands
510   bool ignoreOperands = flags & Flags::IgnoreOperands;
511   if (!ignoreOperands) {
512     // TODO: Allow commutative operations to have different ordering.
513     hash = llvm::hash_combine(
514         hash, llvm::hash_combine_range(op->operand_begin(), op->operand_end()));
515   }
516   return hash;
517 }
518 
519 bool OperationEquivalence::isEquivalentTo(Operation *lhs, Operation *rhs,
520                                           Flags flags) {
521   if (lhs == rhs)
522     return true;
523 
524   // Compare the operation name.
525   if (lhs->getName() != rhs->getName())
526     return false;
527   // Check operand counts.
528   if (lhs->getNumOperands() != rhs->getNumOperands())
529     return false;
530   // Compare attributes.
531   if (lhs->getAttrDictionary() != rhs->getAttrDictionary())
532     return false;
533   // Compare result types.
534   if (lhs->getResultTypes() != rhs->getResultTypes())
535     return false;
536   // Compare operands.
537   bool ignoreOperands = flags & Flags::IgnoreOperands;
538   if (ignoreOperands)
539     return true;
540   // TODO: Allow commutative operations to have different ordering.
541   return std::equal(lhs->operand_begin(), lhs->operand_end(),
542                     rhs->operand_begin());
543 }
544