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