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