base class of all object containers.
Sub-class of objects should declare the following static constexpr fields:
- _type_index: Static type index of the object, if assigned to TypeIndex::kDynamic the type index will be assigned during runtime. Runtime type index can be accessed by ObjectType::TypeIndex();
- _type_key: The unique string identifier of the type.
- _type_final: Whether the type is terminal type(there is no subclass of the type in the object system). This field is automatically set by macro TVM_DECLARE_FINAL_OBJECT_INFO It is still OK to sub-class a terminal object type T and construct it using make_object. But IsInstance check will only show that the object type is T(instead of the sub-class).
The following two fields are necessary for base classes that can be sub-classed.
- _type_child_slots: Number of reserved type index slots for child classes. Used for runtime optimization for type checking in IsInstance. If an object's type_index is within range of [type_index, type_index + _type_child_slots] Then the object can be quickly decided as sub-class of the current object class. If not, a fallback mechanism is used to check the global type table. Recommendation: set to estimate number of children needed.
- _type_child_slots_can_overflow: Whether we can add additional child classes even if the number of child classes exceeds the _type_child_slots. A fallback mechanism to check global type table will be used. Recommendation: set to false for optimal runtime speed if we know exact number of children.
Two macros are used to declare helper functions in the object:
- Use TVM_DECLARE_BASE_OBJECT_INFO for object classes that can be sub-classed.
- Use TVM_DECLARE_FINAL_OBJECT_INFO for object classes that cannot be sub-classed.
New objects can be created using make_object function. Which will automatically populate the type_index and deleter of the object.
- See also
- make_object
-
ObjectPtr
-
ObjectRef
class BaseObj :
public Object {
public:
int field0;
static constexpr
const char*
_type_key =
"test.BaseObj";
};
class LeafObj : public BaseObj {
public:
int child_field0;
static constexpr
const char*
_type_key =
"test.LeafObj";
};
void TestObjects() {
ObjectRef leaf_ref(make_object<LeafObj>());
const LeafObj* leaf_ptr = leaf_ref.as<LeafObj>();
ICHECK(leaf_ptr != nullptr);
ICHECK(leaf_ref.as<BaseObj>() != nullptr);
}
Object()
Definition: object.h:245
static constexpr const char * _type_key
Definition: object.h:226
static constexpr uint32_t _type_index
Definition: object.h:242
#define TVM_DECLARE_BASE_OBJECT_INFO(TypeName, ParentType)
helper macro to declare a base object type that can be inherited.
Definition: object.h:679
#define TVM_REGISTER_OBJECT_TYPE(TypeName)
Helper macro to register the object type to runtime. Makes sure that the runtime type table is correc...
Definition: object.h:725
@ kDynamic
Type index is allocated during runtime.
Definition: object.h:84