1 //===- Operation.h - MLIR Operation Class -----------------------*- C++ -*-===//
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 // This file defines the Operation class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef MLIR_IR_OPERATION_H
14 #define MLIR_IR_OPERATION_H
15 
16 #include "mlir/IR/Block.h"
17 #include "mlir/IR/BuiltinAttributes.h"
18 #include "mlir/IR/Diagnostics.h"
19 #include "mlir/IR/OperationSupport.h"
20 #include "mlir/IR/Region.h"
21 #include "llvm/ADT/Twine.h"
22 
23 namespace mlir {
24 /// Operation is a basic unit of execution within MLIR. Operations can
25 /// be nested within `Region`s held by other operations effectively forming a
26 /// tree. Child operations are organized into operation blocks represented by a
27 /// 'Block' class.
28 class alignas(8) Operation final
29     : public llvm::ilist_node_with_parent<Operation, Block>,
30       private llvm::TrailingObjects<Operation, BlockOperand, Region,
31                                     detail::OperandStorage> {
32 public:
33   /// Create a new Operation with the specific fields.
34   static Operation *create(Location location, OperationName name,
35                            TypeRange resultTypes, ValueRange operands,
36                            ArrayRef<NamedAttribute> attributes,
37                            BlockRange successors, unsigned numRegions);
38 
39   /// Overload of create that takes an existing MutableDictionaryAttr to avoid
40   /// unnecessarily uniquing a list of attributes.
41   static Operation *create(Location location, OperationName name,
42                            TypeRange resultTypes, ValueRange operands,
43                            MutableDictionaryAttr attributes,
44                            BlockRange successors, unsigned numRegions);
45 
46   /// Create a new Operation from the fields stored in `state`.
47   static Operation *create(const OperationState &state);
48 
49   /// Create a new Operation with the specific fields.
50   static Operation *create(Location location, OperationName name,
51                            TypeRange resultTypes, ValueRange operands,
52                            MutableDictionaryAttr attributes,
53                            BlockRange successors = {},
54                            RegionRange regions = {});
55 
56   /// The name of an operation is the key identifier for it.
getName()57   OperationName getName() { return name; }
58 
59   /// If this operation has a registered operation description, return it.
60   /// Otherwise return null.
getAbstractOperation()61   const AbstractOperation *getAbstractOperation() {
62     return getName().getAbstractOperation();
63   }
64 
65   /// Returns true if this operation has a registered operation description,
66   /// otherwise false.
isRegistered()67   bool isRegistered() { return getAbstractOperation(); }
68 
69   /// Remove this operation from its parent block and delete it.
70   void erase();
71 
72   /// Remove the operation from its parent block, but don't delete it.
73   void remove();
74 
75   /// Create a deep copy of this operation, remapping any operands that use
76   /// values outside of the operation using the map that is provided (leaving
77   /// them alone if no entry is present).  Replaces references to cloned
78   /// sub-operations to the corresponding operation that is copied, and adds
79   /// those mappings to the map.
80   Operation *clone(BlockAndValueMapping &mapper);
81   Operation *clone();
82 
83   /// Create a partial copy of this operation without traversing into attached
84   /// regions. The new operation will have the same number of regions as the
85   /// original one, but they will be left empty.
86   /// Operands are remapped using `mapper` (if present), and `mapper` is updated
87   /// to contain the results.
88   Operation *cloneWithoutRegions(BlockAndValueMapping &mapper);
89 
90   /// Create a partial copy of this operation without traversing into attached
91   /// regions. The new operation will have the same number of regions as the
92   /// original one, but they will be left empty.
93   Operation *cloneWithoutRegions();
94 
95   /// Returns the operation block that contains this operation.
getBlock()96   Block *getBlock() { return block; }
97 
98   /// Return the context this operation is associated with.
99   MLIRContext *getContext();
100 
101   /// Return the dialect this operation is associated with, or nullptr if the
102   /// associated dialect is not registered.
103   Dialect *getDialect();
104 
105   /// The source location the operation was defined or derived from.
getLoc()106   Location getLoc() { return location; }
107 
108   /// Set the source location the operation was defined or derived from.
setLoc(Location loc)109   void setLoc(Location loc) { location = loc; }
110 
111   /// Returns the region to which the instruction belongs. Returns nullptr if
112   /// the instruction is unlinked.
113   Region *getParentRegion();
114 
115   /// Returns the closest surrounding operation that contains this operation
116   /// or nullptr if this is a top-level operation.
117   Operation *getParentOp();
118 
119   /// Return the closest surrounding parent operation that is of type 'OpTy'.
getParentOfType()120   template <typename OpTy> OpTy getParentOfType() {
121     auto *op = this;
122     while ((op = op->getParentOp()))
123       if (auto parentOp = dyn_cast<OpTy>(op))
124         return parentOp;
125     return OpTy();
126   }
127 
128   /// Returns the closest surrounding parent operation with trait `Trait`.
129   template <template <typename T> class Trait>
getParentWithTrait()130   Operation *getParentWithTrait() {
131     Operation *op = this;
132     while ((op = op->getParentOp()))
133       if (op->hasTrait<Trait>())
134         return op;
135     return nullptr;
136   }
137 
138   /// Return true if this operation is a proper ancestor of the `other`
139   /// operation.
140   bool isProperAncestor(Operation *other);
141 
142   /// Return true if this operation is an ancestor of the `other` operation. An
143   /// operation is considered as its own ancestor, use `isProperAncestor` to
144   /// avoid this.
isAncestor(Operation * other)145   bool isAncestor(Operation *other) {
146     return this == other || isProperAncestor(other);
147   }
148 
149   /// Replace any uses of 'from' with 'to' within this operation.
150   void replaceUsesOfWith(Value from, Value to);
151 
152   /// Replace all uses of results of this operation with the provided 'values'.
153   template <typename ValuesT>
154   std::enable_if_t<!std::is_convertible<ValuesT, Operation *>::value>
replaceAllUsesWith(ValuesT && values)155   replaceAllUsesWith(ValuesT &&values) {
156     assert(std::distance(values.begin(), values.end()) == getNumResults() &&
157            "expected 'values' to correspond 1-1 with the number of results");
158 
159     auto valueIt = values.begin();
160     for (unsigned i = 0, e = getNumResults(); i != e; ++i)
161       getResult(i).replaceAllUsesWith(*(valueIt++));
162   }
163 
164   /// Replace all uses of results of this operation with results of 'op'.
replaceAllUsesWith(Operation * op)165   void replaceAllUsesWith(Operation *op) {
166     assert(getNumResults() == op->getNumResults());
167     for (unsigned i = 0, e = getNumResults(); i != e; ++i)
168       getResult(i).replaceAllUsesWith(op->getResult(i));
169   }
170 
171   /// Destroys this operation and its subclass data.
172   void destroy();
173 
174   /// This drops all operand uses from this operation, which is an essential
175   /// step in breaking cyclic dependences between references when they are to
176   /// be deleted.
177   void dropAllReferences();
178 
179   /// Drop uses of all values defined by this operation or its nested regions.
180   void dropAllDefinedValueUses();
181 
182   /// Unlink this operation from its current block and insert it right before
183   /// `existingOp` which may be in the same or another block in the same
184   /// function.
185   void moveBefore(Operation *existingOp);
186 
187   /// Unlink this operation from its current block and insert it right before
188   /// `iterator` in the specified block.
189   void moveBefore(Block *block, llvm::iplist<Operation>::iterator iterator);
190 
191   /// Unlink this operation from its current block and insert it right after
192   /// `existingOp` which may be in the same or another block in the same
193   /// function.
194   void moveAfter(Operation *existingOp);
195 
196   /// Unlink this operation from its current block and insert it right after
197   /// `iterator` in the specified block.
198   void moveAfter(Block *block, llvm::iplist<Operation>::iterator iterator);
199 
200   /// Given an operation 'other' that is within the same parent block, return
201   /// whether the current operation is before 'other' in the operation list
202   /// of the parent block.
203   /// Note: This function has an average complexity of O(1), but worst case may
204   /// take O(N) where N is the number of operations within the parent block.
205   bool isBeforeInBlock(Operation *other);
206 
207   void print(raw_ostream &os, OpPrintingFlags flags = llvm::None);
208   void print(raw_ostream &os, AsmState &state,
209              OpPrintingFlags flags = llvm::None);
210   void dump();
211 
212   //===--------------------------------------------------------------------===//
213   // Operands
214   //===--------------------------------------------------------------------===//
215 
216   /// Replace the current operands of this operation with the ones provided in
217   /// 'operands'.
218   void setOperands(ValueRange operands);
219 
220   /// Replace the operands beginning at 'start' and ending at 'start' + 'length'
221   /// with the ones provided in 'operands'. 'operands' may be smaller or larger
222   /// than the range pointed to by 'start'+'length'.
223   void setOperands(unsigned start, unsigned length, ValueRange operands);
224 
225   /// Insert the given operands into the operand list at the given 'index'.
226   void insertOperands(unsigned index, ValueRange operands);
227 
getNumOperands()228   unsigned getNumOperands() {
229     return LLVM_LIKELY(hasOperandStorage) ? getOperandStorage().size() : 0;
230   }
231 
getOperand(unsigned idx)232   Value getOperand(unsigned idx) { return getOpOperand(idx).get(); }
setOperand(unsigned idx,Value value)233   void setOperand(unsigned idx, Value value) {
234     return getOpOperand(idx).set(value);
235   }
236 
237   /// Erase the operand at position `idx`.
eraseOperand(unsigned idx)238   void eraseOperand(unsigned idx) { eraseOperands(idx); }
239 
240   /// Erase the operands starting at position `idx` and ending at position
241   /// 'idx'+'length'.
242   void eraseOperands(unsigned idx, unsigned length = 1) {
243     getOperandStorage().eraseOperands(idx, length);
244   }
245 
246   // Support operand iteration.
247   using operand_range = OperandRange;
248   using operand_iterator = operand_range::iterator;
249 
operand_begin()250   operand_iterator operand_begin() { return getOperands().begin(); }
operand_end()251   operand_iterator operand_end() { return getOperands().end(); }
252 
253   /// Returns an iterator on the underlying Value's.
getOperands()254   operand_range getOperands() { return operand_range(this); }
255 
getOpOperands()256   MutableArrayRef<OpOperand> getOpOperands() {
257     return LLVM_LIKELY(hasOperandStorage) ? getOperandStorage().getOperands()
258                                           : MutableArrayRef<OpOperand>();
259   }
260 
getOpOperand(unsigned idx)261   OpOperand &getOpOperand(unsigned idx) { return getOpOperands()[idx]; }
262 
263   // Support operand type iteration.
264   using operand_type_iterator = operand_range::type_iterator;
265   using operand_type_range = operand_range::type_range;
operand_type_begin()266   operand_type_iterator operand_type_begin() { return operand_begin(); }
operand_type_end()267   operand_type_iterator operand_type_end() { return operand_end(); }
getOperandTypes()268   operand_type_range getOperandTypes() { return getOperands().getTypes(); }
269 
270   //===--------------------------------------------------------------------===//
271   // Results
272   //===--------------------------------------------------------------------===//
273 
274   /// Return the number of results held by this operation.
275   unsigned getNumResults();
276 
277   /// Get the 'idx'th result of this operation.
getResult(unsigned idx)278   OpResult getResult(unsigned idx) { return OpResult(this, idx); }
279 
280   /// Support result iteration.
281   using result_range = ResultRange;
282   using result_iterator = result_range::iterator;
283 
result_begin()284   result_iterator result_begin() { return getResults().begin(); }
result_end()285   result_iterator result_end() { return getResults().end(); }
getResults()286   result_range getResults() { return result_range(this); }
287 
getOpResults()288   result_range getOpResults() { return getResults(); }
getOpResult(unsigned idx)289   OpResult getOpResult(unsigned idx) { return getResult(idx); }
290 
291   /// Support result type iteration.
292   using result_type_iterator = result_range::type_iterator;
293   using result_type_range = result_range::type_range;
result_type_begin()294   result_type_iterator result_type_begin() { return getResultTypes().begin(); }
result_type_end()295   result_type_iterator result_type_end() { return getResultTypes().end(); }
296   result_type_range getResultTypes();
297 
298   //===--------------------------------------------------------------------===//
299   // Attributes
300   //===--------------------------------------------------------------------===//
301 
302   // Operations may optionally carry a list of attributes that associate
303   // constants to names.  Attributes may be dynamically added and removed over
304   // the lifetime of an operation.
305 
306   /// Return all of the attributes on this operation.
getAttrs()307   ArrayRef<NamedAttribute> getAttrs() { return attrs.getAttrs(); }
308 
309   /// Return all of the attributes on this operation as a DictionaryAttr.
getAttrDictionary()310   DictionaryAttr getAttrDictionary() {
311     return attrs.getDictionary(getContext());
312   }
313 
314   /// Return mutable container of all the attributes on this operation.
getMutableAttrDict()315   MutableDictionaryAttr &getMutableAttrDict() { return attrs; }
316 
317   /// Set the attribute dictionary on this operation.
318   /// Using a MutableDictionaryAttr is more efficient as it does not require new
319   /// uniquing in the MLIRContext.
setAttrs(MutableDictionaryAttr newAttrs)320   void setAttrs(MutableDictionaryAttr newAttrs) { attrs = newAttrs; }
321 
322   /// Return the specified attribute if present, null otherwise.
getAttr(Identifier name)323   Attribute getAttr(Identifier name) { return attrs.get(name); }
getAttr(StringRef name)324   Attribute getAttr(StringRef name) { return attrs.get(name); }
325 
getAttrOfType(Identifier name)326   template <typename AttrClass> AttrClass getAttrOfType(Identifier name) {
327     return getAttr(name).dyn_cast_or_null<AttrClass>();
328   }
getAttrOfType(StringRef name)329   template <typename AttrClass> AttrClass getAttrOfType(StringRef name) {
330     return getAttr(name).dyn_cast_or_null<AttrClass>();
331   }
332 
333   /// Return true if the operation has an attribute with the provided name,
334   /// false otherwise.
hasAttr(Identifier name)335   bool hasAttr(Identifier name) { return static_cast<bool>(getAttr(name)); }
hasAttr(StringRef name)336   bool hasAttr(StringRef name) { return static_cast<bool>(getAttr(name)); }
337   template <typename AttrClass, typename NameT>
hasAttrOfType(NameT && name)338   bool hasAttrOfType(NameT &&name) {
339     return static_cast<bool>(
340         getAttrOfType<AttrClass>(std::forward<NameT>(name)));
341   }
342 
343   /// If the an attribute exists with the specified name, change it to the new
344   /// value.  Otherwise, add a new attribute with the specified name/value.
setAttr(Identifier name,Attribute value)345   void setAttr(Identifier name, Attribute value) { attrs.set(name, value); }
setAttr(StringRef name,Attribute value)346   void setAttr(StringRef name, Attribute value) {
347     setAttr(Identifier::get(name, getContext()), value);
348   }
349 
350   /// Remove the attribute with the specified name if it exists.  The return
351   /// value indicates whether the attribute was present or not.
removeAttr(Identifier name)352   MutableDictionaryAttr::RemoveResult removeAttr(Identifier name) {
353     return attrs.remove(name);
354   }
removeAttr(StringRef name)355   MutableDictionaryAttr::RemoveResult removeAttr(StringRef name) {
356     return attrs.remove(Identifier::get(name, getContext()));
357   }
358 
359   /// A utility iterator that filters out non-dialect attributes.
360   class dialect_attr_iterator
361       : public llvm::filter_iterator<ArrayRef<NamedAttribute>::iterator,
362                                      bool (*)(NamedAttribute)> {
filter(NamedAttribute attr)363     static bool filter(NamedAttribute attr) {
364       // Dialect attributes are prefixed by the dialect name, like operations.
365       return attr.first.strref().count('.');
366     }
367 
dialect_attr_iterator(ArrayRef<NamedAttribute>::iterator it,ArrayRef<NamedAttribute>::iterator end)368     explicit dialect_attr_iterator(ArrayRef<NamedAttribute>::iterator it,
369                                    ArrayRef<NamedAttribute>::iterator end)
370         : llvm::filter_iterator<ArrayRef<NamedAttribute>::iterator,
371                                 bool (*)(NamedAttribute)>(it, end, &filter) {}
372 
373     // Allow access to the constructor.
374     friend Operation;
375   };
376   using dialect_attr_range = iterator_range<dialect_attr_iterator>;
377 
378   /// Return a range corresponding to the dialect attributes for this operation.
getDialectAttrs()379   dialect_attr_range getDialectAttrs() {
380     auto attrs = getAttrs();
381     return {dialect_attr_iterator(attrs.begin(), attrs.end()),
382             dialect_attr_iterator(attrs.end(), attrs.end())};
383   }
dialect_attr_begin()384   dialect_attr_iterator dialect_attr_begin() {
385     auto attrs = getAttrs();
386     return dialect_attr_iterator(attrs.begin(), attrs.end());
387   }
dialect_attr_end()388   dialect_attr_iterator dialect_attr_end() {
389     auto attrs = getAttrs();
390     return dialect_attr_iterator(attrs.end(), attrs.end());
391   }
392 
393   /// Set the dialect attributes for this operation, and preserve all dependent.
394   template <typename DialectAttrT>
setDialectAttrs(DialectAttrT && dialectAttrs)395   void setDialectAttrs(DialectAttrT &&dialectAttrs) {
396     SmallVector<NamedAttribute, 16> attrs;
397     attrs.assign(std::begin(dialectAttrs), std::end(dialectAttrs));
398     for (auto attr : getAttrs())
399       if (!attr.first.strref().count('.'))
400         attrs.push_back(attr);
401     setAttrs(llvm::makeArrayRef(attrs));
402   }
403 
404   //===--------------------------------------------------------------------===//
405   // Blocks
406   //===--------------------------------------------------------------------===//
407 
408   /// Returns the number of regions held by this operation.
getNumRegions()409   unsigned getNumRegions() { return numRegions; }
410 
411   /// Returns the regions held by this operation.
getRegions()412   MutableArrayRef<Region> getRegions() {
413     auto *regions = getTrailingObjects<Region>();
414     return {regions, numRegions};
415   }
416 
417   /// Returns the region held by this operation at position 'index'.
getRegion(unsigned index)418   Region &getRegion(unsigned index) {
419     assert(index < numRegions && "invalid region index");
420     return getRegions()[index];
421   }
422 
423   //===--------------------------------------------------------------------===//
424   // Successors
425   //===--------------------------------------------------------------------===//
426 
getBlockOperands()427   MutableArrayRef<BlockOperand> getBlockOperands() {
428     return {getTrailingObjects<BlockOperand>(), numSuccs};
429   }
430 
431   // Successor iteration.
432   using succ_iterator = SuccessorRange::iterator;
successor_begin()433   succ_iterator successor_begin() { return getSuccessors().begin(); }
successor_end()434   succ_iterator successor_end() { return getSuccessors().end(); }
getSuccessors()435   SuccessorRange getSuccessors() { return SuccessorRange(this); }
436 
hasSuccessors()437   bool hasSuccessors() { return numSuccs != 0; }
getNumSuccessors()438   unsigned getNumSuccessors() { return numSuccs; }
439 
getSuccessor(unsigned index)440   Block *getSuccessor(unsigned index) {
441     assert(index < getNumSuccessors());
442     return getBlockOperands()[index].get();
443   }
444   void setSuccessor(Block *block, unsigned index);
445 
446   //===--------------------------------------------------------------------===//
447   // Accessors for various properties of operations
448   //===--------------------------------------------------------------------===//
449 
450   /// Returns whether the operation is commutative.
isCommutative()451   bool isCommutative() {
452     if (auto *absOp = getAbstractOperation())
453       return absOp->hasProperty(OperationProperty::Commutative);
454     return false;
455   }
456 
457   /// Represents the status of whether an operation is a terminator. We
458   /// represent an 'unknown' status because we want to support unregistered
459   /// terminators.
460   enum class TerminatorStatus { Terminator, NonTerminator, Unknown };
461 
462   /// Returns the status of whether this operation is a terminator or not.
getTerminatorStatus()463   TerminatorStatus getTerminatorStatus() {
464     if (auto *absOp = getAbstractOperation()) {
465       return absOp->hasProperty(OperationProperty::Terminator)
466                  ? TerminatorStatus::Terminator
467                  : TerminatorStatus::NonTerminator;
468     }
469     return TerminatorStatus::Unknown;
470   }
471 
472   /// Returns true if the operation is known to be a terminator.
isKnownTerminator()473   bool isKnownTerminator() {
474     return getTerminatorStatus() == TerminatorStatus::Terminator;
475   }
476 
477   /// Returns true if the operation is known to *not* be a terminator.
isKnownNonTerminator()478   bool isKnownNonTerminator() {
479     return getTerminatorStatus() == TerminatorStatus::NonTerminator;
480   }
481 
482   /// Returns true if the operation is known to be completely isolated from
483   /// enclosing regions, i.e., no internal regions reference values defined
484   /// above this operation.
isKnownIsolatedFromAbove()485   bool isKnownIsolatedFromAbove() {
486     if (auto *absOp = getAbstractOperation())
487       return absOp->hasProperty(OperationProperty::IsolatedFromAbove);
488     return false;
489   }
490 
491   /// Attempt to fold this operation with the specified constant operand values
492   /// - the elements in "operands" will correspond directly to the operands of
493   /// the operation, but may be null if non-constant. If folding is successful,
494   /// this fills in the `results` vector. If not, `results` is unspecified.
495   LogicalResult fold(ArrayRef<Attribute> operands,
496                      SmallVectorImpl<OpFoldResult> &results);
497 
498   /// Returns true if the operation was registered with a particular trait, e.g.
499   /// hasTrait<OperandsAreSignlessIntegerLike>().
hasTrait()500   template <template <typename T> class Trait> bool hasTrait() {
501     auto *absOp = getAbstractOperation();
502     return absOp ? absOp->hasTrait<Trait>() : false;
503   }
504 
505   //===--------------------------------------------------------------------===//
506   // Operation Walkers
507   //===--------------------------------------------------------------------===//
508 
509   /// Walk the operation in postorder, calling the callback for each nested
510   /// operation(including this one). The callback method can take any of the
511   /// following forms:
512   ///   void(Operation*) : Walk all operations opaquely.
513   ///     * op->walk([](Operation *nestedOp) { ...});
514   ///   void(OpT) : Walk all operations of the given derived type.
515   ///     * op->walk([](ReturnOp returnOp) { ...});
516   ///   WalkResult(Operation*|OpT) : Walk operations, but allow for
517   ///                                interruption/cancellation.
518   ///     * op->walk([](... op) {
519   ///         // Interrupt, i.e cancel, the walk based on some invariant.
520   ///         if (some_invariant)
521   ///           return WalkResult::interrupt();
522   ///         return WalkResult::advance();
523   ///       });
524   template <typename FnT, typename RetT = detail::walkResultType<FnT>>
walk(FnT && callback)525   RetT walk(FnT &&callback) {
526     return detail::walk(this, std::forward<FnT>(callback));
527   }
528 
529   //===--------------------------------------------------------------------===//
530   // Uses
531   //===--------------------------------------------------------------------===//
532 
533   /// Drop all uses of results of this operation.
dropAllUses()534   void dropAllUses() {
535     for (OpResult result : getOpResults())
536       result.dropAllUses();
537   }
538 
539   /// This class implements a use iterator for the Operation. This iterates over
540   /// all uses of all results.
541   class UseIterator final
542       : public llvm::iterator_facade_base<
543             UseIterator, std::forward_iterator_tag, OpOperand> {
544   public:
545     /// Initialize UseIterator for op, specify end to return iterator to last
546     /// use.
547     explicit UseIterator(Operation *op, bool end = false);
548 
549     using llvm::iterator_facade_base<UseIterator, std::forward_iterator_tag,
550                                      OpOperand>::operator++;
551     UseIterator &operator++();
552     OpOperand *operator->() const { return use.getOperand(); }
553     OpOperand &operator*() const { return *use.getOperand(); }
554 
555     bool operator==(const UseIterator &rhs) const { return use == rhs.use; }
556     bool operator!=(const UseIterator &rhs) const { return !(*this == rhs); }
557 
558   private:
559     void skipOverResultsWithNoUsers();
560 
561     /// The operation whose uses are being iterated over.
562     Operation *op;
563     /// The result of op who's uses are being iterated over.
564     Operation::result_iterator res;
565     /// The use of the result.
566     Value::use_iterator use;
567   };
568   using use_iterator = UseIterator;
569   using use_range = iterator_range<use_iterator>;
570 
use_begin()571   use_iterator use_begin() { return use_iterator(this); }
use_end()572   use_iterator use_end() { return use_iterator(this, /*end=*/true); }
573 
574   /// Returns a range of all uses, which is useful for iterating over all uses.
getUses()575   use_range getUses() { return {use_begin(), use_end()}; }
576 
577   /// Returns true if this operation has exactly one use.
hasOneUse()578   bool hasOneUse() { return llvm::hasSingleElement(getUses()); }
579 
580   /// Returns true if this operation has no uses.
use_empty()581   bool use_empty() {
582     return llvm::all_of(getOpResults(),
583                         [](OpResult result) { return result.use_empty(); });
584   }
585 
586   /// Returns true if the results of this operation are used outside of the
587   /// given block.
isUsedOutsideOfBlock(Block * block)588   bool isUsedOutsideOfBlock(Block *block) {
589     return llvm::any_of(getOpResults(), [block](OpResult result) {
590       return result.isUsedOutsideOfBlock(block);
591     });
592   }
593 
594   //===--------------------------------------------------------------------===//
595   // Users
596   //===--------------------------------------------------------------------===//
597 
598   using user_iterator = ValueUserIterator<use_iterator, OpOperand>;
599   using user_range = iterator_range<user_iterator>;
600 
user_begin()601   user_iterator user_begin() { return user_iterator(use_begin()); }
user_end()602   user_iterator user_end() { return user_iterator(use_end()); }
603 
604   /// Returns a range of all users.
getUsers()605   user_range getUsers() { return {user_begin(), user_end()}; }
606 
607   //===--------------------------------------------------------------------===//
608   // Other
609   //===--------------------------------------------------------------------===//
610 
611   /// Emit an error with the op name prefixed, like "'dim' op " which is
612   /// convenient for verifiers.
613   InFlightDiagnostic emitOpError(const Twine &message = {});
614 
615   /// Emit an error about fatal conditions with this operation, reporting up to
616   /// any diagnostic handlers that may be listening.
617   InFlightDiagnostic emitError(const Twine &message = {});
618 
619   /// Emit a warning about this operation, reporting up to any diagnostic
620   /// handlers that may be listening.
621   InFlightDiagnostic emitWarning(const Twine &message = {});
622 
623   /// Emit a remark about this operation, reporting up to any diagnostic
624   /// handlers that may be listening.
625   InFlightDiagnostic emitRemark(const Twine &message = {});
626 
627 private:
628   //===--------------------------------------------------------------------===//
629   // Ordering
630   //===--------------------------------------------------------------------===//
631 
632   /// This value represents an invalid index ordering for an operation within a
633   /// block.
634   static constexpr unsigned kInvalidOrderIdx = -1;
635 
636   /// This value represents the stride to use when computing a new order for an
637   /// operation.
638   static constexpr unsigned kOrderStride = 5;
639 
640   /// Update the order index of this operation of this operation if necessary,
641   /// potentially recomputing the order of the parent block.
642   void updateOrderIfNecessary();
643 
644   /// Returns true if this operation has a valid order.
hasValidOrder()645   bool hasValidOrder() { return orderIndex != kInvalidOrderIdx; }
646 
647 private:
648   Operation(Location location, OperationName name, TypeRange resultTypes,
649             unsigned numSuccessors, unsigned numRegions,
650             const MutableDictionaryAttr &attributes, bool hasOperandStorage);
651 
652   // Operations are deleted through the destroy() member because they are
653   // allocated with malloc.
654   ~Operation();
655 
656   /// Returns the additional size necessary for allocating the given objects
657   /// before an Operation in-memory.
prefixAllocSize(unsigned numTrailingResults,unsigned numInlineResults)658   static size_t prefixAllocSize(unsigned numTrailingResults,
659                                 unsigned numInlineResults) {
660     return sizeof(detail::TrailingOpResult) * numTrailingResults +
661            sizeof(detail::InLineOpResult) * numInlineResults;
662   }
663   /// Returns the additional size allocated before this Operation in-memory.
prefixAllocSize()664   size_t prefixAllocSize() {
665     unsigned numResults = getNumResults();
666     unsigned numTrailingResults = OpResult::getNumTrailing(numResults);
667     unsigned numInlineResults = OpResult::getNumInline(numResults);
668     return prefixAllocSize(numTrailingResults, numInlineResults);
669   }
670 
671   /// Returns the operand storage object.
getOperandStorage()672   detail::OperandStorage &getOperandStorage() {
673     assert(hasOperandStorage && "expected operation to have operand storage");
674     return *getTrailingObjects<detail::OperandStorage>();
675   }
676 
677   /// Returns a pointer to the use list for the given trailing result.
getTrailingResult(unsigned resultNumber)678   detail::TrailingOpResult *getTrailingResult(unsigned resultNumber) {
679     // Trailing results are stored in reverse order after(before in memory) the
680     // inline results.
681     return reinterpret_cast<detail::TrailingOpResult *>(
682                getInlineResult(OpResult::getMaxInlineResults() - 1)) -
683            ++resultNumber;
684   }
685 
686   /// Returns a pointer to the use list for the given inline result.
getInlineResult(unsigned resultNumber)687   detail::InLineOpResult *getInlineResult(unsigned resultNumber) {
688     // Inline results are stored in reverse order before the operation in
689     // memory.
690     return reinterpret_cast<detail::InLineOpResult *>(this) - ++resultNumber;
691   }
692 
693   /// Provide a 'getParent' method for ilist_node_with_parent methods.
694   /// We mark it as a const function because ilist_node_with_parent specifically
695   /// requires a 'getParent() const' method. Once ilist_node removes this
696   /// constraint, we should drop the const to fit the rest of the MLIR const
697   /// model.
getParent()698   Block *getParent() const { return block; }
699 
700   /// The operation block that contains this operation.
701   Block *block = nullptr;
702 
703   /// This holds information about the source location the operation was defined
704   /// or derived from.
705   Location location;
706 
707   /// Relative order of this operation in its parent block. Used for
708   /// O(1) local dominance checks between operations.
709   mutable unsigned orderIndex = 0;
710 
711   const unsigned numSuccs;
712   const unsigned numRegions : 30;
713 
714   /// This bit signals whether this operation has an operand storage or not. The
715   /// operand storage may be elided for operations that are known to never have
716   /// operands.
717   bool hasOperandStorage : 1;
718 
719   /// This holds the result types of the operation. There are three different
720   /// states recorded here:
721   /// - 0 results : The type below is null.
722   /// - 1 result  : The single result type is held here.
723   /// - N results : The type here is a tuple holding the result types.
724   /// Note: We steal a bit for 'hasSingleResult' from somewhere else so that we
725   /// can use 'resultType` in an ArrayRef<Type>.
726   bool hasSingleResult : 1;
727   Type resultType;
728 
729   /// This holds the name of the operation.
730   OperationName name;
731 
732   /// This holds general named attributes for the operation.
733   MutableDictionaryAttr attrs;
734 
735   // allow ilist_traits access to 'block' field.
736   friend struct llvm::ilist_traits<Operation>;
737 
738   // allow block to access the 'orderIndex' field.
739   friend class Block;
740 
741   // allow value to access the 'ResultStorage' methods.
742   friend class Value;
743 
744   // allow ilist_node_with_parent to access the 'getParent' method.
745   friend class llvm::ilist_node_with_parent<Operation, Block>;
746 
747   // This stuff is used by the TrailingObjects template.
748   friend llvm::TrailingObjects<Operation, BlockOperand, Region,
749                                detail::OperandStorage>;
750   size_t numTrailingObjects(OverloadToken<BlockOperand>) const {
751     return numSuccs;
752   }
753   size_t numTrailingObjects(OverloadToken<Region>) const { return numRegions; }
754 };
755 
756 inline raw_ostream &operator<<(raw_ostream &os, Operation &op) {
757   op.print(os, OpPrintingFlags().useLocalScope());
758   return os;
759 }
760 
761 } // end namespace mlir
762 
763 namespace llvm {
764 /// Provide isa functionality for operation casts.
765 template <typename T> struct isa_impl<T, ::mlir::Operation> {
766   static inline bool doit(const ::mlir::Operation &op) {
767     return T::classof(const_cast<::mlir::Operation *>(&op));
768   }
769 };
770 
771 /// Provide specializations for operation casts as the resulting T is value
772 /// typed.
773 template <typename T> struct cast_retty_impl<T, ::mlir::Operation *> {
774   using ret_type = T;
775 };
776 template <typename T> struct cast_retty_impl<T, ::mlir::Operation> {
777   using ret_type = T;
778 };
779 template <class T>
780 struct cast_convert_val<T, ::mlir::Operation, ::mlir::Operation> {
781   static T doit(::mlir::Operation &val) { return T(&val); }
782 };
783 template <class T>
784 struct cast_convert_val<T, ::mlir::Operation *, ::mlir::Operation *> {
785   static T doit(::mlir::Operation *val) { return T(val); }
786 };
787 } // end namespace llvm
788 
789 #endif // MLIR_IR_OPERATION_H
790