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