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