1 //===- OwningOpRef.h - MLIR OwningOpRef -------------------------*- 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 provides a base class for owning op refs. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #ifndef MLIR_IR_OWNINGOPREF_H 14 #define MLIR_IR_OWNINGOPREF_H 15 16 #include <utility> 17 18 namespace mlir { 19 20 /// This class acts as an owning reference to an op, and will automatically 21 /// destroy the held op on destruction if the held op is valid. 22 /// 23 /// Note that OpBuilder and related functionality should be highly preferred 24 /// instead, and this should only be used in situations where existing solutions 25 /// are not viable. 26 template <typename OpTy> 27 class OwningOpRef { 28 public: 29 /// The underlying operation type stored in this reference. 30 using OperationT = OpTy; 31 32 OwningOpRef(std::nullptr_t = nullptr) {} OwningOpRef(OpTy op)33 OwningOpRef(OpTy op) : op(op) {} OwningOpRef(OwningOpRef && other)34 OwningOpRef(OwningOpRef &&other) : op(other.release()) {} ~OwningOpRef()35 ~OwningOpRef() { 36 if (op) 37 op->erase(); 38 } 39 40 /// Assign from another op reference. 41 OwningOpRef &operator=(OwningOpRef &&other) { 42 if (op) 43 op->erase(); 44 op = other.release(); 45 return *this; 46 } 47 48 /// Allow accessing the internal op. get()49 OpTy get() const { return op; } 50 OpTy operator*() const { return op; } 51 OpTy *operator->() { return &op; } 52 explicit operator bool() const { return op; } 53 54 /// Release the referenced op. release()55 OpTy release() { 56 OpTy released; 57 std::swap(released, op); 58 return released; 59 } 60 61 private: 62 OpTy op; 63 }; 64 65 } // end namespace mlir 66 67 #endif // MLIR_IR_OWNINGOPREF_H 68