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 //===----------------------------------------------------------------------===//
8 
9 #include "mlir/IR/Operation.h"
10 #include "mlir/IR/BlockAndValueMapping.h"
11 #include "mlir/IR/BuiltinTypes.h"
12 #include "mlir/IR/Dialect.h"
13 #include "mlir/IR/OpImplementation.h"
14 #include "mlir/IR/PatternMatch.h"
15 #include "mlir/IR/TypeUtilities.h"
16 #include "mlir/Interfaces/FoldInterfaces.h"
17 #include <numeric>
18 
19 using namespace mlir;
20 
21 OpAsmParser::~OpAsmParser() {}
22 
23 //===----------------------------------------------------------------------===//
24 // OperationName
25 //===----------------------------------------------------------------------===//
26 
27 /// Form the OperationName for an op with the specified string.  This either is
28 /// a reference to an AbstractOperation if one is known, or a uniqued Identifier
29 /// if not.
30 OperationName::OperationName(StringRef name, MLIRContext *context) {
31   if (auto *op = AbstractOperation::lookup(name, context))
32     representation = op;
33   else
34     representation = Identifier::get(name, context);
35 }
36 
37 /// Return the name of the dialect this operation is registered to.
38 StringRef OperationName::getDialect() const {
39   return getStringRef().split('.').first;
40 }
41 
42 /// Return the operation name with dialect name stripped, if it has one.
43 StringRef OperationName::stripDialect() const {
44   auto splitName = getStringRef().split(".");
45   return splitName.second.empty() ? splitName.first : splitName.second;
46 }
47 
48 /// Return the name of this operation. This always succeeds.
49 StringRef OperationName::getStringRef() const {
50   return getIdentifier().strref();
51 }
52 
53 /// Return the name of this operation as an identifier. This always succeeds.
54 Identifier OperationName::getIdentifier() const {
55   if (auto *op = representation.dyn_cast<const AbstractOperation *>())
56     return op->name;
57   return representation.get<Identifier>();
58 }
59 
60 const AbstractOperation *OperationName::getAbstractOperation() const {
61   return representation.dyn_cast<const AbstractOperation *>();
62 }
63 
64 OperationName OperationName::getFromOpaquePointer(const void *pointer) {
65   return OperationName(
66       RepresentationUnion::getFromOpaqueValue(const_cast<void *>(pointer)));
67 }
68 
69 //===----------------------------------------------------------------------===//
70 // Operation
71 //===----------------------------------------------------------------------===//
72 
73 /// Create a new Operation with the specific fields.
74 Operation *Operation::create(Location location, OperationName name,
75                              TypeRange resultTypes, ValueRange operands,
76                              ArrayRef<NamedAttribute> attributes,
77                              BlockRange successors, unsigned numRegions) {
78   return create(location, name, resultTypes, operands,
79                 DictionaryAttr::get(location.getContext(), attributes),
80                 successors, numRegions);
81 }
82 
83 /// Create a new Operation from operation state.
84 Operation *Operation::create(const OperationState &state) {
85   return create(state.location, state.name, state.types, state.operands,
86                 state.attributes.getDictionary(state.getContext()),
87                 state.successors, state.regions);
88 }
89 
90 /// Create a new Operation with the specific fields.
91 Operation *Operation::create(Location location, OperationName name,
92                              TypeRange resultTypes, ValueRange operands,
93                              DictionaryAttr attributes, BlockRange successors,
94                              RegionRange regions) {
95   unsigned numRegions = regions.size();
96   Operation *op = create(location, name, resultTypes, operands, attributes,
97                          successors, numRegions);
98   for (unsigned i = 0; i < numRegions; ++i)
99     if (regions[i])
100       op->getRegion(i).takeBody(*regions[i]);
101   return op;
102 }
103 
104 /// Overload of create that takes an existing DictionaryAttr to avoid
105 /// unnecessarily uniquing a list of attributes.
106 Operation *Operation::create(Location location, OperationName name,
107                              TypeRange resultTypes, ValueRange operands,
108                              DictionaryAttr attributes, BlockRange successors,
109                              unsigned numRegions) {
110   // We only need to allocate additional memory for a subset of results.
111   unsigned numTrailingResults = OpResult::getNumTrailing(resultTypes.size());
112   unsigned numInlineResults = OpResult::getNumInline(resultTypes.size());
113   unsigned numSuccessors = successors.size();
114   unsigned numOperands = operands.size();
115 
116   // If the operation is known to have no operands, don't allocate an operand
117   // storage.
118   bool needsOperandStorage = true;
119   if (operands.empty()) {
120     if (const AbstractOperation *abstractOp = name.getAbstractOperation())
121       needsOperandStorage = !abstractOp->hasTrait<OpTrait::ZeroOperands>();
122   }
123 
124   // Compute the byte size for the operation and the operand storage. This takes
125   // into account the size of the operation, its trailing objects, and its
126   // prefixed objects.
127   size_t byteSize =
128       totalSizeToAlloc<BlockOperand, Region, detail::OperandStorage>(
129           numSuccessors, numRegions, needsOperandStorage ? 1 : 0) +
130       detail::OperandStorage::additionalAllocSize(numOperands);
131   size_t prefixByteSize = llvm::alignTo(
132       Operation::prefixAllocSize(numTrailingResults, numInlineResults),
133       alignof(Operation));
134   char *mallocMem = reinterpret_cast<char *>(malloc(byteSize + prefixByteSize));
135   void *rawMem = mallocMem + prefixByteSize;
136 
137   // Create the new Operation.
138   Operation *op =
139       ::new (rawMem) Operation(location, name, resultTypes, numSuccessors,
140                                numRegions, attributes, needsOperandStorage);
141 
142   assert((numSuccessors == 0 || op->mightHaveTrait<OpTrait::IsTerminator>()) &&
143          "unexpected successors in a non-terminator operation");
144 
145   // Initialize the results.
146   for (unsigned i = 0; i < numInlineResults; ++i)
147     new (op->getInlineResult(i)) detail::InLineOpResult();
148   for (unsigned i = 0; i < numTrailingResults; ++i)
149     new (op->getTrailingResult(i)) detail::TrailingOpResult(i);
150 
151   // Initialize the regions.
152   for (unsigned i = 0; i != numRegions; ++i)
153     new (&op->getRegion(i)) Region(op);
154 
155   // Initialize the operands.
156   if (needsOperandStorage)
157     new (&op->getOperandStorage()) detail::OperandStorage(op, operands);
158 
159   // Initialize the successors.
160   auto blockOperands = op->getBlockOperands();
161   for (unsigned i = 0; i != numSuccessors; ++i)
162     new (&blockOperands[i]) BlockOperand(op, successors[i]);
163 
164   return op;
165 }
166 
167 Operation::Operation(Location location, OperationName name,
168                      TypeRange resultTypes, unsigned numSuccessors,
169                      unsigned numRegions, DictionaryAttr attributes,
170                      bool hasOperandStorage)
171     : location(location), numSuccs(numSuccessors), numRegions(numRegions),
172       hasOperandStorage(hasOperandStorage), hasSingleResult(false), name(name),
173       attrs(attributes) {
174   assert(attributes && "unexpected null attribute dictionary");
175   assert(llvm::all_of(resultTypes, [](Type t) { return t; }) &&
176          "unexpected null result type");
177   if (!resultTypes.empty()) {
178     // If there is a single result it is stored in-place, otherwise use a tuple.
179     hasSingleResult = resultTypes.size() == 1;
180     if (hasSingleResult)
181       resultType = resultTypes.front();
182     else
183       resultType = TupleType::get(location->getContext(), resultTypes);
184   }
185 }
186 
187 // Operations are deleted through the destroy() member because they are
188 // allocated via malloc.
189 Operation::~Operation() {
190   assert(block == nullptr && "operation destroyed but still in a block");
191 
192   // Explicitly run the destructors for the operands.
193   if (hasOperandStorage)
194     getOperandStorage().~OperandStorage();
195 
196   // Explicitly run the destructors for the successors.
197   for (auto &successor : getBlockOperands())
198     successor.~BlockOperand();
199 
200   // Explicitly destroy the regions.
201   for (auto &region : getRegions())
202     region.~Region();
203 }
204 
205 /// Destroy this operation or one of its subclasses.
206 void Operation::destroy() {
207   // Operations may have additional prefixed allocation, which needs to be
208   // accounted for here when computing the address to free.
209   char *rawMem = reinterpret_cast<char *>(this) -
210                  llvm::alignTo(prefixAllocSize(), alignof(Operation));
211   this->~Operation();
212   free(rawMem);
213 }
214 
215 /// Return the context this operation is associated with.
216 MLIRContext *Operation::getContext() { return location->getContext(); }
217 
218 /// Return the dialect this operation is associated with, or nullptr if the
219 /// associated dialect is not registered.
220 Dialect *Operation::getDialect() {
221   if (auto *abstractOp = getAbstractOperation())
222     return &abstractOp->dialect;
223 
224   // If this operation hasn't been registered or doesn't have abstract
225   // operation, try looking up the dialect name in the context.
226   return getContext()->getLoadedDialect(getName().getDialect());
227 }
228 
229 Region *Operation::getParentRegion() {
230   return block ? block->getParent() : nullptr;
231 }
232 
233 Operation *Operation::getParentOp() {
234   return block ? block->getParentOp() : nullptr;
235 }
236 
237 /// Return true if this operation is a proper ancestor of the `other`
238 /// operation.
239 bool Operation::isProperAncestor(Operation *other) {
240   while ((other = other->getParentOp()))
241     if (this == other)
242       return true;
243   return false;
244 }
245 
246 /// Replace any uses of 'from' with 'to' within this operation.
247 void Operation::replaceUsesOfWith(Value from, Value to) {
248   if (from == to)
249     return;
250   for (auto &operand : getOpOperands())
251     if (operand.get() == from)
252       operand.set(to);
253 }
254 
255 /// Replace the current operands of this operation with the ones provided in
256 /// 'operands'.
257 void Operation::setOperands(ValueRange operands) {
258   if (LLVM_LIKELY(hasOperandStorage))
259     return getOperandStorage().setOperands(this, operands);
260   assert(operands.empty() && "setting operands without an operand storage");
261 }
262 
263 /// Replace the operands beginning at 'start' and ending at 'start' + 'length'
264 /// with the ones provided in 'operands'. 'operands' may be smaller or larger
265 /// than the range pointed to by 'start'+'length'.
266 void Operation::setOperands(unsigned start, unsigned length,
267                             ValueRange operands) {
268   assert((start + length) <= getNumOperands() &&
269          "invalid operand range specified");
270   if (LLVM_LIKELY(hasOperandStorage))
271     return getOperandStorage().setOperands(this, start, length, operands);
272   assert(operands.empty() && "setting operands without an operand storage");
273 }
274 
275 /// Insert the given operands into the operand list at the given 'index'.
276 void Operation::insertOperands(unsigned index, ValueRange operands) {
277   if (LLVM_LIKELY(hasOperandStorage))
278     return setOperands(index, /*length=*/0, operands);
279   assert(operands.empty() && "inserting operands without an operand storage");
280 }
281 
282 //===----------------------------------------------------------------------===//
283 // Diagnostics
284 //===----------------------------------------------------------------------===//
285 
286 /// Emit an error about fatal conditions with this operation, reporting up to
287 /// any diagnostic handlers that may be listening.
288 InFlightDiagnostic Operation::emitError(const Twine &message) {
289   InFlightDiagnostic diag = mlir::emitError(getLoc(), message);
290   if (getContext()->shouldPrintOpOnDiagnostic()) {
291     // Print out the operation explicitly here so that we can print the generic
292     // form.
293     // TODO: It would be nice if we could instead provide the
294     // specific printing flags when adding the operation as an argument to the
295     // diagnostic.
296     std::string printedOp;
297     {
298       llvm::raw_string_ostream os(printedOp);
299       print(os, OpPrintingFlags().printGenericOpForm().useLocalScope());
300     }
301     diag.attachNote(getLoc()) << "see current operation: " << printedOp;
302   }
303   return diag;
304 }
305 
306 /// Emit a warning about this operation, reporting up to any diagnostic
307 /// handlers that may be listening.
308 InFlightDiagnostic Operation::emitWarning(const Twine &message) {
309   InFlightDiagnostic diag = mlir::emitWarning(getLoc(), message);
310   if (getContext()->shouldPrintOpOnDiagnostic())
311     diag.attachNote(getLoc()) << "see current operation: " << *this;
312   return diag;
313 }
314 
315 /// Emit a remark about this operation, reporting up to any diagnostic
316 /// handlers that may be listening.
317 InFlightDiagnostic Operation::emitRemark(const Twine &message) {
318   InFlightDiagnostic diag = mlir::emitRemark(getLoc(), message);
319   if (getContext()->shouldPrintOpOnDiagnostic())
320     diag.attachNote(getLoc()) << "see current operation: " << *this;
321   return diag;
322 }
323 
324 //===----------------------------------------------------------------------===//
325 // Operation Ordering
326 //===----------------------------------------------------------------------===//
327 
328 constexpr unsigned Operation::kInvalidOrderIdx;
329 constexpr unsigned Operation::kOrderStride;
330 
331 /// Given an operation 'other' that is within the same parent block, return
332 /// whether the current operation is before 'other' in the operation list
333 /// of the parent block.
334 /// Note: This function has an average complexity of O(1), but worst case may
335 /// take O(N) where N is the number of operations within the parent block.
336 bool Operation::isBeforeInBlock(Operation *other) {
337   assert(block && "Operations without parent blocks have no order.");
338   assert(other && other->block == block &&
339          "Expected other operation to have the same parent block.");
340   // If the order of the block is already invalid, directly recompute the
341   // parent.
342   if (!block->isOpOrderValid()) {
343     block->recomputeOpOrder();
344   } else {
345     // Update the order either operation if necessary.
346     updateOrderIfNecessary();
347     other->updateOrderIfNecessary();
348   }
349 
350   return orderIndex < other->orderIndex;
351 }
352 
353 /// Update the order index of this operation of this operation if necessary,
354 /// potentially recomputing the order of the parent block.
355 void Operation::updateOrderIfNecessary() {
356   assert(block && "expected valid parent");
357 
358   // If the order is valid for this operation there is nothing to do.
359   if (hasValidOrder())
360     return;
361   Operation *blockFront = &block->front();
362   Operation *blockBack = &block->back();
363 
364   // This method is expected to only be invoked on blocks with more than one
365   // operation.
366   assert(blockFront != blockBack && "expected more than one operation");
367 
368   // If the operation is at the end of the block.
369   if (this == blockBack) {
370     Operation *prevNode = getPrevNode();
371     if (!prevNode->hasValidOrder())
372       return block->recomputeOpOrder();
373 
374     // Add the stride to the previous operation.
375     orderIndex = prevNode->orderIndex + kOrderStride;
376     return;
377   }
378 
379   // If this is the first operation try to use the next operation to compute the
380   // ordering.
381   if (this == blockFront) {
382     Operation *nextNode = getNextNode();
383     if (!nextNode->hasValidOrder())
384       return block->recomputeOpOrder();
385     // There is no order to give this operation.
386     if (nextNode->orderIndex == 0)
387       return block->recomputeOpOrder();
388 
389     // If we can't use the stride, just take the middle value left. This is safe
390     // because we know there is at least one valid index to assign to.
391     if (nextNode->orderIndex <= kOrderStride)
392       orderIndex = (nextNode->orderIndex / 2);
393     else
394       orderIndex = kOrderStride;
395     return;
396   }
397 
398   // Otherwise, this operation is between two others. Place this operation in
399   // the middle of the previous and next if possible.
400   Operation *prevNode = getPrevNode(), *nextNode = getNextNode();
401   if (!prevNode->hasValidOrder() || !nextNode->hasValidOrder())
402     return block->recomputeOpOrder();
403   unsigned prevOrder = prevNode->orderIndex, nextOrder = nextNode->orderIndex;
404 
405   // Check to see if there is a valid order between the two.
406   if (prevOrder + 1 == nextOrder)
407     return block->recomputeOpOrder();
408   orderIndex = prevOrder + ((nextOrder - prevOrder) / 2);
409 }
410 
411 //===----------------------------------------------------------------------===//
412 // ilist_traits for Operation
413 //===----------------------------------------------------------------------===//
414 
415 auto llvm::ilist_detail::SpecificNodeAccess<
416     typename llvm::ilist_detail::compute_node_options<
417         ::mlir::Operation>::type>::getNodePtr(pointer N) -> node_type * {
418   return NodeAccess::getNodePtr<OptionsT>(N);
419 }
420 
421 auto llvm::ilist_detail::SpecificNodeAccess<
422     typename llvm::ilist_detail::compute_node_options<
423         ::mlir::Operation>::type>::getNodePtr(const_pointer N)
424     -> const node_type * {
425   return NodeAccess::getNodePtr<OptionsT>(N);
426 }
427 
428 auto llvm::ilist_detail::SpecificNodeAccess<
429     typename llvm::ilist_detail::compute_node_options<
430         ::mlir::Operation>::type>::getValuePtr(node_type *N) -> pointer {
431   return NodeAccess::getValuePtr<OptionsT>(N);
432 }
433 
434 auto llvm::ilist_detail::SpecificNodeAccess<
435     typename llvm::ilist_detail::compute_node_options<
436         ::mlir::Operation>::type>::getValuePtr(const node_type *N)
437     -> const_pointer {
438   return NodeAccess::getValuePtr<OptionsT>(N);
439 }
440 
441 void llvm::ilist_traits<::mlir::Operation>::deleteNode(Operation *op) {
442   op->destroy();
443 }
444 
445 Block *llvm::ilist_traits<::mlir::Operation>::getContainingBlock() {
446   size_t Offset(size_t(&((Block *)nullptr->*Block::getSublistAccess(nullptr))));
447   iplist<Operation> *Anchor(static_cast<iplist<Operation> *>(this));
448   return reinterpret_cast<Block *>(reinterpret_cast<char *>(Anchor) - Offset);
449 }
450 
451 /// This is a trait method invoked when an operation is added to a block.  We
452 /// keep the block pointer up to date.
453 void llvm::ilist_traits<::mlir::Operation>::addNodeToList(Operation *op) {
454   assert(!op->getBlock() && "already in an operation block!");
455   op->block = getContainingBlock();
456 
457   // Invalidate the order on the operation.
458   op->orderIndex = Operation::kInvalidOrderIdx;
459 }
460 
461 /// This is a trait method invoked when an operation is removed from a block.
462 /// We keep the block pointer up to date.
463 void llvm::ilist_traits<::mlir::Operation>::removeNodeFromList(Operation *op) {
464   assert(op->block && "not already in an operation block!");
465   op->block = nullptr;
466 }
467 
468 /// This is a trait method invoked when an operation is moved from one block
469 /// to another.  We keep the block pointer up to date.
470 void llvm::ilist_traits<::mlir::Operation>::transferNodesFromList(
471     ilist_traits<Operation> &otherList, op_iterator first, op_iterator last) {
472   Block *curParent = getContainingBlock();
473 
474   // Invalidate the ordering of the parent block.
475   curParent->invalidateOpOrder();
476 
477   // If we are transferring operations within the same block, the block
478   // pointer doesn't need to be updated.
479   if (curParent == otherList.getContainingBlock())
480     return;
481 
482   // Update the 'block' member of each operation.
483   for (; first != last; ++first)
484     first->block = curParent;
485 }
486 
487 /// Remove this operation (and its descendants) from its Block and delete
488 /// all of them.
489 void Operation::erase() {
490   if (auto *parent = getBlock())
491     parent->getOperations().erase(this);
492   else
493     destroy();
494 }
495 
496 /// Remove the operation from its parent block, but don't delete it.
497 void Operation::remove() {
498   if (Block *parent = getBlock())
499     parent->getOperations().remove(this);
500 }
501 
502 /// Unlink this operation from its current block and insert it right before
503 /// `existingOp` which may be in the same or another block in the same
504 /// function.
505 void Operation::moveBefore(Operation *existingOp) {
506   moveBefore(existingOp->getBlock(), existingOp->getIterator());
507 }
508 
509 /// Unlink this operation from its current basic block and insert it right
510 /// before `iterator` in the specified basic block.
511 void Operation::moveBefore(Block *block,
512                            llvm::iplist<Operation>::iterator iterator) {
513   block->getOperations().splice(iterator, getBlock()->getOperations(),
514                                 getIterator());
515 }
516 
517 /// Unlink this operation from its current block and insert it right after
518 /// `existingOp` which may be in the same or another block in the same function.
519 void Operation::moveAfter(Operation *existingOp) {
520   moveAfter(existingOp->getBlock(), existingOp->getIterator());
521 }
522 
523 /// Unlink this operation from its current block and insert it right after
524 /// `iterator` in the specified block.
525 void Operation::moveAfter(Block *block,
526                           llvm::iplist<Operation>::iterator iterator) {
527   assert(iterator != block->end() && "cannot move after end of block");
528   moveBefore(&*std::next(iterator));
529 }
530 
531 /// This drops all operand uses from this operation, which is an essential
532 /// step in breaking cyclic dependences between references when they are to
533 /// be deleted.
534 void Operation::dropAllReferences() {
535   for (auto &op : getOpOperands())
536     op.drop();
537 
538   for (auto &region : getRegions())
539     region.dropAllReferences();
540 
541   for (auto &dest : getBlockOperands())
542     dest.drop();
543 }
544 
545 /// This drops all uses of any values defined by this operation or its nested
546 /// regions, wherever they are located.
547 void Operation::dropAllDefinedValueUses() {
548   dropAllUses();
549 
550   for (auto &region : getRegions())
551     for (auto &block : region)
552       block.dropAllDefinedValueUses();
553 }
554 
555 /// Return the number of results held by this operation.
556 unsigned Operation::getNumResults() {
557   if (!resultType)
558     return 0;
559   return hasSingleResult ? 1 : resultType.cast<TupleType>().size();
560 }
561 
562 auto Operation::getResultTypes() -> result_type_range {
563   if (!resultType)
564     return llvm::None;
565   if (hasSingleResult)
566     return resultType;
567   return resultType.cast<TupleType>().getTypes();
568 }
569 
570 void Operation::setSuccessor(Block *block, unsigned index) {
571   assert(index < getNumSuccessors());
572   getBlockOperands()[index].set(block);
573 }
574 
575 /// Attempt to fold this operation using the Op's registered foldHook.
576 LogicalResult Operation::fold(ArrayRef<Attribute> operands,
577                               SmallVectorImpl<OpFoldResult> &results) {
578   // If we have a registered operation definition matching this one, use it to
579   // try to constant fold the operation.
580   auto *abstractOp = getAbstractOperation();
581   if (abstractOp && succeeded(abstractOp->foldHook(this, operands, results)))
582     return success();
583 
584   // Otherwise, fall back on the dialect hook to handle it.
585   Dialect *dialect = getDialect();
586   if (!dialect)
587     return failure();
588 
589   auto *interface = dialect->getRegisteredInterface<DialectFoldInterface>();
590   if (!interface)
591     return failure();
592 
593   return interface->fold(this, operands, results);
594 }
595 
596 /// Emit an error with the op name prefixed, like "'dim' op " which is
597 /// convenient for verifiers.
598 InFlightDiagnostic Operation::emitOpError(const Twine &message) {
599   return emitError() << "'" << getName() << "' op " << message;
600 }
601 
602 //===----------------------------------------------------------------------===//
603 // Operation Cloning
604 //===----------------------------------------------------------------------===//
605 
606 /// Create a deep copy of this operation but keep the operation regions empty.
607 /// Operands are remapped using `mapper` (if present), and `mapper` is updated
608 /// to contain the results.
609 Operation *Operation::cloneWithoutRegions(BlockAndValueMapping &mapper) {
610   SmallVector<Value, 8> operands;
611   SmallVector<Block *, 2> successors;
612 
613   // Remap the operands.
614   operands.reserve(getNumOperands());
615   for (auto opValue : getOperands())
616     operands.push_back(mapper.lookupOrDefault(opValue));
617 
618   // Remap the successors.
619   successors.reserve(getNumSuccessors());
620   for (Block *successor : getSuccessors())
621     successors.push_back(mapper.lookupOrDefault(successor));
622 
623   // Create the new operation.
624   auto *newOp = create(getLoc(), getName(), getResultTypes(), operands, attrs,
625                        successors, getNumRegions());
626 
627   // Remember the mapping of any results.
628   for (unsigned i = 0, e = getNumResults(); i != e; ++i)
629     mapper.map(getResult(i), newOp->getResult(i));
630 
631   return newOp;
632 }
633 
634 Operation *Operation::cloneWithoutRegions() {
635   BlockAndValueMapping mapper;
636   return cloneWithoutRegions(mapper);
637 }
638 
639 /// Create a deep copy of this operation, remapping any operands that use
640 /// values outside of the operation using the map that is provided (leaving
641 /// them alone if no entry is present).  Replaces references to cloned
642 /// sub-operations to the corresponding operation that is copied, and adds
643 /// those mappings to the map.
644 Operation *Operation::clone(BlockAndValueMapping &mapper) {
645   auto *newOp = cloneWithoutRegions(mapper);
646 
647   // Clone the regions.
648   for (unsigned i = 0; i != numRegions; ++i)
649     getRegion(i).cloneInto(&newOp->getRegion(i), mapper);
650 
651   return newOp;
652 }
653 
654 Operation *Operation::clone() {
655   BlockAndValueMapping mapper;
656   return clone(mapper);
657 }
658 
659 //===----------------------------------------------------------------------===//
660 // OpState trait class.
661 //===----------------------------------------------------------------------===//
662 
663 // The fallback for the parser is to reject the custom assembly form.
664 ParseResult OpState::parse(OpAsmParser &parser, OperationState &result) {
665   return parser.emitError(parser.getNameLoc(), "has no custom assembly form");
666 }
667 
668 // The fallback for the printer is to print in the generic assembly form.
669 void OpState::print(Operation *op, OpAsmPrinter &p) { p.printGenericOp(op); }
670 
671 /// Emit an error about fatal conditions with this operation, reporting up to
672 /// any diagnostic handlers that may be listening.
673 InFlightDiagnostic OpState::emitError(const Twine &message) {
674   return getOperation()->emitError(message);
675 }
676 
677 /// Emit an error with the op name prefixed, like "'dim' op " which is
678 /// convenient for verifiers.
679 InFlightDiagnostic OpState::emitOpError(const Twine &message) {
680   return getOperation()->emitOpError(message);
681 }
682 
683 /// Emit a warning about this operation, reporting up to any diagnostic
684 /// handlers that may be listening.
685 InFlightDiagnostic OpState::emitWarning(const Twine &message) {
686   return getOperation()->emitWarning(message);
687 }
688 
689 /// Emit a remark about this operation, reporting up to any diagnostic
690 /// handlers that may be listening.
691 InFlightDiagnostic OpState::emitRemark(const Twine &message) {
692   return getOperation()->emitRemark(message);
693 }
694 
695 //===----------------------------------------------------------------------===//
696 // Op Trait implementations
697 //===----------------------------------------------------------------------===//
698 
699 OpFoldResult OpTrait::impl::foldIdempotent(Operation *op) {
700   auto *argumentOp = op->getOperand(0).getDefiningOp();
701   if (argumentOp && op->getName() == argumentOp->getName()) {
702     // Replace the outer operation output with the inner operation.
703     return op->getOperand(0);
704   }
705 
706   return {};
707 }
708 
709 OpFoldResult OpTrait::impl::foldInvolution(Operation *op) {
710   auto *argumentOp = op->getOperand(0).getDefiningOp();
711   if (argumentOp && op->getName() == argumentOp->getName()) {
712     // Replace the outer involutions output with inner's input.
713     return argumentOp->getOperand(0);
714   }
715 
716   return {};
717 }
718 
719 LogicalResult OpTrait::impl::verifyZeroOperands(Operation *op) {
720   if (op->getNumOperands() != 0)
721     return op->emitOpError() << "requires zero operands";
722   return success();
723 }
724 
725 LogicalResult OpTrait::impl::verifyOneOperand(Operation *op) {
726   if (op->getNumOperands() != 1)
727     return op->emitOpError() << "requires a single operand";
728   return success();
729 }
730 
731 LogicalResult OpTrait::impl::verifyNOperands(Operation *op,
732                                              unsigned numOperands) {
733   if (op->getNumOperands() != numOperands) {
734     return op->emitOpError() << "expected " << numOperands
735                              << " operands, but found " << op->getNumOperands();
736   }
737   return success();
738 }
739 
740 LogicalResult OpTrait::impl::verifyAtLeastNOperands(Operation *op,
741                                                     unsigned numOperands) {
742   if (op->getNumOperands() < numOperands)
743     return op->emitOpError()
744            << "expected " << numOperands << " or more operands";
745   return success();
746 }
747 
748 /// If this is a vector type, or a tensor type, return the scalar element type
749 /// that it is built around, otherwise return the type unmodified.
750 static Type getTensorOrVectorElementType(Type type) {
751   if (auto vec = type.dyn_cast<VectorType>())
752     return vec.getElementType();
753 
754   // Look through tensor<vector<...>> to find the underlying element type.
755   if (auto tensor = type.dyn_cast<TensorType>())
756     return getTensorOrVectorElementType(tensor.getElementType());
757   return type;
758 }
759 
760 LogicalResult OpTrait::impl::verifyIsIdempotent(Operation *op) {
761   // FIXME: Add back check for no side effects on operation.
762   // Currently adding it would cause the shared library build
763   // to fail since there would be a dependency of IR on SideEffectInterfaces
764   // which is cyclical.
765   return success();
766 }
767 
768 LogicalResult OpTrait::impl::verifyIsInvolution(Operation *op) {
769   // FIXME: Add back check for no side effects on operation.
770   // Currently adding it would cause the shared library build
771   // to fail since there would be a dependency of IR on SideEffectInterfaces
772   // which is cyclical.
773   return success();
774 }
775 
776 LogicalResult
777 OpTrait::impl::verifyOperandsAreSignlessIntegerLike(Operation *op) {
778   for (auto opType : op->getOperandTypes()) {
779     auto type = getTensorOrVectorElementType(opType);
780     if (!type.isSignlessIntOrIndex())
781       return op->emitOpError() << "requires an integer or index type";
782   }
783   return success();
784 }
785 
786 LogicalResult OpTrait::impl::verifyOperandsAreFloatLike(Operation *op) {
787   for (auto opType : op->getOperandTypes()) {
788     auto type = getTensorOrVectorElementType(opType);
789     if (!type.isa<FloatType>())
790       return op->emitOpError("requires a float type");
791   }
792   return success();
793 }
794 
795 LogicalResult OpTrait::impl::verifySameTypeOperands(Operation *op) {
796   // Zero or one operand always have the "same" type.
797   unsigned nOperands = op->getNumOperands();
798   if (nOperands < 2)
799     return success();
800 
801   auto type = op->getOperand(0).getType();
802   for (auto opType : llvm::drop_begin(op->getOperandTypes(), 1))
803     if (opType != type)
804       return op->emitOpError() << "requires all operands to have the same type";
805   return success();
806 }
807 
808 LogicalResult OpTrait::impl::verifyZeroRegion(Operation *op) {
809   if (op->getNumRegions() != 0)
810     return op->emitOpError() << "requires zero regions";
811   return success();
812 }
813 
814 LogicalResult OpTrait::impl::verifyOneRegion(Operation *op) {
815   if (op->getNumRegions() != 1)
816     return op->emitOpError() << "requires one region";
817   return success();
818 }
819 
820 LogicalResult OpTrait::impl::verifyNRegions(Operation *op,
821                                             unsigned numRegions) {
822   if (op->getNumRegions() != numRegions)
823     return op->emitOpError() << "expected " << numRegions << " regions";
824   return success();
825 }
826 
827 LogicalResult OpTrait::impl::verifyAtLeastNRegions(Operation *op,
828                                                    unsigned numRegions) {
829   if (op->getNumRegions() < numRegions)
830     return op->emitOpError() << "expected " << numRegions << " or more regions";
831   return success();
832 }
833 
834 LogicalResult OpTrait::impl::verifyZeroResult(Operation *op) {
835   if (op->getNumResults() != 0)
836     return op->emitOpError() << "requires zero results";
837   return success();
838 }
839 
840 LogicalResult OpTrait::impl::verifyOneResult(Operation *op) {
841   if (op->getNumResults() != 1)
842     return op->emitOpError() << "requires one result";
843   return success();
844 }
845 
846 LogicalResult OpTrait::impl::verifyNResults(Operation *op,
847                                             unsigned numOperands) {
848   if (op->getNumResults() != numOperands)
849     return op->emitOpError() << "expected " << numOperands << " results";
850   return success();
851 }
852 
853 LogicalResult OpTrait::impl::verifyAtLeastNResults(Operation *op,
854                                                    unsigned numOperands) {
855   if (op->getNumResults() < numOperands)
856     return op->emitOpError()
857            << "expected " << numOperands << " or more results";
858   return success();
859 }
860 
861 LogicalResult OpTrait::impl::verifySameOperandsShape(Operation *op) {
862   if (failed(verifyAtLeastNOperands(op, 1)))
863     return failure();
864 
865   auto type = op->getOperand(0).getType();
866   for (auto opType : llvm::drop_begin(op->getOperandTypes(), 1)) {
867     if (failed(verifyCompatibleShape(opType, type)))
868       return op->emitOpError() << "requires the same shape for all operands";
869   }
870   return success();
871 }
872 
873 LogicalResult OpTrait::impl::verifySameOperandsAndResultShape(Operation *op) {
874   if (failed(verifyAtLeastNOperands(op, 1)) ||
875       failed(verifyAtLeastNResults(op, 1)))
876     return failure();
877 
878   auto type = op->getOperand(0).getType();
879   for (auto resultType : op->getResultTypes()) {
880     if (failed(verifyCompatibleShape(resultType, type)))
881       return op->emitOpError()
882              << "requires the same shape for all operands and results";
883   }
884   for (auto opType : llvm::drop_begin(op->getOperandTypes(), 1)) {
885     if (failed(verifyCompatibleShape(opType, type)))
886       return op->emitOpError()
887              << "requires the same shape for all operands and results";
888   }
889   return success();
890 }
891 
892 LogicalResult OpTrait::impl::verifySameOperandsElementType(Operation *op) {
893   if (failed(verifyAtLeastNOperands(op, 1)))
894     return failure();
895   auto elementType = getElementTypeOrSelf(op->getOperand(0));
896 
897   for (auto operand : llvm::drop_begin(op->getOperands(), 1)) {
898     if (getElementTypeOrSelf(operand) != elementType)
899       return op->emitOpError("requires the same element type for all operands");
900   }
901 
902   return success();
903 }
904 
905 LogicalResult
906 OpTrait::impl::verifySameOperandsAndResultElementType(Operation *op) {
907   if (failed(verifyAtLeastNOperands(op, 1)) ||
908       failed(verifyAtLeastNResults(op, 1)))
909     return failure();
910 
911   auto elementType = getElementTypeOrSelf(op->getResult(0));
912 
913   // Verify result element type matches first result's element type.
914   for (auto result : llvm::drop_begin(op->getResults(), 1)) {
915     if (getElementTypeOrSelf(result) != elementType)
916       return op->emitOpError(
917           "requires the same element type for all operands and results");
918   }
919 
920   // Verify operand's element type matches first result's element type.
921   for (auto operand : op->getOperands()) {
922     if (getElementTypeOrSelf(operand) != elementType)
923       return op->emitOpError(
924           "requires the same element type for all operands and results");
925   }
926 
927   return success();
928 }
929 
930 LogicalResult OpTrait::impl::verifySameOperandsAndResultType(Operation *op) {
931   if (failed(verifyAtLeastNOperands(op, 1)) ||
932       failed(verifyAtLeastNResults(op, 1)))
933     return failure();
934 
935   auto type = op->getResult(0).getType();
936   auto elementType = getElementTypeOrSelf(type);
937   for (auto resultType : op->getResultTypes().drop_front(1)) {
938     if (getElementTypeOrSelf(resultType) != elementType ||
939         failed(verifyCompatibleShape(resultType, type)))
940       return op->emitOpError()
941              << "requires the same type for all operands and results";
942   }
943   for (auto opType : op->getOperandTypes()) {
944     if (getElementTypeOrSelf(opType) != elementType ||
945         failed(verifyCompatibleShape(opType, type)))
946       return op->emitOpError()
947              << "requires the same type for all operands and results";
948   }
949   return success();
950 }
951 
952 LogicalResult OpTrait::impl::verifyIsTerminator(Operation *op) {
953   Block *block = op->getBlock();
954   // Verify that the operation is at the end of the respective parent block.
955   if (!block || &block->back() != op)
956     return op->emitOpError("must be the last operation in the parent block");
957   return success();
958 }
959 
960 static LogicalResult verifyTerminatorSuccessors(Operation *op) {
961   auto *parent = op->getParentRegion();
962 
963   // Verify that the operands lines up with the BB arguments in the successor.
964   for (Block *succ : op->getSuccessors())
965     if (succ->getParent() != parent)
966       return op->emitError("reference to block defined in another region");
967   return success();
968 }
969 
970 LogicalResult OpTrait::impl::verifyZeroSuccessor(Operation *op) {
971   if (op->getNumSuccessors() != 0) {
972     return op->emitOpError("requires 0 successors but found ")
973            << op->getNumSuccessors();
974   }
975   return success();
976 }
977 
978 LogicalResult OpTrait::impl::verifyOneSuccessor(Operation *op) {
979   if (op->getNumSuccessors() != 1) {
980     return op->emitOpError("requires 1 successor but found ")
981            << op->getNumSuccessors();
982   }
983   return verifyTerminatorSuccessors(op);
984 }
985 LogicalResult OpTrait::impl::verifyNSuccessors(Operation *op,
986                                                unsigned numSuccessors) {
987   if (op->getNumSuccessors() != numSuccessors) {
988     return op->emitOpError("requires ")
989            << numSuccessors << " successors but found "
990            << op->getNumSuccessors();
991   }
992   return verifyTerminatorSuccessors(op);
993 }
994 LogicalResult OpTrait::impl::verifyAtLeastNSuccessors(Operation *op,
995                                                       unsigned numSuccessors) {
996   if (op->getNumSuccessors() < numSuccessors) {
997     return op->emitOpError("requires at least ")
998            << numSuccessors << " successors but found "
999            << op->getNumSuccessors();
1000   }
1001   return verifyTerminatorSuccessors(op);
1002 }
1003 
1004 LogicalResult OpTrait::impl::verifyResultsAreBoolLike(Operation *op) {
1005   for (auto resultType : op->getResultTypes()) {
1006     auto elementType = getTensorOrVectorElementType(resultType);
1007     bool isBoolType = elementType.isInteger(1);
1008     if (!isBoolType)
1009       return op->emitOpError() << "requires a bool result type";
1010   }
1011 
1012   return success();
1013 }
1014 
1015 LogicalResult OpTrait::impl::verifyResultsAreFloatLike(Operation *op) {
1016   for (auto resultType : op->getResultTypes())
1017     if (!getTensorOrVectorElementType(resultType).isa<FloatType>())
1018       return op->emitOpError() << "requires a floating point type";
1019 
1020   return success();
1021 }
1022 
1023 LogicalResult
1024 OpTrait::impl::verifyResultsAreSignlessIntegerLike(Operation *op) {
1025   for (auto resultType : op->getResultTypes())
1026     if (!getTensorOrVectorElementType(resultType).isSignlessIntOrIndex())
1027       return op->emitOpError() << "requires an integer or index type";
1028   return success();
1029 }
1030 
1031 static LogicalResult verifyValueSizeAttr(Operation *op, StringRef attrName,
1032                                          bool isOperand) {
1033   auto sizeAttr = op->getAttrOfType<DenseIntElementsAttr>(attrName);
1034   if (!sizeAttr)
1035     return op->emitOpError("requires 1D vector attribute '") << attrName << "'";
1036 
1037   auto sizeAttrType = sizeAttr.getType().dyn_cast<VectorType>();
1038   if (!sizeAttrType || sizeAttrType.getRank() != 1)
1039     return op->emitOpError("requires 1D vector attribute '") << attrName << "'";
1040 
1041   if (llvm::any_of(sizeAttr.getIntValues(), [](const APInt &element) {
1042         return !element.isNonNegative();
1043       }))
1044     return op->emitOpError("'")
1045            << attrName << "' attribute cannot have negative elements";
1046 
1047   size_t totalCount = std::accumulate(
1048       sizeAttr.begin(), sizeAttr.end(), 0,
1049       [](unsigned all, APInt one) { return all + one.getZExtValue(); });
1050 
1051   if (isOperand && totalCount != op->getNumOperands())
1052     return op->emitOpError("operand count (")
1053            << op->getNumOperands() << ") does not match with the total size ("
1054            << totalCount << ") specified in attribute '" << attrName << "'";
1055   else if (!isOperand && totalCount != op->getNumResults())
1056     return op->emitOpError("result count (")
1057            << op->getNumResults() << ") does not match with the total size ("
1058            << totalCount << ") specified in attribute '" << attrName << "'";
1059   return success();
1060 }
1061 
1062 LogicalResult OpTrait::impl::verifyOperandSizeAttr(Operation *op,
1063                                                    StringRef attrName) {
1064   return verifyValueSizeAttr(op, attrName, /*isOperand=*/true);
1065 }
1066 
1067 LogicalResult OpTrait::impl::verifyResultSizeAttr(Operation *op,
1068                                                   StringRef attrName) {
1069   return verifyValueSizeAttr(op, attrName, /*isOperand=*/false);
1070 }
1071 
1072 LogicalResult OpTrait::impl::verifyNoRegionArguments(Operation *op) {
1073   for (Region &region : op->getRegions()) {
1074     if (region.empty())
1075       continue;
1076 
1077     if (region.getNumArguments() != 0) {
1078       if (op->getNumRegions() > 1)
1079         return op->emitOpError("region #")
1080                << region.getRegionNumber() << " should have no arguments";
1081       else
1082         return op->emitOpError("region should have no arguments");
1083     }
1084   }
1085   return success();
1086 }
1087 
1088 /// Checks if two ShapedTypes are the same, ignoring the element type.
1089 static bool areSameShapedTypeIgnoringElementType(ShapedType a, ShapedType b) {
1090   if (a.getTypeID() != b.getTypeID())
1091     return false;
1092   if (!a.hasRank())
1093     return !b.hasRank();
1094   return a.getShape() == b.getShape();
1095 }
1096 
1097 LogicalResult OpTrait::impl::verifyElementwiseMappable(Operation *op) {
1098   auto isMappableType = [](Type type) {
1099     return type.isa<VectorType, TensorType>();
1100   };
1101   auto resultMappableTypes = llvm::to_vector<1>(
1102       llvm::make_filter_range(op->getResultTypes(), isMappableType));
1103   auto operandMappableTypes = llvm::to_vector<2>(
1104       llvm::make_filter_range(op->getOperandTypes(), isMappableType));
1105 
1106   // If the op only has scalar operand/result types, then we have nothing to
1107   // check.
1108   if (resultMappableTypes.empty() && operandMappableTypes.empty())
1109     return success();
1110 
1111   if (!resultMappableTypes.empty() && operandMappableTypes.empty())
1112     return op->emitOpError("if a result is non-scalar, then at least one "
1113                            "operand must be non-scalar");
1114 
1115   assert(!operandMappableTypes.empty());
1116 
1117   if (resultMappableTypes.empty())
1118     return op->emitOpError("if an operand is non-scalar, then there must be at "
1119                            "least one non-scalar result");
1120 
1121   if (resultMappableTypes.size() != op->getNumResults())
1122     return op->emitOpError(
1123         "if an operand is non-scalar, then all results must be non-scalar");
1124 
1125   auto mustMatchType = operandMappableTypes[0].cast<ShapedType>();
1126   for (auto type :
1127        llvm::concat<Type>(resultMappableTypes, operandMappableTypes)) {
1128     if (!areSameShapedTypeIgnoringElementType(type.cast<ShapedType>(),
1129                                               mustMatchType)) {
1130       return op->emitOpError() << "all non-scalar operands/results must have "
1131                                   "the same shape and base type: found "
1132                                << type << " and " << mustMatchType;
1133     }
1134   }
1135 
1136   return success();
1137 }
1138 
1139 //===----------------------------------------------------------------------===//
1140 // BinaryOp implementation
1141 //===----------------------------------------------------------------------===//
1142 
1143 // These functions are out-of-line implementations of the methods in BinaryOp,
1144 // which avoids them being template instantiated/duplicated.
1145 
1146 void impl::buildBinaryOp(OpBuilder &builder, OperationState &result, Value lhs,
1147                          Value rhs) {
1148   assert(lhs.getType() == rhs.getType());
1149   result.addOperands({lhs, rhs});
1150   result.types.push_back(lhs.getType());
1151 }
1152 
1153 ParseResult impl::parseOneResultSameOperandTypeOp(OpAsmParser &parser,
1154                                                   OperationState &result) {
1155   SmallVector<OpAsmParser::OperandType, 2> ops;
1156   Type type;
1157   return failure(parser.parseOperandList(ops) ||
1158                  parser.parseOptionalAttrDict(result.attributes) ||
1159                  parser.parseColonType(type) ||
1160                  parser.resolveOperands(ops, type, result.operands) ||
1161                  parser.addTypeToList(type, result.types));
1162 }
1163 
1164 void impl::printOneResultOp(Operation *op, OpAsmPrinter &p) {
1165   assert(op->getNumResults() == 1 && "op should have one result");
1166 
1167   // If not all the operand and result types are the same, just use the
1168   // generic assembly form to avoid omitting information in printing.
1169   auto resultType = op->getResult(0).getType();
1170   if (llvm::any_of(op->getOperandTypes(),
1171                    [&](Type type) { return type != resultType; })) {
1172     p.printGenericOp(op);
1173     return;
1174   }
1175 
1176   p << op->getName() << ' ';
1177   p.printOperands(op->getOperands());
1178   p.printOptionalAttrDict(op->getAttrs());
1179   // Now we can output only one type for all operands and the result.
1180   p << " : " << resultType;
1181 }
1182 
1183 //===----------------------------------------------------------------------===//
1184 // CastOp implementation
1185 //===----------------------------------------------------------------------===//
1186 
1187 /// Attempt to fold the given cast operation.
1188 LogicalResult
1189 impl::foldCastInterfaceOp(Operation *op, ArrayRef<Attribute> attrOperands,
1190                           SmallVectorImpl<OpFoldResult> &foldResults) {
1191   OperandRange operands = op->getOperands();
1192   if (operands.empty())
1193     return failure();
1194   ResultRange results = op->getResults();
1195 
1196   // Check for the case where the input and output types match 1-1.
1197   if (operands.getTypes() == results.getTypes()) {
1198     foldResults.append(operands.begin(), operands.end());
1199     return success();
1200   }
1201 
1202   return failure();
1203 }
1204 
1205 /// Attempt to verify the given cast operation.
1206 LogicalResult impl::verifyCastInterfaceOp(
1207     Operation *op, function_ref<bool(TypeRange, TypeRange)> areCastCompatible) {
1208   auto resultTypes = op->getResultTypes();
1209   if (llvm::empty(resultTypes))
1210     return op->emitOpError()
1211            << "expected at least one result for cast operation";
1212 
1213   auto operandTypes = op->getOperandTypes();
1214   if (!areCastCompatible(operandTypes, resultTypes)) {
1215     InFlightDiagnostic diag = op->emitOpError("operand type");
1216     if (llvm::empty(operandTypes))
1217       diag << "s []";
1218     else if (llvm::size(operandTypes) == 1)
1219       diag << " " << *operandTypes.begin();
1220     else
1221       diag << "s " << operandTypes;
1222     return diag << " and result type" << (resultTypes.size() == 1 ? " " : "s ")
1223                 << resultTypes << " are cast incompatible";
1224   }
1225 
1226   return success();
1227 }
1228 
1229 void impl::buildCastOp(OpBuilder &builder, OperationState &result, Value source,
1230                        Type destType) {
1231   result.addOperands(source);
1232   result.addTypes(destType);
1233 }
1234 
1235 ParseResult impl::parseCastOp(OpAsmParser &parser, OperationState &result) {
1236   OpAsmParser::OperandType srcInfo;
1237   Type srcType, dstType;
1238   return failure(parser.parseOperand(srcInfo) ||
1239                  parser.parseOptionalAttrDict(result.attributes) ||
1240                  parser.parseColonType(srcType) ||
1241                  parser.resolveOperand(srcInfo, srcType, result.operands) ||
1242                  parser.parseKeywordType("to", dstType) ||
1243                  parser.addTypeToList(dstType, result.types));
1244 }
1245 
1246 void impl::printCastOp(Operation *op, OpAsmPrinter &p) {
1247   p << op->getName() << ' ' << op->getOperand(0);
1248   p.printOptionalAttrDict(op->getAttrs());
1249   p << " : " << op->getOperand(0).getType() << " to "
1250     << op->getResult(0).getType();
1251 }
1252 
1253 Value impl::foldCastOp(Operation *op) {
1254   // Identity cast
1255   if (op->getOperand(0).getType() == op->getResult(0).getType())
1256     return op->getOperand(0);
1257   return nullptr;
1258 }
1259 
1260 LogicalResult
1261 impl::verifyCastOp(Operation *op,
1262                    function_ref<bool(Type, Type)> areCastCompatible) {
1263   auto opType = op->getOperand(0).getType();
1264   auto resType = op->getResult(0).getType();
1265   if (!areCastCompatible(opType, resType))
1266     return op->emitError("operand type ")
1267            << opType << " and result type " << resType
1268            << " are cast incompatible";
1269 
1270   return success();
1271 }
1272 
1273 //===----------------------------------------------------------------------===//
1274 // Misc. utils
1275 //===----------------------------------------------------------------------===//
1276 
1277 /// Insert an operation, generated by `buildTerminatorOp`, at the end of the
1278 /// region's only block if it does not have a terminator already. If the region
1279 /// is empty, insert a new block first. `buildTerminatorOp` should return the
1280 /// terminator operation to insert.
1281 void impl::ensureRegionTerminator(
1282     Region &region, OpBuilder &builder, Location loc,
1283     function_ref<Operation *(OpBuilder &, Location)> buildTerminatorOp) {
1284   OpBuilder::InsertionGuard guard(builder);
1285   if (region.empty())
1286     builder.createBlock(&region);
1287 
1288   Block &block = region.back();
1289   if (!block.empty() && block.back().hasTrait<OpTrait::IsTerminator>())
1290     return;
1291 
1292   builder.setInsertionPointToEnd(&block);
1293   builder.insert(buildTerminatorOp(builder, loc));
1294 }
1295 
1296 /// Create a simple OpBuilder and forward to the OpBuilder version of this
1297 /// function.
1298 void impl::ensureRegionTerminator(
1299     Region &region, Builder &builder, Location loc,
1300     function_ref<Operation *(OpBuilder &, Location)> buildTerminatorOp) {
1301   OpBuilder opBuilder(builder.getContext());
1302   ensureRegionTerminator(region, opBuilder, loc, buildTerminatorOp);
1303 }
1304 
1305 //===----------------------------------------------------------------------===//
1306 // UseIterator
1307 //===----------------------------------------------------------------------===//
1308 
1309 Operation::UseIterator::UseIterator(Operation *op, bool end)
1310     : op(op), res(end ? op->result_end() : op->result_begin()) {
1311   // Only initialize current use if there are results/can be uses.
1312   if (op->getNumResults())
1313     skipOverResultsWithNoUsers();
1314 }
1315 
1316 Operation::UseIterator &Operation::UseIterator::operator++() {
1317   // We increment over uses, if we reach the last use then move to next
1318   // result.
1319   if (use != (*res).use_end())
1320     ++use;
1321   if (use == (*res).use_end()) {
1322     ++res;
1323     skipOverResultsWithNoUsers();
1324   }
1325   return *this;
1326 }
1327 
1328 void Operation::UseIterator::skipOverResultsWithNoUsers() {
1329   while (res != op->result_end() && (*res).use_empty())
1330     ++res;
1331 
1332   // If we are at the last result, then set use to first use of
1333   // first result (sentinel value used for end).
1334   if (res == op->result_end())
1335     use = {};
1336   else
1337     use = (*res).use_begin();
1338 }
1339