[clang][modules] Don't prevent translation of FW_Private includes when explicitly...
[llvm-project.git] / mlir / lib / IR / Operation.cpp
blob7507e0cd0c99b31fce7bcac1b5edb1bf534362d0
1 //===- Operation.cpp - Operation support code -----------------------------===//
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 //===----------------------------------------------------------------------===//
9 #include "mlir/IR/Operation.h"
10 #include "mlir/IR/Attributes.h"
11 #include "mlir/IR/BuiltinAttributes.h"
12 #include "mlir/IR/BuiltinTypes.h"
13 #include "mlir/IR/Dialect.h"
14 #include "mlir/IR/IRMapping.h"
15 #include "mlir/IR/Matchers.h"
16 #include "mlir/IR/OpImplementation.h"
17 #include "mlir/IR/OperationSupport.h"
18 #include "mlir/IR/PatternMatch.h"
19 #include "mlir/IR/TypeUtilities.h"
20 #include "mlir/Interfaces/FoldInterfaces.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include <numeric>
24 #include <optional>
26 using namespace mlir;
28 //===----------------------------------------------------------------------===//
29 // Operation
30 //===----------------------------------------------------------------------===//
32 /// Create a new Operation from operation state.
33 Operation *Operation::create(const OperationState &state) {
34 Operation *op =
35 create(state.location, state.name, state.types, state.operands,
36 state.attributes.getDictionary(state.getContext()),
37 state.properties, state.successors, state.regions);
38 if (LLVM_UNLIKELY(state.propertiesAttr)) {
39 assert(!state.properties);
40 LogicalResult result =
41 op->setPropertiesFromAttribute(state.propertiesAttr,
42 /*diagnostic=*/nullptr);
43 assert(result.succeeded() && "invalid properties in op creation");
44 (void)result;
46 return op;
49 /// Create a new Operation with the specific fields.
50 Operation *Operation::create(Location location, OperationName name,
51 TypeRange resultTypes, ValueRange operands,
52 NamedAttrList &&attributes,
53 OpaqueProperties properties, BlockRange successors,
54 RegionRange regions) {
55 unsigned numRegions = regions.size();
56 Operation *op =
57 create(location, name, resultTypes, operands, std::move(attributes),
58 properties, successors, numRegions);
59 for (unsigned i = 0; i < numRegions; ++i)
60 if (regions[i])
61 op->getRegion(i).takeBody(*regions[i]);
62 return op;
65 /// Create a new Operation with the specific fields.
66 Operation *Operation::create(Location location, OperationName name,
67 TypeRange resultTypes, ValueRange operands,
68 NamedAttrList &&attributes,
69 OpaqueProperties properties, BlockRange successors,
70 unsigned numRegions) {
71 // Populate default attributes.
72 name.populateDefaultAttrs(attributes);
74 return create(location, name, resultTypes, operands,
75 attributes.getDictionary(location.getContext()), properties,
76 successors, numRegions);
79 /// Overload of create that takes an existing DictionaryAttr to avoid
80 /// unnecessarily uniquing a list of attributes.
81 Operation *Operation::create(Location location, OperationName name,
82 TypeRange resultTypes, ValueRange operands,
83 DictionaryAttr attributes,
84 OpaqueProperties properties, BlockRange successors,
85 unsigned numRegions) {
86 assert(llvm::all_of(resultTypes, [](Type t) { return t; }) &&
87 "unexpected null result type");
89 // We only need to allocate additional memory for a subset of results.
90 unsigned numTrailingResults = OpResult::getNumTrailing(resultTypes.size());
91 unsigned numInlineResults = OpResult::getNumInline(resultTypes.size());
92 unsigned numSuccessors = successors.size();
93 unsigned numOperands = operands.size();
94 unsigned numResults = resultTypes.size();
95 int opPropertiesAllocSize = llvm::alignTo<8>(name.getOpPropertyByteSize());
97 // If the operation is known to have no operands, don't allocate an operand
98 // storage.
99 bool needsOperandStorage =
100 operands.empty() ? !name.hasTrait<OpTrait::ZeroOperands>() : true;
102 // Compute the byte size for the operation and the operand storage. This takes
103 // into account the size of the operation, its trailing objects, and its
104 // prefixed objects.
105 size_t byteSize =
106 totalSizeToAlloc<detail::OperandStorage, detail::OpProperties,
107 BlockOperand, Region, OpOperand>(
108 needsOperandStorage ? 1 : 0, opPropertiesAllocSize, numSuccessors,
109 numRegions, numOperands);
110 size_t prefixByteSize = llvm::alignTo(
111 Operation::prefixAllocSize(numTrailingResults, numInlineResults),
112 alignof(Operation));
113 char *mallocMem = reinterpret_cast<char *>(malloc(byteSize + prefixByteSize));
114 void *rawMem = mallocMem + prefixByteSize;
116 // Create the new Operation.
117 Operation *op = ::new (rawMem) Operation(
118 location, name, numResults, numSuccessors, numRegions,
119 opPropertiesAllocSize, attributes, properties, needsOperandStorage);
121 assert((numSuccessors == 0 || op->mightHaveTrait<OpTrait::IsTerminator>()) &&
122 "unexpected successors in a non-terminator operation");
124 // Initialize the results.
125 auto resultTypeIt = resultTypes.begin();
126 for (unsigned i = 0; i < numInlineResults; ++i, ++resultTypeIt)
127 new (op->getInlineOpResult(i)) detail::InlineOpResult(*resultTypeIt, i);
128 for (unsigned i = 0; i < numTrailingResults; ++i, ++resultTypeIt) {
129 new (op->getOutOfLineOpResult(i))
130 detail::OutOfLineOpResult(*resultTypeIt, i);
133 // Initialize the regions.
134 for (unsigned i = 0; i != numRegions; ++i)
135 new (&op->getRegion(i)) Region(op);
137 // Initialize the operands.
138 if (needsOperandStorage) {
139 new (&op->getOperandStorage()) detail::OperandStorage(
140 op, op->getTrailingObjects<OpOperand>(), operands);
143 // Initialize the successors.
144 auto blockOperands = op->getBlockOperands();
145 for (unsigned i = 0; i != numSuccessors; ++i)
146 new (&blockOperands[i]) BlockOperand(op, successors[i]);
148 // This must be done after properties are initalized.
149 op->setAttrs(attributes);
151 return op;
154 Operation::Operation(Location location, OperationName name, unsigned numResults,
155 unsigned numSuccessors, unsigned numRegions,
156 int fullPropertiesStorageSize, DictionaryAttr attributes,
157 OpaqueProperties properties, bool hasOperandStorage)
158 : location(location), numResults(numResults), numSuccs(numSuccessors),
159 numRegions(numRegions), hasOperandStorage(hasOperandStorage),
160 propertiesStorageSize((fullPropertiesStorageSize + 7) / 8), name(name) {
161 assert(attributes && "unexpected null attribute dictionary");
162 assert(fullPropertiesStorageSize <= propertiesCapacity &&
163 "Properties size overflow");
164 #ifndef NDEBUG
165 if (!getDialect() && !getContext()->allowsUnregisteredDialects())
166 llvm::report_fatal_error(
167 name.getStringRef() +
168 " created with unregistered dialect. If this is intended, please call "
169 "allowUnregisteredDialects() on the MLIRContext, or use "
170 "-allow-unregistered-dialect with the MLIR tool used.");
171 #endif
172 if (fullPropertiesStorageSize)
173 name.initOpProperties(getPropertiesStorage(), properties);
176 // Operations are deleted through the destroy() member because they are
177 // allocated via malloc.
178 Operation::~Operation() {
179 assert(block == nullptr && "operation destroyed but still in a block");
180 #ifndef NDEBUG
181 if (!use_empty()) {
183 InFlightDiagnostic diag =
184 emitOpError("operation destroyed but still has uses");
185 for (Operation *user : getUsers())
186 diag.attachNote(user->getLoc()) << "- use: " << *user << "\n";
188 llvm::report_fatal_error("operation destroyed but still has uses");
190 #endif
191 // Explicitly run the destructors for the operands.
192 if (hasOperandStorage)
193 getOperandStorage().~OperandStorage();
195 // Explicitly run the destructors for the successors.
196 for (auto &successor : getBlockOperands())
197 successor.~BlockOperand();
199 // Explicitly destroy the regions.
200 for (auto &region : getRegions())
201 region.~Region();
202 if (propertiesStorageSize)
203 name.destroyOpProperties(getPropertiesStorage());
206 /// Destroy this operation or one of its subclasses.
207 void Operation::destroy() {
208 // Operations may have additional prefixed allocation, which needs to be
209 // accounted for here when computing the address to free.
210 char *rawMem = reinterpret_cast<char *>(this) -
211 llvm::alignTo(prefixAllocSize(), alignof(Operation));
212 this->~Operation();
213 free(rawMem);
216 /// Return true if this operation is a proper ancestor of the `other`
217 /// operation.
218 bool Operation::isProperAncestor(Operation *other) {
219 while ((other = other->getParentOp()))
220 if (this == other)
221 return true;
222 return false;
225 /// Replace any uses of 'from' with 'to' within this operation.
226 void Operation::replaceUsesOfWith(Value from, Value to) {
227 if (from == to)
228 return;
229 for (auto &operand : getOpOperands())
230 if (operand.get() == from)
231 operand.set(to);
234 /// Replace the current operands of this operation with the ones provided in
235 /// 'operands'.
236 void Operation::setOperands(ValueRange operands) {
237 if (LLVM_LIKELY(hasOperandStorage))
238 return getOperandStorage().setOperands(this, operands);
239 assert(operands.empty() && "setting operands without an operand storage");
242 /// Replace the operands beginning at 'start' and ending at 'start' + 'length'
243 /// with the ones provided in 'operands'. 'operands' may be smaller or larger
244 /// than the range pointed to by 'start'+'length'.
245 void Operation::setOperands(unsigned start, unsigned length,
246 ValueRange operands) {
247 assert((start + length) <= getNumOperands() &&
248 "invalid operand range specified");
249 if (LLVM_LIKELY(hasOperandStorage))
250 return getOperandStorage().setOperands(this, start, length, operands);
251 assert(operands.empty() && "setting operands without an operand storage");
254 /// Insert the given operands into the operand list at the given 'index'.
255 void Operation::insertOperands(unsigned index, ValueRange operands) {
256 if (LLVM_LIKELY(hasOperandStorage))
257 return setOperands(index, /*length=*/0, operands);
258 assert(operands.empty() && "inserting operands without an operand storage");
261 //===----------------------------------------------------------------------===//
262 // Diagnostics
263 //===----------------------------------------------------------------------===//
265 /// Emit an error about fatal conditions with this operation, reporting up to
266 /// any diagnostic handlers that may be listening.
267 InFlightDiagnostic Operation::emitError(const Twine &message) {
268 InFlightDiagnostic diag = mlir::emitError(getLoc(), message);
269 if (getContext()->shouldPrintOpOnDiagnostic()) {
270 diag.attachNote(getLoc())
271 .append("see current operation: ")
272 .appendOp(*this, OpPrintingFlags().printGenericOpForm());
274 return diag;
277 /// Emit a warning about this operation, reporting up to any diagnostic
278 /// handlers that may be listening.
279 InFlightDiagnostic Operation::emitWarning(const Twine &message) {
280 InFlightDiagnostic diag = mlir::emitWarning(getLoc(), message);
281 if (getContext()->shouldPrintOpOnDiagnostic())
282 diag.attachNote(getLoc()) << "see current operation: " << *this;
283 return diag;
286 /// Emit a remark about this operation, reporting up to any diagnostic
287 /// handlers that may be listening.
288 InFlightDiagnostic Operation::emitRemark(const Twine &message) {
289 InFlightDiagnostic diag = mlir::emitRemark(getLoc(), message);
290 if (getContext()->shouldPrintOpOnDiagnostic())
291 diag.attachNote(getLoc()) << "see current operation: " << *this;
292 return diag;
295 DictionaryAttr Operation::getAttrDictionary() {
296 if (getPropertiesStorageSize()) {
297 NamedAttrList attrsList = attrs;
298 getName().populateInherentAttrs(this, attrsList);
299 return attrsList.getDictionary(getContext());
301 return attrs;
304 void Operation::setAttrs(DictionaryAttr newAttrs) {
305 assert(newAttrs && "expected valid attribute dictionary");
306 if (getPropertiesStorageSize()) {
307 // We're spliting the providing DictionaryAttr by removing the inherentAttr
308 // which will be stored in the properties.
309 SmallVector<NamedAttribute> discardableAttrs;
310 discardableAttrs.reserve(newAttrs.size());
311 for (NamedAttribute attr : newAttrs) {
312 if (getInherentAttr(attr.getName()))
313 setInherentAttr(attr.getName(), attr.getValue());
314 else
315 discardableAttrs.push_back(attr);
317 if (discardableAttrs.size() != newAttrs.size())
318 newAttrs = DictionaryAttr::get(getContext(), discardableAttrs);
320 attrs = newAttrs;
322 void Operation::setAttrs(ArrayRef<NamedAttribute> newAttrs) {
323 if (getPropertiesStorageSize()) {
324 // We're spliting the providing array of attributes by removing the inherentAttr
325 // which will be stored in the properties.
326 SmallVector<NamedAttribute> discardableAttrs;
327 discardableAttrs.reserve(newAttrs.size());
328 for (NamedAttribute attr : newAttrs) {
329 if (getInherentAttr(attr.getName()))
330 setInherentAttr(attr.getName(), attr.getValue());
331 else
332 discardableAttrs.push_back(attr);
334 attrs = DictionaryAttr::get(getContext(), discardableAttrs);
335 return;
337 attrs = DictionaryAttr::get(getContext(), newAttrs);
340 std::optional<Attribute> Operation::getInherentAttr(StringRef name) {
341 return getName().getInherentAttr(this, name);
344 void Operation::setInherentAttr(StringAttr name, Attribute value) {
345 getName().setInherentAttr(this, name, value);
348 Attribute Operation::getPropertiesAsAttribute() {
349 std::optional<RegisteredOperationName> info = getRegisteredInfo();
350 if (LLVM_UNLIKELY(!info))
351 return *getPropertiesStorage().as<Attribute *>();
352 return info->getOpPropertiesAsAttribute(this);
354 LogicalResult Operation::setPropertiesFromAttribute(
355 Attribute attr, function_ref<InFlightDiagnostic()> emitError) {
356 std::optional<RegisteredOperationName> info = getRegisteredInfo();
357 if (LLVM_UNLIKELY(!info)) {
358 *getPropertiesStorage().as<Attribute *>() = attr;
359 return success();
361 return info->setOpPropertiesFromAttribute(
362 this->getName(), this->getPropertiesStorage(), attr, emitError);
365 void Operation::copyProperties(OpaqueProperties rhs) {
366 name.copyOpProperties(getPropertiesStorage(), rhs);
369 llvm::hash_code Operation::hashProperties() {
370 return name.hashOpProperties(getPropertiesStorage());
373 //===----------------------------------------------------------------------===//
374 // Operation Ordering
375 //===----------------------------------------------------------------------===//
377 constexpr unsigned Operation::kInvalidOrderIdx;
378 constexpr unsigned Operation::kOrderStride;
380 /// Given an operation 'other' that is within the same parent block, return
381 /// whether the current operation is before 'other' in the operation list
382 /// of the parent block.
383 /// Note: This function has an average complexity of O(1), but worst case may
384 /// take O(N) where N is the number of operations within the parent block.
385 bool Operation::isBeforeInBlock(Operation *other) {
386 assert(block && "Operations without parent blocks have no order.");
387 assert(other && other->block == block &&
388 "Expected other operation to have the same parent block.");
389 // If the order of the block is already invalid, directly recompute the
390 // parent.
391 if (!block->isOpOrderValid()) {
392 block->recomputeOpOrder();
393 } else {
394 // Update the order either operation if necessary.
395 updateOrderIfNecessary();
396 other->updateOrderIfNecessary();
399 return orderIndex < other->orderIndex;
402 /// Update the order index of this operation of this operation if necessary,
403 /// potentially recomputing the order of the parent block.
404 void Operation::updateOrderIfNecessary() {
405 assert(block && "expected valid parent");
407 // If the order is valid for this operation there is nothing to do.
408 if (hasValidOrder())
409 return;
410 Operation *blockFront = &block->front();
411 Operation *blockBack = &block->back();
413 // This method is expected to only be invoked on blocks with more than one
414 // operation.
415 assert(blockFront != blockBack && "expected more than one operation");
417 // If the operation is at the end of the block.
418 if (this == blockBack) {
419 Operation *prevNode = getPrevNode();
420 if (!prevNode->hasValidOrder())
421 return block->recomputeOpOrder();
423 // Add the stride to the previous operation.
424 orderIndex = prevNode->orderIndex + kOrderStride;
425 return;
428 // If this is the first operation try to use the next operation to compute the
429 // ordering.
430 if (this == blockFront) {
431 Operation *nextNode = getNextNode();
432 if (!nextNode->hasValidOrder())
433 return block->recomputeOpOrder();
434 // There is no order to give this operation.
435 if (nextNode->orderIndex == 0)
436 return block->recomputeOpOrder();
438 // If we can't use the stride, just take the middle value left. This is safe
439 // because we know there is at least one valid index to assign to.
440 if (nextNode->orderIndex <= kOrderStride)
441 orderIndex = (nextNode->orderIndex / 2);
442 else
443 orderIndex = kOrderStride;
444 return;
447 // Otherwise, this operation is between two others. Place this operation in
448 // the middle of the previous and next if possible.
449 Operation *prevNode = getPrevNode(), *nextNode = getNextNode();
450 if (!prevNode->hasValidOrder() || !nextNode->hasValidOrder())
451 return block->recomputeOpOrder();
452 unsigned prevOrder = prevNode->orderIndex, nextOrder = nextNode->orderIndex;
454 // Check to see if there is a valid order between the two.
455 if (prevOrder + 1 == nextOrder)
456 return block->recomputeOpOrder();
457 orderIndex = prevOrder + ((nextOrder - prevOrder) / 2);
460 //===----------------------------------------------------------------------===//
461 // ilist_traits for Operation
462 //===----------------------------------------------------------------------===//
464 auto llvm::ilist_detail::SpecificNodeAccess<
465 typename llvm::ilist_detail::compute_node_options<
466 ::mlir::Operation>::type>::getNodePtr(pointer n) -> node_type * {
467 return NodeAccess::getNodePtr<OptionsT>(n);
470 auto llvm::ilist_detail::SpecificNodeAccess<
471 typename llvm::ilist_detail::compute_node_options<
472 ::mlir::Operation>::type>::getNodePtr(const_pointer n)
473 -> const node_type * {
474 return NodeAccess::getNodePtr<OptionsT>(n);
477 auto llvm::ilist_detail::SpecificNodeAccess<
478 typename llvm::ilist_detail::compute_node_options<
479 ::mlir::Operation>::type>::getValuePtr(node_type *n) -> pointer {
480 return NodeAccess::getValuePtr<OptionsT>(n);
483 auto llvm::ilist_detail::SpecificNodeAccess<
484 typename llvm::ilist_detail::compute_node_options<
485 ::mlir::Operation>::type>::getValuePtr(const node_type *n)
486 -> const_pointer {
487 return NodeAccess::getValuePtr<OptionsT>(n);
490 void llvm::ilist_traits<::mlir::Operation>::deleteNode(Operation *op) {
491 op->destroy();
494 Block *llvm::ilist_traits<::mlir::Operation>::getContainingBlock() {
495 size_t offset(size_t(&((Block *)nullptr->*Block::getSublistAccess(nullptr))));
496 iplist<Operation> *anchor(static_cast<iplist<Operation> *>(this));
497 return reinterpret_cast<Block *>(reinterpret_cast<char *>(anchor) - offset);
500 /// This is a trait method invoked when an operation is added to a block. We
501 /// keep the block pointer up to date.
502 void llvm::ilist_traits<::mlir::Operation>::addNodeToList(Operation *op) {
503 assert(!op->getBlock() && "already in an operation block!");
504 op->block = getContainingBlock();
506 // Invalidate the order on the operation.
507 op->orderIndex = Operation::kInvalidOrderIdx;
510 /// This is a trait method invoked when an operation is removed from a block.
511 /// We keep the block pointer up to date.
512 void llvm::ilist_traits<::mlir::Operation>::removeNodeFromList(Operation *op) {
513 assert(op->block && "not already in an operation block!");
514 op->block = nullptr;
517 /// This is a trait method invoked when an operation is moved from one block
518 /// to another. We keep the block pointer up to date.
519 void llvm::ilist_traits<::mlir::Operation>::transferNodesFromList(
520 ilist_traits<Operation> &otherList, op_iterator first, op_iterator last) {
521 Block *curParent = getContainingBlock();
523 // Invalidate the ordering of the parent block.
524 curParent->invalidateOpOrder();
526 // If we are transferring operations within the same block, the block
527 // pointer doesn't need to be updated.
528 if (curParent == otherList.getContainingBlock())
529 return;
531 // Update the 'block' member of each operation.
532 for (; first != last; ++first)
533 first->block = curParent;
536 /// Remove this operation (and its descendants) from its Block and delete
537 /// all of them.
538 void Operation::erase() {
539 if (auto *parent = getBlock())
540 parent->getOperations().erase(this);
541 else
542 destroy();
545 /// Remove the operation from its parent block, but don't delete it.
546 void Operation::remove() {
547 if (Block *parent = getBlock())
548 parent->getOperations().remove(this);
551 /// Unlink this operation from its current block and insert it right before
552 /// `existingOp` which may be in the same or another block in the same
553 /// function.
554 void Operation::moveBefore(Operation *existingOp) {
555 moveBefore(existingOp->getBlock(), existingOp->getIterator());
558 /// Unlink this operation from its current basic block and insert it right
559 /// before `iterator` in the specified basic block.
560 void Operation::moveBefore(Block *block,
561 llvm::iplist<Operation>::iterator iterator) {
562 block->getOperations().splice(iterator, getBlock()->getOperations(),
563 getIterator());
566 /// Unlink this operation from its current block and insert it right after
567 /// `existingOp` which may be in the same or another block in the same function.
568 void Operation::moveAfter(Operation *existingOp) {
569 moveAfter(existingOp->getBlock(), existingOp->getIterator());
572 /// Unlink this operation from its current block and insert it right after
573 /// `iterator` in the specified block.
574 void Operation::moveAfter(Block *block,
575 llvm::iplist<Operation>::iterator iterator) {
576 assert(iterator != block->end() && "cannot move after end of block");
577 moveBefore(block, std::next(iterator));
580 /// This drops all operand uses from this operation, which is an essential
581 /// step in breaking cyclic dependences between references when they are to
582 /// be deleted.
583 void Operation::dropAllReferences() {
584 for (auto &op : getOpOperands())
585 op.drop();
587 for (auto &region : getRegions())
588 region.dropAllReferences();
590 for (auto &dest : getBlockOperands())
591 dest.drop();
594 /// This drops all uses of any values defined by this operation or its nested
595 /// regions, wherever they are located.
596 void Operation::dropAllDefinedValueUses() {
597 dropAllUses();
599 for (auto &region : getRegions())
600 for (auto &block : region)
601 block.dropAllDefinedValueUses();
604 void Operation::setSuccessor(Block *block, unsigned index) {
605 assert(index < getNumSuccessors());
606 getBlockOperands()[index].set(block);
609 /// Attempt to fold this operation using the Op's registered foldHook.
610 LogicalResult Operation::fold(ArrayRef<Attribute> operands,
611 SmallVectorImpl<OpFoldResult> &results) {
612 // If we have a registered operation definition matching this one, use it to
613 // try to constant fold the operation.
614 if (succeeded(name.foldHook(this, operands, results)))
615 return success();
617 // Otherwise, fall back on the dialect hook to handle it.
618 Dialect *dialect = getDialect();
619 if (!dialect)
620 return failure();
622 auto *interface = dyn_cast<DialectFoldInterface>(dialect);
623 if (!interface)
624 return failure();
626 return interface->fold(this, operands, results);
629 LogicalResult Operation::fold(SmallVectorImpl<OpFoldResult> &results) {
630 // Check if any operands are constants.
631 SmallVector<Attribute> constants;
632 constants.assign(getNumOperands(), Attribute());
633 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
634 matchPattern(getOperand(i), m_Constant(&constants[i]));
635 return fold(constants, results);
638 /// Emit an error with the op name prefixed, like "'dim' op " which is
639 /// convenient for verifiers.
640 InFlightDiagnostic Operation::emitOpError(const Twine &message) {
641 return emitError() << "'" << getName() << "' op " << message;
644 //===----------------------------------------------------------------------===//
645 // Operation Cloning
646 //===----------------------------------------------------------------------===//
648 Operation::CloneOptions::CloneOptions()
649 : cloneRegionsFlag(false), cloneOperandsFlag(false) {}
651 Operation::CloneOptions::CloneOptions(bool cloneRegions, bool cloneOperands)
652 : cloneRegionsFlag(cloneRegions), cloneOperandsFlag(cloneOperands) {}
654 Operation::CloneOptions Operation::CloneOptions::all() {
655 return CloneOptions().cloneRegions().cloneOperands();
658 Operation::CloneOptions &Operation::CloneOptions::cloneRegions(bool enable) {
659 cloneRegionsFlag = enable;
660 return *this;
663 Operation::CloneOptions &Operation::CloneOptions::cloneOperands(bool enable) {
664 cloneOperandsFlag = enable;
665 return *this;
668 /// Create a deep copy of this operation but keep the operation regions empty.
669 /// Operands are remapped using `mapper` (if present), and `mapper` is updated
670 /// to contain the results. The `mapResults` flag specifies whether the results
671 /// of the cloned operation should be added to the map.
672 Operation *Operation::cloneWithoutRegions(IRMapping &mapper) {
673 return clone(mapper, CloneOptions::all().cloneRegions(false));
676 Operation *Operation::cloneWithoutRegions() {
677 IRMapping mapper;
678 return cloneWithoutRegions(mapper);
681 /// Create a deep copy of this operation, remapping any operands that use
682 /// values outside of the operation using the map that is provided (leaving
683 /// them alone if no entry is present). Replaces references to cloned
684 /// sub-operations to the corresponding operation that is copied, and adds
685 /// those mappings to the map.
686 Operation *Operation::clone(IRMapping &mapper, CloneOptions options) {
687 SmallVector<Value, 8> operands;
688 SmallVector<Block *, 2> successors;
690 // Remap the operands.
691 if (options.shouldCloneOperands()) {
692 operands.reserve(getNumOperands());
693 for (auto opValue : getOperands())
694 operands.push_back(mapper.lookupOrDefault(opValue));
697 // Remap the successors.
698 successors.reserve(getNumSuccessors());
699 for (Block *successor : getSuccessors())
700 successors.push_back(mapper.lookupOrDefault(successor));
702 // Create the new operation.
703 auto *newOp = create(getLoc(), getName(), getResultTypes(), operands, attrs,
704 getPropertiesStorage(), successors, getNumRegions());
705 mapper.map(this, newOp);
707 // Clone the regions.
708 if (options.shouldCloneRegions()) {
709 for (unsigned i = 0; i != numRegions; ++i)
710 getRegion(i).cloneInto(&newOp->getRegion(i), mapper);
713 // Remember the mapping of any results.
714 for (unsigned i = 0, e = getNumResults(); i != e; ++i)
715 mapper.map(getResult(i), newOp->getResult(i));
717 return newOp;
720 Operation *Operation::clone(CloneOptions options) {
721 IRMapping mapper;
722 return clone(mapper, options);
725 //===----------------------------------------------------------------------===//
726 // OpState trait class.
727 //===----------------------------------------------------------------------===//
729 // The fallback for the parser is to try for a dialect operation parser.
730 // Otherwise, reject the custom assembly form.
731 ParseResult OpState::parse(OpAsmParser &parser, OperationState &result) {
732 if (auto parseFn = result.name.getDialect()->getParseOperationHook(
733 result.name.getStringRef()))
734 return (*parseFn)(parser, result);
735 return parser.emitError(parser.getNameLoc(), "has no custom assembly form");
738 // The fallback for the printer is to try for a dialect operation printer.
739 // Otherwise, it prints the generic form.
740 void OpState::print(Operation *op, OpAsmPrinter &p, StringRef defaultDialect) {
741 if (auto printFn = op->getDialect()->getOperationPrinter(op)) {
742 printOpName(op, p, defaultDialect);
743 printFn(op, p);
744 } else {
745 p.printGenericOp(op);
749 /// Print an operation name, eliding the dialect prefix if necessary and doesn't
750 /// lead to ambiguities.
751 void OpState::printOpName(Operation *op, OpAsmPrinter &p,
752 StringRef defaultDialect) {
753 StringRef name = op->getName().getStringRef();
754 if (name.startswith((defaultDialect + ".").str()) && name.count('.') == 1)
755 name = name.drop_front(defaultDialect.size() + 1);
756 p.getStream() << name;
759 /// Parse properties as a Attribute.
760 ParseResult OpState::genericParseProperties(OpAsmParser &parser,
761 Attribute &result) {
762 if (parser.parseLess() || parser.parseAttribute(result) ||
763 parser.parseGreater())
764 return failure();
765 return success();
768 /// Print the properties as a Attribute.
769 void OpState::genericPrintProperties(OpAsmPrinter &p, Attribute properties) {
770 p << "<" << properties << ">";
773 /// Emit an error about fatal conditions with this operation, reporting up to
774 /// any diagnostic handlers that may be listening.
775 InFlightDiagnostic OpState::emitError(const Twine &message) {
776 return getOperation()->emitError(message);
779 /// Emit an error with the op name prefixed, like "'dim' op " which is
780 /// convenient for verifiers.
781 InFlightDiagnostic OpState::emitOpError(const Twine &message) {
782 return getOperation()->emitOpError(message);
785 /// Emit a warning about this operation, reporting up to any diagnostic
786 /// handlers that may be listening.
787 InFlightDiagnostic OpState::emitWarning(const Twine &message) {
788 return getOperation()->emitWarning(message);
791 /// Emit a remark about this operation, reporting up to any diagnostic
792 /// handlers that may be listening.
793 InFlightDiagnostic OpState::emitRemark(const Twine &message) {
794 return getOperation()->emitRemark(message);
797 //===----------------------------------------------------------------------===//
798 // Op Trait implementations
799 //===----------------------------------------------------------------------===//
801 LogicalResult
802 OpTrait::impl::foldCommutative(Operation *op, ArrayRef<Attribute> operands,
803 SmallVectorImpl<OpFoldResult> &results) {
804 // Nothing to fold if there are not at least 2 operands.
805 if (op->getNumOperands() < 2)
806 return failure();
807 // Move all constant operands to the end.
808 OpOperand *operandsBegin = op->getOpOperands().begin();
809 auto isNonConstant = [&](OpOperand &o) {
810 return !static_cast<bool>(operands[std::distance(operandsBegin, &o)]);
812 auto *firstConstantIt = llvm::find_if_not(op->getOpOperands(), isNonConstant);
813 auto *newConstantIt = std::stable_partition(
814 firstConstantIt, op->getOpOperands().end(), isNonConstant);
815 // Return success if the op was modified.
816 return success(firstConstantIt != newConstantIt);
819 OpFoldResult OpTrait::impl::foldIdempotent(Operation *op) {
820 if (op->getNumOperands() == 1) {
821 auto *argumentOp = op->getOperand(0).getDefiningOp();
822 if (argumentOp && op->getName() == argumentOp->getName()) {
823 // Replace the outer operation output with the inner operation.
824 return op->getOperand(0);
826 } else if (op->getOperand(0) == op->getOperand(1)) {
827 return op->getOperand(0);
830 return {};
833 OpFoldResult OpTrait::impl::foldInvolution(Operation *op) {
834 auto *argumentOp = op->getOperand(0).getDefiningOp();
835 if (argumentOp && op->getName() == argumentOp->getName()) {
836 // Replace the outer involutions output with inner's input.
837 return argumentOp->getOperand(0);
840 return {};
843 LogicalResult OpTrait::impl::verifyZeroOperands(Operation *op) {
844 if (op->getNumOperands() != 0)
845 return op->emitOpError() << "requires zero operands";
846 return success();
849 LogicalResult OpTrait::impl::verifyOneOperand(Operation *op) {
850 if (op->getNumOperands() != 1)
851 return op->emitOpError() << "requires a single operand";
852 return success();
855 LogicalResult OpTrait::impl::verifyNOperands(Operation *op,
856 unsigned numOperands) {
857 if (op->getNumOperands() != numOperands) {
858 return op->emitOpError() << "expected " << numOperands
859 << " operands, but found " << op->getNumOperands();
861 return success();
864 LogicalResult OpTrait::impl::verifyAtLeastNOperands(Operation *op,
865 unsigned numOperands) {
866 if (op->getNumOperands() < numOperands)
867 return op->emitOpError()
868 << "expected " << numOperands << " or more operands, but found "
869 << op->getNumOperands();
870 return success();
873 /// If this is a vector type, or a tensor type, return the scalar element type
874 /// that it is built around, otherwise return the type unmodified.
875 static Type getTensorOrVectorElementType(Type type) {
876 if (auto vec = llvm::dyn_cast<VectorType>(type))
877 return vec.getElementType();
879 // Look through tensor<vector<...>> to find the underlying element type.
880 if (auto tensor = llvm::dyn_cast<TensorType>(type))
881 return getTensorOrVectorElementType(tensor.getElementType());
882 return type;
885 LogicalResult OpTrait::impl::verifyIsIdempotent(Operation *op) {
886 // FIXME: Add back check for no side effects on operation.
887 // Currently adding it would cause the shared library build
888 // to fail since there would be a dependency of IR on SideEffectInterfaces
889 // which is cyclical.
890 return success();
893 LogicalResult OpTrait::impl::verifyIsInvolution(Operation *op) {
894 // FIXME: Add back check for no side effects on operation.
895 // Currently adding it would cause the shared library build
896 // to fail since there would be a dependency of IR on SideEffectInterfaces
897 // which is cyclical.
898 return success();
901 LogicalResult
902 OpTrait::impl::verifyOperandsAreSignlessIntegerLike(Operation *op) {
903 for (auto opType : op->getOperandTypes()) {
904 auto type = getTensorOrVectorElementType(opType);
905 if (!type.isSignlessIntOrIndex())
906 return op->emitOpError() << "requires an integer or index type";
908 return success();
911 LogicalResult OpTrait::impl::verifyOperandsAreFloatLike(Operation *op) {
912 for (auto opType : op->getOperandTypes()) {
913 auto type = getTensorOrVectorElementType(opType);
914 if (!llvm::isa<FloatType>(type))
915 return op->emitOpError("requires a float type");
917 return success();
920 LogicalResult OpTrait::impl::verifySameTypeOperands(Operation *op) {
921 // Zero or one operand always have the "same" type.
922 unsigned nOperands = op->getNumOperands();
923 if (nOperands < 2)
924 return success();
926 auto type = op->getOperand(0).getType();
927 for (auto opType : llvm::drop_begin(op->getOperandTypes(), 1))
928 if (opType != type)
929 return op->emitOpError() << "requires all operands to have the same type";
930 return success();
933 LogicalResult OpTrait::impl::verifyZeroRegions(Operation *op) {
934 if (op->getNumRegions() != 0)
935 return op->emitOpError() << "requires zero regions";
936 return success();
939 LogicalResult OpTrait::impl::verifyOneRegion(Operation *op) {
940 if (op->getNumRegions() != 1)
941 return op->emitOpError() << "requires one region";
942 return success();
945 LogicalResult OpTrait::impl::verifyNRegions(Operation *op,
946 unsigned numRegions) {
947 if (op->getNumRegions() != numRegions)
948 return op->emitOpError() << "expected " << numRegions << " regions";
949 return success();
952 LogicalResult OpTrait::impl::verifyAtLeastNRegions(Operation *op,
953 unsigned numRegions) {
954 if (op->getNumRegions() < numRegions)
955 return op->emitOpError() << "expected " << numRegions << " or more regions";
956 return success();
959 LogicalResult OpTrait::impl::verifyZeroResults(Operation *op) {
960 if (op->getNumResults() != 0)
961 return op->emitOpError() << "requires zero results";
962 return success();
965 LogicalResult OpTrait::impl::verifyOneResult(Operation *op) {
966 if (op->getNumResults() != 1)
967 return op->emitOpError() << "requires one result";
968 return success();
971 LogicalResult OpTrait::impl::verifyNResults(Operation *op,
972 unsigned numOperands) {
973 if (op->getNumResults() != numOperands)
974 return op->emitOpError() << "expected " << numOperands << " results";
975 return success();
978 LogicalResult OpTrait::impl::verifyAtLeastNResults(Operation *op,
979 unsigned numOperands) {
980 if (op->getNumResults() < numOperands)
981 return op->emitOpError()
982 << "expected " << numOperands << " or more results";
983 return success();
986 LogicalResult OpTrait::impl::verifySameOperandsShape(Operation *op) {
987 if (failed(verifyAtLeastNOperands(op, 1)))
988 return failure();
990 if (failed(verifyCompatibleShapes(op->getOperandTypes())))
991 return op->emitOpError() << "requires the same shape for all operands";
993 return success();
996 LogicalResult OpTrait::impl::verifySameOperandsAndResultShape(Operation *op) {
997 if (failed(verifyAtLeastNOperands(op, 1)) ||
998 failed(verifyAtLeastNResults(op, 1)))
999 return failure();
1001 SmallVector<Type, 8> types(op->getOperandTypes());
1002 types.append(llvm::to_vector<4>(op->getResultTypes()));
1004 if (failed(verifyCompatibleShapes(types)))
1005 return op->emitOpError()
1006 << "requires the same shape for all operands and results";
1008 return success();
1011 LogicalResult OpTrait::impl::verifySameOperandsElementType(Operation *op) {
1012 if (failed(verifyAtLeastNOperands(op, 1)))
1013 return failure();
1014 auto elementType = getElementTypeOrSelf(op->getOperand(0));
1016 for (auto operand : llvm::drop_begin(op->getOperands(), 1)) {
1017 if (getElementTypeOrSelf(operand) != elementType)
1018 return op->emitOpError("requires the same element type for all operands");
1021 return success();
1024 LogicalResult
1025 OpTrait::impl::verifySameOperandsAndResultElementType(Operation *op) {
1026 if (failed(verifyAtLeastNOperands(op, 1)) ||
1027 failed(verifyAtLeastNResults(op, 1)))
1028 return failure();
1030 auto elementType = getElementTypeOrSelf(op->getResult(0));
1032 // Verify result element type matches first result's element type.
1033 for (auto result : llvm::drop_begin(op->getResults(), 1)) {
1034 if (getElementTypeOrSelf(result) != elementType)
1035 return op->emitOpError(
1036 "requires the same element type for all operands and results");
1039 // Verify operand's element type matches first result's element type.
1040 for (auto operand : op->getOperands()) {
1041 if (getElementTypeOrSelf(operand) != elementType)
1042 return op->emitOpError(
1043 "requires the same element type for all operands and results");
1046 return success();
1049 LogicalResult OpTrait::impl::verifySameOperandsAndResultType(Operation *op) {
1050 if (failed(verifyAtLeastNOperands(op, 1)) ||
1051 failed(verifyAtLeastNResults(op, 1)))
1052 return failure();
1054 auto type = op->getResult(0).getType();
1055 auto elementType = getElementTypeOrSelf(type);
1056 Attribute encoding = nullptr;
1057 if (auto rankedType = dyn_cast<RankedTensorType>(type))
1058 encoding = rankedType.getEncoding();
1059 for (auto resultType : llvm::drop_begin(op->getResultTypes())) {
1060 if (getElementTypeOrSelf(resultType) != elementType ||
1061 failed(verifyCompatibleShape(resultType, type)))
1062 return op->emitOpError()
1063 << "requires the same type for all operands and results";
1064 if (encoding)
1065 if (auto rankedType = dyn_cast<RankedTensorType>(resultType);
1066 encoding != rankedType.getEncoding())
1067 return op->emitOpError()
1068 << "requires the same encoding for all operands and results";
1070 for (auto opType : op->getOperandTypes()) {
1071 if (getElementTypeOrSelf(opType) != elementType ||
1072 failed(verifyCompatibleShape(opType, type)))
1073 return op->emitOpError()
1074 << "requires the same type for all operands and results";
1075 if (encoding)
1076 if (auto rankedType = dyn_cast<RankedTensorType>(opType);
1077 encoding != rankedType.getEncoding())
1078 return op->emitOpError()
1079 << "requires the same encoding for all operands and results";
1081 return success();
1084 LogicalResult OpTrait::impl::verifySameOperandsAndResultRank(Operation *op) {
1085 if (failed(verifyAtLeastNOperands(op, 1)))
1086 return failure();
1088 // delegate function that returns true if type is a shaped type with known
1089 // rank
1090 auto hasRank = [](const Type type) {
1091 if (auto shaped_type = dyn_cast<ShapedType>(type))
1092 return shaped_type.hasRank();
1094 return false;
1097 auto rankedOperandTypes =
1098 llvm::make_filter_range(op->getOperandTypes(), hasRank);
1099 auto rankedResultTypes =
1100 llvm::make_filter_range(op->getResultTypes(), hasRank);
1102 // If all operands and results are unranked, then no further verification.
1103 if (rankedOperandTypes.empty() && rankedResultTypes.empty())
1104 return success();
1106 // delegate function that returns rank of shaped type with known rank
1107 auto getRank = [](const Type type) {
1108 return type.cast<ShapedType>().getRank();
1111 auto rank = !rankedOperandTypes.empty() ? getRank(*rankedOperandTypes.begin())
1112 : getRank(*rankedResultTypes.begin());
1114 for (const auto type : rankedOperandTypes) {
1115 if (rank != getRank(type)) {
1116 return op->emitOpError("operands don't have matching ranks");
1120 for (const auto type : rankedResultTypes) {
1121 if (rank != getRank(type)) {
1122 return op->emitOpError("result type has different rank than operands");
1126 return success();
1129 LogicalResult OpTrait::impl::verifyIsTerminator(Operation *op) {
1130 Block *block = op->getBlock();
1131 // Verify that the operation is at the end of the respective parent block.
1132 if (!block || &block->back() != op)
1133 return op->emitOpError("must be the last operation in the parent block");
1134 return success();
1137 static LogicalResult verifyTerminatorSuccessors(Operation *op) {
1138 auto *parent = op->getParentRegion();
1140 // Verify that the operands lines up with the BB arguments in the successor.
1141 for (Block *succ : op->getSuccessors())
1142 if (succ->getParent() != parent)
1143 return op->emitError("reference to block defined in another region");
1144 return success();
1147 LogicalResult OpTrait::impl::verifyZeroSuccessors(Operation *op) {
1148 if (op->getNumSuccessors() != 0) {
1149 return op->emitOpError("requires 0 successors but found ")
1150 << op->getNumSuccessors();
1152 return success();
1155 LogicalResult OpTrait::impl::verifyOneSuccessor(Operation *op) {
1156 if (op->getNumSuccessors() != 1) {
1157 return op->emitOpError("requires 1 successor but found ")
1158 << op->getNumSuccessors();
1160 return verifyTerminatorSuccessors(op);
1162 LogicalResult OpTrait::impl::verifyNSuccessors(Operation *op,
1163 unsigned numSuccessors) {
1164 if (op->getNumSuccessors() != numSuccessors) {
1165 return op->emitOpError("requires ")
1166 << numSuccessors << " successors but found "
1167 << op->getNumSuccessors();
1169 return verifyTerminatorSuccessors(op);
1171 LogicalResult OpTrait::impl::verifyAtLeastNSuccessors(Operation *op,
1172 unsigned numSuccessors) {
1173 if (op->getNumSuccessors() < numSuccessors) {
1174 return op->emitOpError("requires at least ")
1175 << numSuccessors << " successors but found "
1176 << op->getNumSuccessors();
1178 return verifyTerminatorSuccessors(op);
1181 LogicalResult OpTrait::impl::verifyResultsAreBoolLike(Operation *op) {
1182 for (auto resultType : op->getResultTypes()) {
1183 auto elementType = getTensorOrVectorElementType(resultType);
1184 bool isBoolType = elementType.isInteger(1);
1185 if (!isBoolType)
1186 return op->emitOpError() << "requires a bool result type";
1189 return success();
1192 LogicalResult OpTrait::impl::verifyResultsAreFloatLike(Operation *op) {
1193 for (auto resultType : op->getResultTypes())
1194 if (!llvm::isa<FloatType>(getTensorOrVectorElementType(resultType)))
1195 return op->emitOpError() << "requires a floating point type";
1197 return success();
1200 LogicalResult
1201 OpTrait::impl::verifyResultsAreSignlessIntegerLike(Operation *op) {
1202 for (auto resultType : op->getResultTypes())
1203 if (!getTensorOrVectorElementType(resultType).isSignlessIntOrIndex())
1204 return op->emitOpError() << "requires an integer or index type";
1205 return success();
1208 LogicalResult OpTrait::impl::verifyValueSizeAttr(Operation *op,
1209 StringRef attrName,
1210 StringRef valueGroupName,
1211 size_t expectedCount) {
1212 auto sizeAttr = op->getAttrOfType<DenseI32ArrayAttr>(attrName);
1213 if (!sizeAttr)
1214 return op->emitOpError("requires dense i32 array attribute '")
1215 << attrName << "'";
1217 ArrayRef<int32_t> sizes = sizeAttr.asArrayRef();
1218 if (llvm::any_of(sizes, [](int32_t element) { return element < 0; }))
1219 return op->emitOpError("'")
1220 << attrName << "' attribute cannot have negative elements";
1222 size_t totalCount =
1223 std::accumulate(sizes.begin(), sizes.end(), 0,
1224 [](unsigned all, int32_t one) { return all + one; });
1226 if (totalCount != expectedCount)
1227 return op->emitOpError()
1228 << valueGroupName << " count (" << expectedCount
1229 << ") does not match with the total size (" << totalCount
1230 << ") specified in attribute '" << attrName << "'";
1231 return success();
1234 LogicalResult OpTrait::impl::verifyOperandSizeAttr(Operation *op,
1235 StringRef attrName) {
1236 return verifyValueSizeAttr(op, attrName, "operand", op->getNumOperands());
1239 LogicalResult OpTrait::impl::verifyResultSizeAttr(Operation *op,
1240 StringRef attrName) {
1241 return verifyValueSizeAttr(op, attrName, "result", op->getNumResults());
1244 LogicalResult OpTrait::impl::verifyNoRegionArguments(Operation *op) {
1245 for (Region &region : op->getRegions()) {
1246 if (region.empty())
1247 continue;
1249 if (region.getNumArguments() != 0) {
1250 if (op->getNumRegions() > 1)
1251 return op->emitOpError("region #")
1252 << region.getRegionNumber() << " should have no arguments";
1253 return op->emitOpError("region should have no arguments");
1256 return success();
1259 LogicalResult OpTrait::impl::verifyElementwise(Operation *op) {
1260 auto isMappableType = [](Type type) {
1261 return llvm::isa<VectorType, TensorType>(type);
1263 auto resultMappableTypes = llvm::to_vector<1>(
1264 llvm::make_filter_range(op->getResultTypes(), isMappableType));
1265 auto operandMappableTypes = llvm::to_vector<2>(
1266 llvm::make_filter_range(op->getOperandTypes(), isMappableType));
1268 // If the op only has scalar operand/result types, then we have nothing to
1269 // check.
1270 if (resultMappableTypes.empty() && operandMappableTypes.empty())
1271 return success();
1273 if (!resultMappableTypes.empty() && operandMappableTypes.empty())
1274 return op->emitOpError("if a result is non-scalar, then at least one "
1275 "operand must be non-scalar");
1277 assert(!operandMappableTypes.empty());
1279 if (resultMappableTypes.empty())
1280 return op->emitOpError("if an operand is non-scalar, then there must be at "
1281 "least one non-scalar result");
1283 if (resultMappableTypes.size() != op->getNumResults())
1284 return op->emitOpError(
1285 "if an operand is non-scalar, then all results must be non-scalar");
1287 SmallVector<Type, 4> types = llvm::to_vector<2>(
1288 llvm::concat<Type>(operandMappableTypes, resultMappableTypes));
1289 TypeID expectedBaseTy = types.front().getTypeID();
1290 if (!llvm::all_of(types,
1291 [&](Type t) { return t.getTypeID() == expectedBaseTy; }) ||
1292 failed(verifyCompatibleShapes(types))) {
1293 return op->emitOpError() << "all non-scalar operands/results must have the "
1294 "same shape and base type";
1297 return success();
1300 /// Check for any values used by operations regions attached to the
1301 /// specified "IsIsolatedFromAbove" operation defined outside of it.
1302 LogicalResult OpTrait::impl::verifyIsIsolatedFromAbove(Operation *isolatedOp) {
1303 assert(isolatedOp->hasTrait<OpTrait::IsIsolatedFromAbove>() &&
1304 "Intended to check IsolatedFromAbove ops");
1306 // List of regions to analyze. Each region is processed independently, with
1307 // respect to the common `limit` region, so we can look at them in any order.
1308 // Therefore, use a simple vector and push/pop back the current region.
1309 SmallVector<Region *, 8> pendingRegions;
1310 for (auto &region : isolatedOp->getRegions()) {
1311 pendingRegions.push_back(&region);
1313 // Traverse all operations in the region.
1314 while (!pendingRegions.empty()) {
1315 for (Operation &op : pendingRegions.pop_back_val()->getOps()) {
1316 for (Value operand : op.getOperands()) {
1317 // Check that any value that is used by an operation is defined in the
1318 // same region as either an operation result.
1319 auto *operandRegion = operand.getParentRegion();
1320 if (!operandRegion)
1321 return op.emitError("operation's operand is unlinked");
1322 if (!region.isAncestor(operandRegion)) {
1323 return op.emitOpError("using value defined outside the region")
1324 .attachNote(isolatedOp->getLoc())
1325 << "required by region isolation constraints";
1329 // Schedule any regions in the operation for further checking. Don't
1330 // recurse into other IsolatedFromAbove ops, because they will check
1331 // themselves.
1332 if (op.getNumRegions() &&
1333 !op.hasTrait<OpTrait::IsIsolatedFromAbove>()) {
1334 for (Region &subRegion : op.getRegions())
1335 pendingRegions.push_back(&subRegion);
1341 return success();
1344 bool OpTrait::hasElementwiseMappableTraits(Operation *op) {
1345 return op->hasTrait<Elementwise>() && op->hasTrait<Scalarizable>() &&
1346 op->hasTrait<Vectorizable>() && op->hasTrait<Tensorizable>();
1349 //===----------------------------------------------------------------------===//
1350 // Misc. utils
1351 //===----------------------------------------------------------------------===//
1353 /// Insert an operation, generated by `buildTerminatorOp`, at the end of the
1354 /// region's only block if it does not have a terminator already. If the region
1355 /// is empty, insert a new block first. `buildTerminatorOp` should return the
1356 /// terminator operation to insert.
1357 void impl::ensureRegionTerminator(
1358 Region &region, OpBuilder &builder, Location loc,
1359 function_ref<Operation *(OpBuilder &, Location)> buildTerminatorOp) {
1360 OpBuilder::InsertionGuard guard(builder);
1361 if (region.empty())
1362 builder.createBlock(&region);
1364 Block &block = region.back();
1365 if (!block.empty() && block.back().hasTrait<OpTrait::IsTerminator>())
1366 return;
1368 builder.setInsertionPointToEnd(&block);
1369 builder.insert(buildTerminatorOp(builder, loc));
1372 /// Create a simple OpBuilder and forward to the OpBuilder version of this
1373 /// function.
1374 void impl::ensureRegionTerminator(
1375 Region &region, Builder &builder, Location loc,
1376 function_ref<Operation *(OpBuilder &, Location)> buildTerminatorOp) {
1377 OpBuilder opBuilder(builder.getContext());
1378 ensureRegionTerminator(region, opBuilder, loc, buildTerminatorOp);