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(attributes, location.getContext()),
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->isKnownNonTerminator()) &&
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 Dialect *OpState::getDialect() { return getOperation()->getDialect(); }
696 Region *OpState::getParentRegion() { return getOperation()->getParentRegion(); }
697 Operation *OpState::getParentOp() { return getOperation()->getParentOp(); }
698 OpState::dialect_attr_range OpState::getDialectAttrs() {
699   return state->getDialectAttrs();
700 }
701 OpState::dialect_attr_iterator OpState::dialect_attr_begin() {
702   return state->dialect_attr_begin();
703 }
704 OpState::dialect_attr_iterator OpState::dialect_attr_end() {
705   return state->dialect_attr_end();
706 }
707 Attribute OpState::getAttr(StringRef name) { return state->getAttr(name); }
708 void OpState::setAttr(Identifier name, Attribute value) {
709   state->setAttr(name, value);
710 }
711 void OpState::setAttr(StringRef name, Attribute value) {
712   setAttr(Identifier::get(name, getContext()), value);
713 }
714 void OpState::setAttrs(ArrayRef<NamedAttribute> attributes) {
715   state->setAttrs(DictionaryAttr::get(attributes, getContext()));
716 }
717 void OpState::setAttrs(DictionaryAttr newAttrs) { state->setAttrs(newAttrs); }
718 
719 //===----------------------------------------------------------------------===//
720 // Op Trait implementations
721 //===----------------------------------------------------------------------===//
722 
723 OpFoldResult OpTrait::impl::foldIdempotent(Operation *op) {
724   auto *argumentOp = op->getOperand(0).getDefiningOp();
725   if (argumentOp && op->getName() == argumentOp->getName()) {
726     // Replace the outer operation output with the inner operation.
727     return op->getOperand(0);
728   }
729 
730   return {};
731 }
732 
733 OpFoldResult OpTrait::impl::foldInvolution(Operation *op) {
734   auto *argumentOp = op->getOperand(0).getDefiningOp();
735   if (argumentOp && op->getName() == argumentOp->getName()) {
736     // Replace the outer involutions output with inner's input.
737     return argumentOp->getOperand(0);
738   }
739 
740   return {};
741 }
742 
743 LogicalResult OpTrait::impl::verifyZeroOperands(Operation *op) {
744   if (op->getNumOperands() != 0)
745     return op->emitOpError() << "requires zero operands";
746   return success();
747 }
748 
749 LogicalResult OpTrait::impl::verifyOneOperand(Operation *op) {
750   if (op->getNumOperands() != 1)
751     return op->emitOpError() << "requires a single operand";
752   return success();
753 }
754 
755 LogicalResult OpTrait::impl::verifyNOperands(Operation *op,
756                                              unsigned numOperands) {
757   if (op->getNumOperands() != numOperands) {
758     return op->emitOpError() << "expected " << numOperands
759                              << " operands, but found " << op->getNumOperands();
760   }
761   return success();
762 }
763 
764 LogicalResult OpTrait::impl::verifyAtLeastNOperands(Operation *op,
765                                                     unsigned numOperands) {
766   if (op->getNumOperands() < numOperands)
767     return op->emitOpError()
768            << "expected " << numOperands << " or more operands";
769   return success();
770 }
771 
772 /// If this is a vector type, or a tensor type, return the scalar element type
773 /// that it is built around, otherwise return the type unmodified.
774 static Type getTensorOrVectorElementType(Type type) {
775   if (auto vec = type.dyn_cast<VectorType>())
776     return vec.getElementType();
777 
778   // Look through tensor<vector<...>> to find the underlying element type.
779   if (auto tensor = type.dyn_cast<TensorType>())
780     return getTensorOrVectorElementType(tensor.getElementType());
781   return type;
782 }
783 
784 LogicalResult OpTrait::impl::verifyIsIdempotent(Operation *op) {
785   // FIXME: Add back check for no side effects on operation.
786   // Currently adding it would cause the shared library build
787   // to fail since there would be a dependency of IR on SideEffectInterfaces
788   // which is cyclical.
789   return success();
790 }
791 
792 LogicalResult OpTrait::impl::verifyIsInvolution(Operation *op) {
793   // FIXME: Add back check for no side effects on operation.
794   // Currently adding it would cause the shared library build
795   // to fail since there would be a dependency of IR on SideEffectInterfaces
796   // which is cyclical.
797   return success();
798 }
799 
800 LogicalResult
801 OpTrait::impl::verifyOperandsAreSignlessIntegerLike(Operation *op) {
802   for (auto opType : op->getOperandTypes()) {
803     auto type = getTensorOrVectorElementType(opType);
804     if (!type.isSignlessIntOrIndex())
805       return op->emitOpError() << "requires an integer or index type";
806   }
807   return success();
808 }
809 
810 LogicalResult OpTrait::impl::verifyOperandsAreFloatLike(Operation *op) {
811   for (auto opType : op->getOperandTypes()) {
812     auto type = getTensorOrVectorElementType(opType);
813     if (!type.isa<FloatType>())
814       return op->emitOpError("requires a float type");
815   }
816   return success();
817 }
818 
819 LogicalResult OpTrait::impl::verifySameTypeOperands(Operation *op) {
820   // Zero or one operand always have the "same" type.
821   unsigned nOperands = op->getNumOperands();
822   if (nOperands < 2)
823     return success();
824 
825   auto type = op->getOperand(0).getType();
826   for (auto opType : llvm::drop_begin(op->getOperandTypes(), 1))
827     if (opType != type)
828       return op->emitOpError() << "requires all operands to have the same type";
829   return success();
830 }
831 
832 LogicalResult OpTrait::impl::verifyZeroRegion(Operation *op) {
833   if (op->getNumRegions() != 0)
834     return op->emitOpError() << "requires zero regions";
835   return success();
836 }
837 
838 LogicalResult OpTrait::impl::verifyOneRegion(Operation *op) {
839   if (op->getNumRegions() != 1)
840     return op->emitOpError() << "requires one region";
841   return success();
842 }
843 
844 LogicalResult OpTrait::impl::verifyNRegions(Operation *op,
845                                             unsigned numRegions) {
846   if (op->getNumRegions() != numRegions)
847     return op->emitOpError() << "expected " << numRegions << " regions";
848   return success();
849 }
850 
851 LogicalResult OpTrait::impl::verifyAtLeastNRegions(Operation *op,
852                                                    unsigned numRegions) {
853   if (op->getNumRegions() < numRegions)
854     return op->emitOpError() << "expected " << numRegions << " or more regions";
855   return success();
856 }
857 
858 LogicalResult OpTrait::impl::verifyZeroResult(Operation *op) {
859   if (op->getNumResults() != 0)
860     return op->emitOpError() << "requires zero results";
861   return success();
862 }
863 
864 LogicalResult OpTrait::impl::verifyOneResult(Operation *op) {
865   if (op->getNumResults() != 1)
866     return op->emitOpError() << "requires one result";
867   return success();
868 }
869 
870 LogicalResult OpTrait::impl::verifyNResults(Operation *op,
871                                             unsigned numOperands) {
872   if (op->getNumResults() != numOperands)
873     return op->emitOpError() << "expected " << numOperands << " results";
874   return success();
875 }
876 
877 LogicalResult OpTrait::impl::verifyAtLeastNResults(Operation *op,
878                                                    unsigned numOperands) {
879   if (op->getNumResults() < numOperands)
880     return op->emitOpError()
881            << "expected " << numOperands << " or more results";
882   return success();
883 }
884 
885 LogicalResult OpTrait::impl::verifySameOperandsShape(Operation *op) {
886   if (failed(verifyAtLeastNOperands(op, 1)))
887     return failure();
888 
889   auto type = op->getOperand(0).getType();
890   for (auto opType : llvm::drop_begin(op->getOperandTypes(), 1)) {
891     if (failed(verifyCompatibleShape(opType, type)))
892       return op->emitOpError() << "requires the same shape for all operands";
893   }
894   return success();
895 }
896 
897 LogicalResult OpTrait::impl::verifySameOperandsAndResultShape(Operation *op) {
898   if (failed(verifyAtLeastNOperands(op, 1)) ||
899       failed(verifyAtLeastNResults(op, 1)))
900     return failure();
901 
902   auto type = op->getOperand(0).getType();
903   for (auto resultType : op->getResultTypes()) {
904     if (failed(verifyCompatibleShape(resultType, type)))
905       return op->emitOpError()
906              << "requires the same shape for all operands and results";
907   }
908   for (auto opType : llvm::drop_begin(op->getOperandTypes(), 1)) {
909     if (failed(verifyCompatibleShape(opType, type)))
910       return op->emitOpError()
911              << "requires the same shape for all operands and results";
912   }
913   return success();
914 }
915 
916 LogicalResult OpTrait::impl::verifySameOperandsElementType(Operation *op) {
917   if (failed(verifyAtLeastNOperands(op, 1)))
918     return failure();
919   auto elementType = getElementTypeOrSelf(op->getOperand(0));
920 
921   for (auto operand : llvm::drop_begin(op->getOperands(), 1)) {
922     if (getElementTypeOrSelf(operand) != elementType)
923       return op->emitOpError("requires the same element type for all operands");
924   }
925 
926   return success();
927 }
928 
929 LogicalResult
930 OpTrait::impl::verifySameOperandsAndResultElementType(Operation *op) {
931   if (failed(verifyAtLeastNOperands(op, 1)) ||
932       failed(verifyAtLeastNResults(op, 1)))
933     return failure();
934 
935   auto elementType = getElementTypeOrSelf(op->getResult(0));
936 
937   // Verify result element type matches first result's element type.
938   for (auto result : llvm::drop_begin(op->getResults(), 1)) {
939     if (getElementTypeOrSelf(result) != elementType)
940       return op->emitOpError(
941           "requires the same element type for all operands and results");
942   }
943 
944   // Verify operand's element type matches first result's element type.
945   for (auto operand : op->getOperands()) {
946     if (getElementTypeOrSelf(operand) != elementType)
947       return op->emitOpError(
948           "requires the same element type for all operands and results");
949   }
950 
951   return success();
952 }
953 
954 LogicalResult OpTrait::impl::verifySameOperandsAndResultType(Operation *op) {
955   if (failed(verifyAtLeastNOperands(op, 1)) ||
956       failed(verifyAtLeastNResults(op, 1)))
957     return failure();
958 
959   auto type = op->getResult(0).getType();
960   auto elementType = getElementTypeOrSelf(type);
961   for (auto resultType : op->getResultTypes().drop_front(1)) {
962     if (getElementTypeOrSelf(resultType) != elementType ||
963         failed(verifyCompatibleShape(resultType, type)))
964       return op->emitOpError()
965              << "requires the same type for all operands and results";
966   }
967   for (auto opType : op->getOperandTypes()) {
968     if (getElementTypeOrSelf(opType) != elementType ||
969         failed(verifyCompatibleShape(opType, type)))
970       return op->emitOpError()
971              << "requires the same type for all operands and results";
972   }
973   return success();
974 }
975 
976 LogicalResult OpTrait::impl::verifyIsTerminator(Operation *op) {
977   Block *block = op->getBlock();
978   // Verify that the operation is at the end of the respective parent block.
979   if (!block || &block->back() != op)
980     return op->emitOpError("must be the last operation in the parent block");
981   return success();
982 }
983 
984 static LogicalResult verifyTerminatorSuccessors(Operation *op) {
985   auto *parent = op->getParentRegion();
986 
987   // Verify that the operands lines up with the BB arguments in the successor.
988   for (Block *succ : op->getSuccessors())
989     if (succ->getParent() != parent)
990       return op->emitError("reference to block defined in another region");
991   return success();
992 }
993 
994 LogicalResult OpTrait::impl::verifyZeroSuccessor(Operation *op) {
995   if (op->getNumSuccessors() != 0) {
996     return op->emitOpError("requires 0 successors but found ")
997            << op->getNumSuccessors();
998   }
999   return success();
1000 }
1001 
1002 LogicalResult OpTrait::impl::verifyOneSuccessor(Operation *op) {
1003   if (op->getNumSuccessors() != 1) {
1004     return op->emitOpError("requires 1 successor but found ")
1005            << op->getNumSuccessors();
1006   }
1007   return verifyTerminatorSuccessors(op);
1008 }
1009 LogicalResult OpTrait::impl::verifyNSuccessors(Operation *op,
1010                                                unsigned numSuccessors) {
1011   if (op->getNumSuccessors() != numSuccessors) {
1012     return op->emitOpError("requires ")
1013            << numSuccessors << " successors but found "
1014            << op->getNumSuccessors();
1015   }
1016   return verifyTerminatorSuccessors(op);
1017 }
1018 LogicalResult OpTrait::impl::verifyAtLeastNSuccessors(Operation *op,
1019                                                       unsigned numSuccessors) {
1020   if (op->getNumSuccessors() < numSuccessors) {
1021     return op->emitOpError("requires at least ")
1022            << numSuccessors << " successors but found "
1023            << op->getNumSuccessors();
1024   }
1025   return verifyTerminatorSuccessors(op);
1026 }
1027 
1028 LogicalResult OpTrait::impl::verifyResultsAreBoolLike(Operation *op) {
1029   for (auto resultType : op->getResultTypes()) {
1030     auto elementType = getTensorOrVectorElementType(resultType);
1031     bool isBoolType = elementType.isInteger(1);
1032     if (!isBoolType)
1033       return op->emitOpError() << "requires a bool result type";
1034   }
1035 
1036   return success();
1037 }
1038 
1039 LogicalResult OpTrait::impl::verifyResultsAreFloatLike(Operation *op) {
1040   for (auto resultType : op->getResultTypes())
1041     if (!getTensorOrVectorElementType(resultType).isa<FloatType>())
1042       return op->emitOpError() << "requires a floating point type";
1043 
1044   return success();
1045 }
1046 
1047 LogicalResult
1048 OpTrait::impl::verifyResultsAreSignlessIntegerLike(Operation *op) {
1049   for (auto resultType : op->getResultTypes())
1050     if (!getTensorOrVectorElementType(resultType).isSignlessIntOrIndex())
1051       return op->emitOpError() << "requires an integer or index type";
1052   return success();
1053 }
1054 
1055 static LogicalResult verifyValueSizeAttr(Operation *op, StringRef attrName,
1056                                          bool isOperand) {
1057   auto sizeAttr = op->getAttrOfType<DenseIntElementsAttr>(attrName);
1058   if (!sizeAttr)
1059     return op->emitOpError("requires 1D vector attribute '") << attrName << "'";
1060 
1061   auto sizeAttrType = sizeAttr.getType().dyn_cast<VectorType>();
1062   if (!sizeAttrType || sizeAttrType.getRank() != 1)
1063     return op->emitOpError("requires 1D vector attribute '") << attrName << "'";
1064 
1065   if (llvm::any_of(sizeAttr.getIntValues(), [](const APInt &element) {
1066         return !element.isNonNegative();
1067       }))
1068     return op->emitOpError("'")
1069            << attrName << "' attribute cannot have negative elements";
1070 
1071   size_t totalCount = std::accumulate(
1072       sizeAttr.begin(), sizeAttr.end(), 0,
1073       [](unsigned all, APInt one) { return all + one.getZExtValue(); });
1074 
1075   if (isOperand && totalCount != op->getNumOperands())
1076     return op->emitOpError("operand count (")
1077            << op->getNumOperands() << ") does not match with the total size ("
1078            << totalCount << ") specified in attribute '" << attrName << "'";
1079   else if (!isOperand && totalCount != op->getNumResults())
1080     return op->emitOpError("result count (")
1081            << op->getNumResults() << ") does not match with the total size ("
1082            << totalCount << ") specified in attribute '" << attrName << "'";
1083   return success();
1084 }
1085 
1086 LogicalResult OpTrait::impl::verifyOperandSizeAttr(Operation *op,
1087                                                    StringRef attrName) {
1088   return verifyValueSizeAttr(op, attrName, /*isOperand=*/true);
1089 }
1090 
1091 LogicalResult OpTrait::impl::verifyResultSizeAttr(Operation *op,
1092                                                   StringRef attrName) {
1093   return verifyValueSizeAttr(op, attrName, /*isOperand=*/false);
1094 }
1095 
1096 LogicalResult OpTrait::impl::verifyNoRegionArguments(Operation *op) {
1097   for (Region &region : op->getRegions()) {
1098     if (region.empty())
1099       continue;
1100 
1101     if (region.getNumArguments() != 0) {
1102       if (op->getNumRegions() > 1)
1103         return op->emitOpError("region #")
1104                << region.getRegionNumber() << " should have no arguments";
1105       else
1106         return op->emitOpError("region should have no arguments");
1107     }
1108   }
1109   return success();
1110 }
1111 
1112 /// Checks if two ShapedTypes are the same, ignoring the element type.
1113 static bool areSameShapedTypeIgnoringElementType(ShapedType a, ShapedType b) {
1114   if (a.getTypeID() != b.getTypeID())
1115     return false;
1116   if (!a.hasRank())
1117     return !b.hasRank();
1118   return a.getShape() == b.getShape();
1119 }
1120 
1121 LogicalResult OpTrait::impl::verifyElementwiseMappable(Operation *op) {
1122   auto isMappableType = [](Type type) {
1123     return type.isa<VectorType, TensorType>();
1124   };
1125   auto resultMappableTypes = llvm::to_vector<1>(
1126       llvm::make_filter_range(op->getResultTypes(), isMappableType));
1127   auto operandMappableTypes = llvm::to_vector<2>(
1128       llvm::make_filter_range(op->getOperandTypes(), isMappableType));
1129 
1130   // If the op only has scalar operand/result types, then we have nothing to
1131   // check.
1132   if (resultMappableTypes.empty() && operandMappableTypes.empty())
1133     return success();
1134 
1135   if (!resultMappableTypes.empty() && operandMappableTypes.empty())
1136     return op->emitOpError("if a result is non-scalar, then at least one "
1137                            "operand must be non-scalar");
1138 
1139   assert(!operandMappableTypes.empty());
1140 
1141   if (resultMappableTypes.empty())
1142     return op->emitOpError("if an operand is non-scalar, then there must be at "
1143                            "least one non-scalar result");
1144 
1145   if (resultMappableTypes.size() != op->getNumResults())
1146     return op->emitOpError(
1147         "if an operand is non-scalar, then all results must be non-scalar");
1148 
1149   auto mustMatchType = operandMappableTypes[0].cast<ShapedType>();
1150   for (auto type :
1151        llvm::concat<Type>(resultMappableTypes, operandMappableTypes)) {
1152     if (!areSameShapedTypeIgnoringElementType(type.cast<ShapedType>(),
1153                                               mustMatchType)) {
1154       return op->emitOpError() << "all non-scalar operands/results must have "
1155                                   "the same shape and base type: found "
1156                                << type << " and " << mustMatchType;
1157     }
1158   }
1159 
1160   return success();
1161 }
1162 
1163 //===----------------------------------------------------------------------===//
1164 // BinaryOp implementation
1165 //===----------------------------------------------------------------------===//
1166 
1167 // These functions are out-of-line implementations of the methods in BinaryOp,
1168 // which avoids them being template instantiated/duplicated.
1169 
1170 void impl::buildBinaryOp(OpBuilder &builder, OperationState &result, Value lhs,
1171                          Value rhs) {
1172   assert(lhs.getType() == rhs.getType());
1173   result.addOperands({lhs, rhs});
1174   result.types.push_back(lhs.getType());
1175 }
1176 
1177 ParseResult impl::parseOneResultSameOperandTypeOp(OpAsmParser &parser,
1178                                                   OperationState &result) {
1179   SmallVector<OpAsmParser::OperandType, 2> ops;
1180   Type type;
1181   return failure(parser.parseOperandList(ops) ||
1182                  parser.parseOptionalAttrDict(result.attributes) ||
1183                  parser.parseColonType(type) ||
1184                  parser.resolveOperands(ops, type, result.operands) ||
1185                  parser.addTypeToList(type, result.types));
1186 }
1187 
1188 void impl::printOneResultOp(Operation *op, OpAsmPrinter &p) {
1189   assert(op->getNumResults() == 1 && "op should have one result");
1190 
1191   // If not all the operand and result types are the same, just use the
1192   // generic assembly form to avoid omitting information in printing.
1193   auto resultType = op->getResult(0).getType();
1194   if (llvm::any_of(op->getOperandTypes(),
1195                    [&](Type type) { return type != resultType; })) {
1196     p.printGenericOp(op);
1197     return;
1198   }
1199 
1200   p << op->getName() << ' ';
1201   p.printOperands(op->getOperands());
1202   p.printOptionalAttrDict(op->getAttrs());
1203   // Now we can output only one type for all operands and the result.
1204   p << " : " << resultType;
1205 }
1206 
1207 //===----------------------------------------------------------------------===//
1208 // CastOp implementation
1209 //===----------------------------------------------------------------------===//
1210 
1211 /// Attempt to fold the given cast operation.
1212 LogicalResult
1213 impl::foldCastInterfaceOp(Operation *op, ArrayRef<Attribute> attrOperands,
1214                           SmallVectorImpl<OpFoldResult> &foldResults) {
1215   OperandRange operands = op->getOperands();
1216   if (operands.empty())
1217     return failure();
1218   ResultRange results = op->getResults();
1219 
1220   // Check for the case where the input and output types match 1-1.
1221   if (operands.getTypes() == results.getTypes()) {
1222     foldResults.append(operands.begin(), operands.end());
1223     return success();
1224   }
1225 
1226   return failure();
1227 }
1228 
1229 /// Attempt to verify the given cast operation.
1230 LogicalResult impl::verifyCastInterfaceOp(
1231     Operation *op, function_ref<bool(TypeRange, TypeRange)> areCastCompatible) {
1232   auto resultTypes = op->getResultTypes();
1233   if (llvm::empty(resultTypes))
1234     return op->emitOpError()
1235            << "expected at least one result for cast operation";
1236 
1237   auto operandTypes = op->getOperandTypes();
1238   if (!areCastCompatible(operandTypes, resultTypes)) {
1239     InFlightDiagnostic diag = op->emitOpError("operand type");
1240     if (llvm::empty(operandTypes))
1241       diag << "s []";
1242     else if (llvm::size(operandTypes) == 1)
1243       diag << " " << *operandTypes.begin();
1244     else
1245       diag << "s " << operandTypes;
1246     return diag << " and result type" << (resultTypes.size() == 1 ? " " : "s ")
1247                 << resultTypes << " are cast incompatible";
1248   }
1249 
1250   return success();
1251 }
1252 
1253 void impl::buildCastOp(OpBuilder &builder, OperationState &result, Value source,
1254                        Type destType) {
1255   result.addOperands(source);
1256   result.addTypes(destType);
1257 }
1258 
1259 ParseResult impl::parseCastOp(OpAsmParser &parser, OperationState &result) {
1260   OpAsmParser::OperandType srcInfo;
1261   Type srcType, dstType;
1262   return failure(parser.parseOperand(srcInfo) ||
1263                  parser.parseOptionalAttrDict(result.attributes) ||
1264                  parser.parseColonType(srcType) ||
1265                  parser.resolveOperand(srcInfo, srcType, result.operands) ||
1266                  parser.parseKeywordType("to", dstType) ||
1267                  parser.addTypeToList(dstType, result.types));
1268 }
1269 
1270 void impl::printCastOp(Operation *op, OpAsmPrinter &p) {
1271   p << op->getName() << ' ' << op->getOperand(0);
1272   p.printOptionalAttrDict(op->getAttrs());
1273   p << " : " << op->getOperand(0).getType() << " to "
1274     << op->getResult(0).getType();
1275 }
1276 
1277 Value impl::foldCastOp(Operation *op) {
1278   // Identity cast
1279   if (op->getOperand(0).getType() == op->getResult(0).getType())
1280     return op->getOperand(0);
1281   return nullptr;
1282 }
1283 
1284 LogicalResult
1285 impl::verifyCastOp(Operation *op,
1286                    function_ref<bool(Type, Type)> areCastCompatible) {
1287   auto opType = op->getOperand(0).getType();
1288   auto resType = op->getResult(0).getType();
1289   if (!areCastCompatible(opType, resType))
1290     return op->emitError("operand type ")
1291            << opType << " and result type " << resType
1292            << " are cast incompatible";
1293 
1294   return success();
1295 }
1296 
1297 //===----------------------------------------------------------------------===//
1298 // Misc. utils
1299 //===----------------------------------------------------------------------===//
1300 
1301 /// Insert an operation, generated by `buildTerminatorOp`, at the end of the
1302 /// region's only block if it does not have a terminator already. If the region
1303 /// is empty, insert a new block first. `buildTerminatorOp` should return the
1304 /// terminator operation to insert.
1305 void impl::ensureRegionTerminator(
1306     Region &region, OpBuilder &builder, Location loc,
1307     function_ref<Operation *(OpBuilder &, Location)> buildTerminatorOp) {
1308   OpBuilder::InsertionGuard guard(builder);
1309   if (region.empty())
1310     builder.createBlock(&region);
1311 
1312   Block &block = region.back();
1313   if (!block.empty() && block.back().isKnownTerminator())
1314     return;
1315 
1316   builder.setInsertionPointToEnd(&block);
1317   builder.insert(buildTerminatorOp(builder, loc));
1318 }
1319 
1320 /// Create a simple OpBuilder and forward to the OpBuilder version of this
1321 /// function.
1322 void impl::ensureRegionTerminator(
1323     Region &region, Builder &builder, Location loc,
1324     function_ref<Operation *(OpBuilder &, Location)> buildTerminatorOp) {
1325   OpBuilder opBuilder(builder.getContext());
1326   ensureRegionTerminator(region, opBuilder, loc, buildTerminatorOp);
1327 }
1328 
1329 //===----------------------------------------------------------------------===//
1330 // UseIterator
1331 //===----------------------------------------------------------------------===//
1332 
1333 Operation::UseIterator::UseIterator(Operation *op, bool end)
1334     : op(op), res(end ? op->result_end() : op->result_begin()) {
1335   // Only initialize current use if there are results/can be uses.
1336   if (op->getNumResults())
1337     skipOverResultsWithNoUsers();
1338 }
1339 
1340 Operation::UseIterator &Operation::UseIterator::operator++() {
1341   // We increment over uses, if we reach the last use then move to next
1342   // result.
1343   if (use != (*res).use_end())
1344     ++use;
1345   if (use == (*res).use_end()) {
1346     ++res;
1347     skipOverResultsWithNoUsers();
1348   }
1349   return *this;
1350 }
1351 
1352 void Operation::UseIterator::skipOverResultsWithNoUsers() {
1353   while (res != op->result_end() && (*res).use_empty())
1354     ++res;
1355 
1356   // If we are at the last result, then set use to first use of
1357   // first result (sentinel value used for end).
1358   if (res == op->result_end())
1359     use = {};
1360   else
1361     use = (*res).use_begin();
1362 }
1363